-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathwls_rest_python.py
More file actions
434 lines (347 loc) · 13.4 KB
/
wls_rest_python.py
File metadata and controls
434 lines (347 loc) · 13.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
"""
A Python client for the Weblogic Server REST API.
https://github.com/magnuswatn/wls-rest-python
"""
import logging
import requests
__version__ = "0.1.5"
logger = logging.getLogger(__name__)
# This is quite high, as the WLS server will, by default,
# do operations that take "approximately 5 minutes" synchronous.
DEFAULT_TIMEOUT = 305
class WLSException(Exception):
"""Superclass for exceptions thrown by this module"""
class BadRequestException(WLSException):
"""
A REST method returns 400 (BAD REQUEST) if the request failed because
something is wrong in the specified request, for example, invalid argument values.
"""
class UnauthorizedException(WLSException):
"""
A REST method returns 401 (UNAUTHORIZED) if the user does not have permission
to perform the operation. 401 is also returned if the user supplied incorrect
credentials (for example, a bad password).
"""
class ForbiddenException(WLSException):
"""
A REST method returns 403 (FORBIDDEN) if the user is not in the ADMIN,
OPERATOR, DEPLOYER or MONITOR role.
"""
class NotFoundException(WLSException):
"""
A REST method returns 404 (NOT FOUND) if the requested URL does not refer to an
existing entity.
"""
class MethodNotAllowedException(WLSException):
"""
A REST method returns 405 (METHOD NOT ALLOWED) if the resource exists but
does not support the HTTP method, for example, if the user tries to create a server by
using a resource in the domain configuration tree (only the edit tree allows
configuration editing).
"""
class NotAcceptableException(WLSException):
"""
The resource identified by this request is not capable of generating a representation
corresponding to one of the media types in the Accept header of the request. For
example, the client's Accept header asks for XML but the resource can only return
JSON.
"""
class ServerErrorException(WLSException):
"""
A REST method returns 500 (INTERNAL SERVER ERROR) if an error occurred that
is not caused by something wrong in the request. Since the REST layer generally
treats exceptions thrown by the MBeans as BAD REQUEST, 500 is generally used for
reporting unexpected exceptions that occur in the REST layer. These responses do not
include the text of the error or a stack trace, however, generally they are logged in the
server log.
"""
class ServiceUnavailableException(WLSException):
"""
The server is currently unable to handle the request due to temporary overloading or
maintenance of the server. The WLS REST web application is not currently running.
"""
class WLS(object):
"""
Represents a WLS REST server
:param string host: protocol://hostname:port of the server.
:param string username: Username used to authenticate against the server
:param string password: Password used to authenticate against the server
:param string version: Version of the rest interface to use. Defaults to "latest"
:param bool verify: Whether to verify certificates on SSL connections.
:param float timeout: The timeout value to use, in seconds. Default is 305.
"""
def __init__(
self,
host,
username,
password,
version="latest",
verify=True,
timeout=DEFAULT_TIMEOUT,
):
self.session = requests.Session()
self.session.verify = verify
self.session.auth = (username, password)
user_agent = "wls-rest-python {} ({})".format(
__version__, self.session.headers["User-Agent"]
)
self.session.headers.update(
{
"Accept": "application/json",
"User-Agent": user_agent,
"X-Requested-By": user_agent,
}
)
self.timeout = timeout
self.base_url = "{}/management/weblogic/{}".format(host, version)
collection = self.get(self.base_url)
self.version = collection["version"]
self.isLatest = collection["isLatest"]
self.lifecycle = collection["lifecycle"]
for link in collection["links"]:
link_obj = WLSObject(link["rel"], link["href"], self)
setattr(self, link["rel"], link_obj)
def __repr__(self):
return "<WLS url='{}' username='{}' version='{}'>".format(
self.base_url, self.session.auth[0], self.version
)
def get(self, url, **kwargs):
"""
Does a GET request to the specified URL.
Returns the decoded JSON.
"""
response = self.session.get(url, timeout=self.timeout, **kwargs)
return self._handle_response(response)
def post(self, url, prefer_async=False, **kwargs):
"""
Does a POST request to the specified URL.
If the response is a job or an collection, it will return an
WLSObject. Otherwise it will return the decoded JSON
"""
headers = {"Prefer": "respond-async"} if prefer_async else None
response = self.session.post(
url, headers=headers, timeout=self.timeout, **kwargs
)
return self._handle_response(response)
def delete(self, url, prefer_async=False, **kwargs):
"""
Does a DELETE request to the specified URL.
If the response is a job or an collection, it will return an
WLSObject. Otherwise it will return the decoded JSON
"""
headers = {"Prefer": "respond-async"} if prefer_async else None
response = self.session.delete(
url, headers=headers, timeout=self.timeout, **kwargs
)
return self._handle_response(response)
def _handle_response(self, response):
logger.debug(
"Sent %s request to %s, with headers:\n%s\n\nand body:\n%s",
response.request.method,
response.request.url,
"\n".join(
["{0}: {1}".format(k, v) for k, v in response.request.headers.items()]
),
response.request.body,
)
logger.debug(
"Recieved response:\nHTTP %s\n%s\n\n%s",
response.status_code,
"\n".join(["{0}: {1}".format(k, v) for k, v in response.headers.items()]),
response.content.decode(),
)
if not response.ok:
self._handle_error(response)
# GET is used by the WLSObject to retrieve the collection
# so it must return only the decoded JSON, not an WLSobject
if response.request.method == "GET":
return response.json()
response_json = response.json()
if not response_json:
return None
try:
link = next(
(
x["href"]
for x in response_json["links"]
if x["rel"] in ("self", "job")
)
)
name = response_json["name"]
except (KeyError, StopIteration):
# Not a job, and not a collection.
# Don't know what it is, so just return the decoded json
return response_json
return WLSObject(name, link, self)
@staticmethod
def _handle_error(response):
exception_type = WLSException
exception_message = "An unknown error occured."
if response.status_code == 400:
exception_type = BadRequestException
elif response.status_code == 401:
# does not return json
raise UnauthorizedException()
elif response.status_code == 403:
exception_type = ForbiddenException
elif response.status_code == 404:
exception_type = NotFoundException
elif response.status_code == 405:
exception_type = MethodNotAllowedException
elif response.status_code == 406:
exception_type = NotAcceptableException
elif response.status_code == 500:
exception_type = ServerErrorException
elif response.status_code == 503:
exception_type = ServiceUnavailableException
try:
exception_message = response.json()["detail"]
except KeyError:
exception_message = response.json()
except ValueError:
exception_message = response.text
raise exception_type(exception_message)
class WLSObject(object):
"""
Represents all the different WLS objects.
The attributes will differ based on the
collection used to instantiate it
"""
def __init__(self, name, url, wls):
self._name = name
self._url = url
self._wls = wls
def __dir__(self):
attrs = []
collection = self._wls.get(self._url)
for key in collection:
item = collection[key]
if key == "links":
for link in item:
if link["rel"] == "action":
name = link["title"]
else:
name = link["rel"]
attrs.append(name)
elif key == "items":
for itm in item:
attrs.append(itm["name"])
else:
attrs.append(key)
return attrs
def __getattr__(self, attr):
"""
Retrieves the properties dynamically from the collection
We store actions and links for re-use, since they are expected not to change
"""
collection = self._wls.get(self._url)
for key in collection:
item = collection[key]
if key == "links":
for link in item:
if link["rel"] == "action":
name = link["title"]
if name == attr:
obj = WLSAction(name, link["href"], self._wls)
setattr(self, name, obj)
return obj
else:
name = link["rel"]
if name == attr:
obj = WLSObject(name, link["href"], self._wls)
setattr(self, name, obj)
return obj
elif key == "items":
for itm in item:
if itm["name"] == attr:
self_link = next(
(x["href"] for x in itm["links"] if x["rel"] == "self")
)
return WLSObject(itm["name"], self_link, self._wls)
else:
if key == attr:
return item
raise AttributeError(
"'{}' object has no attribute '{}'".format(self._name, attr)
)
def __getitem__(self, key):
# this is here for items with weird names
# e.g. webapps with version number (myWebapp#1.2.3)
try:
return self.__getattr__(key)
except AttributeError:
pass
raise KeyError(key)
def __iter__(self):
collection = self._wls.get(self._url)
is_iterable = False
iter_items = []
for key in collection:
item = collection[key]
if key == "items":
is_iterable = True
for itm in item:
self_link = next(
(x["href"] for x in itm["links"] if x["rel"] == "self")
)
iter_items.append(WLSObject(itm["name"], self_link, self._wls))
if is_iterable:
return WLSItems(iter_items)
raise TypeError("'{}' object is not iterable".format(self._name))
def __len__(self):
try:
return len(self.__iter__().items)
except TypeError:
pass
raise TypeError("object of type '{}' has no len()".format(self._name))
def __repr__(self):
return "<WLSObject name='{}' url='{}'>".format(self._name, self._url)
def delete(self, prefer_async=False, **kwargs):
"""
Deletes the resource. Will result in an DELETE request to the self url
The kwargs are sendt through to requests
"""
return self._wls.delete(self._url, prefer_async, **kwargs)
def create(self, prefer_async=False, **kwargs):
"""
Creates a resource. Will result in an POST request to the self url
The kwargs are sendt through to requests
"""
return self._wls.post(self._url, prefer_async, **kwargs)
def update(self, prefer_async=False, **kwargs):
"""
Updates an property of the resource.
The kwargs will be sent as json
"""
return self._wls.post(self._url, prefer_async, json=kwargs)
class WLSItems(object):
"""
Items from an object.
Used as an iterator
"""
def __init__(self, items):
self.items = items
self.counter = 0
def __next__(self):
try:
item = self.items[self.counter]
except IndexError:
raise StopIteration
self.counter += 1
return item
def next(self):
# python 2
return self.__next__()
class WLSAction(object):
"""
An action from a collection.
Identified by a link with rel=action.
"""
def __init__(self, name, url, wls):
self._url = url
self._name = name
self._wls = wls
def __repr__(self):
return "<WLSAction name='{}' url='{}'>".format(self._name, self._url)
def __call__(self, prefer_async=False, **kwargs):
return self._wls.post(self._url, prefer_async, json=kwargs if kwargs else {})