def handle(self, *args, **options): if len(args) != 1: raise CommandError("Invalid number of arguments") urls = filter( lambda u: len(u) < settings.MAXIMUM_ALLOWED_REDIRECT_URI_LENGTH, options['urls']) if len(options['urls']) != len(urls): self.stdout.write('The following urls are over the allowed limit ' 'and are going to be ignored: %s\n' % ','.join(set(options['urls']) - set(urls))) if not urls: raise CommandError("There should be at least one redirect URI") identifier = args[0].decode('utf8') try: c = Client(identifier=identifier, secret=options['secret'], type=options['type'], is_trusted=options['is_trusted']) c.save() c.redirecturl_set.bulk_create( (RedirectUrl(client=c, url=url) for url in urls)) c.save() except BaseException, e: raise CommandError(e)
def handle(self, *args, **options): if len(args) < 1: raise CommandError("Invalid number of arguments") name = args[0].strip() try: profile = Profile.objects.get(name=name) except Profile.DoesNotExist: raise CommandError("Invalid profile name") users = [] try: users = [ AstakosUser.objects.get(pk=int(pk)) for pk in options.get('users') ] except AstakosUser.DoesNotExist: raise CommandError("Invalid user id") groups = [] try: groups = [ Group.objects.get(pk=int(pk)) for pk in options.get('groups') ] except Group.DoesNotExist: raise CommandError("Invalid group id") update_profile(profile, users, groups)
def handle(self, *args, **options): self.output_format = options['output_format'] if len(args) != 1: raise CommandError("Please provide a commission serial.") try: serial = int(args[0]) except ValueError: raise CommandError('Expecting an integer serial.') try: commission = Commission.objects.get(serial=serial) except Commission.DoesNotExist: m = 'There is no pending commission with serial %s.' % serial raise CommandError(m) data = {'serial': serial, 'name': commission.name, 'clientkey': commission.clientkey, 'issue_time': commission.issue_datetime, } self.pprint_dict(data) provisions = Provision.objects.filter(serial=commission) data, labels = self.show_provisions(provisions) self.stdout.write('\n') self.pprint_table(data, labels, title='Provisions')
def handle(self, *args, **options): if len(args) != 3: raise CommandError("Invalid number of arguments") email, first_name, last_name = args[:3] password = options['password'] or \ AstakosUser.objects.make_random_password() try: validate_email(email) except ValidationError: raise CommandError("Invalid email") has_signed_terms = not (get_latest_terms()) try: user = make_local_user(email, first_name=first_name, last_name=last_name, password=password, has_signed_terms=has_signed_terms) if options['is_superuser']: user.is_superuser = True user.save() except BaseException, e: raise CommandError(e)
def handle(self, *args, **options): all_base = options["all_system_projects"] exclude = options["exclude"] self.check_args(args, all_base, exclude) try: changes = {} for key, value in options.iteritems(): param = PARAMS.get(key) if param is None or value is None: continue if all_base and not param.is_main: m = "Cannot modify field '%s' in bulk" % key raise CommandError(m) k = key if param.key is Simple else param.key v = value if param.mod is Simple else param.mod(value) changes[k] = v if all_base: flt = self.mk_all_base_filter(all_base, exclude) functions.modify_projects_in_bulk(flt, changes) else: functions.modify_project(args[0], changes) except BaseException as e: raise CommandError(e)
def handle(self, *args, **options): self.output_format = options["output_format"] message = options['message'] actions = { 'terminate': terminate, 'reinstate': reinstate, 'unsuspend': unsuspend, 'suspend': suspend, 'approve': approve_application, 'deny': lambda a: deny_application(a, reason=message), 'check_expired': lambda _: self.expire(execute=False), 'terminate_expired': lambda _: self.expire(execute=True), } opts = [(key, value) for (key, value) in options.items() if key in actions and value] if len(opts) != 1: raise CommandError("Specify exactly one operation.") key, value = opts[0] action = actions[key] try: action(value) except BaseException as e: raise CommandError(e)
def check_args(self, args, all_base, exclude): if all_base and args or not all_base and len(args) != 1: m = "Please provide a project ID or --all-system-projects" raise CommandError(m) if not all_base and exclude: m = ("Option --exclude is meaningful only combined with " " --all-system-projects.") raise CommandError(m)
def handle(self, *args, **options): if len(args) != 1: raise CommandError("Invalid number of arguments") try: profile = Profile.objects.get(name=args[0]) profile.delete() except Profile.DoesNotExist: raise CommandError("Invalid profile name")
def handle(self, *args, **options): if len(args) != 1: raise CommandError("Please provide a volume ID") volume_type = common.get_resource("volume-type", args[0]) pprint.pprint_volume_type(volume_type, stdout=self.stdout)
def handle(self, *args, **options): if len(args) != 1: raise CommandError("Please provide project ID or name") self.unit_style = options['unit_style'] check_style(self.unit_style) show_pending = bool(options['pending']) show_members = bool(options['members']) show_quota = bool(options['list_quotas']) self.output_format = options['output_format'] id_ = args[0] if True: project = get_chain_state(id_) self.print_project(project, show_quota) if show_members and project is not None: self.stdout.write("\n") fields, labels = members_fields(project) self.pprint_table(fields, labels, title="Members") if show_pending: app = project.last_application if app and app.state == ProjectApplication.PENDING: self.stdout.write("\n") self.print_app(app)
def handle(self, *args, **options): if options["backend"] is not None: backend = get_resource("backend", options["backend"]) else: backend = None clusters = parse_bool(options["clusters"]) servers = parse_bool(options["servers"]) images = parse_bool(options["images"]) if backend is None: ip_pools = parse_bool(options["ip_pools"]) networks = parse_bool(options["networks"]) else: ip_pools = False networks = False if options["json_file"] is None: stats = statistics.get_cyclades_stats(backend, clusters, servers, ip_pools, networks, images) else: with open(options["json_file"]) as data_file: stats = json.load(data_file) output_format = options["output_format"] if output_format == "json": self.stdout.write(json.dumps(stats, indent=4) + "\n") elif output_format == "pretty": cluster_details = parse_bool(options["cluster_details"]) pretty_print_stats(stats, self.stdout, cluster_details=cluster_details) else: raise CommandError("Output format '%s' not supported." % output_format)
def parse_limit(self, limit): try: return units.parse(limit) except units.ParseError: m = ("Quota limit should be an integer, " "optionally followed by a unit, or 'inf'.") raise CommandError(m)
def get_handlers(self, resources, resources_soft): def exists(v, from_soft=False): origin = resources_soft if from_soft else resources try: origin.remove(v) return True except KeyError: return False def check_unknown_left(resource_set, soft=False): if resource_set: m = ("'%s' is not a supported resource for %senforce" % (resource_set.pop(), "soft " if soft else "")) raise CommandError(m) resources = set([] if resources is None else resources.split(",")) resources_soft = set( [] if resources_soft is None else resources_soft.split(",")) if not resources.isdisjoint(resources_soft): raise CommandError("A resource shouldn't appear in both sets") handlers = [] for handler in enforce.RESOURCE_HANDLING: resource_name = handler[0] is_soft = handler[1] if exists(resource_name, is_soft): handlers.append(handler) check_unknown_left(resources) check_unknown_left(resources_soft, soft=True) return handlers
def handle(self, *args, **options): if len(args) != 1: raise CommandError("Please provide a snapshot ID") snapshot_id = args[0] try: with PlanktonBackend(None) as backend: snapshot = backend.get_snapshot(snapshot_id, check_permissions=False) except: raise CommandError("An error occurred, verify that snapshot and " "user ID are valid") utils.pprint_table(out=self.stdout, table=[snapshot.values()], headers=snapshot.keys(), vertical=True)
def handle(self, *args, **options): if len(args) != 1: raise CommandError("Please provide a component name or ID.") identifier = args[0] if identifier.isdigit(): try: component = Component.objects.get(id=int(identifier)) except Component.DoesNotExist: raise CommandError('No component found with ID %s.' % identifier) else: try: component = Component.objects.get(name=identifier) except Component.DoesNotExist: raise CommandError('No component found named %s.' % identifier) kv = OrderedDict([ ('id', component.id), ('name', component.name), ('base url', component.base_url), ('ui url', component.url), ('token', component.auth_token), ('token created', component.auth_token_created), ('token expires', component.auth_token_expires), ]) utils.pprint_table(self.stdout, [kv.values()], kv.keys(), options["output_format"], vertical=True) services = component.service_set.all() service_data = [] for service in services: service_data.append((service.id, service.name, service.type)) if service_data: self.stdout.write('\n') labels = ('id', 'name', 'type') utils.pprint_table(self.stdout, service_data, labels, options["output_format"], title='Registered services')
def handle(self, *args, **options): if len(args) != 1: raise CommandError("Please provide a component ID or name") ident = args[0] try: try: ident = int(ident) component = Component.objects.get(id=ident) except ValueError: component = Component.objects.get(name=ident) except Component.DoesNotExist: raise CommandError( "Component does not exist. You may run snf-manage " "component-list for available component IDs.") component.delete()
def handle(self, *args, **options): if len(args) != 1: raise CommandError("Please provide a component ID or name") ident = args[0] try: try: ident = int(ident) component = Component.objects.get(id=ident) except ValueError: component = Component.objects.get(name=ident) except Component.DoesNotExist: raise CommandError( "Component does not exist. You may run snf-manage " "component-list for available component IDs.") ui_url = options.get('ui_url') base_url = options.get('base_url') auth_token = options.get('auth_token') renew_token = options.get('renew_token') purge_services = options.get('purge_services') if not any([ui_url, base_url, auth_token, renew_token, purge_services ]): raise CommandError("No option specified.") if ui_url: component.url = ui_url if base_url: component.base_url = base_url if auth_token: component.auth_token = auth_token if renew_token and not auth_token: component.renew_token() component.save() if purge_services: component.service_set.all().delete() if renew_token: self.stdout.write('Component\'s new token: %s\n' % component.auth_token)
def get_accepted_user(user_ident): if is_uuid(user_ident): try: user = AstakosUser.objects.get(uuid=user_ident) except AstakosUser.DoesNotExist: raise CommandError('There is no user with uuid: %s' % user_ident) elif is_email(user_ident): try: user = AstakosUser.objects.get(username=user_ident) except AstakosUser.DoesNotExist: raise CommandError('There is no user with email: %s' % user_ident) else: raise CommandError('Please specify user by uuid or email') if not user.is_accepted(): raise CommandError('%s is not an accepted user.' % user.uuid) return user
def handle(self, *args, **options): if len(args) != 1: raise CommandError("Please provide a floating IP ID") ip = common.get_resource("floating-ip", args[0]) pprint.pprint_floating_ip(ip, stdout=self.stdout, display_mails=options["displaymail"])
def read_from_file(f_name): if f_name == '-': return sys.stdin.read() else: try: with open(f_name) as file_desc: return file_desc.read() except IOError as e: raise CommandError(e)
def handle(self, *args, **options): json_file = options['json'] if not json_file: m = "Expecting option --json." raise CommandError(m) else: data = read_from_file(json_file) m = ('Input should be a JSON dict mapping service names ' 'to definitions.') try: data = json.loads(data) except json.JSONDecodeError: raise CommandError(m) if not isinstance(data, dict): raise CommandError(m) self.add_services(data)
def handle(self, *args, **options): if len(args) != 1: raise CommandError("Invalid number of arguments") location = abspath(args[0].decode('utf8')) try: open(location, 'r') except IOError: raise CommandError("Invalid location") terms = ApprovalTerms(location=location) terms.save() AstakosUser.objects.select_for_update().\ filter(has_signed_terms=True).\ update(has_signed_terms=False, date_signed_terms=None) msg = "Created term id %d" % (terms.id, ) self.stdout.write(msg + '\n')
def handle(self, **options): try: fixed = fix_superusers() count = len(fixed) if count != 0: self.stderr.write("Fixed %s superuser(s).\n" % count) else: self.stderr.write("No superuser needed a fix.\n") except BaseException, e: raise CommandError(e)
def set_ui_visible(self, resource, allow): try: allow = utils.parse_bool(allow) except ValueError: raise CommandError("Expecting a boolean value.") resource.ui_visible = allow if allow and not resource.api_visible: self.stderr.write("Also setting 'api_visible' for consistency.\n") resource.api_visible = True resource.save()
def handle(self, *args, **options): if len(args) != 1: raise CommandError("Please provide a client ID or identifier") ident = args[0] try: try: ident = int(ident) client = Client.objects.get(id=ident) except ValueError: client = Client.objects.get(identifier=ident) except Client.DoesNotExist: raise CommandError("Client does not exist. You may run snf-manage " "oa2-client-list for available client IDs.") client.redirecturl_set.all().delete() client.authorizationcode_set.all().delete() client.token_set.all().delete() client.delete()
def handle(self, *args, **options): if len(args) != 1: raise CommandError("Please provide a volume ID") volume = common.get_resource("volume", args[0]) pprint.pprint_volume(volume, stdout=self.stdout, display_mails=options["displaymail"]) self.stdout.write('\n\n')
def handle_args(self, *args, **options): overdue = options['overdue'] if overdue is not None: try: overdue = int(overdue) except ValueError: raise CommandError("Expecting an integer.") delta = datetime.timedelta(0, overdue) until = datetime.datetime.now() - delta self.filters["issue_datetime__lt"] = until
def handle(self, *args, **options): if len(args) < 2: raise CommandError("Invalid number of arguments") profile = None update = options.get('update') name = args[0].strip() provider = args[1].strip() if Profile.objects.filter(name=name).count(): if update: profile = Profile.objects.get(name=name) else: raise CommandError("Profile with the same name already exists") if not profile: profile = Profile() profile.name = name profile.provider = provider profile.is_exclusive = options.get('exclusive') for policy, value in options.iteritems(): if policy.startswith('policy_') and value is not None: if isinstance(value, basestring) and value[0] in string.digits: value = int(value) if value == 'False' or value == '0': value = False if value == 'True' or value == '1': value = True setattr(profile, policy, value) if update and policy.startswith('unset_'): policy = policy.replace('unset_', '') setattr(profile, policy, None) profile.save() if update: self.stderr.write("Profile updated\n") else: self.stderr.write("Profile stored\n")
def make_policies(limits): policies = {} for (name, member_capacity, project_capacity) in limits: try: member_capacity = units.parse(member_capacity) project_capacity = units.parse(project_capacity) except units.ParseError: m = "Please specify capacity as a decimal integer" raise CommandError(m) policies[name] = {"member_capacity": member_capacity, "project_capacity": project_capacity} return policies
def handle(self, *args, **options): if len(args) != 1: raise CommandError("Please profile name") try: profile = Profile.objects.get(name=args[0]) except Profile.DoesNotExist: raise CommandError("Profile does not exist") kv = OrderedDict([('id', profile.id), ('is active', str(profile.active)), ('name', profile.name), ('is exclusive', profile.is_exclusive), ('policies', profile.policies), ('groups', profile.groups.all()), ('users', profile.users.all())]) utils.pprint_table(self.stdout, [kv.values()], kv.keys(), options["output_format"], vertical=True)