def post(self): # arguments = { k.lower(): self.get_argument(k) for k in self.request.arguments } first_name = self.get_argument("name", "") last_name = self.get_argument("lastname", "") email = self.get_argument("email", "") subject = self.get_argument("subject", "") message = self.get_argument("question", "") topic = self.get_argument("topic", "") topics = topic.replace(',', '\n') log.debug( f'''{first_name}, {last_name}, {email}, {topics}, {message}''') try: token = DB.add_new_request({ 'email': email, 'last_name': last_name, 'first_name': first_name, 'subject': subject, 'message': message, 'topics': topics, }) except Exception as e: log.error(f'''Error adding form record: {e}''') self.write( 'There was an error submitting your form. Please try again.') self.set_status(500) self.flush() self.finish() return try: if token: send_confirmation_email( base_url=BASE_URL, token=token, email=email, last_name=last_name, first_name=first_name, subject=subject, message=message, topics=topics, ) self.set_status(200) self.flush() self.finish() return else: self.write( 'There was an error submitting your form. Please try again.' ) self.set_status(500) self.flush() self.finish() return except Exception as e: log.error(f'''Error sending confirmation email to "{email}"''') self.write( 'There was an error submitting your form. Please try again.') self.set_status(500) self.flush() self.finish() return
def on_message(self, message): data = json.loads(message) for command, args in data.iteritems(): if command in self.command: log.debug("Command executed: %s(%s)" % (command, args)) self.command[command](args) else: log.error("Command % s not found" % command)
def handle_beacon(self, fd, event): """ Reads response from nodes Creates :class:`Peer` objects and tracks them in `self.peers`. Finally sends messages through pipe to main application thread. :param fd: not used :param event: not used """ log.debug("Waiting for a beacon.") try: data, host = self._next_packet() except ReceiveTimeout: msg_parts = [b"RECEIVE_TIMEOUT"] try: self._send_to_pipe_multipart(msg_parts) except Exception: return return if data == PING_MESSAGE: log.debug("Ignoring ping message received from network from %s.", host) return log.debug("Received a beacon from %s.", host) ip_address, device_id = decode_discovery_response(data) # if host != ip_address: # print("Host {} != ip_address {}".format(host, ip_address)) log.debug("Getting hardware address of %s.", ip_address) hw_address = arpreq(ip_address) if is_py3 and not isinstance(hw_address, bytes): hw_address = bytes(hw_address, "utf-8") if hw_address is None: log.error("Unable to get HW adress of %s.", ip_address) msg_parts = [b"ERROR", device_id, ip_address] try: self._send_to_pipe_multipart(msg_parts) except Exception: return # print("Host {} has MAC address {}".format(ip_address, hw_address)) if hw_address in self.peers: log.debug("Peer %s seen before.", hw_address) return self.process_seen_peer(hw_address, device_id, ip_address) else: log.debug("Never seen %s before.", hw_address) return self.process_new_peer(hw_address, device_id, ip_address)
def _send_to_pipe_multipart(self, msg_parts): """ Handle errors while sending message to pipe as ERROR message sent to pipe Caller should catch use these messages to stop interface thread and thus agent as well. :param iterable msg_parts: A sequence of objects to send as a multipart message. :raises TypeError: after error is caught and ERROR message sent to pipe """ log.debug("Going to send %r.", msg_parts) try: self.pipe.send_multipart(msg_parts) except TypeError as err: log.error("Failed to send multipart message to pipe: %s", err) self.pipe.send_multipart( [b"ERROR", b"Failed to send a message to main thread."] ) self.stop() raise
def get_mac_address(self, ip_address): """ Gets the MAC address of the device at ip_address. :param ip_address: The IP address or hostname to the device :return: The MAC address, or None in case of failure """ ip = ip_address.decode("utf-8") base_url = "http://{}/xled/v1/gestalt".format(ip) r = requests.get(base_url) if r.status_code != 200: log.error( "Failure getting MAC address from device at {}. Not a Twinkly?".format( ip ) ) return None try: hw_address = r.json().get("mac").encode("utf-8") return hw_address except Exception: return None
def get(self): global clientsList uuid = self.get_argument("uuid") client = self.get_argument("network") # Find graph network = clientsList.find(client).network # Find packet packet = [p for l in network.links for p in l.packet_list() if p.uuid == uuid] if len(packet) == 0: packet = [p for n in network.nodes for p in n.packet_list() if p.uuid == uuid] if len(packet) == 0: log.error("Packet not found") self.set_status(204) return p = packet[0] # Render packet template_name, template_args = p.template() if not template_name: self.set_status(204) return path_template = "packet/" + template_name if not os.path.isfile(os.path.join("www", path_template)): path_template = "../" + custom.dir + path_template self.render(path_template, **template_args)
def get(self, token=None): if not token: self.set_status(400) self.write('A token is required.') self.flush() self.finish() return request_data = DB.get_request_data(token) if not request_data: log.info(f'''Invalid token: {token}''') self.render('invalid_token.html', rootPath=r'{}/'.format(Settings.APP_ROOT)) else: token = request_data[0][0] email = request_data[0][1] last_name = request_data[0][2] first_name = request_data[0][3] subject = request_data[0][4] message = request_data[0][5] topics = request_data[0][6] received = request_data[0][7] if received == 1: self.render('already_received.html', rootPath=r'{}/'.format(Settings.APP_ROOT)) return if subject.lower() == 'testing': log.info( 'TESTING. Skipping Jira ticket creation and DESDM team email.' ) DB.mark_received(token) self.set_status(200) self.render('submission_confirmed.html', rootPath=r'{}/'.format(Settings.APP_ROOT)) return try: jira_ticket.create_ticket( first_name, last_name, email, topics, subject, message, ) except Exception as e: log.error(f'''Error creating Jira ticket: {e}''') self.write( '<p>There was an error confirming your form. Please try again.</p><pre>{e}</pre>' ) self.set_status(500) self.flush() self.finish() return try: assert DB.mark_received(token) except Exception as e: log.error(f'''Error deleting request record: {e}''') self.set_status(200) self.flush() self.finish() return self.set_status(200) self.render('submission_confirmed.html', rootPath=r'{}/'.format(Settings.APP_ROOT))
def get(self, path): global user_sessions global connection_factory global server_address log = logging.getLogger(__name__) cookie_user_id = None session = None try: cookie_user_id = int( self.get_secure_cookie(COOKIE_NAME, max_age_days=COOKIE_DURATION_DAYS)) except ValueError: pass except TypeError: pass if cookie_user_id is not None: session = user_sessions.find_session(cookie_user_id) if session is not None: connection = session.create_connection() rsp = connection.allocate_authentication_token() connection.disconnect() if rsp.is_error(): log.error( 'Failed to allocate login token for user "{}", code: {}'. format( session.username(), rsp.error_code(), )) raise RuntimeError() auth_token = rsp.as_allocate_auth_token_response().token log.info( 'Existing session found authentication token allocated, username="******"' .format(session.username())) if len(path) > 1: path = zyn_util.util.normalized_remote_path('/' + path) path_parent, name = zyn_util.util.split_remote_path(path) else: path_parent, name = ('/', '') log.info('get, path_parent="{}", name="{}"'.format( path_parent, name, )) self.render( "main.html", zyn_user_id=str(cookie_user_id), root_url=self.HANDLER_URL, path_parent=path_parent, name=name, authentication_token=auth_token, server_address=server_address, ) else: log.info('Unauthenticated user') self.render("login.html")
def xdiscover(find_id=None, destination_host=None, timeout=None): """Generator discover all devices or device of specific id Device can be specified either by id or by host. :param str find_id: (optional) Device id to look for. If not set first node that responded is returned. :param str destination_host: (optional) Ping selected node only. :param float timeout: (optional) Number of seconds until discovery timeouts. :return: namedtuple of hardware address, device id and host name. :rtype: namedtuple :raises DiscoverTimeout: timeout exceeded while waiting for a device """ assert not (find_id and destination_host) receive_timeout = None if timeout: receive_timeout = timeout / 2 hw_address = device_id = ip_address = None start = monotonic() with DiscoveryInterface( destination_host, receive_timeout=receive_timeout ) as interface: while True: try: response = interface.recv() except KeyboardInterrupt: raise assert len(response) > 0 event = response.pop(0) if event == b"JOINED": assert len(response) == 3 hw_address, device_id, ip_address = response if isinstance(hw_address, bytes): hw_address = hw_address.decode("utf-8") if isinstance(device_id, bytes): device_id = device_id.decode("utf-8") if isinstance(ip_address, bytes): ip_address = ip_address.decode("utf-8") if find_id is None or find_id == device_id: DiscoveredDevice = collections.namedtuple( "DiscoveredDevice", ["hw_address", "id", "ip_address"] ) yield DiscoveredDevice(hw_address, device_id, ip_address) if find_id == device_id: return else: log.debug( "Device id {} ({}) joined: {}".format( device_id, hw_address, ip_address ) ) if timeout and (monotonic() - start) > timeout: raise DiscoverTimeout() elif event == b"ERROR": log.error( "Received error from discovery. Parameters: {}".format(response) ) raise Exception("Error") elif event == b"RECEIVE_TIMEOUT": assert timeout if monotonic() - start > timeout: raise DiscoverTimeout() else: continue elif event == b"ALIVE": if timeout and (monotonic() - start) > timeout: raise DiscoverTimeout() else: log.error("Unknown event: {}".format(event)) log.error("Parameters: {}".format(response)) raise Exception("Unknown event")
async def send_event(self, obj): try: await self.write_message(json.dumps(obj)) except tornado.websocket.WebSocketClosedError as e: log.error('Closed socket, unexpected... %s', e) self.on_close()
def handle_beacon(self, fd, event): """ Reads response from nodes Creates :class:`Peer` objects and tracks them in `self.peers`. Finally sends messages through pipe to main application thread. :param fd: not used :param event: not used """ log.debug("Waiting for a beacon.") data, host = self.udp.recv(64) if data == PING_MESSAGE: log.debug("Ignoring ping message received from network from %s.", host) return log.debug("Received a beacon from %s.", host) ip_address, device_name = decode_discovery_response(data) # if host != ip_address: # print("Host {} != ip_address {}".format(host, ip_address)) log.debug("Getting hardware address of %s.", ip_address) hw_address = arpreq(ip_address) if is_py3 and not isinstance(hw_address, bytes): hw_address = bytes(hw_address, "utf-8") if hw_address is None: log.error("Unable to get HW adress of %s.", ip_address) msg_parts = [b"ERROR", device_name, ip_address] try: self._send_to_pipe_multipart(msg_parts) except Exception: return # print("Host {} has MAC address {}".format(ip_address, hw_address)) if hw_address in self.peers: log.debug("Peer %s seen before.", hw_address) self.peers[hw_address].is_alive() if device_name != self.peers[hw_address].device_name: old_device_name = self.peers[hw_address].device_name self.peers[hw_address].device_name = device_name msg_parts = [ b"RENAMED", hw_address, old_device_name, device_name ] try: self._send_to_pipe_multipart(msg_parts) except Exception: return if ip_address != self.peers[hw_address].ip_address: old_ip_address = self.peers[hw_address].ip_address self.peers[hw_address].ip_address = ip_address msg_parts = [ b"ADDRESS_CHANGED", hw_address, old_ip_address, ip_address ] try: self._send_to_pipe_multipart(msg_parts) except Exception: return else: log.debug("Never seen %s before.", hw_address) self.peers[hw_address] = Peer(hw_address, device_name, ip_address) msg_parts = [b"JOINED", hw_address, device_name, ip_address] try: self._send_to_pipe_multipart(msg_parts) except Exception: return