def update_resource(self, resource_data): """ Update a resource. Broadcast it on the bus and store the update in the database. """ ds = DataStore.instance() resource = R.deserialize(resource_data) version = Version(resource.id) version.data = resource_data version.save() if not ds.contains(Resource, version.resource_id): res = Resource(version.resource_id) res.save() if not ds.contains(Agent, res.agent_name): agent = Agent(res.agent_name) agent.save() # broadcast topic = "%s.%s" % (resource.id.agent_name, resource.id.entity_type) msg = amqp.Message(json.dumps({"operation" : "UPDATE", "resource": resource_data})) msg.content_type = "application/json" self._channel.basic_publish(msg, exchange = self._exchange_name, routing_key = "resources.%s" % topic)
def on_message(self, msg): """ Receive a new file """ message = json.loads(msg.body) if "operation" in message: operation = message["operation"] else: return if operation == "FACTS_REPLY": if "code" in message and message["code"] != 200: self._logger.error("Received a 404 message on a facts reply. " + str(message)) return if "facts" in message: facts = message['facts'] for subject,facts in message['facts'].items(): self._logger.info("Received facts from %s" % subject) for fact in facts: value = facts[fact] if not isinstance(value, str): value = json.dumps(value) fact_obj = Fact() fact_obj.value_time = time.time() fact_obj.resource_id = Id.parse_id(subject) fact_obj.name = fact fact_obj.value = value fact_obj.entity_type = fact_obj.resource_id.entity_type fact_obj.save() else: self._logger.error("No facts in message: " + str(message)) elif operation == "PONG": if "hostname" not in message: self._logger.error("Invalid PONG heartbeat received") return for host in message["hostname"]: h = Agent(host) h.save() elif operation == "UPDATED": if "id" not in message or "version" not in message: self._logger.error("Invalid UPDATED operation") return version = DataStore.instance().get(Version, message['id']) if version is not None: version.mark_updated() version.save() elif operation == "UPDATE": # ignore pass elif operation == "FACTS": pass else: self._logger.debug("Received message with unknown operation. operation = %s" % str(operation))