Exemplo n.º 1
0
def _boot(cs, args, reservation_id=None, min_count=None, max_count=None):
    """Boot a new server."""
    if min_count is None:
        min_count = 1
    if max_count is None:
        max_count = min_count
    if min_count > max_count:
        raise exceptions.CommandError("min_instances should be <= "
                                      "max_instances")
    if not min_count or not max_count:
        raise exceptions.CommandError("min_instances nor max_instances should"
                                      "be 0")

    if not args.image and not args.block_device_mapping:
        raise exceptions.CommandError("you need to specify an Image ID "
                                      "or a block device mapping ")
    if not args.flavor:
        raise exceptions.CommandError("you need to specify a Flavor ID ")

    flavor = args.flavor
    image = args.image

    meta = dict(v.split('=') for v in args.meta)

    files = {}
    for f in args.files:
        dst, src = f.split('=', 1)
        try:
            files[dst] = open(src)
        except IOError, e:
            raise exceptions.CommandError("Can't open '%s': %s" % (src, e))
Exemplo n.º 2
0
def find_resource(manager, name_or_id):
    """Helper for the _find_* methods."""
    # first try to get entity as integer id
    try:
        if isinstance(name_or_id, int) or name_or_id.isdigit():
            return manager.get(int(name_or_id))
    except exceptions.NotFound:
        pass

    # now try to get entity as uuid
    try:
        uuid.UUID(str(name_or_id))
        return manager.get(name_or_id)
    except (ValueError, exceptions.NotFound):
        pass

    # finally try to find entity by name
    try:
        return manager.find(name=name_or_id)
    except exceptions.NotFound:
        try:
            # Volumes does not have name, but displayName
            return manager.find(displayName=name_or_id)
        except exceptions.NotFound:
            msg = "No %s with a name or ID of '%s' exists." % \
                (manager.resource_class.__name__.lower(), name_or_id)
            raise exceptions.CommandError(msg)
Exemplo n.º 3
0
def do_floating_ip_delete(cs, args):
    """De-allocate a floating IP."""
    floating_ips = cs.floating_ips.list()
    for floating_ip in floating_ips:
        if floating_ip.ip == args.address:
            return cs.floating_ips.delete(floating_ip.id)
    raise exceptions.CommandError("Floating ip %s not found.", args.address)
Exemplo n.º 4
0
def do_dns_list(cs, args):
    """List current DNS entries for zone and ip or zone and name."""
    if not (args.ip or args.name):
        raise exceptions.CommandError("You must specify either --ip or --name")
    entries = cs.floating_ip_dns.get_entries(args.zone,
                                             ip=args.ip,
                                             name=args.name)
    _print_dns_list(entries)
Exemplo n.º 5
0
def do_root_password(cs, args):
    """
    Change the root password for a server.
    """
    server = _find_server(cs, args.server)
    p1 = getpass.getpass('New password: '******'Again: ')
    if p1 != p2:
        raise exceptions.CommandError("Passwords do not match.")
    server.change_password(p1)
Exemplo n.º 6
0
def do_keypair_add(cs, args):
    """Create a new key pair for use with instances"""
    name = args.name
    pub_key = args.pub_key

    if pub_key:
        try:
            with open(pub_key) as f:
                pub_key = f.read()
        except IOError, e:
            raise exceptions.CommandError("Can't open or read '%s': %s" % \
                                                          (pub_key, e))
Exemplo n.º 7
0
def do_secgroup_delete_rule(cs, args):
    """Delete a rule from a security group."""

    secgroup = _get_secgroup(cs, args.secgroup)
    for rule in secgroup.rules:
        if (rule['ip_protocol'] == args.ip_proto
                and rule['from_port'] == int(args.from_port)
                and rule['to_port'] == int(args.to_port)
                and rule['ip_range']['cidr'] == args.cidr):
            return cs.security_group_rules.delete(rule['id'])

    raise exceptions.CommandError("Rule not found")
Exemplo n.º 8
0
 def do_help(self, args):
     """
     Display help about this program or one of its subcommands.
     """
     if args.command:
         if args.command in self.subcommands:
             self.subcommands[args.command].print_help()
         else:
             raise exc.CommandError("'%s' is not a valid subcommand" %
                                    args.command)
     else:
         self.parser.print_help()
Exemplo n.º 9
0
def do_secgroup_delete_group_rule(cs, args):
    """Delete a source group rule from a security group."""
    secgroup = _get_secgroup(cs, args.secgroup)
    source_group = _get_secgroup(cs, args.source_group)
    params = {}
    params['group_name'] = source_group.name

    if args.ip_proto or args.from_port or args.to_port:
        if not (args.ip_proto and args.from_port and args.to_port):
            raise exceptions.CommandError("ip_proto, from_port, and to_port"
                                          " must be specified together")
        params['ip_protocol'] = args.ip_proto
        params['from_port'] = int(args.from_port)
        params['to_port'] = int(args.to_port)

    for rule in secgroup.rules:
        if (rule.get('ip_protocol') == params.get('ip_protocol') and
            rule.get('from_port') == params.get('from_port') and
            rule.get('to_port') == params.get('to_port') and
            rule.get('group', {}).get('name') ==\
                     params.get('group_name')):
            return cs.security_group_rules.delete(rule['id'])

    raise exceptions.CommandError("Rule not found")
Exemplo n.º 10
0
def do_secgroup_add_group_rule(cs, args):
    """Add a source group rule to a security group."""
    secgroup = _get_secgroup(cs, args.secgroup)
    source_group = _get_secgroup(cs, args.source_group)
    params = {}
    params['group_id'] = source_group.id

    if args.ip_proto or args.from_port or args.to_port:
        if not (args.ip_proto and args.from_port and args.to_port):
            raise exceptions.CommandError("ip_proto, from_port, and to_port"
                                          " must be specified together")
        params['ip_protocol'] = args.ip_proto
        params['from_port'] = args.from_port
        params['to_port'] = args.to_port

    rule = cs.security_group_rules.create(secgroup.id, **params)
    _print_secgroup_rules([rule])
Exemplo n.º 11
0
def _get_secgroup(cs, secgroup):
    for s in cs.security_groups.list():
        if secgroup == s.name:
            return s
    raise exceptions.CommandError("Secgroup %s not found" % secgroup)
Exemplo n.º 12
0
        key_name = args.key_name

    # or use file injection functionality (independent of os-keypair extension)
    keyfile = None
    if args.key_path is AUTO_KEY:
        possible_keys = [
            os.path.join(os.path.expanduser('~'), '.ssh', k)
            for k in ('id_dsa.pub', 'id_rsa.pub')
        ]
        for k in possible_keys:
            if os.path.exists(k):
                keyfile = k
                break
        else:
            raise exceptions.CommandError(
                "Couldn't find a key file: tried "
                "~/.ssh/id_dsa.pub or ~/.ssh/id_rsa.pub")
    elif args.key_path:
        keyfile = args.key_path

    if keyfile:
        try:
            files['/root/.ssh/authorized_keys2'] = open(keyfile)
        except IOError, e:
            raise exceptions.CommandError("Can't open '%s': %s" % (keyfile, e))

    if args.user_data:
        try:
            userdata = open(args.user_data)
        except IOError, e:
            raise exceptions.CommandError("Can't open '%s': %s" % \
Exemplo n.º 13
0
    def main(self, argv):
        # Parse args once to find version
        parser = self.get_base_parser()
        (options, args) = parser.parse_known_args(argv)

        # build available subcommands based on version
        self.extensions = self._discover_extensions(options.version)
        self._run_extension_hooks('__pre_parse_args__')

        subcommand_parser = self.get_subcommand_parser(options.version)
        self.parser = subcommand_parser

        args = subcommand_parser.parse_args(argv)
        self._run_extension_hooks('__post_parse_args__', args)

        # Deal with global arguments
        if args.debug:
            httplib2.debuglevel = 1

        # Short-circuit and deal with help right away.
        if args.func == self.do_help:
            self.do_help(args)
            return 0
        elif args.func == self.do_bash_completion:
            self.do_bash_completion(args)
            return 0

        (user, apikey, password, projectid, url, region_name, endpoint_name,
         insecure) = (args.username, args.apikey, args.password,
                      args.projectid, args.url, args.region_name,
                      args.endpoint_name, args.insecure)

        if not endpoint_name:
            endpoint_name = 'publicURL'

        #FIXME(usrleon): Here should be restrict for project id same as
        # for username or password but for compatibility it is not.

        if not utils.isunauthenticated(args.func):
            if not user:
                raise exc.CommandError("You must provide a username, either "
                                       "via --username or via "
                                       "env[OS_USERNAME]")

            if not password:
                if not apikey:
                    raise exc.CommandError(
                        "You must provide a password, "
                        "either via --password or via env[OS_PASSWORD]")
                else:
                    password = apikey

            if not projectid:
                raise exc.CommandError("You must provide an projectid, either "
                                       "via --projectid or via "
                                       "env[OS_TENANT_NAME]")

            if not url:
                raise exc.CommandError("You must provide a auth url, either "
                                       "via --url or via "
                                       "env[OS_AUTH_URL]")

        if options.version and options.version != '1.0':
            if not projectid:
                raise exc.CommandError("You must provide an projectid, "
                                       "either via --projectid or via "
                                       "env[ENGINE_PROJECT_ID]")

            if not url:
                raise exc.CommandError("You must provide a auth url,"
                                       " either via --url or via "
                                       "env[ENGINE_URL]")

        self.cs = client.Client(options.version,
                                user,
                                password,
                                projectid,
                                url,
                                insecure,
                                region_name=region_name,
                                endpoint_name=endpoint_name,
                                extensions=self.extensions)

        try:
            if not utils.isunauthenticated(args.func):
                self.cs.authenticate()
        except exc.Unauthorized:
            raise exc.CommandError("Invalid X7 Engine credentials.")
        except exc.AuthorizationFailure:
            raise exc.CommandError("Unable to authorize user")

        args.func(self.cs, args)