def orchestrate(self, xml, operation): self.logger.info("Received a request with this xml %s"%(xml,)) try: #TODO: parallel execution, async, rollback with BufferingLogTap(name = "Orchestration") as tap: mapping = {} opname = "Orchestration" testbed = self.prepareInput(xml) self.logger.info("Orchestrating...") for c in testbed._sortedcomponents: for k, v in c._conf_dict.items(): if isinstance(v, DynamicReference): self.logger.debug("Resolving dynid %s" % (v.identifier, )) c._conf_dict[k] = T1Resource(mapping[v.identifier], self.__tgw) self.logger.info("Resolved dynid %s -> %s" % (v.identifier, c._conf_dict[k])) try: fun = getattr(self, 'orchestrate_%s' %(operation,)) except AttributeError: raise OperationNotFoundError(operation) ############## c._conf_dict["vctname"] = testbed._name instance = fun(c) #instance = self.orchestrate_startVct(c) self.logger.info("Finished processing %s" % (c._id, )) mapping[c._id] = instance.identifier #instance_data = [] #instance_data.append(instance) self.logger.info("Orchestration finished.") except Exception, e: self.logger.exception("Error during orchestration") return OrchestrationResult(1, errorstr(e), log = Logbook(opname, "Orchestration Engine", entries = tap.log))
def _handle_request(self, request, path): try: path = self._mangle_path(request, path) result = super(AbstractT1Controller, self)._handle_request(request, path) xml = self.__serializer.serialize(result) except Exception, e: for t in request.META.get("HTTP_ACCEPT", "").split(","): if "html" in t: raise self.logger.exception("Error serving T1 request") if isinstance(e, T1ErrorResponse): return HttpResponse(content = self.__result_serializer.serialize_result(e), status = 500, content_type = "text/xml") return HttpResponse(content = errorstr(e), status = 500, content_type = "text/plain")
def handle_error(self): self.result = TestResult(False, errorstr(sys.exc_value)) self.close()
try: return self.result == o.result except AttributeError: return False def __ne__(self, o): return not (self == o) def test_port(host, port, family = AF_INET, type = SOCK_STREAM): try: with socket(family, type) as s: s.connect((host, port)) except error, e: return TestResult(False, "%s (%d)" % (e.strerror, e.errno)) except Exception, e: return TestResult(False, errorstr(e)) return TestResult(True) class PortTester(dispatcher): result = TestResult(False, "Test did not run") def __init__(self, host, port, family = AF_INET, type = SOCK_STREAM, map = None): dispatcher.__init__(self, map = map) self.create_socket(family, type) self.connect((host, port)) self.host = host self.port = port def handle_connect(self): self.result = TestResult(True) self.close()
def _handle_parse_error(self, e): super(LegacyRPRequestSerializer, self)._handle_parse_error(e) raise IllegalInput("Error parsing RP request: " + errorstr(e))
def __call__(self, request): try: response = Response(mimetype="text/html") req_url = request.path msg = "" if request.method == "POST": if req_url.startswith("/add"): goterror = False id = self._get_id_from_path(req_url[4:]) params = [] config = {} form = request.form typename = form.get("typename", "") typeerror = check_typename(typename) if typeerror: goterror = True n = 0 checker = ParamChecker() while True: k = "param%d_" % (n,) nk = k + "name" vk = k + "value" if nk not in form and vk not in form: break name = form.get(nk, "") value = form.get(vk, "") if name or value: type = form.get(k + "type", "string") params.append(checker.doparam(name, type, value)) if params[-1][-1]: goterror = True else: config[name] = params[-1][2] n += 1 if goterror: msg = "Illegal input" else: try: t1C.add(id, config.get("name", None), typename, config) return redirect(id) except Exception, e: self.logger.exception("error") msg = "An error occured: %s" % (e,) else: req_url = self._get_id_from_path(req_url) # raise Exception(req_url) entity = t1C.get_entity(req_url) old = entity.config config = {} for k, v in request.form.iteritems(): print "%s - %s" % (k, v) if "-" not in k: continue type, _, name = k.partition("-") if type == "boolean": v = v.lower().startswith("t") elif type == "integer": v = int(v) elif type == "float": v = float(v) elif type == "reference": raise NotImplementedError() if name not in old or old[name] != v: config[name] = v if config: entity.update(config) msg = "Update successful" else: msg = "No values changed, nothing to do" if req_url.startswith("/add/"): id = req_url[5:] if request.method != "POST": params = [("", "", "", None) for _ in range(10)] typename = "" typeerror = None t_test = self.template_lookup.get_template("add.html") response.data = t_test.render_unicode( url=self.__make_url, request=request, params=params, id=id, typename=typename, types=types, typeerror=typeerror, msg=escape(msg), log=(), ) elif req_url.startswith("/del/"): id = req_url[5:] t1C.delete(id) parent = id.rpartition("/") return redirect(parent[0] + parent[1]) else: if req_url.startswith("/show"): req_url = req_url[5:] if req_url.startswith("/"): pspos = req_url.find("./") if pspos >= 0 and pspos <= req_url[1:].find("/"): req_url = req_url[1:] # raise Exception("huhu", req_url) elif not req_url: req_url = "/" if req_url.endswith("/"): try: self.logger.debug("listing: " + req_url) instances = t1C.list_entities(req_url) except NoAdapterFoundError: instances = False except Exception, e: instances = escape(errorstr(e)) template = self.template_lookup.get_template("list.html") add_url = not req_url.startswith("/") and req_url or req_url[1:] response.data = template.render_unicode( url=self.__make_url, request=request, list=instances, req_url=req_url, msg=escape(msg), add_url=add_url, ) else:
v = "*********" if isinstance(v, bool): t = "boolean" elif isinstance(v, int): t = "integer" elif isinstance(v, float): t = "float" elif isinstance(v, T1Entity): t = "reference" config[k] = (v, t) p_id = entity.parent_id # raise Exception(entity.identifier) except Exception, e: self.logger.exception("Error while rendering") entity = None msg = errorstr(e) try: p_id = GlobalIdentifier(req_url, default_prefix=self.prefix).parent except IdentifierException: self.logger.exception("Error deriving parent url") p_id = GlobalIdentifier.SEPARATOR response.data = template.render_unicode( url=self.__make_url, request=request, p_id=p_id, id=req_url, entity=entity, config=config, req_url=req_url, msg=escape(msg), )
def handle_request(self, user, vct,operation): opname = "operation %s with request: vct=%s user=%s" % (operation, vct, user) try: with BufferingLogTap(name = "Request Processor") as tap: self.repo.refresh() username = user and uc(user) or raise_error(ValueError("No user given")) vctname = vct and uc(vct) or raise_error(ValueError("No vct name given")) self.logger.debug("Processing %s", opname) user = self.repo.get_unique_entity(Person, userName = username) vct = self.repo.get_unique_entity(Vct, commonName = vctname, user = user) self._prep_vct(vct) xml = self.serializer.serialize(vct) result = self.oe.orchestrate(xml,operation) tap.emit(result.log) if result.successful: self.logger.info("Orchestration succeeded") vct.state = self.repo.VCT_STATE_BOOKED updated = set([vct]) instances = {} for i in vct.instances: instances[i.identifier] = i for c in i.get_reference_configurations(): if c.is_array or c.is_dict: raise NotImplementedError() try: c.paramValue = result.idmapping[c.paramValue] except KeyError: pass else: updated.add(c) replace_instances = False for designid, runtimeid in result.idmapping.iteritems(): if designid != runtimeid: design_instance = self.repo.get_unique_entity(ResourceInstance, commonName = designid) try: existing = self.repo.get_unique_entity(ResourceInstance, commonName = runtimeid) except NoEntityFound: self.logger.debug("Renaming instance %s: %s => %s" % (repr(design_instance), design_instance.commonName, runtimeid)) design_instance.commonName = runtimeid design_instance.state = self.repo.RESOURCE_INSTANCE_STATE_PROVISIONED updated.add(design_instance) else: existing.copy_config(instances[designid]) del instances[designid] instances[runtimeid] = existing replace_instances = True updated.add(existing) if replace_instances: vct.providesResources = instances.values() self.repo.persist(updated) else: self.logger.info("Orchestration not successful.") except Exception, e: return OrchestrationResult(2, errorstr(e), log = Logbook(opname, "Request Processor", tap.log))