def disconnect_from_nifty_channel(message): Group('nifty-channel').discard(message.reply_channel)
def onDestroy(self, message_value, topology_id, client_id): Group("workers").send({"text": json.dumps(["Destroy", topology_id])})
def onFacts(self, message, topology_id): send_updates = False print message['key'] name = message['key'] device, created = Device.objects.get_or_create(topology_id=topology_id, name=name, defaults=dict(x=0, y=0, type="switch", id=0)) if created: device.id = device.pk device.save() send_updates = True print "Created device ", device interfaces = dpath.util.get(message, '/value/ansible_local/lldp/lldp') or [] for interface in interfaces: pprint(interface) for inner_interface in interface.get('interface', []): name = inner_interface.get('name') if not name: continue interface, created = Interface.objects.get_or_create(device_id=device.pk, name=name, defaults=dict(id=0)) if created: interface.id = interface.pk interface.save() send_updates = True print "Created interface ", interface connected_interface = None connected_device = None for chassis in inner_interface.get('chassis', []): name = chassis.get('name', [{}])[0].get('value') if not name: continue connected_device, created = Device.objects.get_or_create(topology_id=topology_id, name=name, defaults=dict(x=0, y=0, type="switch", id=0)) if created: connected_device.id = connected_device.pk connected_device.save() send_updates = True print "Created device ", connected_device break if connected_device: for port in inner_interface.get('port', []): for port_id in port.get('id', []): if port_id['type'] == 'ifname': name = port_id['value'] break connected_interface, created = Interface.objects.get_or_create(device_id=connected_device.pk, name=name, defaults=dict(id=0)) if created: connected_interface.id = connected_interface.pk connected_interface.save() print "Created interface ", connected_interface send_updates = True if connected_device and connected_interface: exists = Link.objects.filter(Q(from_device_id=device.pk, to_device_id=connected_device.pk, from_interface_id=interface.pk, to_interface_id=connected_interface.pk) | Q(from_device_id=connected_device.pk, to_device_id=device.pk, from_interface_id=connected_interface.pk, to_interface_id=interface.pk)).count() > 0 if not exists: link = Link(from_device_id=device.pk, to_device_id=connected_device.pk, from_interface_id=interface.pk, to_interface_id=connected_interface.pk, id=0) link.save() link.id = link.pk link.save() print "Created link ", link send_updates = True if send_updates: send_snapshot(Group("topology-%s" % topology_id), topology_id)
def ws_disconnect(message): label = message.channel_session['room'] Group('chat' + label).discard(message.reply_channel)
def ws_disconnect(message, group_pk): Group("id-%s" % group_pk).discard(message.reply_channel)
def ws_message(message): # TODO if more than one Session not feasible global SessChain global fileList from .Block.IO_Block import IO_Block if SessChain == "init" or SessChain is None: print("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA") print(type(SessChain)) print("loading from cache for message") oldT = time.time() SessChain = cache.get("alexa", "doesn't exist") if SessChain == "doesn't exist": SessChain = BlockChain(name="alexa", session="alexa") print("\033[93m made a new session \033[0m") print("done after: ", (time.time() - oldT), "seconds") print(type(SessChain)) print("Session:", SessChain) data = json.loads(message.content['text']) # print("JSON: ", data, "DATA: ", message.content['text']) if data['type'] == "msg" : block = MessageBlock(name="[user] ", session="alexa", msg=data['msg']) # add to Chain SessChain.addBlock(block) # send to group Group("alexa").send({ "text": block.GetNode() }) print("\033[95m BLOCK \033[0m", block) elif data["type"] == "histogram": block = HistogramBlock(name="Histogram", session="alexa") # add to Chain SessChain.addBlock(block) Group("alexa").send({ "text": block.GetNode() }) elif data['type'] == "cmd" : if data['cmd'] == "reset": SessChain.delBlocksAll() data = {"type": "cmd", "cmd": "reset"} Group("alexa").send({ "text": json.dumps(data) }) elif data['cmd'] == "init": print("init config ordered") # artificial sleep to show off loading # time.sleep(1) # serve BlockChain Contents to client if SessChain.getBlockListLength() != 0: for block in SessChain.getBlockList(): message.reply_channel.send({ "text": block.GetNode() }) else: data = {"type": "cmd", "cmd": "init_done"} message.reply_channel.send({ "text": json.dumps(data) }) # send import list data = {"type": "cmd", "cmd": "file_list", "files": fileList} message.reply_channel.send({ "text": json.dumps(data) }) elif data['cmd'] == "img": print("img ordered") block = ImageBlock(name="test.jpg", session="alexa", img_path="/home/alexa_server/Alexa_Server/import/test.jpg") # add to Chain SessChain.addBlock(block) # send to group Group("alexa").send({ "text": block.GetNode() }) print("\033[95m BLOCK \033[0m", block) elif data['cmd'] == "alexa": print("alexa called") elif data['cmd'] == "click": print("\033[95m CLICK \033[0m") print(data['num'], data['opt']) if "show" in str(data['opt']): SessChain.getBlock(data['num']).showBlock(data['num']) elif data['opt'] == 'execute': SessChain.getBlock(data['num']).executeBlock(data['num']) elif "del" in str(data['opt']): print("deleting:", data['num']) SessChain.delBlockByIndex(data['num']) data = {"type": "cmd", "cmd": "del_block", "block_num": data['num']} Group("alexa").send({ "text": json.dumps(data) }) elif data['cmd'] == "load": IO = IO_Block(file_name=data['file'], session="alexa") print("NEW IO BLOCK") SessChain.addBlock(IO) print("IO added") Group("alexa").send({ "text": IO.GetNode() }) elif data['cmd'] == "minimize": data = {"type": "cmd", "cmd": "minimize", } Group("alexa").send({ "text": json.dumps(data) }) # needs active alexa session # TODO derive better system to add functions here automatically #if data['opt'] == 'read': # msg = SessChain.getBlock(data['num']).readBlock(data['num']) # "autosave" SessChain.Chain_pickle()
def get_litcoin_price(): data = get_coin_price('LTC') Group('ltc-price').send({'text': data})
def disconnect_from_graph_channel(message): Group('NIFTY-50').discard(message.reply_channel)
def graphDataPush(): graphData = graph('NIFTY 50') Group('NIFTY-50').send({ 'text': json.dumps(graphData, cls=DjangoJSONEncoder), })
def leaderboardChannelDataPush(): leaderboard_data = leaderboardData() Group('leaderboard-channel').send( {'text': json.dumps(leaderboard_data, cls=DjangoJSONEncoder)})
def connect_to_graph_channel(message): Group('NIFTY-50').add(message.reply_channel) print 'New graph listener!'
def disconnect_from_leaderboard_channel(message): Group('leaderboard-channel').discard(message.reply_channel)
def connect_to_leaderboard_channel(message): Group('leaderboard-channel').add(message.reply_channel) print("New leaderboard listener added!")
def niftyChannelDataPush(): nifty_data = niftyData() Group('nifty-channel').send( {'text': json.dumps(nifty_data, cls=DjangoJSONEncoder)})
def ws_disconnect(message): Group("chat-%s" % message.channel_session['room']).discard(message.reply_channel)
def ws_connect(message): prefix, label = message['path'].strip('/').split('/') message.channel_session['room'] = label print("WSconnect", label) Group('chat-' + label, channel_layer=message.channel_layer).add(message.reply_channel)
def ws_disconnect(message): # TODO implement longer timeout (say days) or put a timestamp check in the exchanged data Group("alexa").discard(message.reply_channel)
def ws_disconnect(message): label = message.channel_session['room'] print("WSdisc", label) Group('chat-' + label, channel_layer=message.channel_layer).discard(message.reply_channel)
def get_bitcoin_price(): data = get_coin_price('BTC') Group('btc-price').send({'text': data})
def on_ws_disconnect(message): Group("mqtt").discard(message.reply_channel)
def form_valid(self, form): message = form.cleaned_data.get("comment") image = form.cleaned_data.get("image") users = (self.request.POST.get("users[]", "")).split(",") user = self.request.user subject = self.pdf_file.topic.subject if users[0] != "": for u in users: to_user = User.objects.get(email=u) talk, create = Conversation.objects.get_or_create( user_one=user, user_two=to_user) created = TalkMessages.objects.create(text=message, talk=talk, user=user, subject=subject, image=image) simple_notify = textwrap.shorten(strip_tags(message), width=30, placeholder="...") if image != "": simple_notify += " ".join(_("[Photo]")) notification = { "type": "chat", "subtype": "subject", "space": subject.slug, "user_icon": created.user.image_url, "notify_title": str(created.user), "simple_notify": simple_notify, "view_url": reverse("chat:view_message", args=(created.id, ), kwargs={}), "complete": render_to_string("chat/_message.html", {"talk_msg": created}, self.request), "container": "chat-" + str(created.user.id), "last_date": _("Last message in %s") % (formats.date_format( created.create_date, "SHORT_DATETIME_FORMAT")), } notification = json.dumps(notification) Group("user-%s" % to_user.id).send({"text": notification}) ChatVisualizations.objects.create(viewed=False, message=created, user=to_user) success = str(_("The message was successfull sent!")) return JsonResponse({"message": success}) erro = HttpResponse(str(_("No user selected!"))) erro.status_code = 404 return erro
def on_mqtt_message(message): msg = "{}: {}".format(message.content["topic"], message.content["payload"].decode("utf-8")) Group("mqtt").send({"text": msg})
def ws_connect(message): prefix, label = message['path'].strip('/').split('/') room = Room.objects.get(label=label) message.reply_channel.send({"accept": True}) Group('chat' + label).add(message.reply_channel) message.channel_session['room'] = room.label
def on_ws_connect(message): message.reply_channel.send({"accept": True}) Group("mqtt").add(message.reply_channel)
def tier_layout(topology_id): devices = list(Device.objects.filter(topology_id=topology_id)) device_map = {x.pk: x for x in devices} links = Link.objects.filter(Q(from_device__topology_id=topology_id) | Q(to_device__topology_id=topology_id)) def guess_role(devices): for device in devices: if getattr(device, "role", None): continue if device.type == "host": device.role = "host" continue if device.type == "switch": if 'leaf' in device.name.lower(): device.role = "leaf" continue if 'spine' in device.name.lower(): device.role = "spine" continue device.role = "unknown" guess_role(devices) edges = defaultdict(set) racks = [] for l in links: edges[device_map[l.from_device.pk]].add(device_map[l.to_device.pk]) edges[device_map[l.to_device.pk]].add(device_map[l.from_device.pk]) pprint(devices) similar_connections = defaultdict(list) for device, connections in edges.iteritems(): similar_connections[tuple(connections)].append(device) pprint(dict(**similar_connections)) for connections, from_devices in similar_connections.iteritems(): if len(from_devices) > 0 and from_devices[0].role == "host": racks.append(from_devices) pprint(racks) pprint(devices) tiers = defaultdict(list) for device in devices: if getattr(device, 'tier', None): pass elif device.role == "leaf": device.tier = 1 elif device.role == "spine": device.tier = 2 elif device.role == "host": device.tier = 0 else: device.tier = 3 tiers[device.tier].append(device) for rack in racks: rack.sort(key=lambda x: x.name) racks.sort(key=lambda x: x[0].name) for tier in tiers.values(): tier.sort(key=lambda x: x.name) pprint(tiers) for device in devices: print device, getattr(device, 'tier', None) if getattr(device, 'tier', None) is None: device.y = 0 device.x = 0 else: device.y = SPACING * 3 - device.tier * SPACING device.x = 0 - (len(tiers[device.tier]) * SPACING) / 2 + tiers[device.tier].index(device) * SPACING device.save() for j, rack in enumerate(racks): x = 0 - (len(racks) * SPACING) / 2 + j * SPACING for i, device in enumerate(rack): device.x = x device.y = SPACING * 3 + i * RACK_SPACING device.save() send_snapshot(Group("topology-%s" % topology_id), topology_id)
def ws_connect(message): Group('new-tasks').add(message.reply_channel) message.channel_session['task'] = 'new-tasks' message.reply_channel.send({'accept': True})
def onDiscover(self, message_value, topology_id, client_id): Group("workers").send({"text": json.dumps(["Discover", topology_id, yaml_serialize_topology(topology_id)])})
def ws_message(message): Group("chat-%s" % message.channel_session['room']).send({ "text": message['text'], })
def ansible_message(message): # Channel('console_printer').send({"text": message['text']}) Group("topology-%s" % message.channel_session['topology_id']).send({"text": message['text']}) Channel('discovery').send({"text": message['text'], "topology": message.channel_session['topology_id']})
def connect_to_nifty_channel(message): Group('nifty-channel').add(message.reply_channel) print("New nifty listener added!")