%PDF- %PDF-
Direktori : /opt/imunify360/venv/lib64/python3.8/site-packages/defence360agent/api/server/ |
Current File : //opt/imunify360/venv/lib64/python3.8/site-packages/defence360agent/api/server/send_message.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 asyncio import json import socket import urllib.error import urllib.request from abc import ABC, abstractmethod from logging import getLogger from typing import Optional from defence360agent.contracts.config import Core from defence360agent.contracts.messages import Message from defence360agent.internals.iaid import IndependentAgentIDAPI from defence360agent.utils.json import ServerJSONEncoder from defence360agent.api.server import API, APIError logger = getLogger(__name__) class BaseSendMessageAPI(API, ABC): URL = "/api/v2/send-message/{method}" @abstractmethod async def _send_request(self, message_method, headers, post_data) -> dict: pass # pragma: no cover def check_response(self, result: dict) -> None: if 'status' not in result: raise APIError( 'unexpected server response: {!r}'.format(result) ) if result['status'] != 'ok': raise APIError( 'server error: {}'.format(result.get('msg')) ) async def send_data(self, method: str, post_data: bytes) -> None: if IndependentAgentIDAPI.is_token_expired(): await IndependentAgentIDAPI.login() headers = { "Content-Type": "application/json", "X-Auth": IndependentAgentIDAPI.get_token() } result = await self._send_request(method, headers, post_data) self.check_response(result) class SendMessageAPI(BaseSendMessageAPI): def __init__(self, rpm_ver: str, base_url: str = None, executor=None): self._executor = executor self.rpm_ver = rpm_ver self.product_name = '' self.server_id = None # type: Optional[str] self.license = {} # type: dict if base_url: self.base_url = base_url else: self.base_url = self._BASE_URL def set_product_name(self, product_name: str) -> None: self.product_name = product_name def set_server_id(self, server_id: Optional[str]) -> None: self.server_id = server_id def set_license(self, license: dict) -> None: self.license = license async def _send_request(self, message_method, headers, post_data): request = urllib.request.Request( self.base_url + self.URL.format(method=message_method), data=post_data, headers=headers, method='POST' ) loop = asyncio.get_event_loop() return await loop.run_in_executor(self._executor, _do_request, request) async def send_message(self, message: Message) -> None: data2send = { 'payload': message.payload, 'rpm_ver': self.rpm_ver, 'message_id': message.message_id, 'server_id': self.server_id, 'name': self.product_name, } post_data = json.dumps(data2send, cls=ServerJSONEncoder).encode() await self.send_data(message.method, post_data) def _do_request(request: urllib.request.Request) -> None: try: with urllib.request.urlopen( request, timeout=Core.DEFAULT_SOCKET_TIMEOUT ) as response: if response.status != 200: raise APIError('status code is {}'.format(response.status)) return json.loads(response.read().decode()) except ( UnicodeDecodeError, json.JSONDecodeError, urllib.error.URLError, socket.timeout, ) as e: raise APIError(f"request failed {e}") from e