def get_server_port_forwarding(vm, vm_nics, fqdn): """Create API 'port_forwarding' attribute from corresponding setting. Create the 'port_forwarding' API vm attribute based on the corresponding setting (CYCLADES_PORT_FORWARDING), which can be either a tuple of the form (host, port) or a callable object returning such tuple. In case of callable object, must be called with the following arguments: * ip_address * server_id * fqdn * owner UUID NOTE: 'vm_nics' objects have prefetched the ips """ port_forwarding = {} public_ip = get_server_public_ip(vm_nics) if public_ip is None: return port_forwarding for dport, to_dest in settings.CYCLADES_PORT_FORWARDING.items(): if hasattr(to_dest, "__call__"): to_dest = to_dest(public_ip.address, vm.id, fqdn, vm.userid) msg = ("Invalid setting: CYCLADES_PORT_FOWARDING." " Value must be a tuple of two elements (host, port).") if not isinstance(to_dest, tuple) or len(to_dest) != 2: raise faults.InternalServerError(msg) else: try: host, port = to_dest except (TypeError, ValueError): raise faults.InternalServerError(msg) port_forwarding[dport] = {"host": host, "port": str(port)} return port_forwarding
def get_server_fqdn(vm, vm_nics): fqdn_setting = settings.CYCLADES_SERVERS_FQDN if fqdn_setting is None: return None elif isinstance(fqdn_setting, basestring): return fqdn_setting % {"id": vm.id} else: msg = ("Invalid setting: CYCLADES_SERVERS_FQDN." " Value must be a string.") raise faults.InternalServerError(msg)
def __exit__(self, exc_type, value, traceback): if value is not None: # exception if not isinstance(value, errors.AstakosClientException): return False # reraise if exc_type is errors.QuotaLimit: msg, details = render_overlimit_exception(value) raise faults.OverLimit(msg, details=details) log.exception("Unexpected error %s" % value.message) raise faults.InternalServerError("Unexpected error")
def __exit__(self, exc_type, value, traceback): if value is not None: # exception if not isinstance(value, errors.AstakosClientException): return False # reraise if exc_type is errors.QuotaLimit: raise faults.OverLimit(value.message, details=value.details) if exc_type is errors.NotFound: self.check_not_found() log.exception("Unexpected error %s" % value.message) raise faults.InternalServerError("Unexpected error")
def check_not_found(self): if not self.user or not self.projects: return try: qh = Quotaholder.get() user_quota = qh.service_get_quotas(self.user) except errors.AstakosClientException as e: log.exception("Unexpected error %s" % e.message) raise faults.InternalServerError("Unexpected error") user_quota = user_quota[self.user] for project in self.projects: try: user_quota[project] except KeyError: m = "User %s not in project %s" % (self.user, project) raise faults.BadRequest(m)
def wrapper(request, *args, **kwargs): try: # Explicitly set request encoding to UTF-8 instead of relying # to the DEFAULT_CHARSET setting. See: # https://docs.djangoproject.com/en/1.4/ref/unicode/#form-submission # flake8: noqa request.encoding = 'utf-8' # Get the requested serialization format serialization = get_serialization(request, format_allowed, serializations[0]) # If guessed serialization is not supported, fallback to # the default serialization or return an API error in case # strict serialization flag is set. if not serialization in serializations: if strict_serlization: raise faults.BadRequest(("%s serialization not " "supported") % serialization) serialization = serializations[0] request.serialization = serialization # Check HTTP method if http_method and request.method != http_method: raise faults.NotAllowed("Method not allowed", allowed_methods=[http_method]) # Get authentication token request.x_auth_token = None if token_required or user_required: token = get_token(request) if not token: msg = "Access denied. No authentication token" raise faults.Unauthorized(msg) request.x_auth_token = token # Authenticate if user_required: assert (token_required), "Can not get user without token" client_ip = get_client_ip(request) user_info = retrieve_user(token, astakos_auth_url, logger=logger, client_ip=client_ip) _user_access = user_info["access"]["user"] request.user_uniq = _user_access["id"] request.user_projects = _user_access.get("projects", None) request.user = user_info # Get the response object response = func(request, *args, **kwargs) # Fill in response variables update_response_headers(request, response) return response except faults.Fault as fault: if fault.code >= 500: django_logger.error("Unexpected API Error: %s", request.path, exc_info=sys.exc_info(), extra={ "status_code": fault.code, "request": request }) return render_fault(request, fault) except AstakosClientException as err: fault = faults.Fault(message=err.message, details=err.details, code=err.status) if fault.code >= 500: django_logger.error("Unexpected AstakosClient Error: %s", request.path, exc_info=sys.exc_info(), extra={ "status_code": fault.code, "request": request }) return render_fault(request, fault) except: django_logger.error("Internal Server Error: %s", request.path, exc_info=sys.exc_info(), extra={ "status_code": '500', "request": request }) fault = faults.InternalServerError("Unexpected error") return render_fault(request, fault)
def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except AstakosClientException: log.exception("Unexpected error") raise faults.InternalServerError("Unexpected error")
update_response_headers(request, response) return response except faults.Fault, fault: if fault.code >= 500: logger.exception("API ERROR") return render_fault(request, fault) except AstakosClientException as err: fault = faults.Fault(message=err.message, details=err.details, code=err.status) if fault.code >= 500: logger.exception("Astakos ERROR") return render_fault(request, fault) except: logger.exception("Unexpected ERROR") fault = faults.InternalServerError("Unexpected error") return render_fault(request, fault) return csrf.csrf_exempt(wrapper) return decorator def get_serialization(request, format_allowed=True, default_serialization="json"): """Return the serialization format requested. Valid formats are 'json' and 'xml' and 'text' """ if not format_allowed: return "text" # Try to get serialization from 'format' parameter