Ejemplo n.º 1
0
    def run(self):
        cmdline = sys.argv[1:]  # Grab args from cmdline

        # Initial setup of logging (to allow for a few early debug statements)
        Logging.setup_logging(verbose=True, quiet=False)

        # If we are running in an openshift pod (via `oc new-app`) then
        # there is no cmdline but we want to default to "atomicapp run".
        if Utils.running_on_openshift():
            cmdline = 'run -v --dest=none --provider=openshift /{}'
            cmdline = cmdline.format(APP_ENT_PATH).split()  # now a list

        # If the user has elected to provide all arguments via the
        # ATOMICAPP_ARGS environment variable then set it now
        argstr = os.environ.get('ATOMICAPP_ARGS')
        if argstr:
            logger.debug("Setting cmdline args to: {}".format(argstr))
            cmdline = argstr.split()

        # If the user has elected to provide some arguments via the
        # ATOMICAPP_APPEND_ARGS environment variable then add those now
        argstr = os.environ.get('ATOMICAPP_APPEND_ARGS')
        if argstr:
            logger.debug("Appending args to cmdline: {}".format(argstr))
            cmdline.extend(argstr.split())

        # We want to be able to place options anywhere on the command
        # line. We have added all global options to each subparser,
        # but subparsers require all options to be after the 'action'
        # keyword. In order to handle this we just need to figure out
        # what subparser will be used and move it's keyword to the front
        # of the line.
        # NOTE: Also allow "mode" to override 'action' if specified
        args, _ = self.parser.parse_known_args(cmdline)
        cmdline.remove(args.action)  # Remove 'action' from the cmdline
        if args.mode:
            args.action = args.mode  # Allow mode to override 'action'
        cmdline.insert(0, args.action)  # Place 'action' at front

        # Finally, parse args and give error if necessary
        args = self.parser.parse_args(cmdline)

        # Setup logging (now with arguments from cmdline) and log a few msgs
        Logging.setup_logging(args.verbose, args.quiet, args.logtype)
        logger.info("Action/Mode Selected is: %s" % args.action)
        logger.debug("Final parsed cmdline: {}".format(' '.join(cmdline)))

        # In the case of Atomic CLI we want to allow the user to specify
        # a directory if they want to for "run". For that reason we won't
        # default the RUN label for Atomic App to provide an app_spec argument.
        # In this case pick up app_spec from $IMAGE env var (set by RUN label).
        if args.app_spec is None:
            if os.environ.get('IMAGE') is not None:
                logger.debug("Setting app_spec based on $IMAGE env var")
                args.app_spec = os.environ['IMAGE']
            else:
                print("Error. Too few arguments. Must provide app_spec.")
                print("Run with '--help' for more info")
                sys.exit(1)

        # Take the arguments that correspond to "answers" config file data
        # and make a dictionary of it to pass along in args.
        setattr(args, 'cli_answers', {})
        for item in [
                'providerapi', 'providercafile', 'providerconfig',
                'providertlsverify', 'namespace'
        ]:
            if hasattr(args, item) and getattr(args, item) is not None:
                args.cli_answers[item] = getattr(args, item)

        lock = LockFile(Utils.getLockFile())
        try:
            lock.acquire(timeout=-1)
            args.func(args)
        except AttributeError:
            if hasattr(args, 'func'):
                raise
            else:
                self.parser.print_help()
        except KeyboardInterrupt:
            pass
        except AlreadyLocked:
            logger.error(
                "Could not proceed - there is probably another instance of Atomic App running on this machine."
            )
        except Exception as ex:
            if args.verbose:
                raise
            else:
                logger.error("Exception caught: %s", repr(ex))
                logger.error(
                    "Run the command again with -v option to get more information."
                )
        finally:
            if lock.i_am_locking():
                lock.release()
Ejemplo n.º 2
0
    def run(self):
        cmdline = sys.argv[1:]  # Grab args from cmdline

        # Initial setup of logging (to allow for a few early debug statements)
        Logging.setup_logging(verbose=True, quiet=False)

        # If we are running in an openshift pod (via `oc new-app`) then
        # there is no cmdline but we want to default to "atomicapp run".
        if Utils.running_on_openshift():
            cmdline = 'run -v --dest=none --provider=openshift /{}'
            cmdline = cmdline.format(APP_ENT_PATH).split()  # now a list

        # If the user has elected to provide all arguments via the
        # ATOMICAPP_ARGS environment variable then set it now
        argstr = os.environ.get('ATOMICAPP_ARGS')
        if argstr:
            logger.debug("Setting cmdline args to: {}".format(argstr))
            cmdline = argstr.split()

        # If the user has elected to provide some arguments via the
        # ATOMICAPP_APPEND_ARGS environment variable then add those now
        argstr = os.environ.get('ATOMICAPP_APPEND_ARGS')
        if argstr:
            logger.debug("Appending args to cmdline: {}".format(argstr))
            cmdline.extend(argstr.split())

        # We want to be able to place options anywhere on the command
        # line. We have added all global options to each subparser,
        # but subparsers require all options to be after the 'action'
        # keyword. In order to handle this we just need to figure out
        # what subparser will be used and move it's keyword to the front
        # of the line.
        # NOTE: Also allow "mode" to override 'action' if specified
        args, _ = self.parser.parse_known_args(cmdline)
        cmdline.remove(args.action)     # Remove 'action' from the cmdline
        if args.mode:
            args.action = args.mode     # Allow mode to override 'action'
        cmdline.insert(0, args.action)  # Place 'action' at front

        # Finally, parse args and give error if necessary
        args = self.parser.parse_args(cmdline)

        # Setup logging (now with arguments from cmdline) and log a few msgs
        Logging.setup_logging(args.verbose, args.quiet, args.logtype)
        logger.info("Action/Mode Selected is: %s" % args.action)
        logger.debug("Final parsed cmdline: {}".format(' '.join(cmdline)))

        # In the case of Atomic CLI we want to allow the user to specify
        # a directory if they want to for "run". For that reason we won't
        # default the RUN label for Atomic App to provide an app_spec argument.
        # In this case pick up app_spec from $IMAGE env var (set by RUN label).
        if args.app_spec is None:
            if os.environ.get('IMAGE') is not None:
                logger.debug("Setting app_spec based on $IMAGE env var")
                args.app_spec = os.environ['IMAGE']
            else:
                print("Error. Too few arguments. Must provide app_spec.")
                print("Run with '--help' for more info")
                sys.exit(1)

        # Take the arguments that correspond to "answers" config file data
        # and make a dictionary of it to pass along in args.
        setattr(args, 'cli_answers', {})
        for item in ['providerapi', 'providercafile',
                     'providerconfig', 'providertlsverify', 'namespace']:
            if hasattr(args, item) and getattr(args, item) is not None:
                args.cli_answers[item] = getattr(args, item)

        lock = LockFile(Utils.getLockFile())
        try:
            lock.acquire(timeout=-1)
            args.func(args)
        except AttributeError:
            if hasattr(args, 'func'):
                raise
            else:
                self.parser.print_help()
        except KeyboardInterrupt:
            pass
        except AlreadyLocked:
            logger.error("Could not proceed - there is probably another instance of Atomic App running on this machine.")
        except Exception as ex:
            if args.verbose:
                raise
            else:
                logger.error("Exception caught: %s", repr(ex))
                logger.error(
                    "Run the command again with -v option to get more information.")
        finally:
            if lock.i_am_locking():
                lock.release()