Example #1
0
    def handle(self, *args, **options):
        if len(args) != 1:
            raise CommandError("Please provide a backend ID")

        backend = get_backend(args[0])

        # Ensure fields correspondence with options and Backend model
        credentials_changed = False
        fields = ('clustername', 'port', 'username', 'password')
        for field in fields:
            value = options.get(field)
            if value is not None:
                backend.__setattr__(field, value)
                credentials_changed = True

        if credentials_changed:
                # check credentials, if any of them changed!
                check_backend_credentials(backend.clustername, backend.port,
                                          backend.username, backend.password)
        if options['drained']:
            backend.drained = parse_bool(options['drained'], strict=True)
        if options['offline']:
            backend.offline = parse_bool(options['offline'], strict=True)
        hypervisor = options["hypervisor"]
        if hypervisor:
            backend.hypervisor = hypervisor

        backend.save()
Example #2
0
    def handle(self, *args, **options):
        if len(args) != 1:
            raise CommandError("Please provide a backend ID")

        backend = common.get_resource("backend", args[0], for_update=True)

        # Ensure fields correspondence with options and Backend model
        credentials_changed = False
        fields = ('clustername', 'port', 'username', 'password')
        for field in fields:
            value = options.get(field)
            if value is not None:
                backend.__setattr__(field, value)
                credentials_changed = True

        if credentials_changed:
                # check credentials, if any of them changed!
                common.check_backend_credentials(backend.clustername,
                                                 backend.port,
                                                 backend.username,
                                                 backend.password)
        if options['drained']:
            backend.drained = parse_bool(options['drained'], strict=True)
        if options['offline']:
            backend.offline = parse_bool(options['offline'], strict=True)
        if options['public']:
            backend.public = parse_bool(options['public'], strict=True)
        hypervisor = options["hypervisor"]
        if hypervisor:
            backend.hypervisor = hypervisor

        backend.save()
Example #3
0
    def handle(self, *args, **options):
        if len(args) != 1:
            raise CommandError("Please provide a backend ID")

        backend = get_backend(args[0])

        # Ensure fields correspondence with options and Backend model
        credentials_changed = False
        fields = ("clustername", "port", "username", "password")
        for field in fields:
            value = options.get(field)
            if value is not None:
                backend.__setattr__(field, value)
                credentials_changed = True

        if credentials_changed:
            # check credentials, if any of them changed!
            check_backend_credentials(backend.clustername, backend.port, backend.username, backend.password)
        if options["drained"]:
            backend.drained = parse_bool(options["drained"], strict=True)
        if options["offline"]:
            backend.offline = parse_bool(options["offline"], strict=True)
        hypervisor = options["hypervisor"]
        if hypervisor:
            backend.hypervisor = hypervisor

        backend.save()
Example #4
0
    def handle(self, *args, **options):
        if len(args) != 1:
            raise CommandError("Please provide a server ID")

        server = get_resource("server", args[0], for_update=True)

        new_name = options.get("name", None)
        if new_name is not None:
            old_name = server.name
            server = servers.rename(server, new_name)
            self.stdout.write("Renamed server '%s' from '%s' to '%s'\n" %
                              (server, old_name, new_name))

        suspended = options.get("suspended", None)
        if suspended is not None:
            suspended = parse_bool(suspended)
            server.suspended = suspended
            server.save()
            self.stdout.write("Set server '%s' as suspended=%s\n" %
                              (server, suspended))

        new_owner = options.get('user')
        if new_owner is not None:
            if "@" in new_owner:
                raise CommandError("Invalid user UUID.")
            if new_owner == server.userid:
                self.stdout.write("%s is already server owner.\n" % new_owner)
            else:
                servers.change_owner(server, new_owner)
                self.stdout.write(
                    "WARNING: User quotas should be out of sync now,"
                    " run `snf-manage reconcile-resources-cyclades'"
                    " to review and update them.\n")

        wait = parse_bool(options["wait"])
        new_flavor_id = options.get("flavor")
        if new_flavor_id is not None:
            new_flavor = get_resource("flavor", new_flavor_id)
            old_flavor = server.flavor
            msg = "Resizing server '%s' from flavor '%s' to '%s'.\n"
            self.stdout.write(msg % (server, old_flavor, new_flavor))
            server = servers.resize(server, new_flavor)
            wait_server_task(server, wait, stdout=self.stdout)

        action = options.get("action")
        if action is not None:
            if action == "start":
                server = servers.start(server)
            elif action == "stop":
                server = servers.stop(server)
            elif action == "reboot_hard":
                server = servers.reboot(server, reboot_type="HARD")
            elif action == "reboot_soft":
                server = servers.reboot(server, reboot_type="SOFT")
            else:
                raise CommandError("Unknown action.")
            wait_server_task(server, wait, stdout=self.stdout)
Example #5
0
    def handle(self, *args, **options):
        if len(args) != 1:
            raise CommandError("Please provide a server ID")

        server = get_vm(args[0], for_update=True)

        new_name = options.get("name", None)
        if new_name is not None:
            old_name = server.name
            server = servers.rename(server, new_name)
            self.stdout.write("Renamed server '%s' from '%s' to '%s'\n" %
                              (server, old_name, new_name))

        suspended = options.get("suspended", None)
        if suspended is not None:
            suspended = parse_bool(suspended)
            server.suspended = suspended
            server.save()
            self.stdout.write("Set server '%s' as suspended=%s\n" %
                              (server, suspended))

        new_owner = options.get('owner')
        if new_owner is not None:
            if "@" in new_owner:
                raise CommandError("Invalid owner UUID.")
            old_owner = server.userid
            server.userid = new_owner
            server.save()
            msg = "Changed the owner of server '%s' from '%s' to '%s'.\n"
            self.stdout.write(msg % (server, old_owner, new_owner))

        wait = parse_bool(options["wait"])
        new_flavor_id = options.get("flavor")
        if new_flavor_id is not None:
            new_flavor = get_flavor(new_flavor_id)
            old_flavor = server.flavor
            msg = "Resizing server '%s' from flavor '%s' to '%s'.\n"
            self.stdout.write(msg % (server, old_flavor, new_flavor))
            server = servers.resize(server, new_flavor)
            wait_server_task(server, wait, stdout=self.stdout)

        action = options.get("action")
        if action is not None:
            if action == "start":
                server = servers.start(server)
            elif action == "stop":
                server = servers.stop(server)
            elif action == "reboot_hard":
                server = servers.reboot(server, reboot_type="HARD")
            elif action == "reboot_stof":
                server = servers.reboot(server, reboot_type="SOFT")
            else:
                raise CommandError("Unknown action.")
            wait_server_task(server, wait, stdout=self.stdout)
Example #6
0
    def handle(self, *args, **options):
        if len(args) != 1:
            raise CommandError("Please provide a server ID")

        server = get_resource("server", args[0], for_update=True)

        new_name = options.get("name", None)
        if new_name is not None:
            old_name = server.name
            server = servers.rename(server, new_name)
            self.stdout.write("Renamed server '%s' from '%s' to '%s'\n" %
                              (server, old_name, new_name))

        suspended = options.get("suspended", None)
        if suspended is not None:
            suspended = parse_bool(suspended)
            server.suspended = suspended
            server.save()
            self.stdout.write("Set server '%s' as suspended=%s\n" %
                              (server, suspended))

        new_owner = options.get('user')
        if new_owner is not None:
            if "@" in new_owner:
                raise CommandError("Invalid user UUID.")
            old_owner = server.userid
            server.userid = new_owner
            server.save()
            msg = "Changed the owner of server '%s' from '%s' to '%s'.\n"
            self.stdout.write(msg % (server, old_owner, new_owner))

        wait = parse_bool(options["wait"])
        new_flavor_id = options.get("flavor")
        if new_flavor_id is not None:
            new_flavor = get_resource("flavor", new_flavor_id)
            old_flavor = server.flavor
            msg = "Resizing server '%s' from flavor '%s' to '%s'.\n"
            self.stdout.write(msg % (server, old_flavor, new_flavor))
            server = servers.resize(server, new_flavor)
            wait_server_task(server, wait, stdout=self.stdout)

        action = options.get("action")
        if action is not None:
            if action == "start":
                server = servers.start(server)
            elif action == "stop":
                server = servers.stop(server)
            elif action == "reboot_hard":
                server = servers.reboot(server, reboot_type="HARD")
            elif action == "reboot_stof":
                server = servers.reboot(server, reboot_type="SOFT")
            else:
                raise CommandError("Unknown action.")
            wait_server_task(server, wait, stdout=self.stdout)
Example #7
0
    def handle(self, *args, **options):
        if not args:
            raise CommandError("Please provide a volume ID")

        force = options['force']
        message = "volumes" if len(args) > 1 else "volume"
        self.confirm_deletion(force, message, args)

        for volume_id in args:
            self.stdout.write("\n")
            try:
                volume = common.get_resource("volume", volume_id,
                                             for_update=True)
                volumes.delete(volume)

                wait = parse_bool(options["wait"])
                if volume.machine is not None:
                    volume.machine.task_job_id = volume.backendjobid
                    common.wait_server_task(volume.machine, wait,
                                            stdout=self.stdout)
                else:
                    self.stdout.write("Successfully removed volume %s\n"
                                      % volume)
            except CommandError as e:
                self.stdout.write("Error -- %s\n" % e.message)
Example #8
0
    def handle(self, *args, **options):
        if not args:
            raise CommandError("Please provide a port ID")

        force = options['force']
        message = "ports" if len(args) > 1 else "port"
        self.confirm_deletion(force, message, args)

        for port_id in args:
            self.stdout.write("\n")
            try:
                with transaction.atomic():
                    port = common.get_resource("port",
                                               port_id,
                                               for_update=True)
                    machine = port.machine
                    servers._delete_port(port)

                wait = parse_bool(options["wait"])
                if machine is not None:
                    common.wait_server_task(machine, wait, stdout=self.stdout)
                else:
                    self.stdout.write("Successfully removed port %s\n" % port)
            except CommandError as e:
                self.stdout.write("Error -- %s\n" % e.message)
Example #9
0
    def handle(self, *args, **options):
        if not args:
            raise CommandError("Please provide a port ID")

        force = options['force']
        message = "ports" if len(args) > 1 else "port"
        self.confirm_deletion(force, message, args)

        for port_id in args:
            self.stdout.write("\n")
            try:
                with transaction.atomic():
                    port = common.get_resource(
                        "port", port_id, for_update=True)
                    machine = port.machine
                    servers._delete_port(port)

                wait = parse_bool(options["wait"])
                if machine is not None:
                    common.wait_server_task(machine, wait,
                                            stdout=self.stdout)
                else:
                    self.stdout.write("Successfully removed port %s\n" % port)
            except CommandError as e:
                self.stdout.write("Error -- %s\n" % e.message)
Example #10
0
    def handle(self, *args, **options):
        if not args:
            raise CommandError("Please provide a server ID")

        force = options['force']
        message = "servers" if len(args) > 1 else "server"
        self.confirm_deletion(force, message, args)

        for server_id in args:
            self.stdout.write("\n")
            try:
                server = get_resource("server", server_id)

                self.stdout.write("Trying to remove server '%s' from backend "
                                  "'%s' \n" %
                                  (server.backend_vm_id, server.backend))

                credentials = Credentials("snf-manage", is_admin=True)
                server = servers.destroy(server_id, credentials=credentials)
                jobID = server.task_job_id

                self.stdout.write("Issued OP_INSTANCE_REMOVE with id: %s\n" %
                                  jobID)

                wait = parse_bool(options["wait"])
                wait_server_task(server, wait, self.stdout)
            except (CommandError, faults.BadRequest) as e:
                self.stdout.write("Error -- %s\n" % e.message)
Example #11
0
    def handle(self, *args, **options):
        if not args:
            raise CommandError("Please provide a volume ID")

        force = options['force']
        message = "volumes" if len(args) > 1 else "volume"
        self.confirm_deletion(force, message, args)

        for volume_id in args:
            self.stdout.write("\n")
            try:
                volume = common.get_resource("volume",
                                             volume_id,
                                             for_update=True)
                volumes.delete(volume)

                wait = parse_bool(options["wait"])
                if volume.machine is not None:
                    volume.machine.task_job_id = volume.backendjobid
                    common.wait_server_task(volume.machine,
                                            wait,
                                            stdout=self.stdout)
                else:
                    self.stdout.write("Successfully removed volume %s\n" %
                                      volume)
            except CommandError as e:
                self.stdout.write("Error -- %s\n" % e.message)
Example #12
0
    def handle(self, *args, **options):
        if not args:
            raise CommandError("Please provide a server ID")

        force = options['force']
        message = "servers" if len(args) > 1 else "server"
        self.confirm_deletion(force, message, args)

        for server_id in args:
            self.stdout.write("\n")
            try:
                server = get_resource("server", server_id)

                self.stdout.write("Trying to remove server '%s' from backend "
                                  "'%s' \n" % (server.backend_vm_id,
                                               server.backend))

                credentials = Credentials("snf-manage", is_admin=True)
                server = servers.destroy(server_id, credentials=credentials)
                jobID = server.task_job_id

                self.stdout.write("Issued OP_INSTANCE_REMOVE with id: %s\n" %
                                  jobID)

                wait = parse_bool(options["wait"])
                wait_server_task(server, wait, self.stdout)
            except (CommandError, faults.BadRequest) as e:
                self.stdout.write("Error -- %s\n" % e.message)
Example #13
0
 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()
Example #14
0
 def parse_boolean_option(option, option_str, value, parser):
     if value is not None:
         try:
             value = parse_bool(value)
         except ValueError:
             choices = "True, False"
             raise OptionValueError(
                 "option %s: invalid choice: %r (choose from %s)"
                 % (option, value, choices))
     setattr(parser.values, option.dest, value)
Example #15
0
 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()
Example #16
0
 def parse_boolean_option(option, option_str, value, parser):
     if value is not None:
         try:
             value = parse_bool(value)
         except ValueError:
             choices = "True, False"
             raise OptionValueError(
                 "option %s: invalid choice: %r (choose from %s)" %
                 (option, value, choices))
     setattr(parser.values, option.dest, value)
Example #17
0
    def handle(self, *args, **options):
        if len(args) != 1:
            raise CommandError("Please provide a flavor ID")

        flavor = get_flavor(args[0], for_update=True)

        deleted = options['deleted']

        if deleted:
            deleted = parse_bool(deleted)
            log.info("Marking flavor %s as deleted=%s", flavor, deleted)
            flavor.deleted = deleted
            flavor.save()

        allow_create = options['allow_create']
        if allow_create:
            allow_create = parse_bool(allow_create)
            log.info("Marking flavor %s as allow_create=%s", flavor,
                     allow_create)
            flavor.allow_create = allow_create
            flavor.save()
Example #18
0
    def handle(self, *args, **options):
        if args:
            raise CommandError("Command doesn't accept any arguments")

        name = options['name']
        user_id = options['user_id']
        project = options['project']
        backend_id = options['backend_id']
        image_id = options['image_id']
        flavor_id = options['flavor_id']
        password = options['password']
        volumes = options['volumes']
        helper_vm = options['helper_vm']

        if not name:
            raise CommandError("name is mandatory")
        if not user_id:
            raise CommandError("user is mandatory")
        if not project:
            project = user_id
        if not password:
            raise CommandError("password is mandatory")
        if not flavor_id:
            raise CommandError("flavor is mandatory")
        if not image_id and not volumes:
            raise CommandError("image is mandatory")

        flavor = common.get_resource("flavor", flavor_id)
        if image_id is not None:
            common.get_image(image_id, user_id)

        if backend_id:
            backend = common.get_resource("backend", backend_id)
        else:
            backend = None

        connection_list = parse_connections(options["connections"])
        volumes_list = parse_volumes(volumes)
        credentials = Credentials(user_id)
        server = servers.create(credentials,
                                name,
                                password,
                                flavor,
                                image_id,
                                networks=connection_list,
                                volumes=volumes_list,
                                use_backend=backend,
                                helper=helper_vm,
                                project=project)
        pprint.pprint_server(server, stdout=self.stdout)

        wait = parse_bool(options["wait"])
        common.wait_server_task(server, wait, self.stdout)
Example #19
0
    def handle(self, *args, **options):
        if len(args) != 1:
            raise CommandError("Please provide a flavor ID")

        flavor = get_resource("flavor", args[0], for_update=True)

        deleted = options['deleted']

        if deleted:
            deleted = parse_bool(deleted)
            log.info("Marking flavor %s as deleted=%s", flavor, deleted)
            flavor.deleted = deleted
            flavor.save()

        allow_create = options['allow_create']
        if allow_create:
            allow_create = parse_bool(allow_create)
            log.info("Marking flavor %s as allow_create=%s", flavor,
                     allow_create)
            flavor.allow_create = allow_create
            flavor.save()
Example #20
0
    def handle(self, *args, **options):
        if options["backend"] is not None:
            backend = get_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)
Example #21
0
    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)
Example #22
0
    def set_api_visible(self, resource_name, allow):
        if resource_name is None:
            raise CommandError("Please provide a resource name.")

        try:
            allow = utils.parse_bool(allow)
        except ValueError:
            raise CommandError("Expecting a boolean value.")
        resource = self.get_resource(resource_name)
        resource.api_visible = allow
        if not allow and resource.ui_visible:
            self.stderr.write("Also resetting 'ui_visible' for consistency.\n")
            resource.ui_visible = False
        resource.save()
Example #23
0
    def handle(self, *args, **options):
        if options["backend"] is not None:
            backend = get_backend(options["backend"])
        else:
            backend = None

        clusters = parse_bool(options["clusters"])
        servers = parse_bool(options["servers"])
        resources = parse_bool(options["resources"])
        networks = parse_bool(options["networks"])
        images = parse_bool(options["images"])

        stats = statistics.get_cyclades_stats(backend, clusters, servers,
                                              resources, networks, images)

        output_format = options["output_format"]
        if output_format == "json":
            self.stdout.write(json.dumps(stats, indent=4) + "\n")
        elif output_format == "pretty":
            pretty_print_stats(stats, self.stdout)
        else:
            raise CommandError("Output format '%s' not supported." %
                               output_format)
Example #24
0
    def handle(self, *args, **options):

        if len(args) != 1:
            raise CommandError("Please provide a volume type ID")

        vtype = get_resource("volume-type", args[0], for_update=True)

        # Keep a list with spec keys that are added. If one of these keys
        # appears in the list to be deleted, we should raise an error
        added_keys = []
        spec_add = options.get('spec_add')
        if spec_add:
            spec_regex = re.compile(r'^(?P<key>.+?)=(?P<value>.+)$')

            specs = spec_add.split(',')
            for spec in specs:
                match = spec_regex.match(spec)
                if match is None:
                    raise CommandError("Incorrect spec format. Expected: "
                                       " <key>=<value> ,found: \'%s\' " % spec)
                k, v = match.group('key'), match.group('value')
                spec, _ = vtype.specs.get_or_create(key=k)
                spec.value = v
                spec.save()
                added_keys.append(k)

        spec_delete = options.get('spec_delete')
        if spec_delete:
            spec_keys = spec_delete.split(',')
            for key in spec_keys:
                if key in added_keys:
                    raise CommandError("Cannot add and delete key %s at the "
                                       "same time. If that was the intended "
                                       "action, consider adding first and then"
                                       " deleting it" % key)
                spec = vtype.specs.filter(key=key)
                if not spec:
                    raise CommandError("Spec with key \'%s\' does not exist" %
                                       key)
                spec.delete()

        deleted = options['deleted']
        if deleted:
            deleted = parse_bool(deleted)
            self.stdout.write("Marking volume type '%s' and all related"
                              " flavors as deleted=%s\n" % (vtype.id, deleted))
            vtype.deleted = deleted
            vtype.save()
            vtype.flavors.update(deleted=deleted)
Example #25
0
    def handle(self, *args, **options):
        if len(args) != 1:
            raise CommandError("Please provide a volume type ID")

        vtype = get_resource("volume-type", args[0], for_update=True)

        deleted = options['deleted']

        if deleted:
            deleted = parse_bool(deleted)
            self.stdout.write("Marking volume type '%s' and all related"
                              " flavors as deleted=%s\n" % (vtype.id, deleted))
            vtype.deleted = deleted
            vtype.save()
            vtype.flavors.update(deleted=deleted)
Example #26
0
    def handle(self, *args, **options):
        if args:
            raise CommandError("Command doesn't accept any arguments")

        name = options['name']
        user_id = options['user_id']
        project = options['project']
        backend_id = options['backend_id']
        image_id = options['image_id']
        flavor_id = options['flavor_id']
        password = options['password']
        volumes = options['volumes']
        helper_vm = options['helper_vm']

        if not name:
            raise CommandError("name is mandatory")
        if not user_id:
            raise CommandError("user is mandatory")
        if not project:
            project = user_id
        if not password:
            raise CommandError("password is mandatory")
        if not flavor_id:
            raise CommandError("flavor is mandatory")
        if not image_id and not volumes:
            raise CommandError("image is mandatory")

        flavor = common.get_resource("flavor", flavor_id)
        if image_id is not None:
            common.get_image(image_id, user_id)

        if backend_id:
            backend = common.get_resource("backend", backend_id)
        else:
            backend = None

        connection_list = parse_connections(options["connections"])
        volumes_list = parse_volumes(volumes)
        credentials = Credentials(user_id)
        server = servers.create(credentials, name, password, flavor, image_id,
                                networks=connection_list,
                                volumes=volumes_list,
                                use_backend=backend, helper=helper_vm,
                                project=project)
        pprint.pprint_server(server, stdout=self.stdout)

        wait = parse_bool(options["wait"])
        common.wait_server_task(server, wait, self.stdout)
Example #27
0
    def handle(self, *args, **options):
        output_format = options["output_format"]
        displayname = bool(options["displayname"])
        unit_style = options["unit_style"]
        common.check_style(unit_style)

        filteropt = options["filter_by"]
        if filteropt is not None:
            filters = filteropt.split(",")
        else:
            filters = []

        QHQ, INITQ = Q(), Q()
        for flt in filters:
            q = filtering.make_query(flt, self.QHFLT)
            if q is not None:
                QHQ &= q
            q = filtering.make_query(flt, self.INITFLT)
            if q is not None:
                INITQ &= q

        overlimit = bool(options["overlimit"])
        if overlimit:
            QHQ &= Q(usage_max__gt=F("limit"))

        with_custom = options["with_custom"]
        if with_custom is not None:
            qeq = Q(capacity=F("resource__uplimit"))
            try:
                INITQ &= ~qeq if utils.parse_bool(with_custom) else qeq
            except ValueError as e:
                raise CommandError(e)

        users = AstakosUser.objects.accepted()
        qh_quotas, astakos_i = list_user_quotas(
            users, qhflt=QHQ, initflt=INITQ)

        if displayname:
            info = {}
            for user in users:
                info[user.uuid] = user.email
        else:
            info = None

        print_data, labels = common.show_quotas(
            qh_quotas, astakos_i, info, style=unit_style)
        utils.pprint_table(self.stdout, print_data, labels, output_format)
Example #28
0
    def handle(self, *args, **options):
        if len(args) != 1:
            raise CommandError("Please provide a volume ID")

        volume = common.get_resource("volume", args[0], for_update=True)

        name = options.get("name")
        description = options.get("description")
        delete_on_termination = options.get("delete_on_termination")
        if delete_on_termination is not None:
            delete_on_termination = parse_bool(delete_on_termination)

        volume = volumes.update(volume, name, description,
                                delete_on_termination)

        pprint.pprint_volume(volume, stdout=self.stdout)
        self.stdout.write('\n\n')
Example #29
0
    def handle(self, *args, **options):

        name = options.get('name')
        location = options.get('location')
        location_type = options.get('location_type')
        os_family = options.get('os_family')
        os = options.get('os')
        target_os_family = options.get('target_os_family')
        target_os = options.get('target_os')
        default = options.get('default')

        if default is not None:
            default = parse_bool(default, strict=True)
            if default and RescueImage.objects.filter(
                    is_default=True).count() > 0:
                raise CommandError('There is already a default image')

        if location is None:
            raise CommandError('Location is required')

        if location_type is None:
            if re.match(url_matcher, location):
                location_type = RescueImage.FILETYPE_HTTP
            else:
                location_type = RescueImage.FILETYPE_FILE

        if location_type == RescueImage.FILETYPE_HTTP:
            r = requests.head(location, allow_redirects=True)
            if r.status_code != 200:
                raise CommandError('Link provided for image file returned %d'
                                   'status code' % r.status_code)

        if name is None:
            name = 'rescue-image-%s' % str(uuid.uuid4())

        rescue_image = RescueImage(name=name,
                                   location=location,
                                   location_type=location_type,
                                   os_family=os_family,
                                   os=os,
                                   target_os_family=target_os_family,
                                   target_os=target_os,
                                   is_default=default,
                                   deleted=False)

        rescue_image.save()
Example #30
0
    def handle(self, *args, **options):
        if len(args) != 1:
            raise CommandError("Please provide a volume ID")

        volume = common.get_resource("volume", args[0], for_update=True)

        name = options.get("name")
        description = options.get("description")
        delete_on_termination = options.get("delete_on_termination")
        if delete_on_termination is not None:
            delete_on_termination = parse_bool(delete_on_termination)

        volume = volumes.update(volume, name, description,
                                delete_on_termination)

        pprint.pprint_volume(volume, stdout=self.stdout)
        self.stdout.write('\n\n')
Example #31
0
    def handle(self, *args, **options):
        if len(args) != 1:
            raise CommandError("Please provide a network ID.")

        network = common.get_resource("network", args[0])
        display_mails = options["displaymail"]

        pprint.pprint_network(network, display_mails=display_mails,
                              stdout=self.stdout)
        self.stdout.write("\n\n")
        pprint.pprint_network_subnets(network, stdout=self.stdout)
        self.stdout.write("\n\n")
        pprint.pprint_network_backends(network, stdout=self.stdout)
        backends = parse_bool(options["backends"])
        if backends:
            self.stdout.write("\n\n")
            pprint.pprint_network_in_ganeti(network, stdout=self.stdout)
Example #32
0
    def handle(self, **options):
        backend_id = options['backend-id']
        if backend_id:
            backends = [get_resource("backend", backend_id)]
        else:
            backends = reconciliation.get_online_backends()

        parallel = parse_bool(options["parallel"])
        if parallel and len(backends) > 1:
            cmd = sys.argv
            processes = []
            for backend in backends:
                p = subprocess.Popen(cmd + ["--backend-id=%s" % backend.id])
                processes.append(p)
            for p in processes:
                p.wait()
            return

        verbosity = int(options["verbosity"])

        logger = logging.getLogger("reconcile-servers")
        logger.propagate = 0

        formatter = logging.Formatter("%(message)s")
        log_handler = logging.StreamHandler()
        log_handler.setFormatter(formatter)
        if verbosity == 2:
            formatter =\
                logging.Formatter("%(asctime)s [%(process)d]: %(message)s")
            log_handler.setFormatter(formatter)
            logger.setLevel(logging.DEBUG)
        elif verbosity == 1:
            logger.setLevel(logging.INFO)
        else:
            logger.setLevel(logging.WARNING)

        logger.addHandler(log_handler)

        self._process_args(options)

        for backend in backends:
            r = reconciliation.BackendReconciler(backend=backend,
                                                 logger=logger,
                                                 options=options)
            r.reconcile()
Example #33
0
    def handle(self, **options):
        backend_id = options['backend-id']
        if backend_id:
            backends = [get_resource("backend", backend_id)]
        else:
            backends = reconciliation.get_online_backends()

        parallel = parse_bool(options["parallel"])
        if parallel and len(backends) > 1:
            cmd = sys.argv
            processes = []
            for backend in backends:
                p = subprocess.Popen(cmd + ["--backend-id=%s" % backend.id])
                processes.append(p)
            for p in processes:
                p.wait()
            return

        verbosity = int(options["verbosity"])

        logger = logging.getLogger("reconcile-servers")
        logger.propagate = 0

        formatter = logging.Formatter("%(message)s")
        log_handler = logging.StreamHandler()
        log_handler.setFormatter(formatter)
        if verbosity == 2:
            formatter =\
                logging.Formatter("%(asctime)s [%(process)d]: %(message)s")
            log_handler.setFormatter(formatter)
            logger.setLevel(logging.DEBUG)
        elif verbosity == 1:
            logger.setLevel(logging.INFO)
        else:
            logger.setLevel(logging.WARNING)

        logger.addHandler(log_handler)

        self._process_args(options)

        for backend in backends:
            r = reconciliation.BackendReconciler(backend=backend,
                                                 logger=logger,
                                                 options=options)
            r.reconcile()
Example #34
0
    def handle(self, *args, **options):
        if len(args) != 1:
            raise CommandError("Please provide a network ID.")

        network = common.get_resource("network", args[0])
        display_mails = options["displaymail"]

        pprint.pprint_network(network,
                              display_mails=display_mails,
                              stdout=self.stdout)
        self.stdout.write("\n\n")
        pprint.pprint_network_subnets(network, stdout=self.stdout)
        self.stdout.write("\n\n")
        pprint.pprint_network_backends(network, stdout=self.stdout)
        backends = parse_bool(options["backends"])
        if backends:
            self.stdout.write("\n\n")
            pprint.pprint_network_in_ganeti(network, stdout=self.stdout)
Example #35
0
    def handle(self, *args, **options):
        if args:
            raise CommandError("Command doesn't accept any arguments")

        network_id = options["network_id"]
        cidr = options["cidr"]

        if not network_id:
            raise CommandError("network is mandatory")
        if not cidr:
            raise CommandError("cidr is mandatory")

        user_id = common.get_resource("network", network_id).userid
        name = options["name"] or ""
        allocation_pools = options["allocation_pools"]
        ipversion = options["ipversion"] or 4
        ipversion = int(ipversion)
        gateway = options["gateway"]
        dhcp = parse_bool(options["dhcp"])
        dns = options["dns"]
        host_routes = options["host_routes"]

        alloc = None
        if allocation_pools is not None:
            alloc = subnets.parse_allocation_pools(allocation_pools)
            alloc.sort()

        sub = subnets.create_subnet(name=name,
                                    network_id=network_id,
                                    cidr=cidr,
                                    allocation_pools=alloc,
                                    gateway=gateway,
                                    ipversion=ipversion,
                                    dhcp=dhcp,
                                    slaac=dhcp,
                                    dns_nameservers=dns,
                                    host_routes=host_routes,
                                    user_id=user_id)

        pprint.pprint_subnet_in_db(sub, stdout=self.stdout)
        self.stdout.write("\n\n")
        pprint.pprint_ippool(sub, stdout=self.stdout)
Example #36
0
    def handle(self, *args, **options):
        if args:
            raise CommandError("Command doesn't accept any arguments")

        network_id = options["network_id"]
        cidr = options["cidr"]

        if not network_id:
            raise CommandError("network-id is mandatory")
        if not cidr:
            raise CommandError("cidr is mandatory")

        user_id = common.get_network(network_id).userid
        name = options["name"] or ""
        allocation_pools = options["allocation_pools"]
        ipversion = options["ipversion"] or 4
        ipversion = int(ipversion)
        gateway = options["gateway"]
        dhcp = parse_bool(options["dhcp"])
        dns = options["dns"]
        host_routes = options["host_routes"]

        alloc = None
        if allocation_pools is not None:
            alloc = subnets.parse_allocation_pools(allocation_pools)
            alloc.sort()

        sub = subnets.create_subnet(name=name,
                                    network_id=network_id,
                                    cidr=cidr,
                                    allocation_pools=alloc,
                                    gateway=gateway,
                                    ipversion=ipversion,
                                    dhcp=dhcp,
                                    slaac=dhcp,
                                    dns_nameservers=dns,
                                    host_routes=host_routes,
                                    user_id=user_id)

        pprint.pprint_subnet_in_db(sub, stdout=self.stdout)
        self.stdout.write("\n\n")
        pprint.pprint_ippool(sub, stdout=self.stdout)
Example #37
0
    def handle(self, *args, **options):
        if len(args) > 0:
            raise CommandError("Command takes no arguments")

        clustername = options['clustername']
        port = options['port']
        username = options['username']
        password = options['password']
        public = parse_bool(options['public'], strict=True)

        if not (clustername and username and password):
            raise CommandError("Clustername, user and pass must be supplied")

        # Ensure correctness of credentials
        if options['check']:
            check_backend_credentials(clustername, port, username, password)

        self.create_backend(clustername, port, username, password, public,
                            hypervisor=options["hypervisor"],
                            initialize=options["init"])
Example #38
0
    def handle(self, *args, **options):
        if args:
            raise CommandError("Command doesn't accept any arguments")

        name = options['name']
        user_id = options['user_id']
        backend_id = options['backend_id']
        image_id = options['image_id']
        flavor_id = options['flavor_id']
        password = options['password']

        if not name:
            raise CommandError("name is mandatory")
        if not user_id:
            raise CommandError("user-id is mandatory")
        if not password:
            raise CommandError("password is mandatory")
        if not flavor_id:
            raise CommandError("flavor-id is mandatory")
        if not image_id:
            raise CommandError("image-id is mandatory")

        flavor = common.get_flavor(flavor_id)
        image = common.get_image(image_id, user_id)
        if backend_id:
            backend = common.get_backend(backend_id)
        else:
            backend = None

        connection_list = parse_connections(options["connections"])
        server = servers.create(user_id,
                                name,
                                password,
                                flavor,
                                image,
                                networks=connection_list,
                                use_backend=backend)
        pprint.pprint_server(server, stdout=self.stdout)

        wait = parse_bool(options["wait"])
        common.wait_server_task(server, wait, self.stdout)
Example #39
0
    def handle(self, *args, **options):
        if len(args) != 1:
            raise CommandError("Please provide a volume ID")

        credentials = Credentials("snf_manage", is_admin=True)

        volume = common.get_resource("volume", args[0])

        name = options.get("name")
        description = options.get("description")
        delete_on_termination = options.get("delete_on_termination")
        if delete_on_termination is not None:
            delete_on_termination = parse_bool(delete_on_termination)

        volume = volumes.update(volume.id, name=name,
                                description=description,
                                delete_on_termination=delete_on_termination,
                                credentials=credentials)

        pprint.pprint_volume(volume, stdout=self.stdout)
        self.stdout.write('\n\n')
Example #40
0
    def handle(self, *args, **options):
        if not args:
            raise CommandError("Please provide a volume ID")

        server_id = options.get("server_id")
        wait = parse_bool(options["wait"])

        credentials = Credentials("snf-manage", is_admin=True)
        if not server_id:
            raise CommandError("Please provide a server ID")

        for volume_id in args:
            try:
                volume = volumes.attach(server_id, volume_id, credentials)

                if volume.machine is None:
                    volume.machine.task_job_id = volume.backendjobid
                    common.wait_server_task(volume.machine, wait,
                                            stdout=self.stdout)
                else:
                    self.stdout.write("Successfully attached volume %s\n"
                                      % volume)
            except CommandError as e:
                self.stdout.write("Error -- %s\n" % e.message)
Example #41
0
    def handle(self, *args, **options):
        if not args:
            raise CommandError("Please provide a volume ID")

        force = options['force']
        message = "volumes" if len(args) > 1 else "volume"
        self.confirm_detachment(force, message, args)
        credentials = Credentials("snf-manage", is_admin=True)

        for volume_id in args:
            self.stdout.write("\n")
            try:
                volume = volumes.detach(volume_id, credentials)

                wait = parse_bool(options["wait"])
                if volume.machine is not None:
                    volume.machine.task_job_id = volume.backendjobid
                    common.wait_server_task(volume.machine, wait,
                                            stdout=self.stdout)
                else:
                    self.stdout.write("Successfully detached volume %s\n"
                                      % volume)
            except CommandError as e:
                self.stdout.write("Error -- %s\n" % e.message)
Example #42
0
    def handle(self, *args, **options):
        if not args:
            raise CommandError("Please provide a volume ID")

        server_id = options.get("server_id")
        wait = parse_bool(options["wait"])

        if not server_id:
            raise CommandError("Please provide a server ID")

        for volume_id in args:
            try:
                volume = volumes.attach(server_id, volume_id)

                if volume.machine is None:
                    volume.machine.task_job_id = volume.backendjobid
                    common.wait_server_task(volume.machine,
                                            wait,
                                            stdout=self.stdout)
                else:
                    self.stdout.write("Successfully attached volume %s\n" %
                                      volume)
            except CommandError as e:
                self.stdout.write("Error -- %s\n" % e.message)
Example #43
0
    def handle(self, *args, **options):
        if len(args) > 0:
            raise CommandError("Command takes no arguments")

        clustername = options['clustername']
        port = options['port']
        username = options['username']
        password = options['password']
        public = parse_bool(options['public'], strict=True)

        if not (clustername and username and password):
            raise CommandError("Clustername, user and pass must be supplied")

        # Ensure correctness of credentials
        if options['check']:
            check_backend_credentials(clustername, port, username, password)

        self.create_backend(clustername,
                            port,
                            username,
                            password,
                            public,
                            hypervisor=options["hypervisor"],
                            initialize=options["init"])
Example #44
0
    def handle(self, *args, **options):
        if args:
            raise CommandError("Command doesn't accept any arguments")

        name = options["name"]
        user_id = options["user_id"]
        network_id = options["network_id"]
        server_id = options["server_id"]
        #router_id = options["router_id"]
        router_id = None
        # assume giving security groups comma separated
        security_group_ids = options["security-groups"]
        wait = parse_bool(options["wait"])

        if not name:
            name = ""

        if not network_id:
            raise CommandError("Please specify a 'network'")

        vm = None
        owner = None
        if server_id:
            owner = "vm"
            vm = common.get_resource("server", server_id)
            #if vm.router:
            #    raise CommandError("Server '%s' does not exist." % server_id)
        elif router_id:
            owner = "router"
            vm = common.get_resource("server", router_id)
            if not vm.router:
                raise CommandError("Router '%s' does not exist." % router_id)

        if user_id is None:
            if vm is not None:
                user_id = vm.userid
            else:
                raise CommandError("Please specify the owner of the port.")

        # Get either floating IP or fixed ip address
        ipaddress = None
        floating_ip_id = options["floating_ip_id"]
        ipv4_address = options["ipv4_address"]
        if floating_ip_id:
            ipaddress = common.get_resource("floating-ip", floating_ip_id)
            address = ipaddress.address
            if ipv4_address is not None and address != ipv4_address:
                raise CommandError("Floating IP address '%s' is different from"
                                   " specified address '%s'" %
                                   (address, ipv4_address))
        else:
            address = ipv4_address

        # validate security groups
        sg_list = []
        if security_group_ids:
            security_group_ids = security_group_ids.split(",")
            for gid in security_group_ids:
                sg = util.get_security_group(int(gid))
                sg_list.append(sg)

        credentials = Credentials(user_id)
        new_port = servers.create_port(credentials,
                                       network_id,
                                       machine=vm.id,
                                       name=name,
                                       address=address,
                                       security_groups=sg_list,
                                       device_owner=owner)
        self.stdout.write("Created port '%s' in DB:\n" % new_port)
        pprint.pprint_port(new_port, stdout=self.stdout)
        pprint.pprint_port_ips(new_port, stdout=self.stdout)
        self.stdout.write("\n")
        if vm is not None:
            common.wait_server_task(new_port.machine, wait, stdout=self.stdout)
Example #45
0
    def handle(self, *args, **options):
        if len(args) != 4:
            raise CommandError("Invalid number of arguments")

        cpus = args[0].split(',')
        rams = args[1].split(',')
        disks = args[2].split(',')
        public = parse_bool(options['public'], strict=True)

        for i, r in enumerate(rams):
            value = int(r)
            if value % 4:
                value += 4 - value % 4
                log.warning("Rounding up RAM size: %s -> %s", r, value)

            rams[i] = value

        volume_types = []
        volume_type_ids = args[3].split(',')
        for vol_t_id in volume_type_ids:
            try:
                vol_t_id = int(vol_t_id)
                volume_types.append(
                    VolumeType.objects.get(id=vol_t_id, deleted=False))
            except ValueError:
                raise CommandError("Invalid volume type ID: '%s'" % vol_t_id)
            except (VolumeType.DoesNotExist, ValueError):
                raise CommandError("Volume type with ID '%s' does not exist."
                                   " Use 'snf-manage volume-type-list' to find"
                                   " out available volume types." % vol_t_id)

        flavors = []
        for cpu, ram, disk, volume_type in product(cpus, rams, disks,
                                                   volume_types):
            try:
                flavors.append((int(cpu), ram, int(disk), volume_type))
            except ValueError:
                raise CommandError("Invalid values")

        for cpu, ram, disk, volume_type in flavors:
            if options["dry_run"]:
                flavor = Flavor(cpu=cpu,
                                ram=ram,
                                disk=disk,
                                volume_type=volume_type,
                                public=public)
                self.stdout.write("Creating flavor '%s'\n" % (flavor.name, ))
            else:
                specs = options.get('specs')
                flavor, created = \
                    Flavor.objects.get_or_create(cpu=cpu, ram=ram, disk=disk,
                                                 volume_type=volume_type)
                if created:
                    self.stdout.write("Created flavor '%s'\n" %
                                      (flavor.name, ))

                    flavor.public = public
                    flavor.save()

                    if specs:
                        spec_regex = re.compile(r'(?P<key>.+?)=(?P<value>.+)$')
                        specs = specs.split(',')
                        for spec in specs:
                            match = spec_regex.match(spec)
                            if match is None:
                                raise CommandError("Incorrect spec format. "
                                                   "Expected <key>=<value>."
                                                   " found: \'%s\'" % spec)
                            k, v = match.group('key'), match.group('value')
                            spec = flavor.specs.create(key=k)
                            spec.value = v
                            spec.save()
                else:
                    self.stdout.write("Flavor '%s' already exists\n" %
                                      flavor.name)
                    if flavor.deleted:
                        msg = "Flavor '%s' is marked as deleted." \
                              " Use 'snf-manage flavor-modify' to" \
                              " restore this flavor\n" \
                              % flavor.name
                        self.stdout.write(msg)
                    elif flavor.public != public:
                        status = 'public' if public else 'private'
                        msg = "Flavor '%s' is not %s." \
                              " Use 'snf-manage flavor-modify' to" \
                              " make this flavor %s\n" \
                              % (flavor.name, status, status)
                        self.stdout.write(msg)

                    if specs:
                        msg = "In order to add/update specs to flavor %s, "\
                              "use 'snf-manage flavor-modify %s "\
                              "--spec-add %s'"\
                              % (flavor.name, flavor.id, specs)
                        self.stdout.write(msg)
Example #46
0
    def handle(self, *args, **options):

        if len(args) != 1:
            raise CommandError("Please provide a rescue image ID")

        image_id = int(args[0])
        try:
            rescue_image = RescueImage.objects.get(id=image_id)
        except ObjectDoesNotExist:
            raise CommandError("Could not find an active image with id %d" %
                               image_id)

        name = options.get('name')
        location = options.get('location')
        location_type = options.get('location_type')
        os_family = options.get('os_family')
        os = options.get('os')
        target_os_family = options.get('target_os_family')
        target_os = options.get('target_os')
        default = options.get('default')
        deleted = options.get('deleted')

        # If the image is currently in use, it should not be available
        # for modification
        if (location is not None or location_type is not None) and len(
                util.get_vms_using_rescue_image(rescue_image)) > 0:
            raise CommandError("1 or more VMs are currently using "
                               "image %s" % rescue_image.name)

        if location_type is not None:
            rescue_image.location_type = location_type

        if location is not None:
            rescue_image.location = location
            if location_type is None:
                if re.match(url_matcher, location):
                    rescue_image.location_type = RescueImage.FILETYPE_HTTP
                else:
                    rescue_image.location_type = RescueImage.FILETYPE_FILE

        if rescue_image.location_type == RescueImage.FILETYPE_HTTP:
            r = requests.head(rescue_image.location, allow_redirects=True)
            if r.status_code != 200:
                raise CommandError('Link provided for image file '
                                   'returned %d status code' % r.status_code)

        if name is not None:
            rescue_image.name = name

        if os_family is not None:
            rescue_image.os_family = os_family

        if os is not None:
            rescue_image.os = os

        if target_os_family is not None:
            rescue_image.target_os_family = target_os_family

        if target_os is not None:
            rescue_image.target_os = target_os

        if default is not None:
            default = parse_bool(options.get('default'), strict=True)
            if default is True:
                default_image = RescueImage.objects.filter(
                    deleted=False, is_default=True).first()
                if default_image is not None:
                    log.info('There is already a default image with id %d, '
                             'will make image with id %d default instead' %
                             (default_image.id, rescue_image.id))
                    default_image.is_default = False
                    default_image.save()
            elif rescue_image.is_default:
                raise CommandError('Image %d is marked as default and '
                                   'and therefore can not be unmarked' %
                                   rescue_image.id)

            rescue_image.is_default = default

        if deleted is not None:
            deleted = parse_bool(options.get('deleted'), strict=True)
            rescue_image.deleted = deleted

        rescue_image.save()
Example #47
0
    def handle(self, *args, **options):
        if args:
            raise CommandError("Command doesn't accept any arguments")

        name = options["name"]
        user_id = options["user_id"]
        network_id = options["network_id"]
        server_id = options["server_id"]
        #router_id = options["router_id"]
        router_id = None
        # assume giving security groups comma separated
        security_group_ids = options["security-groups"]
        wait = parse_bool(options["wait"])

        if not name:
            name = ""

        if not network_id:
            raise CommandError("Please specify a 'network'")

        vm = None
        owner = None
        if server_id:
            owner = "vm"
            vm = common.get_resource("server", server_id)
            #if vm.router:
            #    raise CommandError("Server '%s' does not exist." % server_id)
        elif router_id:
            owner = "router"
            vm = common.get_resource("server", router_id)
            if not vm.router:
                raise CommandError("Router '%s' does not exist." % router_id)

        if user_id is None:
            if vm is not None:
                user_id = vm.userid
            else:
                raise CommandError("Please specify the owner of the port.")

        # Get either floating IP or fixed ip address
        ipaddress = None
        floating_ip_id = options["floating_ip_id"]
        ipv4_address = options["ipv4_address"]
        if floating_ip_id:
            ipaddress = common.get_resource("floating-ip", floating_ip_id)
            address = ipaddress.address
            if ipv4_address is not None and address != ipv4_address:
                raise CommandError("Floating IP address '%s' is different from"
                                   " specified address '%s'" %
                                   (address, ipv4_address))
        else:
            address = ipv4_address

        # validate security groups
        sg_list = []
        if security_group_ids:
            security_group_ids = security_group_ids.split(",")
            for gid in security_group_ids:
                sg = util.get_security_group(int(gid))
                sg_list.append(sg)

        credentials = Credentials(user_id)
        new_port = servers.create_port(credentials, network_id, machine=vm.id,
                                       name=name,
                                       address=address,
                                       security_groups=sg_list,
                                       device_owner=owner)
        self.stdout.write("Created port '%s' in DB:\n" % new_port)
        pprint.pprint_port(new_port, stdout=self.stdout)
        pprint.pprint_port_ips(new_port, stdout=self.stdout)
        self.stdout.write("\n")
        if vm is not None:
            common.wait_server_task(new_port.machine, wait, stdout=self.stdout)
Example #48
0
    def handle(self, *args, **options):
        if len(args) != 4:
            raise CommandError("Invalid number of arguments")

        cpus = args[0].split(',')
        rams = args[1].split(',')
        disks = args[2].split(',')
        public = parse_bool(options['public'], strict=True)

        for i, r in enumerate(rams):
            value = int(r)
            if value % 4:
                value += 4 - value % 4
                log.warning("Rounding up RAM size: %s -> %s", r, value)

            rams[i] = value

        volume_types = []
        volume_type_ids = args[3].split(',')
        for vol_t_id in volume_type_ids:
            try:
                vol_t_id = int(vol_t_id)
                volume_types.append(VolumeType.objects.get(id=vol_t_id,
                                                           deleted=False))
            except ValueError:
                raise CommandError("Invalid volume type ID: '%s'" % vol_t_id)
            except (VolumeType.DoesNotExist, ValueError):
                raise CommandError("Volume type with ID '%s' does not exist."
                                   " Use 'snf-manage volume-type-list' to find"
                                   " out available volume types." % vol_t_id)

        flavors = []
        for cpu, ram, disk, volume_type in product(cpus, rams, disks,
                                                   volume_types):
            try:
                flavors.append((int(cpu), ram, int(disk), volume_type))
            except ValueError:
                raise CommandError("Invalid values")

        for cpu, ram, disk, volume_type in flavors:
            if options["dry_run"]:
                flavor = Flavor(cpu=cpu, ram=ram, disk=disk,
                                volume_type=volume_type, public=public)
                self.stdout.write("Creating flavor '%s'\n" % (flavor.name,))
            else:
                specs = options.get('specs')
                flavor, created = \
                    Flavor.objects.get_or_create(cpu=cpu, ram=ram, disk=disk,
                                                 volume_type=volume_type)
                if created:
                    self.stdout.write("Created flavor '%s'\n" % (flavor.name,))

                    flavor.public = public
                    flavor.save()

                    if specs:
                        spec_regex = re.compile(r'(?P<key>.+?)=(?P<value>.+)$')
                        specs = specs.split(',')
                        for spec in specs:
                            match = spec_regex.match(spec)
                            if match is None:
                                raise CommandError("Incorrect spec format. "
                                                   "Expected <key>=<value>."
                                                   " found: \'%s\'" % spec)
                            k, v = match.group('key'), match.group('value')
                            spec = flavor.specs.create(key=k)
                            spec.value = v
                            spec.save()
                else:
                    self.stdout.write("Flavor '%s' already exists\n"
                                      % flavor.name)
                    if flavor.deleted:
                        msg = "Flavor '%s' is marked as deleted." \
                              " Use 'snf-manage flavor-modify' to" \
                              " restore this flavor\n" \
                              % flavor.name
                        self.stdout.write(msg)
                    elif flavor.public != public:
                        status = 'public' if public else 'private'
                        msg = "Flavor '%s' is not %s." \
                              " Use 'snf-manage flavor-modify' to" \
                              " make this flavor %s\n" \
                              % (flavor.name, status, status)
                        self.stdout.write(msg)

                    if specs:
                        msg = "In order to add/update specs to flavor %s, "\
                              "use 'snf-manage flavor-modify %s "\
                              "--spec-add %s'"\
                              % (flavor.name, flavor.id, specs)
                        self.stdout.write(msg)
Example #49
0
    def handle(self, *args, **options):
        if args:
            raise CommandError("Command doesn't accept any arguments")

        name = options['name']
        subnet = options['subnet']
        gateway = options['gateway']
        subnet6 = options['subnet6']
        gateway6 = options['gateway6']
        public = options['public']
        flavor = options['flavor']
        mode = options['mode']
        link = options['link']
        mac_prefix = options['mac_prefix']
        tags = options['tags']
        userid = options["user"]
        project = options['project']
        allocation_pools = options["allocation_pools"]
        floating_ip_pool = parse_bool(options["floating_ip_pool"])
        dhcp = parse_bool(options["dhcp"])
        drained = parse_bool(options["drained"])

        if name is None:
            name = ""
        if flavor is None:
            raise CommandError("flavor is required")

        if ((subnet is None) and (subnet6 is None)) and dhcp is not False:
            raise CommandError("Cannot set DHCP without subnet or subnet6")

        if subnet is None and gateway is not None:
            raise CommandError("Cannot use gateway without subnet")
        if subnet is None and allocation_pools is not None:
            raise CommandError("Cannot use allocation-pools without subnet")
        if subnet6 is None and gateway6 is not None:
            raise CommandError("Cannot use gateway6 without subnet6")
        if flavor == "IP_LESS_ROUTED" and not (subnet or subnet6):
            raise CommandError("Cannot create 'IP_LESS_ROUTED' network without"
                               " subnet")

        if not (userid or public):
            raise CommandError("'user' is required for private networks")
        if not project:
            project = userid

        network = networks.create(userid=userid,
                                  name=name,
                                  flavor=flavor,
                                  public=public,
                                  mode=mode,
                                  project=project,
                                  link=link,
                                  mac_prefix=mac_prefix,
                                  tags=tags,
                                  floating_ip_pool=floating_ip_pool,
                                  drained=drained)

        if subnet is not None:
            alloc = None
            if allocation_pools is not None:
                alloc = subnets.parse_allocation_pools(allocation_pools)
                alloc.sort()
            name = "IPv4 Subnet of Network %s" % network.id
            subnets.create_subnet(network.id,
                                  cidr=subnet,
                                  name=name,
                                  ipversion=4,
                                  gateway=gateway,
                                  dhcp=dhcp,
                                  user_id=userid,
                                  allocation_pools=alloc)

        if subnet6 is not None:
            name = "IPv6 Subnet of Network %s" % network.id
            subnets.create_subnet(network.id,
                                  cidr=subnet6,
                                  name=name,
                                  ipversion=6,
                                  gateway=gateway6,
                                  dhcp=dhcp,
                                  user_id=userid)

        self.stdout.write("Created network '%s' in DB:\n" % network)
        pprint.pprint_network(network, stdout=self.stdout)
        pprint.pprint_network_subnets(network, stdout=self.stdout)

        networks.create_network_in_backends(network)
        # TODO: Add --wait option to track job progress and report successful
        # creation in each backend.
        self.stdout.write("\nSuccessfully issued job to create network in"
                          " backends\n")
    def handle(self, *args, **options):
        if len(args) != 1:
            raise CommandError("Please provide a server ID")

        server = get_resource("server", args[0], for_update=True)

        new_name = options.get("name", None)
        if new_name is not None:
            old_name = server.name
            server = servers.rename(server, new_name)
            self.stdout.write("Renamed server '%s' from '%s' to '%s'\n" %
                              (server, old_name, new_name))

        suspended = options.get("suspended", None)
        if suspended is not None:
            suspended = parse_bool(suspended)
            server.suspended = suspended
            server.save()
            self.stdout.write("Set server '%s' as suspended=%s\n" %
                              (server, suspended))

        new_owner = options.get('user')
        if new_owner is not None:
            if "@" in new_owner:
                raise CommandError("Invalid user UUID.")
            old_owner = server.userid
            server.userid = new_owner
            old_project = server.project
            server.project = new_owner
            server.save()
            msg = "Changed the owner of server '%s' from '%s' to '%s'.\n"
            self.stdout.write(msg % (server, old_owner, new_owner))
            msg = "Changed the project of server '%s' from '%s' to '%s'.\n"
            self.stdout.write(msg % (server, old_project, new_owner))
            for vol in server.volumes.filter(
                    userid=old_owner).select_for_update():
                vol.userid = new_owner
                vol_old_project = vol.project
                vol.project = new_owner
                vol.save()
                msg = "Changed the owner of volume '%s' from '%s' to '%s'.\n"
                self.stdout.write(msg % (vol, old_owner, new_owner))
                msg = "Changed the project of volume '%s' from '%s' to '%s'.\n"
                self.stdout.write(msg % (vol, vol_old_project, new_owner))
            self.stdout.write("WARNING: User quotas should be out of sync now,"
                              " run `snf-manage reconcile-resources-cyclades'"
                              " to review and update them.\n")

        wait = parse_bool(options["wait"])
        new_flavor_id = options.get("flavor")
        if new_flavor_id is not None:
            new_flavor = get_resource("flavor", new_flavor_id)
            old_flavor = server.flavor
            msg = "Resizing server '%s' from flavor '%s' to '%s'.\n"
            self.stdout.write(msg % (server, old_flavor, new_flavor))
            server = servers.resize(server, new_flavor)
            wait_server_task(server, wait, stdout=self.stdout)

        action = options.get("action")
        if action is not None:
            if action == "start":
                server = servers.start(server)
            elif action == "stop":
                server = servers.stop(server)
            elif action == "reboot_hard":
                server = servers.reboot(server, reboot_type="HARD")
            elif action == "reboot_stof":
                server = servers.reboot(server, reboot_type="SOFT")
            else:
                raise CommandError("Unknown action.")
            wait_server_task(server, wait, stdout=self.stdout)
Example #51
0
    def handle(self, *args, **options):
        if args:
            raise CommandError("Command doesn't accept any arguments")

        size = options.get("size")
        user_id = options.get("user_id")
        project_id = options.get("project")
        server_id = options.get("server_id")
        volume_type_id = options.get("volume_type_id")
        wait = parse_bool(options["wait"])
        credentials = Credentials(user_id)

        display_name = options.get("name", "")
        display_description = options.get("description", "")

        if size is None:
            raise CommandError("Please specify the size of the volume")

        if server_id:
            vm = common.get_resource("server", server_id)
            if project_id is None:
                project_id = vm.project

        if user_id is None and server_id is None:
            raise CommandError("Please specify the id of a user or a server")
        elif user_id is None and server_id is not None:
            user_id = vm.userid

        if volume_type_id is not None:
            vtype = common.get_resource("volume-type", volume_type_id)
        elif server_id:
            vtype = vm.flavor.volume_type
        else:
            raise CommandError("Please specify the id of the volume type")

        # At this point, user_id, vtype must have been provided or extracted by
        # the server. The project_id is optional and will default to the user's
        # project.

        source_image_id = source_volume_id = source_snapshot_id = None
        source = options.get("source")
        if source is not None:
            try:
                source_type, source_uuid = source.split(":", 1)
            except (ValueError, TypeError):
                raise CommandError("Invalid '--source' option. Value must be"
                                   " of the form <source_type>:<source_uuid>")
            if source_type == "image":
                source_image_id = source_uuid
            elif source_type == "snapshot":
                source_snapshot_id = source_uuid
            else:
                raise CommandError("Unknown volume source type '%s'" %
                                   source_type)

        volume = volumes.create(credentials,
                                size,
                                server_id,
                                name=display_name,
                                description=display_description,
                                source_image_id=source_image_id,
                                source_snapshot_id=source_snapshot_id,
                                source_volume_id=source_volume_id,
                                volume_type_id=vtype.id,
                                metadata={},
                                project_id=project_id)

        self.stdout.write("Created volume '%s' in DB:\n" % volume.id)

        pprint.pprint_volume(volume, stdout=self.stdout)
        self.stdout.write("\n")
        if volume.machine is not None:
            volume.machine.task_job_id = volume.backendjobid
            common.wait_server_task(volume.machine, wait, stdout=self.stdout)
Example #52
0
    def handle(self, *args, **options):
        if args:
            raise CommandError("Command doesn't accept any arguments")

        name = options['name']
        subnet = options['subnet']
        gateway = options['gateway']
        subnet6 = options['subnet6']
        gateway6 = options['gateway6']
        public = options['public']
        flavor = options['flavor']
        mode = options['mode']
        link = options['link']
        mac_prefix = options['mac_prefix']
        tags = options['tags']
        userid = options["user"]
        project = options['project']
        allocation_pools = options["allocation_pools"]
        floating_ip_pool = parse_bool(options["floating_ip_pool"])
        dhcp = parse_bool(options["dhcp"])
        drained = parse_bool(options["drained"])

        if name is None:
            name = ""
        if flavor is None:
            raise CommandError("flavor is required")

        if ((subnet is None) and (subnet6 is None)) and dhcp is not False:
            raise CommandError("Cannot set DHCP without subnet or subnet6")

        if subnet is None and gateway is not None:
            raise CommandError("Cannot use gateway without subnet")
        if subnet is None and allocation_pools is not None:
            raise CommandError("Cannot use allocation-pools without subnet")
        if subnet6 is None and gateway6 is not None:
            raise CommandError("Cannot use gateway6 without subnet6")
        if flavor == "IP_LESS_ROUTED" and not (subnet or subnet6):
            raise CommandError("Cannot create 'IP_LESS_ROUTED' network without"
                               " subnet")

        if not (userid or public):
            raise CommandError("'user' is required for private networks")
        if not project:
            project = userid

        network = networks.create(userid=userid, name=name, flavor=flavor,
                                  public=public, mode=mode, project=project,
                                  link=link, mac_prefix=mac_prefix, tags=tags,
                                  floating_ip_pool=floating_ip_pool,
                                  drained=drained)

        if subnet is not None:
            alloc = None
            if allocation_pools is not None:
                alloc = subnets.parse_allocation_pools(allocation_pools)
                alloc.sort()
            name = "IPv4 Subnet of Network %s" % network.id
            subnets.create_subnet(network.id, cidr=subnet, name=name,
                                  ipversion=4, gateway=gateway, dhcp=dhcp,
                                  user_id=userid,
                                  allocation_pools=alloc)

        if subnet6 is not None:
            name = "IPv6 Subnet of Network %s" % network.id
            subnets.create_subnet(network.id, cidr=subnet6, name=name,
                                  ipversion=6, gateway=gateway6,
                                  dhcp=dhcp, user_id=userid)

        self.stdout.write("Created network '%s' in DB:\n" % network)
        pprint.pprint_network(network, stdout=self.stdout)
        pprint.pprint_network_subnets(network, stdout=self.stdout)

        networks.create_network_in_backends(network)
        # TODO: Add --wait option to track job progress and report successful
        # creation in each backend.
        self.stdout.write("\nSuccessfully issued job to create network in"
                          " backends\n")
Example #53
0
    def handle(self, *args, **options):
        if args:
            raise CommandError("Command doesn't accept any arguments")

        size = options.get("size")
        user_id = options.get("user_id")
        project_id = options.get("project")
        server_id = options.get("server_id")
        volume_type_id = options.get("volume_type_id")
        wait = parse_bool(options["wait"])
        credentials = Credentials(user_id)

        display_name = options.get("name", "")
        display_description = options.get("description", "")

        if size is None:
            raise CommandError("Please specify the size of the volume")

        if server_id:
            vm = common.get_resource("server", server_id)
            if project_id is None:
                project_id = vm.project

        if user_id is None and server_id is None:
            raise CommandError("Please specify the id of a user or a server")
        elif user_id is None and server_id is not None:
            user_id = vm.userid

        if volume_type_id is not None:
            vtype = common.get_resource("volume-type", volume_type_id)
        elif server_id:
            vtype = vm.flavor.volume_type
        else:
            raise CommandError("Please specify the id of the volume type")

        # At this point, user_id, vtype must have been provided or extracted by
        # the server. The project_id is optional and will default to the user's
        # project.

        source_image_id = source_volume_id = source_snapshot_id = None
        source = options.get("source")
        if source is not None:
            try:
                source_type, source_uuid = source.split(":", 1)
            except (ValueError, TypeError):
                raise CommandError("Invalid '--source' option. Value must be"
                                   " of the form <source_type>:<source_uuid>")
            if source_type == "image":
                source_image_id = source_uuid
            elif source_type == "snapshot":
                source_snapshot_id = source_uuid
            else:
                raise CommandError("Unknown volume source type '%s'"
                                   % source_type)

        volume = volumes.create(credentials, size, server_id,
                                name=display_name,
                                description=display_description,
                                source_image_id=source_image_id,
                                source_snapshot_id=source_snapshot_id,
                                source_volume_id=source_volume_id,
                                volume_type_id=vtype.id, metadata={},
                                project_id=project_id)

        self.stdout.write("Created volume '%s' in DB:\n" % volume.id)

        pprint.pprint_volume(volume, stdout=self.stdout)
        self.stdout.write("\n")
        if volume.machine is not None:
            volume.machine.task_job_id = volume.backendjobid
            common.wait_server_task(volume.machine, wait, stdout=self.stdout)
Example #54
0
    def handle(self, *args, **options):
        if len(args) != 1:
            raise CommandError("Please provide a network ID")

        network = get_network(args[0])

        new_name = options.get("name")
        if new_name is not None:
            old_name = network.name
            network = networks.rename(network, new_name)
            self.stdout.write("Renamed network '%s' from '%s' to '%s'.\n" %
                              (network, old_name, new_name))

        drained = options.get("drained")
        if drained is not None:
            drained = parse_bool(drained)
            network.drained = drained
            network.save()
            self.stdout.write("Set network '%s' as drained=%s.\n" %
                              (network, drained))

        new_owner = options.get("userid")
        if new_owner is not None:
            if "@" in new_owner:
                raise CommandError("Invalid owner UUID.")
            old_owner = network.userid
            network.userid = new_owner
            network.save()
            msg = "Changed the owner of network '%s' from '%s' to '%s'.\n"
            self.stdout.write(msg % (network, old_owner, new_owner))

        floating_ip_pool = options["floating_ip_pool"]
        if floating_ip_pool is not None:
            floating_ip_pool = parse_bool(floating_ip_pool)
            if floating_ip_pool is False and network.floating_ip_pool is True:
                if network.ips.filter(deleted=False, floating_ip=True)\
                              .exists():
                    msg = ("Cannot make network a non floating IP pool."
                           " There are still reserved floating IPs.")
                    raise CommandError(msg)
            network.floating_ip_pool = floating_ip_pool
            network.save()
            self.stdout.write("Set network '%s' as floating-ip-pool=%s.\n" %
                              (network, floating_ip_pool))
            if floating_ip_pool is True:
                for backend in Backend.objects.filter(offline=False):
                    bnet, jobs =\
                        backend_mod.ensure_network_is_active(backend,
                                                             network.id)
                    if jobs:
                        msg = ("Sent job to create network '%s' in backend"
                               " '%s'\n" % (network, backend))
                        self.stdout.write(msg)

        add_reserved_ips = options.get('add_reserved_ips')
        remove_reserved_ips = options.get('remove_reserved_ips')
        if add_reserved_ips or remove_reserved_ips:
            if add_reserved_ips:
                add_reserved_ips = add_reserved_ips.split(",")
                for ip in add_reserved_ips:
                    network.reserve_address(ip, external=True)
            if remove_reserved_ips:
                remove_reserved_ips = remove_reserved_ips.split(",")
                for ip in remove_reserved_ips:
                    network.release_address(ip, external=True)

        add_to_backend = options["add_to_backend"]
        if add_to_backend is not None:
            backend = get_backend(add_to_backend)
            bnet, jobs = backend_mod.ensure_network_is_active(backend,
                                                              network.id)
            if jobs:
                msg = "Sent job to create network '%s' in backend '%s'\n"
                self.stdout.write(msg % (network, backend))

        remove_from_backend = options["remove_from_backend"]
        if remove_from_backend is not None:
            backend = get_backend(remove_from_backend)
            if network.nics.filter(machine__backend=backend,
                                   machine__deleted=False).exists():
                msg = "Cannot remove. There are still connected VMs to this"\
                      " network"
                raise CommandError(msg)
            backend_mod.delete_network(network, backend, disconnect=True)
            msg = "Sent job to delete network '%s' from backend '%s'\n"
            self.stdout.write(msg % (network, backend))