def delete(self): ip = self.ip if self.many: if not ip: # SELECT count(*) from IPAddress ??? raise ObjectNotFound(model=IPAddress) for i in ip: # SELECT * from IPAddress if i.vm or i.vms.exists(): raise PreconditionRequired( _('IP address "%s" is used by VM') % i.ip) if i.is_node_address(): raise PreconditionRequired( _('IP address "%s" is used by Compute node') % i.ip) msg = LOG_IPS_DELETE dd = {'ips': ','.join(i.ip for i in ip)} else: if ip.vm or ip.vms.exists(): raise PreconditionRequired(_('IP address is used by VM')) if ip.is_node_address(): raise PreconditionRequired( _('IP address is used by Compute node')) msg = LOG_IP_DELETE dd = {'ip': ip.ip} ip.delete() # DELETE from IPAddress return SuccessTaskResponse(self.request, None, obj=self.net, msg=msg, detail_dict=dd, dc_bound=False)
def delete_record(cls, request, record_type, domain_name, name, task_id=None, **kwargs): """Called internally by some api functions""" if not request.dc.settings.DNS_ENABLED: logger.info( 'DNS support disabled: skipping delete_record(%r, %r, %r)', record_type, domain_name, name) return None name = name.lower() # DB constraint c_lowercase_name domain = cls.internal_domain_get(domain_name, task_id=task_id) try: record = Record.objects.get(name=name, type=record_type, domain=domain) except Record.DoesNotExist: raise ObjectNotFound(model=Record) logger.info('Deleting %s record "%s" on domain "%s"', record_type, name, domain) return cls.internal_response(request, 'DELETE', record, {}, task_id=task_id, **kwargs)
def __init__(self, request, service, data=None): super(ServiceStatusView, self).__init__(request) self.service = service self.ctrl = ServiceControl() if service and service not in self.ctrl.services: raise ObjectNotFound(object_name='Service')
def get(self, many=False): """Function retrieves predefined log files from worker""" if not self.node.is_online(): raise NodeIsNotOperational() single_log_file = self.data.get('logname', None) if single_log_file: # make sure that file is among allowed files, # otherwise any file with read permission can be retrieved if single_log_file in self.log_files: self.log_files = (single_log_file, ) else: logger.error( 'Error retrieving log file %s, file not among allowed files!', single_log_file) raise ObjectNotFound(object_name=single_log_file) worker = self.node.worker('fast') logger.debug('Retrieving log files from node "%s"', self.node) log_files_result = worker_command('system_read_logs', worker, log_files=self.log_files, timeout=10) if log_files_result is None: raise GatewayTimeout('Node worker is not responding') return SuccessTaskResponse(self.request, log_files_result, dc_bound=self.dc_bound)
def get(self): """Function retrieves predefined log files from system""" # hardcoded default log files that will be retrieved log_files_result = {} single_log_file = self.data.get('logname', None) if single_log_file: # make sure that file is among allowed files, # otherwise any file with read permission can be retrieved if single_log_file in self.log_files: self.log_files = (single_log_file, ) else: logger.error('Error retrieving log file %s, file not among allowed files!', single_log_file) raise ObjectNotFound(object_name=single_log_file) for log in self.log_files: abs_path_name = os.path.join(self.log_path, log) try: with open(abs_path_name) as f: log_files_result[log] = read_file(f) except IOError as exc: logger.error('Error retrieving log file %s (%s)', abs_path_name, exc) # return an empty string for the log file which raised the exception log_files_result[log] = None return SuccessTaskResponse(self.request, log_files_result, dc_bound=self.dc_bound)
def get_image(self): uuid = self.uuid for img in self.repo.images: if img['uuid'] == uuid: return img else: raise ObjectNotFound(model=Image)
def get_object(request, model, attrs, where=None, exists_ok=False, noexists_fail=False, sr=(), pr=(), extra=None, annotate=None, create_attrs=None, data=None): """ Get or create object with attrs looked up by where. Return error response when needed. """ obj = None try: qs = model.objects if sr: qs = qs.select_related(*sr) if pr: qs = qs.prefetch_related(*pr) if annotate: qs = qs.annotate(**annotate) if extra: qs = qs.extra(**extra) if where: qs = qs.filter(where) obj = qs.get(**attrs) except model.DoesNotExist: if request.method in ('GET', 'PUT', 'DELETE') or noexists_fail: raise ObjectNotFound(model=model) elif request.method == 'POST': if create_attrs: new_obj_attrs = create_attrs else: new_obj_attrs = { key: val for key, val in iteritems(attrs) if '__' not in key } obj = model(**new_obj_attrs) else: if request.method == 'POST' and not exists_ok: raise ObjectAlreadyExists(model=model) return obj
def __init__(self, request, hostname, service, data=None): super(NodeServiceStatusView, self).__init__(request) self.service = service self.hostname = hostname self.data = data self.node = get_node(request, hostname) self.ctrl = NodeServiceControl(self.node) if service and service not in self.ctrl.services: raise ObjectNotFound(object_name='Service')
def get_dc_or_404(request, dc_name, api=True): """ Get Dc for editing purposes. """ try: return Dc.objects.get_by_name(dc_name) except Dc.DoesNotExist: if api: raise ObjectNotFound(model=Dc) else: raise Http404
def __init__(self, request, name, uuid, data): super(ImageStoreImageView, self).__init__(request) self.data = data self.name = name self.uuid = uuid repositories = ImageStore.get_repositories() try: self.repo = ImageStore(name, url=repositories[name]) except KeyError: # The name is not in VMS_IMAGE_REPOSITORIES raise ObjectNotFound(model=ImageStore)
def __init__(self, request, name, data): super(DcStorageView, self).__init__(request) self.data = data self.name = name dc = request.dc if name: try: zpool, hostname = name.split('@') if not (zpool and hostname): raise ValueError except ValueError: raise ObjectNotFound(model=NodeStorage) attrs = {'node__hostname': hostname, 'zpool': zpool} if request.method != 'POST': attrs['dc'] = dc ns = get_object(request, NodeStorage, attrs, sr=( 'node', 'storage', 'storage__owner', ), exists_ok=True, noexists_fail=True) ns.set_dc(dc) try: # Bug #chili-525 + checks if node is attached to Dc (must be!) ns.set_dc_node(DcNode.objects.get(node=ns.node, dc=dc)) except DcNode.DoesNotExist: raise PreconditionRequired(_('Compute node is not available')) else: # many ns = NodeStorage.objects.filter(dc=dc).order_by(*self.order_by) if self.full or self.extended: dc_nodes = { dn.node.hostname: dn for dn in DcNode.objects.select_related('node').filter( dc=request.dc) } ns = ns.select_related('node', 'storage', 'storage__owner') for i in ns: # Bug #chili-525 i.set_dc_node(dc_nodes.get(i.node.hostname, None)) i.set_dc(dc) self.ns = ns
def get_dc(request, dc_name): """Return Datacenter from request""" try: dc = Dc.objects.get_by_name(dc_name) user = request.user if not (user.is_staff or dc.access == Dc.PUBLIC or dc == user.current_dc or user == dc.owner): if not dc.roles.filter(pk__in=user.roles.all()).exists(): raise Dc.DoesNotExist except Dc.DoesNotExist: raise ObjectNotFound(model=Dc) return dc
def __init__(self, request, subnet, data, dc=None): super(NetworkIPPlanView, self).__init__(request) self.data = data self.dc = dc ip_filter = [] if subnet: try: ipi = cidr_validator(subnet, return_ip_interface=True) except ValidationError: raise InvalidInput('Invalid subnet') network, netmask = ipi.with_netmask.split('/') net_filter = {'network': network, 'netmask': netmask} if dc: net_filter['dc'] = dc nets = Subnet.objects.filter(**net_filter) if not nets.exists(): raise ObjectNotFound(model=Subnet) ip_filter.append(Q(subnet__in=nets)) if dc: ip_filter.append(Q(usage=IPAddress.VM)) ip_filter.append((Q(vm__isnull=False) & Q(vm__dc=dc)) | (~Q(vms=None) & Q(vms__dc=dc))) usage = data.get('usage', None) if usage and not dc: try: usage = int(usage) if usage not in dict(IPAddress.USAGE_REAL): raise ValueError except ValueError: raise InvalidInput('Invalid usage') else: ip_filter.append(Q(usage=usage)) if ip_filter: ip_filter = reduce(operator.and_, ip_filter) else: ip_filter = Q() self.ips = IPAddress.objects.select_related('vm', 'vm__dc', 'subnet')\ .prefetch_related('vms', 'vms__dc')\ .filter(ip_filter)\ .order_by(*self.order_by).distinct()
def delete(self): dc, group = self.dc, self.role if not group.dc_set.filter(id=dc.id).exists(): raise ObjectNotFound(model=Role) ser = self.serializer(self.request, group) group.dc_set.remove(self.request.dc) res = SuccessTaskResponse(self.request, None, obj=group, detail_dict=ser.detail_dict(), msg=LOG_GROUP_DETACH) self._remove_dc_binding(res) return res
def delete(self, many=False): record = self.record if many: assert not self.record_id if not record: # SELECT count(*) from record ??? raise ObjectNotFound(model=Record) msg = LOG_RECORDS_DELETE dd = {'records': [r.desc for r in record]} else: msg = LOG_RECORD_DELETE dd = {'record': record.desc} record.delete() return SuccessTaskResponse(self.request, None, obj=self.domain, msg=msg, detail_dict=self._fix_detail_dict(dd), task_id=self.task_id, dc_bound=False)
def __init__(self, request, name, data, many=False): super(ImageStoreView, self).__init__(request) self.data = data self.name = name self.many = many repositories = ImageStore.get_repositories() if name: assert not many try: self.repo = ImageStore(name, url=repositories[name]) except KeyError: # The name is not in VMS_IMAGE_REPOSITORIES raise ObjectNotFound(model=ImageStore) else: assert many if request.method == 'PUT' or (self.full or self.extended): self.repo = ImageStore.all(repositories) else: self.repo = repositories.keys()
def get_snapshots(request, vm, real_disk_id, data): """Return Snapshot queryset according to disk_id and snapshot names in data""" snapnames = data.get('snapnames', None) if not (snapnames and isinstance(snapnames, (list, tuple))): # List and not empty raise InvalidInput('Invalid snapnames') # Stringify data, because if the name is a number, then form/data sent via socket.io is contains numbers snapnames = map(str, snapnames) # TODO: check indexes snaps = Snapshot.objects.select_related('vm').filter(vm=vm, disk_id=real_disk_id, name__in=snapnames) if not snaps: raise ObjectNotFound(model=Snapshot) return snaps, snapnames
def delete(self): dc, group = self.dc, self.role if not group.dc_set.filter(id=dc.id).exists(): raise ObjectNotFound(model=Role) ser = self.serializer(self.request, group) group.dc_set.remove(self.request.dc) connection.on_commit(lambda: group_relationship_changed.send( group_name=group.name, dc_name=dc.name)) res = SuccessTaskResponse(self.request, None, obj=group, detail_dict=ser.detail_dict(), msg=LOG_GROUP_DETACH) self._remove_dc_binding(res) self._update_affected_users(detach=True) return res
def get_backups(request, bkp_filter, data): """Return Backup queryset according to filter and backup names in data""" bkpnames = data.get('bkpnames', None) if not (bkpnames and isinstance(bkpnames, (list, tuple))): # List and not empty raise InvalidInput('Invalid bkpnames') bkp_filter['name__in'] = bkpnames # TODO: check indexes bkps = Backup.objects.select_related('node', 'vm').filter(**bkp_filter) if not bkps: raise ObjectNotFound(model=Backup) bkp = bkps[0] for i in bkps: if i.node != bkp.node or i.vm != bkp.vm: raise InvalidInput('Invalid bkpnames') return bkps, bkpnames
def internal_domain_get(cls, domain_name, task_id=None): """Used internally by some api functions""" try: return Domain.objects.get(name=domain_name) except Domain.DoesNotExist: raise ObjectNotFound(model=Domain, task_id=task_id)