async def ws_auth(self) -> Dict[Any, Any]: """ws private (user account balance request)""" listen_key = ( await self.rest_auth(CONSTANTS.USER_ID_PATH_URL) )["id"] # this is the getUserId from the github latoken api client library client: WSAssistant = await self.api_factory.get_ws_assistant() await client.connect(ws_url=web_utils.ws_url(self.domain), ping_timeout=CONSTANTS.WS_HEARTBEAT_TIME_INTERVAL) msg_out = stomper.Frame() msg_out.cmd = "CONNECT" msg_out.headers.update({"accept-version": "1.1", "heart-beat": "0,0"}) connect_request: WSRequest = WSRequest(payload=msg_out.pack(), is_auth_required=True) await client.send(connect_request) await client.receive() path_params = {'user': listen_key} msg_subscribe_account = stomper.subscribe( CONSTANTS.ACCOUNT_STREAM.format(**path_params), CONSTANTS.SUBSCRIPTION_ID_ACCOUNT, ack="auto") _ = await client.subscribe(request=WSRequest( payload=msg_subscribe_account)) response = [] async for ws_response in client.iter_messages(): msg_in = stomper.Frame() data = msg_in.unpack(ws_response.data.decode()) event_type = int(data['headers']['subscription'].split('_')[0]) if event_type == CONSTANTS.SUBSCRIPTION_ID_ACCOUNT: response.append(ujson.loads(data["body"])["payload"]) break await client.disconnect() return response[0]
def testFramepack1(self): """Testing pack, unpacking and the Frame class. """ # Check bad frame generation: frame = stomper.Frame() def bad(): frame.cmd = 'SOME UNNOWN CMD' self.assertRaises(stomper.FrameError, bad) # Generate a MESSAGE frame: frame = stomper.Frame() frame.cmd = 'MESSAGE' frame.headers['destination'] = '/queue/a' frame.headers['message-id'] = 'card_data' frame.body = "hello queue a" result = frame.pack() # print "\n-- result " + "----" * 10 # pprint.pprint(result) # print # Try bad message unpack catching: bad_frame = stomper.Frame() self.assertRaises(stomper.FrameError, bad_frame.unpack, None) self.assertRaises(stomper.FrameError, bad_frame.unpack, '') # Try to read the generated frame back in # and then check the variables are set up # correctly: frame2 = stomper.Frame() frame2.unpack(result) self.assertEquals(frame2.cmd, 'MESSAGE') self.assertEquals(frame2.headers['destination'], '/queue/a') self.assertEquals(frame2.headers['message-id'], 'card_data') self.assertEquals(frame2.body, 'hello queue a') result = frame2.pack() correct = "MESSAGE\ndestination:/queue/a\nmessage-id:card_data\n\nhello queue a\x00\n" # print "result: " # pprint.pprint(result) # print # print "correct: " # pprint.pprint(correct) # print # self.assertEquals(result, correct) result = stomper.unpack_frame(result) self.assertEquals(result['cmd'], 'MESSAGE') self.assertEquals(result['headers']['destination'], '/queue/a') self.assertEquals(result['headers']['message-id'], 'card_data') self.assertEquals(result['body'], 'hello queue a')
def send(self, routing_key, messages): """Convert a routing key and a list of messages into a STOMP frame.""" f = stomper.Frame() f.unpack(stomper.send(routing_key, simplejson.dumps(messages))) f.headers["exchange"] = "wavelet.direct" f.headers["content-type"] = "application/json" return f.pack().encode("utf-8")
def createMessage(self, cmd, headers, body): """ Creates a package STOMP message. """ frame = stomper.Frame() frame.setCmd(cmd) frame.headers = headers frame.body = body return frame.pack()
def connected(self, msg): """Once I've connected I want to subscribe to my the message queue. """ stomper.Engine.connected(self, msg) self.log.info("senderID:%s Connected: session %s." % ( self.senderID, msg['headers']['session']) ) # I originally called loopingCall(self.send) directly, however it turns # out that we had not fully subscribed. This meant we did not receive # out our first send message. I fixed this by using reactor.callLater # # def setup_looping_call(): lc = LoopingCall(self.send) lc.start(2) reactor.callLater(1, setup_looping_call) f = stomper.Frame() f.unpack(stomper.subscribe(DESTINATION)) # ActiveMQ specific headers: # # prevent the messages we send comming back to us. f.headers['activemq.noLocal'] = 'true' return f.pack()
def testEngineToServerMessages(self): """Test the state machines reaction """ e = TestEngine() # React to a message which should be an ack: msg = stomper.Frame() msg.cmd = 'MESSAGE' msg.headers = { 'subscription': 1, 'destination:': '/queue/a', 'message-id:': 'some-message-id', 'content-type': 'text/plain', } msg.body = "hello queue a" rc = e.react(msg.pack()) self.assertEquals(rc, 'ack') self.assertEquals(e.ackCalled, True) # React to an error: error = stomper.Frame() error.cmd = 'ERROR' error.headers = {'message:': 'malformed packet received!'} error.body = """The message: ----- MESSAGE destined:/queue/a Hello queue a! ----- Did not contain a destination header, which is required for message propagation. \x00 """ rc = e.react(error.pack()) self.assertEquals(rc, 'error') self.assertEquals(e.errorCalled, True) # React to an receipt: receipt = stomper.Frame() receipt.cmd = 'RECEIPT' receipt.headers = {'receipt-id:': 'message-12345'} rc = e.react(receipt.pack()) self.assertEquals(rc, 'receipt') self.assertEquals(e.receiptCalled, True)
def send_message(self, topic, message): f = stomper.Frame() f.unpack(stomper.send(topic, message)) if not self.proto: log.debug("Queueing stomp frame for later delivery") self._frames.append(f) else: self.proto.transport.write(f.pack())
def testFramepack2(self): """Testing pack, unpacking and the Frame class. """ # Check bad frame generation: frame = stomper.Frame() frame.cmd = 'DISCONNECT' result = frame.pack() correct = 'DISCONNECT\n\n\x00\n' self.assertEquals(result, correct)
def connected(self, msg): """Once I've connected I want to subscribe to my the message queue. """ super(MyStomp, self).connected(msg) self.log.info("connected: session %s" % msg['headers']['session']) f = stomper.Frame() f.unpack(stomper.subscribe(DESTINATION)) return f.pack()
def __init__(self, subject): self.subject = subject self.frame = stomper.Frame() self.frame.cmd = 'SEND' self.frame.body = self.name headers = {} headers['from'] = subject.descriptor.id headers['timestamp'] = str(time.time()) self.frame.headers = headers
def __init__(self, src, dst): """ @param invoker instance of the element (host, vm) receiving/sending the word. """ self._frame = stomper.Frame() self._frame.body = self.__name__ headers = {} headers['from'] = src headers['to'] = dst headers['timestamp'] = str(time.time()) self._frame.headers = headers self._frame.cmd = 'SEND'
def send(self): """Send out a hello message periodically. """ self.log.info("Saying hello (%d)." % self.counter) f = stomper.Frame() f.unpack(stomper.send(DESTINATION, 'hello there (%d)' % self.counter)) self.counter += 1 # ActiveMQ specific headers: # #f.headers['persistent'] = 'true' self.transport.write(f.pack())
def send(self): """Send out a hello message periodically. """ counter = self.counter.next() self.log.info("senderID:%s Saying hello (%d)." % (self.senderID, counter)) f = stomper.Frame() f.unpack(stomper.send(DESTINATION, '(%d) hello there from senderID:<%s>' % ( counter, self.senderID ))) # ActiveMQ specific headers: # #f.headers['persistent'] = 'true' self.transport.write(f.pack())
def on_open(ws, c=config): print('on_open:', 'Connection opened!') connDATA = c.getConf() """ stomp connect() lo interesante de marcar aqui son los parametos de conexion. Como podemos ver mandar fruta e igualmente se conecta. Funciona xq websockets ya tiene la conexion abierta. El connect del stomp es puramente formal """ msg = stomper.connect('DUMMY_USER', 'DUMMY_PW', 'DUMMY_HOST', (0,0)) print('stomp connect:', msg) ws.send(msg) f = stomper.Frame() f.unpack(stomper.subscribe(connDATA['endpoint']['bymaMD'], 'bymaMD', ack='auto')) fMsg = f.pack() ws.send(fMsg)
def connected(self, msg): """Once I've connected I want to subscribe to my the message queue. """ stomper.Engine.connected(self, msg) self.log.info("Connected: session %s. Begining say hello." % msg['headers']['session']) lc = LoopingCall(self.send) lc.start(1) f = stomper.Frame() f.unpack(stomper.subscribe(DESTINATION)) # ActiveMQ specific headers: # # prevent the messages we send comming back to us. f.headers['activemq.noLocal'] = 'true' return f.pack()
def connected(self, msg): """Once I've connected I want to subscribe to my the message queue(s).""" super(StompMessageProcessor, self).connected(msg) self.proto.factory.protocolConnected(self.proto) mqis = self.proto.service.messageQueueInfo() if not isinstance(mqis, list): mqis = [mqis] out = "" for mqi in mqis: f = stomper.Frame() f.unpack(stomper.subscribe(mqi["queue_name"])) f.headers["exchange"] = mqi["exchange"] f.headers["routing_key"] = mqi["routing_key"] f.headers["exchange_type"] = mqi["exchange_type"] out += f.pack() return out
def test_notifications(self): global token token = self.getToken() global service_token service_token = self.getServiceToken() global base_tenant_id base_tenant_id = self.getBaseTenantId() global roleIdMap roleIdMap = self.getRoleIdMap() seconds_since_epoch = datetime.now().timestamp() user_ids = [] usernames = [] for i in range(NO_OF_SUBSCRIBERS): # Create User username = self.mailosaur.servers.generate_email_address( MAILOSAUR_SERVER_NAME) user_id = self.createUser(username) print("created user-id: " + user_id) user_ids.append(user_id) usernames.append(username) # Create tenant tenant_id = self.createTenant(tenant_name, usernames) print("created tenant-id: " + tenant_id) # Create subscription self.createSubscription(SERVICE_NAME, tenant_id, user_ids) body = "This is Sample Event one sent - " + str(seconds_since_epoch) execptionRaised = False try: # Generate and send notification ws = create_connection( ws_url + '/audit/ws/audit-ingest', header={"Authorization": "Bearer " + service_token}, sslopt={"cert_reqs": ssl.CERT_NONE}) # Start thread to listen to audit logs auditLogWatcher = CommandWatch( cmd='kubectl -n rainier logs -f --tail 0 rainier-audit-0', countdown=NO_OF_NOTIFICATIONS * NO_OF_SUBSCRIBERS, end_pattern=".*(Email Sent Successfully for:).*", start_pattern= ".*(Size of notification queue is:)\s*\d+\s+(Size of event queue is:)\s*\d+" ) audit_run_task = auditLogWatcher.submit(TIMEOUT) print("Sending " + str(NO_OF_NOTIFICATIONS) + " notification, Body: " + body) msg = stomper.Frame() msg.cmd = 'SEND' msg.headers = { 'destination': '/events/post', 'content_type': 'application/json', 'receipt': 'new-receipt' } msg.body = json.dumps({ "tenant-id": tenant_id, "severity": "CRITICAL", "event-message": body, "event-name": SERVICE_NAME + "Asset", "time": int(round(time.time() * 1000)), "event-type": SERVICE_NAME + "down", "elementId": "oldvalue1", "neId": "newvalue1", "ne-kind": "userid6" }) for i in range(NO_OF_NOTIFICATIONS): ws.send(msg.pack()) ws.close() except Exception as err: print( "-----Exception while trying to send notification via websocket-----" ) print(err) print(traceback.print_exc()) print( "-------------------------------------------------------------------" ) execptionRaised = True exit(1) finally: if not execptionRaised: # Wait till all notifications are read from queue print("Checking audit logs .....") runtime = audit_run_task.result() print("Notifications processing time taken: " + str(runtime) + " s") # Delete subscription self.deleteSubscription(tenant_id) # Delete tenant self.deleteTenant(tenant_id) # Delete user self.deleteUser(user_ids) if validate: # Verify email notifications print("Waiting for emails to be sent .....") time.sleep(10) print("Done waiting") for user in usernames: # 2. Build search criteria to find the email you have sent print("Checking for user: "******"INFO Alert" criteria.sent_from = "*****@*****.**" criteria.body = body try: # 3. Wait for the message (by default only looks for messages received in the last hour) messages = self.mailosaur.messages.search( MAILOSAUR_SERVER_NAME, criteria) message_list = {} if len(messages.items) > 0: for message in messages.items: if message.id not in message_list: message_list[message.id] = message t_end = time.time() + 60 * 2 # wait for 2 mins i = 1 while time.time() < t_end and len( messages.items) < NO_OF_NOTIFICATIONS: time.sleep(10 * i) messages = self.mailosaur.messages.search( MAILOSAUR_SERVER_NAME, criteria) if len(messages.items) > 0: for message in messages.items: if message.id not in message_list: message_list[message.id] = message except MailosaurException as err: print(err.error_type) print(err.message) print("Response code: " + err.http_status_code + ", body: " + err.http_response_body) print(traceback.print_exc()) # 4. Assert that the email subject is what we expect self.assertEqual(NO_OF_NOTIFICATIONS, len(messages.items)) for key in message_list: message = self.mailosaur.messages.get_by_id(key) print("To: " + ",".join(str(p.email) for p in message.to)) print("Bcc: " + ",".join(str(p.email) for p in message.bcc)) print("Text Content: " + str(message.text.body)) print("HTML Content: " + str(message.html.body)) for message in messages.items: self.mailosaur.messages.delete(message.id)
def send(self, msg, mq): f = stomper.Frame() f.unpack(stomper.send(mq, msg)) self.counter += 1 self.transport.write(f.pack())
def makeBinaryMessage ( body = BINBODY, cmd = CMD ): msg = stomper.Frame() msg.cmd = cmd msg.headers = {'destination':DEST, 'content-length':len(body)} msg.body = body return msg.pack()
def makeTextMessage ( body = BODY, cmd = CMD ): msg = stomper.Frame() msg.cmd = cmd msg.headers = {'destination':DEST} msg.body = body return msg.pack()
def subscribe(self, dest, **headers): f = stomper.Frame() f.unpack(stomper.subscribe(dest)) f.headers.update(headers) self.transport.write(f.pack())
def sendFrame(self, cmd, headers, body): f = stomper.Frame() f.cmd = cmd f.headers.update(headers) f.body = body self.transport.write(f.pack())
print("response:\n%s\n" % pprint.pformat(response)) #>>> 'ACK\nmessage-id: some-message-id\n\n\x00\n' # We might want to send a message at some point. We could do this # in two ways # 1. using the the function for send() send_message = stomper.send(DESTINATION, 'hello there') print("1. send_message:\n%s\n" % pprint.pformat(send_message)) #>>> 'SEND\ndestination: /queue/inbox\n\nhello there\x00\n' # 2. using the frame class to add extra custom headers: msg = stomper.Frame() msg.cmd = 'SEND' msg.headers = {'destination':'/queue/a','custom-header':'1234'} msg.body = "hello queue a" print("2. send_message:\n%s\n" % pprint.pformat(msg.pack())) #>>> 'SEND\ncustom-header:1234\ndestination:/queue/a\n\nhello queue a\n\n\x00\n' # And thats pretty much it. There are other functions to send various # messages such as UNSUBSCRIBE, BEGIN, etc. Check out the stomper code # for further details. #
def suscribir(self, c=config): connDATA = c.getConf() f = stomper.Frame() f.unpack(stomper.subscribe(connDATA['endpoint']['bymaMD'], 'bymaMD', ack='auto')) return f.pack()