Exemplo n.º 1
0
    def error(self, msg):
        """error(msg : string)

        Print a usage message incorporating 'msg' to stderr and exit.
        If you override this in a subclass, it should not return -- it
        should either exit or raise an exception.
        """
        raise optparse.OptParseError(msg)
Exemplo n.º 2
0
 def _store_generate_builtins(self, generate_builtins):
     if generate_builtins:
         if self.input:
             raise optparse.OptionConflictError(
                 "Not allowed with an input file", "generate-builtins")
     elif not self.input and not self.show_config:
         raise optparse.OptParseError("Need a filename.")
     self.generate_builtins = generate_builtins
Exemplo n.º 3
0
 def _store_python_version(self, python_version):
     self.python_version = tuple(map(int, python_version.split(".")))
     if len(self.python_version) != 2:
         raise optparse.OptionValueError(
             "--python_version must be <major>.<minor>: %r" %
             python_version)
     if (3, 0) <= self.python_version <= (3, 3):
         # These have odd __build_class__ parameters, store co_code.co_name fields
         # as unicode, and don't yet have the extra qualname parameter to
         # MAKE_FUNCTION. Jumping through these extra hoops is not worth it, given
         # that typing.py isn't introduced until 3.5, anyway.
         raise optparse.OptParseError(
             "Python versions 3.0 - 3.3 are not supported. "
             "Use 3.4 and higher.")
     if self.python_version > (3, 6):
         # We have an explicit per-minor-version mapping in opcodes.py
         raise optparse.OptParseError(
             "Python versions > 3.6 are not yet supported.")
Exemplo n.º 4
0
 def _store_python_exe(self, python_exe):
     """Postprocess --python_exe."""
     if python_exe is None:
         python_exe = utils.get_python_exe(self.python_version)
         err = "Need a valid python%d.%d executable in $PATH" % self.python_version
     else:
         err = "Bad flag --python_exe: could not run %s" % python_exe
     if not utils.is_valid_python_exe(python_exe):
         raise optparse.OptParseError(err)
     self.python_exe = python_exe
Exemplo n.º 5
0
 def _store_verbosity(self, verbosity):
     """Configure logging."""
     if verbosity >= 0:
         if verbosity >= len(LOG_LEVELS):
             raise optparse.OptParseError("invalid --verbosity: %s" %
                                          self._options.verbosity)
         basic_logging_level = LOG_LEVELS[verbosity]
     else:
         # "verbosity=-1" can be used to disable all logging, so configure
         # logging accordingly.
         basic_logging_level = logging.CRITICAL + 1
     logging.basicConfig(level=basic_logging_level)
Exemplo n.º 6
0
 def _store_generate_builtins(self, generate_builtins):
     """Store the generate-builtins option."""
     if generate_builtins:
         if self.input:
             raise optparse.OptionConflictError(
                 "Not allowed with an input file", "generate-builtins")
         if self.pythonpath != [""]:
             raise optparse.OptionConflictError(
                 "Not allowed with --pythonpath", "generate-builtins")
         # Set the default pythonpath to [] rather than [""]
         self.pythonpath = []
     elif not self.input and not self.show_config:
         raise optparse.OptParseError("Need a filename.")
     self.generate_builtins = generate_builtins
Exemplo n.º 7
0
 def _store_python_exe(self, python_exe):
     """Postprocess --python_exe."""
     if python_exe is None:
         python_exe = "python%d.%d" % self.python_version
         try:
             with open(os.devnull, "w") as null:
                 subprocess.check_call(python_exe + " -V",
                                       shell=True,
                                       stderr=null,
                                       stdout=null)
         except subprocess.CalledProcessError:
             raise optparse.OptParseError(
                 "Need valid %s executable in $PATH" % python_exe)
     self.python_exe = python_exe
Exemplo n.º 8
0
def init():
    #try:
    #        import psyco
    #except ImportError:
    #	print "failed to import psyco\n"
    #        pass
    #else:
    #	print "running psyco\n"
    #        psyco.full()
    try:
        parser = optparse.OptionParser()
        option = parser.add_option
        option('-z',
               '--width',
               dest='width',
               type='int',
               default=3000,
               help='Overall width of the generated terrain')

        option('-2',
               '--two',
               dest='two_player',
               action='store_true',
               default=False,
               help='Two player split screen action')
        option('-s',
               '--split',
               dest='split',
               action='store_true',
               default=False,
               help='Split screen, even if there\'s only one player')
        option('-S',
               '--server',
               dest='server',
               type='str',
               default=None,
               help='Create a server using at this IP / domain')
        option(
            '-C',
            '--client',
            dest='client',
            type='str',
            default=None,
            help='Create a client connection this a server at this IP / domain'
        )
        man.opt, args = parser.parse_args()
        if args: raise optparse.OptParseError('Unrecognized args: %s' % args)

        #All object and server query constructors are listed next
        factory = SerialisableFact({
            MyAirfoil.TYP: MyAirfoil,
            Bullet.TYP: Bullet,
            PlanePositionQuery.TYP: PlanePositionQuery
        })

        class BotTracker:
            def __init__(self, factory, types):
                self.types = types
                self.bots = []
                factory.push_handlers(self)

            def __updater(self):
                return man.proxy.getTypesObjs(self.types)

            def on_birth(self, bot):
                if bot.TYP in self.types:
                    self.bots.append(bot)

            def on_death(self, bot):
                self.bots[:] = self.__updater()

        global botTracker
        botTracker = BotTracker(factory, [MyAirfoil.TYP, Bullet.TYP])
        mesh.initBots(factory, [MyAirfoil.TYP])

        scale = manage.scale
        colliders_map = {MyAirfoil.TYP: ("data/models/cockpit/C_*.csv", scale)}
        colliders = [path for (path, scale) in colliders_map.values()]
        mesh.loadColliders(colliders_map)

        global interactive
        interactive = True
        if man.opt.server is None:
            if man.opt.client is None:
                man.server = MyServer()
                man.proxy = Client(factory=factory)
            else:
                man.proxy = Client(server=man.opt.client, factory=factory)
        else:
            if man.opt.client is None:
                interactive = False
                man.server = MyServer(server=man.opt.server, own_thread=True)
                #man.proxy=Client(server=man.opt.server, factory=factory)
                man.proxy = None
            else:
                man.server = MyServer(server=man.opt.server)
                man.proxy = Client(server=man.opt.client, factory=factory)

        if not interactive:
            print 'init. not interactive'
            return (0, [], time.time(), 0)

        print 'init(). starting'
        waitForClient(man.proxy)

        global mouse_cap, fullscreen, views, planes, bots, skybox
        mouse_cap = True
        fullscreen = False
        views = []
        loadTerrain()

        #r = 0.0

        def genMeshArgs(all_glob, moving_maps, onlys, scale, group):
            all = [(all_glob, (mesh.Mesh, scale, group))]
            all.extend(moving_maps.items())
            #all.append(("data/models/hud/*.csv", (mesh.HudMesh, scale, None)))

            movingAndOnly = moving_maps.keys()[:]
            movingAndOnly.append(onlys)

            return (all, movingAndOnly)

        internal_grp, external_grp = range(2)
        (all_internal, not_external) = genMeshArgs(
            "data/models/cockpit/*.csv", {
                "data/models/cockpit/LittlePlane.csv":
                (mesh.LittlePlaneMesh, scale, None),
                "data/models/cockpit/Plane.004.csv":
                (mesh.CompassMesh, scale, None),
                "data/models/cockpit/Plane.003.csv":
                (mesh.AltMeterMesh, scale, None),
                "data/models/cockpit/Plane.005.csv":
                (mesh.ClimbMesh, scale, None),
                "data/models/cockpit/Plane.011.csv":
                (mesh.RPMMesh, scale, None),
                "data/models/cockpit/Plane.006.csv":
                (mesh.AirSpeedMesh, scale, None),
                "data/models/cockpit/Circle.007.csv":
                (mesh.WingAirSpeedMesh, scale, None),
                "data/models/cockpit/Plane.014.csv":
                (mesh.BankingMesh, scale, None)
            }, "data/models/cockpit/I_*.csv", scale, internal_grp)
        not_external.extend(colliders)
        (all_external, not_internal) = genMeshArgs(
            "data/models/cockpit/*.csv", {
                "data/models/cockpit/E_Prop.csv": (mesh.PropMesh, scale, None),
                "data/models/cockpit/E_PropBlend.csv":
                (mesh.PropBlendMesh, scale, None)
            }, "data/models/cockpit/E_*.csv", scale, external_grp)
        not_internal.extend(colliders)

        #must use an association list to map glob paths to (mesh, scale) couples instead of a dict
        #as earlier mappings are superceded by later mappings --- so the order is important. dicts
        #do not maintain ordering
        mesh.loadMeshes(
            {
                (MyAirfoil.TYP, EXTERNAL): (all_external, not_external),
                (MyAirfoil.TYP, INTERNAL): (all_internal, not_internal)
            }, views)

        planes = {}
        plane_ids = []

        if man.opt.two_player == True:
            num_players = 2
        else:
            num_players = 1

        num_views = num_players
        if man.opt.split == True:
            num_views = 2

        assert num_players <= PlanePositionQuery.MAX_POS

        plane_inits = []
        posQuery = PlanePositionQuery(proxy=man.proxy)
        for query in range(0, num_players):
            posQuery.post(
                lambda q: plane_inits.append(q.getPosInitialisation()))
        Query.waitForReplies(man.proxy)
        print 'plane_inits: ' + str(plane_inits)

        for i in range(num_players):
            (pos, att, vel, thrust) = plane_inits[i]
            print 'att: ' + str(att)
            plane = MyAirfoil(pos=pos,
                              attitude=att,
                              velocity=vel,
                              thrust=thrust,
                              proxy=man.proxy)
            plane_ids.append(plane.getId())
            planes[plane.getId()] = plane

        print 'planes: ' + str(planes)
        for i in range(num_views):
            print 'idx: ' + str(i % num_players)
            plane = planes[plane_ids[i % num_players]]
            view = View(plane, num_views, man.opt)
            views.append(view)

        SubjectSelector(man.proxy, [MyAirfoil.TYP], views)

        bots = []
        skybox = Skybox()
        start_time = time.time()
        return num_players, plane_ids, start_time, num_views
    except:
        print_exc()
        start_time = time.time()
        return 0, [], start_time, 0
Exemplo n.º 9
0
def parse_args():
    try:
        import argparse
        parser = argparse.ArgumentParser(prog="install_icsw.py")
        parser.add_argument(
            "-s",
            "--show-commands",
            dest="show_commands",
            action="store_true",
            help="only show commands without actually executing them")
        parser.add_argument("-u",
                            "--user",
                            dest='user',
                            required=True,
                            help="your icsw user name")
        parser.add_argument("-p",
                            "--password",
                            dest='password',
                            required=True,
                            help="your icsw password")
        parser.add_argument("-n",
                            "--cluster-name",
                            dest='cluster_name',
                            required=True,
                            help="cluster name as provided by init.at")
        parser.add_argument(
            "-v",
            "--cluster-version",
            dest='cluster_version',
            required=True,
            help="choose the version to install, either icsw-2.5 or icsw-devel"
        )
        parser.add_argument("--assume-yes",
                            dest='assume_yes',
                            action="store_true",
                            help="Don't ask user to confirm install")
        parser.add_argument(
            "--do-not-config",
            dest='do_not_config',
            action="store_true",
            help="Do also a base configuration of database and license file")
        opts = parser.parse_args()
    except ImportError:
        import optparse
        parser = optparse.OptionParser()
        parser.add_option(
            "-s",
            "--show-commands",
            dest="show_commands",
            action="store_true",
            help="only show commands without actually executing them")
        parser.add_option("-u",
                          "--user",
                          dest='user',
                          help="your icsw user name")
        parser.add_option("-p",
                          "--password",
                          dest='password',
                          help="your icsw password")
        parser.add_option("-n",
                          "--cluster-name",
                          dest='cluster_name',
                          help="cluster name as provided by init.at")
        parser.add_option(
            "-v",
            "--cluster-version",
            dest='cluster_version',
            help="choose the version to install, either 2.5 or devel")
        parser.add_option("-y",
                          "--assume-yes",
                          dest='assume_yes',
                          action="store_true",
                          help="Don't ask user to confirm install")
        parser.add_option(
            "--do-not-config",
            dest='do_not_config',
            action="store_true",
            help="Do also a base configuration of database and license file")
        # emulate required
        opts, _ = parser.parse_args()
        if opts.user is None:
            raise optparse.OptParseError("argument -u/--user is required")
        if opts.password is None:
            raise optparse.OptParseError("argument -p/--password is required")
        if opts.cluster_name is None:
            raise optparse.OptParseError(
                "argument -n/--cluster-name is required")
        if opts.cluster_version is None:
            raise optparse.OptParseError(
                "argument -v/--cluster-version is required")

    return opts
Exemplo n.º 10
0
 def error(self, msg):
     self.print_usage(sys.stderr)
     raise optparse.OptParseError(msg)
Exemplo n.º 11
0
 def exit(self, status=0, msg=None):
     if not status:
         raise StopOptionProcessing(msg)
     else:
         # TODO: don't lose status info here
         raise optparse.OptParseError(msg)
Exemplo n.º 12
0
 def error(self, msg):
     raise optparse.OptParseError(self.get_usage() + "\n" + msg)
Exemplo n.º 13
0
 def error(self, msg):
     raise optparse.OptParseError(msg)
Exemplo n.º 14
0
def process(*args):
    # Check arguments
    if len(args) == 0:
        raise optparse.OptParseError(OBJECT_NOT_SPECIFIED)
    else:
        object_type = args[0]
        if object_type not in OBJECTS:
            raise optparse.OptParseError(SUPPORTED_OBJECTS)

    if len(args) == 1:
        raise optparse.OptParseError(ACTION_NOT_SPECIFIED)
    else:
        action = args[1]
        if action not in ACTIONS:
            raise optparse.OptParseError(SUPPORTED_ACTIONS)

    if len(args) == 2 and action not in ['list']:
        raise optparse.OptParseError(ID_NOT_SPECIFIED)
    else:
        object_id = args[2]

    # Helper functions

    def require_args(args, min, msg):
        """Ensure there are at least `min` arguments"""
        if len(args) < min:
            raise optparse.OptParseError(msg)

    optional_arg = (lambda args, x: len(args) > x and args[x] or None)

    def print_table(header_row, rows):
        """Prints a lists of lists as table in a human readable format"""
        print "\t".join(header_row)
        print '-' * 79
        rows = [[str(col) for col in row] for row in rows]
        print "\n".join(["\t".join(row) for row in rows])

    # Execute command
    if (object_type, action) == ('user', 'add'):
        require_args(args, 4, 'No password specified for fourth argument')
        if api.add_user(name=object_id,
                        password=args[3],
                        tenant=optional_arg(args, 4)):
            print "SUCCESS: User %s created." % object_id

    elif (object_type, action) == ('user', 'list'):
        print_table(('id', 'name', 'enabled', 'tenant'), api.list_users())

    elif (object_type, action) == ('user', 'disable'):
        if api.disable_user(name=object_id):
            print "SUCCESS: User %s disabled." % object_id

    elif object_type == 'user':
        raise optparse.OptParseError(ACTION_NOT_SUPPORTED % ('users'))

    elif (object_type, action) == ('tenant', 'add'):
        if api.add_tenant(name=object_id):
            print "SUCCESS: Tenant %s created." % object_id

    elif (object_type, action) == ('tenant', 'list'):
        print_table(('id', 'name', 'enabled'), api.list_tenants())

    elif (object_type, action) == ('tenant', 'disable'):
        if api.disable_tenant(name=object_id):
            print "SUCCESS: Tenant %s disabled." % object_id

    elif object_type == 'tenant':
        raise optparse.OptParseError(ACTION_NOT_SUPPORTED % ('tenants'))

    elif (object_type, action) == ('role', 'add'):
        if api.add_role(name=object_id):
            print "SUCCESS: Role %s created successfully." % object_id

    elif (object_type, action) == ('role', 'list'):
        tenant = optional_arg(args, 2)
        if tenant:
            # print with users
            print 'Role assignments for tenant %s' % tenant
            print_table(('User', 'Role'), api.list_roles(tenant=tenant))
        else:
            # print without tenants
            print_table(('id', 'name'), api.list_roles())

    elif (object_type, action) == ('role', 'grant'):
        require_args(
            args, 4, "Missing arguments: role grant 'role' 'user' "
            "'tenant (optional)'")
        tenant = optional_arg(args, 4)
        if api.grant_role(object_id, args[3], tenant):
            print("SUCCESS: Granted %s the %s role on %s." %
                  (object_id, args[3], tenant))

    elif object_type == 'role':
        raise optparse.OptParseError(ACTION_NOT_SUPPORTED % ('roles'))

    elif (object_type, action) == ('endpointTemplates', 'add'):
        require_args(
            args, 9, "Missing arguments: endpointTemplates add "
            "'region' 'service' 'publicURL' 'adminURL' 'internalURL' "
            "'enabled' 'global'")
        if api.add_endpoint_template(region=args[2],
                                     service=args[3],
                                     public_url=args[4],
                                     admin_url=args[5],
                                     internal_url=args[6],
                                     enabled=args[7],
                                     is_global=args[8]):
            print("SUCCESS: Created EndpointTemplates for %s pointing to %s." %
                  (args[3], args[4]))

    elif (object_type, action) == ('endpointTemplates', 'list'):
        tenant = optional_arg(args, 2)
        if tenant:
            print 'Endpoints for tenant %s' % tenant
            print_table(('service', 'region', 'Public URL'),
                        api.list_tenant_endpoints())
        else:
            print 'All EndpointTemplates'
            print_table(('service', 'region', 'Public URL'),
                        api.list_endpoint_templates())

    elif object_type == 'endpointTemplates':
        raise optparse.OptParseError(ACTION_NOT_SUPPORTED %
                                     ('endpointTemplates'))

    elif (object_type, action) == ('endpoint', 'add'):
        require_args(
            args, 4, "Missing arguments: endPoint add tenant "
            "endPointTemplate")
        if api.add_endpoint(tenant=args[2], endpoint_template=args[3]):
            print("SUCCESS: Endpoint %s added to tenant %s." %
                  (args[3], args[2]))

    elif object_type == 'endpoint':
        raise optparse.OptParseError(ACTION_NOT_SUPPORTED % ('endpoints'))

    elif (object_type, action) == ('token', 'add'):
        require_args(
            args, 6, 'Creating a token requires a token id, user, '
            'tenant, and expiration')
        if api.add_token(token=object_id,
                         user=args[3],
                         tenant=args[4],
                         expires=args[5]):
            print "SUCCESS: Token %s created." % (object_id, )

    elif (object_type, action) == ('token', 'list'):
        print_table(('token', 'user', 'expiration', 'tenant'),
                    api.list_tokens())

    elif (object_type, action) == ('token', 'delete'):
        if api.delete_token(token=object_id):
            print 'SUCCESS: Token %s deleted.' % (object_id, )

    elif object_type == 'token':
        raise optparse.OptParseError(ACTION_NOT_SUPPORTED % ('tokens'))

    elif (object_type, action) == ('service', 'add'):
        require_args(args, 4, "Missing arguments: service add name " "type")
        type = optional_arg(args, 3)
        desc = optional_arg(args, 4)
        if api.add_service(name=object_id, type=type, desc=desc):
            print "SUCCESS: Service %s created successfully." % (object_id, )

    elif (object_type, action) == ('service', 'list'):
        print_table(('id', 'name', 'type'), api.list_services())

    elif object_type == 'service':
        raise optparse.OptParseError(ACTION_NOT_SUPPORTED % ('services'))

    elif (object_type, action) == ('credentials', 'add'):
        require_args(
            args, 6, 'Creating a credentials requires a type, key, '
            'secret, and tenant_id (id is user_id)')
        if api.add_credentials(user=object_id,
                               type=args[3],
                               key=args[4],
                               secrete=args[5],
                               tenant=optional_arg(args, 6)):
            print "SUCCESS: Credentials %s created." % object_id

    elif object_type == 'credentials':
        raise optparse.OptParseError(ACTION_NOT_SUPPORTED % ('credentials'))

    else:
        # Command recognized but not handled: should never reach this
        raise NotImplementedError()
Exemplo n.º 15
0
def process(*args):
    """
    Usage: keystone-manage [options] type command [id [attributes]]
      type       : role, tenant, user, token, endpoint, endpointTemplates
      command    : add, list, disable, delete, grant, revoke
      id         : name or id
      attributes : depending on type...
        users    : password, tenant
        tokens   : user, tenant, expiration

      role list [tenant] will list roles granted on that tenant

    options
      -c | --config-file : config file to use
      -d | --debug : debug mode

    Example: keystone-manage user add Admin P@ssw0rd
    """
    # Check arguments
    if len(args) == 0:
        raise optparse.OptParseError(
            'No obj type specified for first argument')

    object_type = args[0]
    if object_type not in [
            'user', 'tenant', 'role', 'service', 'endpointTemplates', 'token',
            'endpoint', 'credentials'
    ]:
        raise optparse.OptParseError('%s is not a supported obj type' %
                                     object_type)

    if len(args) == 1:
        raise optparse.OptParseError(
            'No command specified for second argument')
    command = args[1]
    if command not in ['add', 'list', 'disable', 'delete', 'grant', 'revoke']:
        raise optparse.OptParseError('add, disable, delete, and list are the '
                                     'only supported commands (right now)')

    if len(args) == 2:
        if command != 'list':
            raise optparse.OptParseError('No id specified for third argument')
    if len(args) > 2:
        object_id = args[2]

    # Helper functions

    def require_args(args, min, msg):
        """Ensure there are at least `min` arguments"""
        if len(args) < min:
            raise optparse.OptParseError(msg)

    optional_arg = (lambda args, x: len(args) > x and args[x] or None)

    def print_table(header_row, rows):
        """Prints a lists of lists as table in a human readable format"""
        print "\t".join(header_row)
        print '-' * 79
        rows = [[str(col) for col in row] for row in rows]
        print "\n".join(["\t".join(row) for row in rows])

    # Execute command

    if (object_type, command) == ('user', 'add'):
        require_args(args, 4, 'No password specified for fourth argument')
        if api.add_user(name=object_id,
                        password=args[3],
                        tenant=optional_arg(args, 4)):
            print "SUCCESS: User %s created." % object_id

    elif (object_type, command) == ('user', 'disable'):
        if api.disable_user(name=object_id):
            print "SUCCESS: User %s disabled." % object_id

    elif (object_type, command) == ('user', 'list'):
        print_table(('id', 'enabled', 'tenant'), api.list_users())

    elif (object_type, command) == ('tenant', 'add'):
        if api.add_tenant(name=object_id):
            print "SUCCESS: Tenant %s created." % object_id

    elif (object_type, command) == ('tenant', 'list'):
        print_table(('id', 'name', 'enabled'), api.list_tenants())

    elif (object_type, command) == ('tenant', 'disable'):
        if api.disable_tenant(name=object_id):
            print "SUCCESS: Tenant %s disabled." % object_id

    elif (object_type, command) == ('role', 'add'):
        if api.add_role(name=object_id):
            print "SUCCESS: Role %s created successfully." % object_id

    elif (object_type, command) == ('role', 'list'):
        tenant = optional_arg(args, 2)
        if tenant:
            # print with users
            print 'Role assignments for tenant %s' % tenant
            print_table(('User', 'Role'), api.list_roles(tenant=tenant))
        else:
            # print without tenants
            print_table(('id', 'name'), api.list_roles())

    elif (object_type, command) == ('role', 'grant'):
        require_args(
            args, 4, "Missing arguments: role grant 'role' 'user' "
            "'tenant (optional)'")
        tenant = optional_arg(args, 4)
        if api.grant_role(object_id, args[3], tenant):
            print("SUCCESS: Granted %s the %s role on %s." %
                  (object_id, args[3], tenant))

    elif (object_type, command) == ('endpointTemplates', 'add'):
        require_args(
            args, 9, "Missing arguments: endpointTemplates add "
            "'region' 'service' 'publicURL' 'adminURL' 'internalURL' "
            "'enabled' 'global'")
        if api.add_endpoint_template(region=args[2],
                                     service=args[3],
                                     public_url=args[4],
                                     admin_url=args[5],
                                     internal_url=args[6],
                                     enabled=args[7],
                                     is_global=args[8]):
            print("SUCCESS: Created EndpointTemplates for %s pointing to %s." %
                  (args[3], args[4]))

    elif (object_type, command) == ('endpointTemplates', 'list'):
        tenant = optional_arg(args, 2)
        if tenant:
            print 'Endpoints for tenant %s' % tenant
            print_table(('service', 'region', 'Public URL'),
                        api.list_tenant_endpoints())
        else:
            print 'All EndpointTemplates'
            print_table(('service', 'region', 'Public URL'),
                        api.list_endpoint_templates())

    elif (object_type, command) == ('endpoint', 'add'):
        require_args(
            args, 4, "Missing arguments: endPoint add tenant "
            "endPointTemplate")
        if api.add_endpoint(tenant=args[2], endpoint_template=args[3]):
            print("SUCCESS: Endpoint %s added to tenant %s." %
                  (args[3], args[2]))

    elif (object_type, command) == ('token', 'add'):
        require_args(
            args, 6, 'Creating a token requires a token id, user, '
            'tenant, and expiration')
        if api.add_token(token=object_id,
                         user=args[3],
                         tenant=args[4],
                         expires=args[5]):
            print "SUCCESS: Token %s created." % (object_id, )

    elif (object_type, command) == ('token', 'list'):
        print_table(('token', 'user', 'expiration', 'tenant'),
                    api.list_tokens())

    elif (object_type, command) == ('token', 'delete'):
        if api.delete_token(token=object_id):
            print 'SUCCESS: Token %s deleted.' % (object_id, )

    elif (object_type, command) == ('service', 'add'):
        require_args(args, 4, "Missing arguments: service add name " "type")
        type = optional_arg(args, 3)
        desc = optional_arg(args, 4)
        if api.add_service(name=object_id, type=type, desc=desc):
            print "SUCCESS: Service %s created successfully." % (object_id, )

    elif (object_type, command) == ('service', 'list'):
        print_table(('id', 'name', 'type'), api.list_services())

    elif (object_type, command) == ('credentials', 'add'):
        require_args(
            args, 6, 'Creating a credentials requires a type, key, '
            'secret, and tenant_id (id is user_id)')
        if api.add_credentials(user=object_id,
                               type=args[3],
                               key=args[4],
                               secrete=args[5],
                               tenant=optional_arg(args, 6)):
            print "SUCCESS: Credentials %s created." % object_id

    else:
        # Command not handled
        print("ERROR: unrecognized command %s %s" % (object_type, command))
Exemplo n.º 16
0
def process(*args):
    # Check arguments
    if len(args) == 0:
        raise optparse.OptParseError(OBJECT_NOT_SPECIFIED)
    else:
        object_type = args[0]
        if object_type not in OBJECTS:
            raise optparse.OptParseError(SUPPORTED_OBJECTS)

    if len(args) == 1:
        raise optparse.OptParseError(ACTION_NOT_SPECIFIED)
    else:
        action = args[1]
        if action not in ACTIONS:
            raise optparse.OptParseError(SUPPORTED_ACTIONS)

    if action not in ['list', 'sync', 'version_control', 'version']:
        if len(args) == 2:
            raise optparse.OptParseError(ID_NOT_SPECIFIED)
        else:
            object_id = args[2]

    # Helper functions
    def require_args(args, min, msg):
        """Ensure there are at least `min` arguments"""
        if len(args) < min:
            raise optparse.OptParseError(msg)

    optional_arg = (lambda args, x:
        len(args) > x and str(args[x]).strip() or None)

    if object_type == 'database':
        options = get_options(args)

    # Execute command
    if (object_type, action) == ('user', 'add'):
        require_args(args, 4, 'No password specified for fourth argument')
        if api.add_user(name=object_id, password=args[3],
                tenant=optional_arg(args, 4)):
            print "SUCCESS: User %s created." % object_id

    elif (object_type, action) == ('user', 'list'):
        print Table('Users', ['id', 'name', 'enabled', 'tenant'],
                    api.list_users())

    elif (object_type, action) == ('user', 'disable'):
        if api.disable_user(name=object_id):
            print "SUCCESS: User %s disabled." % object_id

    elif object_type == 'user':
        raise optparse.OptParseError(ACTION_NOT_SUPPORTED % ('users'))

    elif (object_type, action) == ('tenant', 'add'):
        if api.add_tenant(name=object_id):
            print "SUCCESS: Tenant %s created." % object_id

    elif (object_type, action) == ('tenant', 'list'):
        print Table('Tenants', ['id', 'name', 'enabled'], api.list_tenants())

    elif (object_type, action) == ('tenant', 'disable'):
        if api.disable_tenant(name=object_id):
            print "SUCCESS: Tenant %s disabled." % object_id

    elif object_type == 'tenant':
        raise optparse.OptParseError(ACTION_NOT_SUPPORTED % ('tenants'))

    elif (object_type, action) == ('role', 'add'):
        if api.add_role(name=object_id, service_name=optional_arg(args, 3)):
            print "SUCCESS: Role %s created successfully." % object_id

    elif (object_type, action) == ('role', 'list'):
        tenant = optional_arg(args, 2)
        if tenant:
            # print with users
            print Table('Role assignments for tenant %s' % tenant,
                        ['User', 'Role'],
                       api.list_roles(tenant=tenant))
        else:
            # print without tenants
            print Table('Roles', ['id', 'name', 'service_id', 'description'],
                api.list_roles())

    elif (object_type, action) == ('role', 'grant'):
        require_args(args, 4, "Missing arguments: role grant 'role' 'user' "
            "'tenant (optional)'")
        tenant = optional_arg(args, 4)
        if api.grant_role(object_id, args[3], tenant):
            print("SUCCESS: Granted %s the %s role on %s." %
                (args[3], object_id, tenant))

    elif object_type == 'role':
        raise optparse.OptParseError(ACTION_NOT_SUPPORTED % ('roles'))

    elif (object_type, action) == ('endpointTemplates', 'add'):
        require_args(args, 9, "Missing arguments: endpointTemplates add "
            "'region' 'service_name' 'publicURL' 'adminURL' 'internalURL' "
            "'enabled' 'global'")
        version_id = optional_arg(args, 9)
        version_list = optional_arg(args, 10)
        version_info = optional_arg(args, 11)
        if api.add_endpoint_template(region=args[2], service=args[3],
                public_url=args[4], admin_url=args[5], internal_url=args[6],
                enabled=args[7], is_global=args[8],
                version_id=version_id, version_list=version_list,
                version_info=version_info):
            print("SUCCESS: Created EndpointTemplates for %s pointing to %s." %
                (args[3], args[4]))

    elif (object_type, action) == ('endpointTemplates', 'list'):
        tenant = optional_arg(args, 2)
        if tenant:
            print Table('Endpoints for tenant %s' % tenant,
                        ['id', 'service', 'region', 'Public URL'],
                        api.list_tenant_endpoints(tenant))
        else:
            print Table('All EndpointTemplates', ['id', 'service', 'type',
                        'region', 'enabled', 'is_global', 'Public URL',
                        'Admin URL'],
                api.list_endpoint_templates())

    elif (object_type, action) == ('endpoint', 'add'):
        require_args(args, 4, "Missing arguments: endPoint add tenant "
            "endPointTemplate")
        if api.add_endpoint(tenant=args[2], endpoint_template=args[3]):
            print("SUCCESS: Endpoint %s added to tenant %s." %
                (args[3], args[2]))

    elif object_type == 'endpoint':
        raise optparse.OptParseError(ACTION_NOT_SUPPORTED % ('endpoints'))

    elif (object_type, action) == ('token', 'add'):
        require_args(args, 6, 'Creating a token requires a token id, user, '
            'tenant, and expiration')
        if api.add_token(token=object_id, user=args[3], tenant=args[4],
                expires=args[5]):
            print "SUCCESS: Token %s created." % (object_id,)

    elif (object_type, action) == ('token', 'list'):
        print Table('Tokens', ('token', 'user', 'expiration', 'tenant'),
            api.list_tokens())

    elif (object_type, action) == ('token', 'delete'):
        if api.delete_token(token=object_id):
            print 'SUCCESS: Token %s deleted.' % (object_id,)

    elif object_type == 'token':
        raise optparse.OptParseError(ACTION_NOT_SUPPORTED % ('tokens'))

    elif (object_type, action) == ('service', 'add'):
        require_args(args, 4, "Missing arguments: service add <name> " \
                     "[type] [desc] [owner_id]"
            "type")
        type = optional_arg(args, 3)
        desc = optional_arg(args, 4)
        owner_id = optional_arg(args, 5)

        if api.add_service(name=object_id, type=type, desc=desc,
                           owner_id=owner_id):
            print "SUCCESS: Service %s created successfully." % (object_id,)

    elif (object_type, action) == ('service', 'list'):
        print Table('Services',
                    ('id', 'name', 'type', 'owner_id', 'description'),
                    api.list_services())

    elif object_type == 'service':
        raise optparse.OptParseError(ACTION_NOT_SUPPORTED % ('services'))

    elif (object_type, action) == ('credentials', 'add'):
        require_args(args, 6, 'Creating a credentials requires a type, key, '
            'secret, and tenant_id (id is user_id)')
        if api.add_credentials(user=object_id, type=args[3], key=args[4],
                secrete=args[5], tenant=optional_arg(args, 6)):
            print "SUCCESS: Credentials %s created." % object_id

    elif object_type == 'credentials':
        raise optparse.OptParseError(ACTION_NOT_SUPPORTED % ('credentials'))

    elif (object_type, action) == ('database', 'sync'):
        require_args(args, 1, 'Syncing database requires a version #')
        backend_names = options.get('backends', None)
        if backend_names:
            if 'keystone.backends.sqlalchemy' in backend_names.split(','):
                do_db_sync(options['keystone.backends.sqlalchemy'],
                                 args)
            else:
                raise optparse.OptParseError(
                    'SQL alchemy backend not specified in config')

    elif (object_type, action) == ('database', 'upgrade'):
        require_args(args, 1, 'Upgrading database requires a version #')
        backend_names = options.get('backends', None)
        if backend_names:
            if 'keystone.backends.sqlalchemy' in backend_names.split(','):
                do_db_upgrade(options['keystone.backends.sqlalchemy'],
                                 args)
            else:
                raise optparse.OptParseError(
                    'SQL alchemy backend not specified in config')

    elif (object_type, action) == ('database', 'downgrade'):
        require_args(args, 1, 'Downgrading database requires a version #')
        backend_names = options.get('backends', None)
        if backend_names:
            if 'keystone.backends.sqlalchemy' in backend_names.split(','):
                do_db_downgrade(options['keystone.backends.sqlalchemy'],
                                 args)
            else:
                raise optparse.OptParseError(
                    'SQL alchemy backend not specified in config')

    elif (object_type, action) == ('database', 'version_control'):
        backend_names = options.get('backends', None)
        if backend_names:
            if 'keystone.backends.sqlalchemy' in backend_names.split(','):
                do_db_version_control(options['keystone.backends.sqlalchemy'])
            else:
                raise optparse.OptParseError(
                    'SQL alchemy backend not specified in config')

    elif (object_type, action) == ('database', 'version'):
        backend_names = options.get('backends', None)
        if backend_names:
            if 'keystone.backends.sqlalchemy' in backend_names.split(','):
                do_db_version(options['keystone.backends.sqlalchemy'])
            else:
                raise optparse.OptParseError(
                    'SQL alchemy backend not specified in config')

    elif (object_type, action) == ('database', 'goto'):
        require_args(args, 1, 'Jumping database versions requires a '
            'version #')
        backend_names = options.get('backends', None)
        if backend_names:
            if 'keystone.backends.sqlalchemy' in backend_names.split(','):
                do_db_goto_version(options['keystone.backends.sqlalchemy'],
                    version=args[2])
            else:
                raise optparse.OptParseError(
                    'SQL alchemy backend not specified in config')

    else:
        # Command recognized but not handled: should never reach this
        raise NotImplementedError()
Exemplo n.º 17
0
 def require_args(args, min, msg):
     """Ensure there are at least `min` arguments"""
     if len(args) < min:
         raise optparse.OptParseError(msg)
Exemplo n.º 18
0
 def exit(self):
     """Trigger the wxApp to exit."""
     raise optparse.OptParseError('exit')
Exemplo n.º 19
0
 def error(self, msg):
     """Overrides optparse's default error handling
     and instead raises an exception which will be caught upstream
     """
     raise optparse.OptParseError(msg)