%PDF- %PDF-
Direktori : /opt/imunify360/venv/lib/python3.8/site-packages/defence360agent/api/server/ |
Current File : //opt/imunify360/venv/lib/python3.8/site-packages/defence360agent/api/server/__init__.py |
""" This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. Copyright © 2019 Cloud Linux Software Inc. This software is also available under ImunifyAV commercial license, see <https://www.imunify360.com/legal/eula> """ import json import socket import urllib.request import urllib.error import logging from defence360agent.contracts.config import Core logger = logging.getLogger(__name__) class APIError(Exception): def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) if len(args) >= 2: _, status_code, *args = args self.status_code = status_code else: self.status_code = None class API: _BASE_URL = Core.API_BASE_URL _SOCKET_TIMEOUT = 300 @staticmethod def request(request: urllib.request.Request, json_loads=True): try: with urllib.request.urlopen( request, # agent should be able to wait for a while # in lb queue before being connected timeout=API._SOCKET_TIMEOUT, ) as response: logger.info('Performed request for url=%s method=%s body=%s ' 'status=%s', request.full_url, getattr(request, 'method', None), request.data, response.status) if response.status != 200: raise APIError( 'status code is {}'.format(response.status), response.status) plain_response = response.read() logger.info('Response=%s ...', plain_response[:50]) if json_loads: result = json.loads(plain_response.decode()) else: result = plain_response return result except (UnicodeDecodeError, json.JSONDecodeError, urllib.error.URLError, socket.timeout) as e: status_code = getattr(e, "code", None) raise APIError( 'request failed, reason: %s' % (e,), status_code ) from e