def patch(self, species_id): """Выполняет принудительное обновление вида листа. :param species_id: Идентификатор вида :type species_id: str """ _id = ObjectId(species_id) species = yield self.application.async_db.species.find_one({"_id": _id}) if species: yield self.application.async_db.species.update( {"_id": _id}, {"$set": {"modified": datetime.utcnow()}} ) species = yield self.application.async_db.species.find_one({"_id": _id}) yield [send_request( branch, "branch/species/{}".format(species["_id"]), "PATCH", species ) for branch in self.application.druid.branch] cursor = self.application.async_db.leaves.find({"type": species["_id"], "active": True}) while (yield cursor.fetch_next): leaf = full_leaf_info(cursor.next_object(), self.application.druid.air, species) branch = next(x for x in self.application.druid.branch if x["name"] == leaf["branch"]) yield branch_start_leaf(branch, leaf) else: self.set_status(404) self.finish("{}")
def air_enable_host(air, host): """Разрешает указанный хост на прокси-сервере. :param air: Прокси-сервер :type air: dict :param host: Добавляемый в список разрешенных хост :type host: str """ response = yield send_request(air, "air/hosts", "POST", {"host": host}) raise Return(response)
def branch_stop_leaf(branch, leaf): """Останавливает лист на указанной ветви. :param branch: Ветвь :type branch: dict :param leaf: Останавливаемый лист :type leaf: dict """ response = yield send_request(branch, "branch/leaf/{}".format(str(leaf["_id"])), "DELETE") raise Return(response)
def branch_start_leaf(branch, leaf): """Запускает лист на указанной ветви. :param branch: Ветвь :type branch: dict :param leaf: Запускаемый лист :type leaf: dict """ response = yield send_request(branch, "branch/leaf", "POST", leaf) raise Return(response)
def branch_prepare_species(branch, species): """Проверяет и подготоваливает указанный вид листа на указанной ветви. :param branch: Ветвь :type branch: dict :param species: Тип листа :type species: dict """ response, code = yield send_request( branch, "branch/species/{}".format(species["_id"]), "GET" ) # TODO: проверять не только код, но и дату модификации вида if code == 404: response, code = yield send_request( branch, "branch/species", "POST", species ) raise Return((response, code))
def get(self, leaf_name): """Возвращает статус листа, полученный с активной ветви. :param leaf_name: Имя листа :type leaf_name: str """ leaf_data = yield self.application.async_db.leaves.find_one({"name": leaf_name}) if not leaf_data: self.set_status(404) self.finish("") branch = next(x for x in self.application.druid.branch if x["name"] == leaf_data["branch"]) leaf_status, code = yield send_request(branch, "branch/leaf/{}".format(str(leaf_data["_id"])), "GET") self.finish(dumps(leaf_status))
def patch(self, species_id): """Выполняет принудительное обновление вида листа. :param species_id: Идентификатор вида :type species_id: str """ _id = ObjectId(species_id) species = yield self.application.async_db.species.find_one( {"_id": _id}) if species: yield self.application.async_db.species.update( {"_id": _id}, {"$set": { "modified": datetime.utcnow() }}) species = yield self.application.async_db.species.find_one( {"_id": _id}) yield [ send_request(branch, "branch/species/{}".format(species["_id"]), "PATCH", species) for branch in self.application.druid.branch ] cursor = self.application.async_db.leaves.find({ "type": species["_id"], "active": True }) while (yield cursor.fetch_next): leaf = full_leaf_info(cursor.next_object(), self.application.druid.air, species) branch = next(x for x in self.application.druid.branch if x["name"] == leaf["branch"]) yield branch_start_leaf(branch, leaf) else: self.set_status(404) self.finish("{}")
def get(self, leaf_name): """Возвращает статус листа, полученный с активной ветви. :param leaf_name: Имя листа :type leaf_name: str """ leaf_data = yield self.application.async_db.leaves.find_one( {"name": leaf_name}) if not leaf_data: self.set_status(404) self.finish("") branch = next(x for x in self.application.druid.branch if x["name"] == leaf_data["branch"]) leaf_status, code = yield send_request( branch, "branch/leaf/{}".format(str(leaf_data["_id"])), "GET") self.finish(dumps(leaf_status))
def post(self, **data): """Создает новый лист.""" with (yield self.application.druid.creation_lock.acquire()): leaf_address_check = yield self.application.async_db.leaves.find_one({ "$or": [ {"address": data["address"]}, {"name": data["name"]} ] }) if leaf_address_check: self.set_status(400) self.finish(dumps({ "result": "error", "message": "Duplicate address" })) raise gen.Return() try: query = {"_id": ObjectId(data["type"])} except (TypeError, InvalidId): query = {"name": data["type"]} species = yield self.application.async_db.species.find_one(query) if not species: self.set_status(400) self.finish(dumps({ "result": "error", "message": "Unknown species" })) raise gen.Return() branch = random.choice(self.application.druid.branch) leaf_id = yield self.application.async_db.leaves.insert( { "name": data["name"], "desc": data.get("description", ""), "type": species["_id"], "active": data.get("start", True), "address": [data["address"]], "branch": branch["name"], "settings": data.get("settings", {}) } ) yield [air_enable_host(air, data["address"]) for air in self.application.druid.air] if species.get("requires", []): roots = self.application.druid.roots[0] db_settings, code = yield send_request( roots, "roots/db", "POST", { "name": leaf_id, "db_type": species["requires"] } ) yield self.application.async_db.leaves.update( {"_id": leaf_id}, {"$set": {"batteries": db_settings}} ) else: pass leaf = yield self.application.async_db.leaves.find_one({"_id": leaf_id}) if leaf.get("active", True): leaf = full_leaf_info(leaf, self.application.druid.air, species) yield branch_prepare_species(branch, species) yield branch_start_leaf(branch, leaf) self.finish(dumps({"result": "success", "message": "OK", "branch": branch["name"]}))
def post(self, **data): """Создает новый лист.""" with (yield self.application.druid.creation_lock.acquire()): leaf_address_check = yield self.application.async_db.leaves.find_one( { "$or": [{ "address": data["address"] }, { "name": data["name"] }] }) if leaf_address_check: self.set_status(400) self.finish( dumps({ "result": "error", "message": "Duplicate address" })) raise gen.Return() try: query = {"_id": ObjectId(data["type"])} except (TypeError, InvalidId): query = {"name": data["type"]} species = yield self.application.async_db.species.find_one(query) if not species: self.set_status(400) self.finish( dumps({ "result": "error", "message": "Unknown species" })) raise gen.Return() branch = random.choice(self.application.druid.branch) leaf_id = yield self.application.async_db.leaves.insert({ "name": data["name"], "desc": data.get("description", ""), "type": species["_id"], "active": data.get("start", True), "address": [data["address"]], "branch": branch["name"], "settings": data.get("settings", {}) }) yield [ air_enable_host(air, data["address"]) for air in self.application.druid.air ] if species.get("requires", []): roots = self.application.druid.roots[0] db_settings, code = yield send_request( roots, "roots/db", "POST", { "name": leaf_id, "db_type": species["requires"] }) yield self.application.async_db.leaves.update( {"_id": leaf_id}, {"$set": { "batteries": db_settings }}) else: pass leaf = yield self.application.async_db.leaves.find_one( {"_id": leaf_id}) if leaf.get("active", True): leaf = full_leaf_info(leaf, self.application.druid.air, species) yield branch_prepare_species(branch, species) yield branch_start_leaf(branch, leaf) self.finish( dumps({ "result": "success", "message": "OK", "branch": branch["name"] }))