Skip to content

Commit d8c1a69

Browse files
committed
reconstruct exception and response
1 parent 9525f59 commit d8c1a69

4 files changed

Lines changed: 75 additions & 88 deletions

File tree

kubesys/analyzer.py

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
"""
44
import kubesys.http_request as http_request
55
from kubesys.common import getLastIndex
6+
from kubesys.exceptions import KindException
67

78
__author__ = ('Tian Yu <[email protected]>',
89
'Heng Wu <[email protected]>')
@@ -20,14 +21,29 @@ def __init__(self) -> None:
2021
self.FullKindToGroupDict = {}
2122
self.FullKindToVerbsDict = {}
2223

24+
def checkAndReturnRealKind(self, kind):
25+
mapper=self.KindToFullKindDict
26+
index = kind.find(".")
27+
if index < 0:
28+
if not mapper.get(kind) or len(mapper.get(kind)) == 0:
29+
raise KindException(f"Invalid kind {kind}")
30+
if len(mapper[kind]) == 1:
31+
return mapper[kind][0]
32+
33+
else:
34+
value = ""
35+
for s in mapper[kind]:
36+
value += "," + s
37+
38+
raise KindException("please use fullKind: " + value[1:])
39+
2340
def learning(self, url, token, config) -> None:
24-
registryValues = http_request.createRequest(url=url, token=token, method="GET", keep_json=False, config=config)[0]
41+
registryValues = http_request.createRequest(url=url, token=token, method="GET", keep_json=False, config=config)
2542

2643
# print(registryValues)
2744
for path in registryValues["paths"]:
2845
if path.startswith("/api") and (len(path.split("/")) == 4 or path.lower().strip() == "/api/v1"):
29-
resourceValues = http_request.createRequest(url=url + path, token=token, method="GET", keep_json=False, config=config)[
30-
0]
46+
resourceValues = http_request.createRequest(url=url + path, token=token, method="GET", keep_json=False, config=config)
3147
apiVersion = str(resourceValues["groupVersion"])
3248

3349
for resourceValue in resourceValues["resources"]:

kubesys/client.py

Lines changed: 40 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
from kubesys.http_request import createRequest,doCreateRequest
88
from kubesys.analyzer import KubernetesAnalyzer
99
import requests
10+
from requests.models import HTTPError,Response
1011
import json
1112
from kubesys.common import jsonBytesToDict
1213
import threading
@@ -15,6 +16,7 @@
1516
from kubesys.watcher import KubernetesWatcher
1617

1718
__author__ = ('Tian Yu <[email protected]>',
19+
'Jiexin Liu <[email protected]>',
1820
'Heng Wu <[email protected]>')
1921

2022

@@ -39,7 +41,7 @@ def __init__(self, url=None, token=None, analyzer=None,
3941

4042
if self.config is None:
4143
if url is None or token is None:
42-
sys.exit('missing url or token')
44+
raise HTTPError('missing url or token')
4345
self.url = url.rstrip("/")
4446
self.token = token
4547
else:
@@ -72,7 +74,7 @@ def getRealKind(self, kind, apiVersion) -> str:
7274
else:
7375
return apiVersion[:index] + "." + kind
7476

75-
def createResource(self, jsonStr, **kwargs) -> Union[dict, bool, str]:
77+
def createResource(self, jsonStr, **kwargs) -> Response:
7678
jsonObj = jsonStr
7779
if type(jsonObj) is str:
7880
jsonObj = json.loads(jsonObj)
@@ -88,7 +90,7 @@ def createResource(self, jsonStr, **kwargs) -> Union[dict, bool, str]:
8890
url += self.analyzer.FullKindToNameDict[kind]
8991
return createRequest(url=url, token=self.token, method="POST", body=jsonStr,keep_json=False, config=self.config, **kwargs)
9092

91-
def updateResource(self, jsonStr, **kwargs) -> Union[dict, bool, str]:
93+
def updateResource(self, jsonStr, **kwargs) -> Response:
9294
jsonObj = jsonStr
9395
if type(jsonObj) is str:
9496
jsonObj = json.loads(jsonObj)
@@ -105,39 +107,36 @@ def updateResource(self, jsonStr, **kwargs) -> Union[dict, bool, str]:
105107

106108
return createRequest(url=url, token=self.token, method="PUT", body=jsonStr, keep_json=False,config=self.config, **kwargs)
107109

108-
def checkAndReturnRealKind(self, kind, mapper) -> Union[str, str]:
109-
index = kind.find(".")
110-
if index < 0:
111-
if len(mapper[kind]) == 1:
112-
return mapper[kind][0], None
113-
114-
elif len(mapper[kind]) == 0:
115-
return "", "invalid kind"
116-
117-
else:
118-
value = ""
119-
for s in mapper[kind]:
120-
value += "," + s
121-
122-
return "", "please use fullKind: " + value[1:]
123-
124-
return kind, None
125-
126-
def deleteResource(self, kind, namespace, name, **kwargs) -> Union[dict, bool, str]:
127-
fullKind, error_str = self.checkAndReturnRealKind(kind, self.analyzer.KindToFullKindDict)
128-
if error_str:
129-
return None, error_str
130-
110+
# def checkAndReturnRealKind(self, kind, mapper):
111+
# index = kind.find(".")
112+
# if index < 0:
113+
# if not mapper.get(kind) or len(mapper.get(kind)) == 0:
114+
# raise KindException(f"Invalid kind {kind}")
115+
# if len(mapper[kind]) == 1:
116+
# return mapper[kind][0]
117+
#
118+
# # elif len(mapper[kind]) == 0:
119+
# # raise Exception(f"Invalid kind {kind}")
120+
#
121+
# else:
122+
# value = ""
123+
# for s in mapper[kind]:
124+
# value += "," + s
125+
#
126+
# raise KindException("please use fullKind: " + value[1:])
127+
#
128+
# return kind
129+
130+
def deleteResource(self, kind, namespace, name, **kwargs) -> Response:
131+
fullKind = self.analyzer.checkAndReturnRealKind(kind)
131132
url = self.analyzer.FullKindToApiPrefixDict[fullKind] + "/"
132133
url += self.getNamespace(self.analyzer.FullKindToNamespaceDict[fullKind], namespace)
133134
url += self.analyzer.FullKindToNameDict[fullKind] + "/" + name
134135

135136
return createRequest(url=url, token=self.token, method="DELETE", keep_json=False,config=self.config, **kwargs)
136137

137-
def getResource(self, kind, name, namespace="", **kwargs) -> Union[dict, bool, str]:
138-
fullKind, error_str = self.checkAndReturnRealKind(kind, self.analyzer.KindToFullKindDict)
139-
if error_str:
140-
return None, error_str
138+
def getResource(self, kind, name, namespace="", **kwargs) -> Response:
139+
fullKind = self.analyzer.checkAndReturnRealKind(kind)
141140

142141
url = self.analyzer.FullKindToApiPrefixDict[fullKind] + "/"
143142
url += self.getNamespace(self.analyzer.FullKindToNamespaceDict[fullKind], namespace)
@@ -146,17 +145,15 @@ def getResource(self, kind, name, namespace="", **kwargs) -> Union[dict, bool, s
146145
return createRequest(url=url, token=self.token, method="GET", keep_json=False, config=self.config,**kwargs)
147146

148147
def listResources(self, kind, namespace="", **kwargs) -> Union[dict, bool, str]:
149-
fullKind, error_str = self.checkAndReturnRealKind(kind, self.analyzer.KindToFullKindDict)
150-
if error_str:
151-
return None, error_str
148+
fullKind = self.analyzer.checkAndReturnRealKind(kind)
152149

153150
url = self.analyzer.FullKindToApiPrefixDict[fullKind] + "/"
154151
url += self.getNamespace(self.analyzer.FullKindToNamespaceDict[fullKind], namespace)
155152
url += self.analyzer.FullKindToNameDict[fullKind]
156153

157154
return createRequest(url=url, token=self.token, method="GET", keep_json=False, config=self.config,**kwargs)
158155

159-
def bindResource(self, pod, host, **kwargs) -> Union[dict, bool, str]:
156+
def bindResource(self, pod, host, **kwargs) -> Response:
160157
jsonObj = {}
161158
jsonObj["apiVersion"] = "v1"
162159
jsonObj["kind"] = "Binding"
@@ -187,10 +184,7 @@ def watchResource(self, kind, namespace, watcherhandler, name=None, thread_name=
187184
'''
188185
if is_daemon is True, when the main thread leave, this thead will leave automatically.
189186
'''
190-
fullKind, error_str = self.checkAndReturnRealKind(kind, self.analyzer.KindToFullKindDict)
191-
if error_str:
192-
print(error_str)
193-
return
187+
fullKind = self.analyzer.checkAndReturnRealKind(kind)
194188

195189
url = self.analyzer.FullKindToApiPrefixDict[fullKind] + "/watch/"
196190
url += self.getNamespace(self.analyzer.FullKindToNamespaceDict[fullKind], namespace)
@@ -218,14 +212,11 @@ def watchResources(self, kind, namespace, watcherhandler, thread_name=None, is_d
218212
isDaemon=is_daemon, **kwargs)
219213

220214
def watchResourceBase(self, kind, namespace, handlerFunction, name=None, thread_name=None, is_daemon=True,
221-
**kwargs) -> KubernetesWatcher:
215+
**kwargs) -> Union[KubernetesWatcher,Response]:
222216
'''
223217
if is_daemon is True, when the main thread leave, this thead will leave automatically.
224218
'''
225-
fullKind, error_str = self.checkAndReturnRealKind(kind, self.analyzer.KindToFullKindDict)
226-
if error_str:
227-
print(error_str)
228-
return
219+
fullKind = self.analyzer.checkAndReturnRealKind(kind)
229220

230221
url = self.analyzer.FullKindToApiPrefixDict[fullKind] + "/watch/"
231222
url += self.getNamespace(self.analyzer.FullKindToNamespaceDict[fullKind], namespace)
@@ -253,7 +244,7 @@ def watchResourcesBase(self, kind, namespace, handlerFunction, thread_name=None,
253244

254245
@staticmethod
255246
def watching(url, token, config, watchHandler, kwargs):
256-
response=doCreateRequest(url=formatURL(url, getParams(kwargs)), token=token, method="GET", config=config,stream=True)[0]
247+
response=doCreateRequest(url=formatURL(url, getParams(kwargs)), token=token, method="GET", config=config,stream=True)
257248
for json_bytes in response.iter_lines():
258249
if len(json_bytes) < 1:
259250
continue
@@ -297,7 +288,7 @@ def watchingBase(url, token, handlerFunction, kwargs):
297288

298289
del KubernetesClient.watcher_threads[threading.currentThread().getName()]
299290

300-
def updateResourceStatus(self, jsonStr, **kwargs) -> Union[dict, bool, str]:
291+
def updateResourceStatus(self, jsonStr, **kwargs) -> Response:
301292
jsonObj = jsonStr
302293
if type(jsonObj) is str:
303294
jsonObj = json.loads(jsonObj)
@@ -314,11 +305,8 @@ def updateResourceStatus(self, jsonStr, **kwargs) -> Union[dict, bool, str]:
314305

315306
return createRequest(url=url, token=self.token, method="PUT", body=jsonObj, keep_json=False,config=self.config, **kwargs)
316307

317-
def listResourcesWithLabelSelector(self, kind, namespace, labels) -> Union[dict, bool, str]:
318-
fullKind, error_str = self.checkAndReturnRealKind(kind, self.analyzer.KindToFullKindDict)
319-
if error_str:
320-
print(error_str)
321-
return
308+
def listResourcesWithLabelSelector(self, kind, namespace, labels) -> Response:
309+
fullKind = self.analyzer.checkAndReturnRealKind(kind)
322310

323311
url = self.analyzer.FullKindToApiPrefixDict[fullKind] + "/"
324312
url += self.getNamespace(self.analyzer.FullKindToNamespaceDict[fullKind], namespace)
@@ -329,11 +317,8 @@ def listResourcesWithLabelSelector(self, kind, namespace, labels) -> Union[dict,
329317
url = url[:len(url) - 1]
330318
return createRequest(url=url, token=self.token, method="GET", keep_json=False,config=self.config)
331319

332-
def listResourcesWithFieldSelector(self, kind, namespace, fields) -> Union[dict, bool, str]:
333-
fullKind, error_str = self.checkAndReturnRealKind(kind, self.analyzer.KindToFullKindDict)
334-
if error_str:
335-
print(error_str)
336-
return
320+
def listResourcesWithFieldSelector(self, kind, namespace, fields) -> Response:
321+
fullKind = self.analyzer.checkAndReturnRealKind(kind)
337322

338323
url = self.analyzer.FullKindToApiPrefixDict[fullKind] + "/"
339324
url += self.getNamespace(self.analyzer.FullKindToNamespaceDict[fullKind], namespace)

kubesys/exceptions.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
from requests.exceptions import HTTPError
2+
3+
class KindException(Exception):
4+
def __init__(self,*args,**kwargs):
5+
pass

kubesys/http_request.py

Lines changed: 11 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
"""
22
* Copyright (2021, ) Institute of Software, Chinese Academy of Sciences
33
"""
4-
from typing import Union
5-
from kubesys.common import formatURL, getParams
4+
from kubesys.common import formatURL, getParams,dictToJsonString
65
import requests
6+
from requests.models import HTTPError
7+
from requests.exceptions import JSONDecodeError
78
import json
89

910
__author__ = ('Tian Yu <[email protected]>',
@@ -14,50 +15,30 @@
1415

1516

1617
def createRequest(url, token, method="GET", body=None, verify=False,
17-
keep_json=False, config=None, **kwargs) -> Union[object, bool, str]:
18-
response, OK, status_code = doCreateRequest(
18+
keep_json=False, config=None, **kwargs):
19+
response = doCreateRequest(
1920
formatURL(url, getParams(kwargs)), token, method, body, config)
2021
try:
2122
result = response.json()
2223
if keep_json:
23-
result = json.dumps(result, indent=4, separators=(',', ': '))
24+
result=dictToJsonString(result)
25+
return result
26+
except JSONDecodeError:
27+
raise HTTPError(response.status_code,response.url+' '+response.reason)
2428

25-
return result, OK, status_code
26-
except:
27-
return response, OK, status_code
28-
29-
30-
def doCreateRequest(url, token, method="GET", body=None, config=None,stream=False) \
31-
-> Union[object, bool, str]:
29+
def doCreateRequest(url, token, method="GET", body=None, config=None,stream=False):
3230
if config is None:
3331
response = doCreateRequestWithToken(url, token, method,stream, body)
3432
else:
3533
response = doCreateRequestWithConfig(url, config, method,stream, body)
36-
37-
if 200 <= response.status_code <= 299:
38-
return response, True, response.status_code
39-
40-
else:
41-
return response, False, response.status_code
34+
return response
4235

4336

4437
def doCreateRequestWithToken(url, token, method,stream, body=None):
4538
header, data = getHeaderAndBody(token, body)
4639
return requests.request(method, url=url,
4740
headers=header, data=data, verify=False,stream=stream)
4841

49-
# if method_upper == "GET":
50-
# return requests.get(url=formatURL(url, getParams(kwargs)), headers=header, verify=False)
51-
# elif method_upper == "PUT":
52-
# return requests.put(url=formatURL(url, getParams(kwargs)), headers=header, data=data, verify=False)
53-
# elif method_upper == "DELETE":
54-
# return requests.delete(url=formatURL(url, getParams(kwargs)), headers=header, verify=False)
55-
# elif method_upper == "POST":
56-
# return requests.post(url=formatURL(url, getParams(kwargs)), headers=header, data=data, verify=False)
57-
# else:
58-
# print("unsupported HTTP request kind! Current method is", method_upper)
59-
# exit(-1)
60-
6142

6243
def doCreateRequestWithConfig(url, config, method, stream,body=None):
6344

0 commit comments

Comments
 (0)