def clean(self): # TODO compare against known environments # TODO compare against known scripts if not isinstance(self.tasks, list): raise ProblemException( status=400, title='ValidationError', detail='tasks must be a list of tasks to run', ext=self.tasks) if any([not isinstance(task, six.string_types) for task in self.tasks]): raise ProblemException(status=400, title='ValidationError', detail='tasks must be strings', ext=self.tasks)
def clean(self): stale = not (self.is_desired or self.scheduled_on_sat or self.scheduled_on_gs) if stale: return gs_reset_time = timedelta(seconds=GS_RESET_TIME_S) overlap_range = (self.start_time - gs_reset_time, self.end_time) start_overlaps_qs = Q(start_time__range=overlap_range) end_overlaps_qs = Q(end_time__range=overlap_range) not_stale = (Q(scheduled_on_sat=True) | Q(scheduled_on_gs=True) | Q(is_desired=True)) same_sat = Q(satellite=self.satellite) same_gs = Q(groundstation=self.groundstation) different_id = ~Q(uuid=self.uuid) overlapping_pass_qs = Pass.objects.filter((same_gs | same_sat) & different_id & not_stale & (start_overlaps_qs | end_overlaps_qs)) overlaps = overlapping_pass_qs.all() if overlaps: ext = {"conflicts": [p.to_dict() for p in overlaps]} raise ProblemException( status=409, title="Conflict", detail="The provided pass conflicts with one on the server", ext=ext, )
def deleteServiceById(user, id): service = _getServiceByIdOrFail(user, id) activeInstances = 0 for instance in service.instances: if instance.status != "ERROR": activeInstances += 1 if activeInstances > 0: raise ProblemException( title="Bad Request", detail= ("The service has {:d} active instances that need to be terminated " "before the service can be deleted.").format(activeInstances), ) # Delete the descriptors from the repository try: repository.delete(f"descriptors/services/{service.descriptor.id}") for descriptor in service.functionDescriptors: repository.delete(f"descriptors/functions/{descriptor.id}") except RequestException as e: raise InternalServerError( detail=f"Failed to delete descriptors from repository: {e}") for instance in service.instances: instance.delete() service.delete() return service
def _getReferencedDescriptors(userId: str, descriptor: Descriptor) -> List[Descriptor]: """ Given a service descriptor, returns a list of all descriptors referenced by the service descriptor or raises a connexion `ProblemException` with a user-friendly message. """ referencedDescriptors = [] referencedDescriptorIds = set() if "network_functions" not in descriptor.content: raise ProblemException( status=400, title="Faulty Descriptor", detail="{} does not specify any network functions.".format( descriptor.content), ) for function in descriptor.content.network_functions: try: vendor = function["vnf_vendor"] name = function["vnf_name"] version = function["vnf_version"] referencedDescriptor = Descriptor.objects( userId=userId, content__descriptor_type="function", content__vendor=vendor, content__name=name, content__version=version, ).get() if referencedDescriptor.id not in referencedDescriptorIds: referencedDescriptors.append(referencedDescriptor) referencedDescriptorIds.add(referencedDescriptor.id) except DoesNotExist: raise ProblemException( status=400, title="Missing Dependency", detail= (f"{descriptor.content} contains reference to missing " f'Descriptor(descriptor_type="function", vendor="{vendor}", ' f'name="{name}",version="{version}"). ' f"Please upload that descriptor and try again."), ) return referencedDescriptors
def put(uuid, task_stack): task_stack["uuid"] = uuid ts_obj, _created = TaskStack.objects.get_or_create(uuid=uuid, defaults=task_stack) ts = ts_obj.to_dict() if not _created: raise ProblemException(status=409, title='Conflict', detail='The provided task-stack already exists', ext={"task_stack": ts}) return ts, 201
def locationiq_get(lat: float, long: float): url = URL.format(GEO_API_KEY, lat, long) try: data = urlopen(url).read() location = json.loads(data.decode("utf-8")) return location["address"]["city"] except Exception as err: raise ProblemException( status=500, title="GEO error for lat:{} long:{}".format(lat, long), detail=str(err), )
def post_change_players_score(player: bool, points: int) -> str: try: game = Game.objects.latest('id') if player: game.score_1 = game.score_1 + points else: game.score_2 = game.score_2 + points game.save() except Game.DoesNotExist as error: raise ProblemException(title='Error - could not resolve game', status=404) from error return "success"
def put(uuid, task_stack): ts_uuid = task_stack.setdefault("uuid", str(uuid4())) ts_obj, _created = TaskStack.objects.get_or_create(uuid=ts_uuid, defaults=task_stack) ts = ts_obj.to_dict() if not _created: raise ProblemException(status=409, title='Conflict', detail='The provided task-stack already exists', ext={"task_stack": ts}) _pass = Pass.objects.get(uuid=uuid) _pass.task_stack = ts_obj _pass.save() return ts, 201
def put(hwid, task_stack): uuid = task_stack.setdefault("uuid", str(uuid4())) ts_obj, _created = TaskStack.objects.get_or_create(uuid=uuid, defaults=task_stack) ts = ts_obj.to_dict() if not _created: raise ProblemException( status=409, title="Conflict", detail="The provided task-stack already exists", ext={"task_stack": ts}, ) sat = Satellite.objects.get(hwid=hwid) sat.task_stack = ts_obj sat.save() return ts, 201
def delete(uuid): pass_obj = Pass.objects.get(uuid=uuid) problems = [] if pass_obj.scheduled_on_gs: problems += [ "pass is scheduled on the groundstation ({hwid})".format( hwid=pass_obj.groundstation.hwid) ] if pass_obj.scheduled_on_sat: problems += [ "pass is scheduled on the satellite ({hwid})".format( hwid=pass_obj.satellite.hwid) ] if problems: raise ProblemException(status=400, title="Cannot delete pass that is scheduled", detail=problems) pass_obj.delete() return None, 204
def api_error(msg): raise ProblemException(detail=msg)
def operation(req): raise ProblemException(418, '', '')
def get_example_by_name(name: str) -> dict: """Query example by name.""" for example in EXAMPLE_DATA: if example["name"] == name: return example raise ProblemException(status=404, detail=f"Cannot find example {name}!")
def instantiateService(user, serviceId, body): service = _getServiceByIdOrFail(user, serviceId) # Send instantiation message validationReply = broker.call_sync( SERVICE_CREATION_TOPIC, { "ingresses": body["ingresses"] if "ingresses" in body else [], "egresses": body["egresses"] if "egresses" in body else [], "nsd": { **to_custom_dict(service.descriptor.content), "id": str(service.descriptor.id), }, "vnfds": [{ **to_custom_dict(descriptor.content), "id": str(descriptor.id) } for descriptor in service.functionDescriptors], }, ) if validationReply.payload["status"] == "ERROR": raise ProblemException( status=500, title="Instantiation Failed", detail=validationReply.payload["error"], ) instance = ServiceInstance( userId=user, status=validationReply.payload["status"], correlationId=validationReply.correlation_id, ) instance.save() service.instances.append(instance) service.save() def onNotificationReceived(message: Message): """ React to the SLM's notification about the instantiation outcome """ if message.correlation_id != instance.correlationId: return payload = message.payload logger.debug("Received instantiation notification: %s", payload) instance.status = payload["status"] if payload["status"] == "ERROR": instance.message = str(payload["error"]) else: # Get instance id instance.internalId = payload["nsr"]["id"] instance.save() broker.unsubscribe(subscriptionId) subscriptionId = broker.register_notification_endpoint( onNotificationReceived, SERVICE_CREATION_TOPIC) return instance