monkey/envs/monkey_zoo/blackbox/island_client/monkey_island_requests.py

112 lines
3.9 KiB
Python
Raw Normal View History

import functools
import logging
from datetime import timedelta
from typing import Dict
2019-09-13 21:12:58 +08:00
import requests
from envs.monkey_zoo.blackbox.island_client.supported_request_method import SupportedRequestMethod
2019-10-01 15:42:51 +08:00
# SHA3-512 of '1234567890!@#$%^&*()_nothing_up_my_sleeve_1234567890!@#$%^&*()'
2021-04-06 21:19:27 +08:00
NO_AUTH_CREDS = (
"55e97c9dcfd22b8079189ddaeea9bce8125887e3237b800c6176c9afa80d2062"
"8d2c8d0b1538d2208c1444ac66535b764a3d902b35e751df3faec1e477ed3557"
)
2019-10-01 21:11:53 +08:00
LOGGER = logging.getLogger(__name__)
2019-09-13 21:12:58 +08:00
2019-10-30 20:38:17 +08:00
# noinspection PyArgumentList
2019-09-13 21:12:58 +08:00
class MonkeyIslandRequests(object):
def __init__(self, server_address):
self.addr = "https://{IP}/".format(IP=server_address)
self.token = self.try_get_jwt_from_server()
2021-04-06 21:19:27 +08:00
self.supported_request_methods = {
SupportedRequestMethod.GET: self.get,
SupportedRequestMethod.POST: self.post,
SupportedRequestMethod.PATCH: self.patch,
SupportedRequestMethod.DELETE: self.delete,
}
def get_request_time(self, url, method: SupportedRequestMethod, data=None):
response = self.send_request_by_method(url, method, data)
if response.ok:
LOGGER.debug(f"Got ok for {url} content peek:\n{response.content[:120].strip()}")
return response.elapsed
else:
LOGGER.error(f"Trying to get {url} but got unexpected {str(response)}")
# instead of raising for status, mark failed responses as maxtime
return timedelta.max
def send_request_by_method(self, url, method=SupportedRequestMethod.GET, data=None):
if data:
return self.supported_request_methods[method](url, data)
else:
return self.supported_request_methods[method](url)
2019-09-13 21:12:58 +08:00
def try_get_jwt_from_server(self):
try:
return self.get_jwt_from_server()
except requests.ConnectionError as err:
LOGGER.error(
2021-04-06 21:19:27 +08:00
"Unable to connect to island, aborting! Error information: {}. Server: {}".format(
err, self.addr
)
)
2019-09-13 21:12:58 +08:00
assert False
2019-10-30 20:38:17 +08:00
class _Decorators:
@classmethod
def refresh_jwt_token(cls, request_function):
@functools.wraps(request_function)
2019-11-27 19:39:47 +08:00
def request_function_wrapper(self, *args, **kwargs):
2019-10-30 20:38:17 +08:00
self.token = self.try_get_jwt_from_server()
# noinspection PyArgumentList
return request_function(self, *args, **kwargs)
2019-11-27 19:39:47 +08:00
2019-10-30 20:38:17 +08:00
return request_function_wrapper
2019-09-13 21:12:58 +08:00
def get_jwt_from_server(self):
2021-04-06 21:19:27 +08:00
resp = requests.post(
self.addr + "api/auth", # noqa: DUO123
json={"username": NO_AUTH_CREDS, "password": NO_AUTH_CREDS},
verify=False,
)
2019-09-13 21:12:58 +08:00
return resp.json()["access_token"]
2019-10-30 20:38:17 +08:00
@_Decorators.refresh_jwt_token
2019-09-13 21:12:58 +08:00
def get(self, url, data=None):
2021-04-06 21:19:27 +08:00
return requests.get(
self.addr + url, # noqa: DUO123
headers=self.get_jwt_header(),
params=data,
verify=False,
)
2019-09-13 21:12:58 +08:00
2019-10-30 20:38:17 +08:00
@_Decorators.refresh_jwt_token
2019-09-13 21:12:58 +08:00
def post(self, url, data):
2021-04-06 21:19:27 +08:00
return requests.post(
self.addr + url, data=data, headers=self.get_jwt_header(), verify=False # noqa: DUO123
)
2019-09-13 21:12:58 +08:00
2019-10-30 20:38:17 +08:00
@_Decorators.refresh_jwt_token
def post_json(self, url, data: Dict):
2021-04-06 21:19:27 +08:00
return requests.post(
self.addr + url, json=data, headers=self.get_jwt_header(), verify=False # noqa: DUO123
)
@_Decorators.refresh_jwt_token
def patch(self, url, data: Dict):
2021-04-06 21:19:27 +08:00
return requests.patch(
self.addr + url, data=data, headers=self.get_jwt_header(), verify=False # noqa: DUO123
)
2019-09-13 21:12:58 +08:00
@_Decorators.refresh_jwt_token
def delete(self, url):
return requests.delete( # noqa: DOU123
2021-04-06 21:19:27 +08:00
self.addr + url, headers=self.get_jwt_header(), verify=False
)
2019-10-30 20:38:17 +08:00
@_Decorators.refresh_jwt_token
2019-09-13 21:12:58 +08:00
def get_jwt_header(self):
return {"Authorization": "Bearer " + self.token}