Example #1
0
def main(argv):
    console_handler = logging.StreamHandler(stream=sys.stderr)
    console_handler.setFormatter(logging.Formatter())
    console_handler.setLevel(logging.DEBUG)

    root_logger = logging.getLogger()
    root_logger.addHandler(console_handler)
    root_logger.setLevel(logging.INFO)
    root_logger.debug('Logger initialized')

    logging.getLogger("requests").propagate = False

    class SslConfiguration(Configuration):
        enabled = False
        key = '/etc/mcloud/ssl.key'
        cert = '/etc/mcloud/ssl.crt'

    class MyAppConfiguration(Configuration):

        CONF_PATHS = [
            '/etc/mcloud/mcloud-client.yml',
            # os.path.expanduser('~/.myapp.yaml'),
            # os.path.abspath('conf/myapp.yaml')
        ]

        haproxy = False

        ssl = SslConfiguration()

    settings = MyAppConfiguration.load()

    interrupt_manager = InterruptManager()
    interrupt_manager.append(ReactorInterruptHandler())
    interrupt_manager.register_interupt_handler()

    def my_config(binder):
        binder.bind('settings', settings)
        binder.bind('interrupt_manager', interrupt_manager)

    # Configure a shared injector.
    inject.configure(my_config)

    # client = ApiRpcClient(host=args.host, settings=settings)
    # subparsers.add_parser('!booo', help='Deploy application')

    if len(argv) == 2 and ('shell' == argv[1] or '@' in argv[1]):
        mcloud_shell(argv[1] if '@' in argv[1] else None)
        reactor.run()

    elif len(argv) == 1:
        arg_parser.print_help()
        sys.exit(2)

    else:
        args = arg_parser.parse_args()

        if args.verbose:
            log.startLogging(sys.stdout)

        args.argv0 = argv[0]

        if isinstance(args.func, str):

            log.msg('Starting task: %s' % args.func)

            @inlineCallbacks
            def call_command():
                client = ApiRpcClient(host=args.host, settings=settings)
                interrupt_manager.append(ClientProcessInterruptHandler(client))

                try:
                    yield getattr(client, args.func)(**vars(args))
                except Exception as e:
                    label = type(e)
                    if isinstance(e, ValueError):
                        label = 'error'
                    else:
                        label = str(label)

                    print '\n  %s: %s\n' % (
                        color_text(label, color='cyan'),
                        color_text(str(e), color='yellow'),
                    )

                interrupt_manager.manual_interrupt()

            call_command()
            reactor.run()

        else:
            ret = args.func(**vars(args))

            if isinstance(ret, defer.Deferred):
                def clb(*args):
                    reactor.callFromThread(reactor.stop)
                ret.addCallback(clb)

                reactor.run()
Example #2
0
def main(argv):
    console_handler = logging.StreamHandler(stream=sys.stderr)
    console_handler.setFormatter(logging.Formatter())
    console_handler.setLevel(logging.DEBUG)

    root_logger = logging.getLogger()
    root_logger.addHandler(console_handler)
    root_logger.setLevel(logging.INFO)
    root_logger.debug('Logger initialized')

    logging.getLogger("requests").propagate = False

    class SslConfiguration(Configuration):
        enabled = False
        key = '/etc/mcloud/ssl.key'
        cert = '/etc/mcloud/ssl.crt'

    class MyAppConfiguration(Configuration):

        CONF_PATHS = [
            '/etc/mcloud/mcloud-client.yml',
            # os.path.expanduser('~/.myapp.yaml'),
            # os.path.abspath('conf/myapp.yaml')
        ]

        haproxy = False

        ssl = SslConfiguration()

    settings = MyAppConfiguration.load()

    interrupt_manager = InterruptManager()
    interrupt_manager.append(ReactorInterruptHandler())
    interrupt_manager.register_interupt_handler()

    def my_config(binder):
        binder.bind('settings', settings)
        binder.bind('interrupt_manager', interrupt_manager)

    # Configure a shared injector.
    inject.configure(my_config)

    # client = ApiRpcClient(host=args.host, settings=settings)
    # subparsers.add_parser('!booo', help='Deploy application')

    if len(argv) == 2 and ('shell' == argv[1] or '@' in argv[1]):
        mcloud_shell(argv[1] if '@' in argv[1] else None)
        reactor.run()

    elif len(argv) == 1:
        arg_parser.print_help()
        sys.exit(2)

    else:
        args = arg_parser.parse_args()

        if args.verbose:
            log.startLogging(sys.stdout)

        args.argv0 = argv[0]

        if isinstance(args.func, str):

            log.msg('Starting task: %s' % args.func)

            @inlineCallbacks
            def call_command():
                client = ApiRpcClient(host=args.host, settings=settings)
                interrupt_manager.append(ClientProcessInterruptHandler(client))

                try:
                    yield getattr(client, args.func)(**vars(args))
                except Exception as e:
                    label = type(e)
                    if isinstance(e, ValueError):
                        label = 'error'
                    else:
                        label = str(label)

                    print '\n  %s: %s\n' % (
                        color_text(label, color='cyan'),
                        color_text(str(e), color='yellow'),
                    )

                interrupt_manager.manual_interrupt()

            call_command()
            reactor.run()

        else:
            ret = args.func(**vars(args))

            if isinstance(ret, defer.Deferred):

                def clb(*args):
                    reactor.callFromThread(reactor.stop)

                ret.addCallback(clb)

                reactor.run()
Example #3
0
def mcloud_shell(host_ref=None):

    settings = inject.instance('settings')
    interrupt_manager = inject.instance('interrupt_manager')

    readline.parse_and_bind('tab: complete')

    if host_ref:
        app, host = host_ref.split('@')
        state = {
            'app': app,
            'host': host,
        }
    else:
        state = {
            'app': None,
            'host': 'me',
        }

    def use(name, **kwargs):
        if '@' in name:
            app, host = name.split('@')
            if host.strip() == '':
                host = 'me'
            if app.strip() == '':
                app = None

            state['app'] = app
            state['host'] = host
        else:
            state['app'] = name

    cmd = subparsers.add_parser('use')
    cmd.add_argument('name', help='Application name', default=None, nargs='?')
    cmd.set_defaults(func=use)

    from mcloud.logo import logo
    print(logo)

    histfile = os.path.join(os.path.expanduser("~"), ".mcloud_history")
    try:
        readline.read_history_file(histfile)
    except IOError:
        pass

    interrupt_manager.append(ShellCancelInterruptHandler())  # prevent stop reactor on Ctrl + C

    line = ''
    while line != 'exit':

        print('')
        prompt = 'mcloud: %s@%s> ' % (state['app'] or '~', state['host'])

        try:
            line = None

            yield sleep(0.05)

            line = raw_input(color_text(prompt, color='white', bcolor='blue') + ' ').strip()

            if line.startswith('!'):
                os.system(line[1:])
                continue

            if line == '':
                continue

            if line == 'exit':
                break

            readline.write_history_file(histfile)

            params = line.split(' ')
            args = arg_parser.parse_args(params)

            args.argv0 = sys.argv[0]

            if args.host:
                host = args.host
            elif state['host'] == 'me' or not state['host']:
                # manual variable
                if 'MCLOUD_HOST' in os.environ:
                    host = os.environ['MCLOUD_HOST']

                # automatic when using docker container-link
                elif 'MCLOUD_PORT' in os.environ:
                    host = os.environ['MCLOUD_PORT']
                    if host.startswith('tcp://'):
                        host = host[6:]
                else:
                    host = '127.0.0.1'

            else:
                host = state['host']

            if ':' in host:
                host, port = host.split(':')
            else:
                port = 7080

            client = ApiRpcClient(host=host, port=port, settings=settings)
            interrupt_manager.append(ClientProcessInterruptHandler(client))

            for key, val in state.items():
                if not hasattr(args, key) or not getattr(args, key):
                    setattr(args, key, val)

            if isinstance(args.func, str):
                yield getattr(client, args.func)(**vars(args))
            else:
                yield args.func(**vars(args))


        except SystemExit:
            pass

        except EOFError:
            print('')
            break

        except KeyboardInterrupt:
            print('')
            pass

        except Exception as e:
            print '\n  %s\n' % color_text(e.message, color='yellow')

    reactor.callFromThread(reactor.stop)