예제 #1
0
    def _handle_pack_command(self):
        """Pack the current mamba application
        """

        try:
            mamba_services = commons.import_services()
            mamba_services.config.Application('config/application.json')
        except Exception:
            mamba_services_not_found()

        use_egg = self.options.subOptions.opts['egg']
        command = 'bdist_egg' if use_egg else 'sdist'

        try:
            print('Packing {} application into {} format...'.format(
                self.options.subOptions.opts['name'],
                'egg' if use_egg else 'source'
            ).ljust(73), end='')
            Packer().pack_application(
                command,
                self.options.subOptions,
                mamba_services.config.Application()
            )
            print('[{}]'.format(darkgreen('Ok')))
        except:
            print('[{}]'.format(darkred('Fail')))
            raise
            sys.exit(-1)
예제 #2
0
    def _handle_uninstall_command(self):
        """Uninstall a package using pip (we don't want to reinvent the wheel)
        """

        if not PIP_IS_AVAILABLE:
            raise usage.UsageError('pip is not available')

        try:
            mamba_services = commons.import_services()
            mamba_services.config.Application('config/application.json')
        except Exception:
            mamba_services_not_found()

        name = 'mamba-{}'.format(mamba_services.config.Application(
            'config/application.json').name.lower()
        )
        print('Uninstalling {}...'.format(name).ljust(73), end='')
        try:
            p = subprocess.Popen(
                ['pip', 'uninstall', name],
                stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                stdin=subprocess.PIPE
            )
            stdout, error = p.communicate('y')
            if error is not '':
                raise RuntimeError(error)
            elif p.returncode is not 0:
                raise RuntimeError(stdout)
            else:
                print('[{}]'.format(darkgreen('Ok')))
        except:
            print('[{}]'.format(darkred('Fail')))
            raise
예제 #3
0
    def _handle_uninstall_command(self):
        """Uninstall a package using pip (we don't want to reinvent the wheel)
        """

        if not PIP_IS_AVAILABLE:
            raise usage.UsageError('pip is not available')

        try:
            mamba_services = commons.import_services()
            mamba_services.config.Application('config/application.json')
        except Exception:
            mamba_services_not_found()

        name = 'mamba-{}'.format(mamba_services.config.Application(
            'config/application.json').name.lower()
        )
        print('Uninstalling {}...'.format(name).ljust(73), end='')
        try:
            p = subprocess.Popen(
                ['pip', 'uninstall', name],
                stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                stdin=subprocess.PIPE
            )
            stdout, error = p.communicate('y')
            if error is not '':
                raise RuntimeError(error)
            elif p.returncode is not 0:
                raise RuntimeError(stdout)
            else:
                print('[{}]'.format(darkgreen('Ok')))
        except:
            print('[{}]'.format(darkred('Fail')))
            raise
예제 #4
0
def handle_stop_command():
    """I handle the stop command
    """

    try:
        import_services()
    except ImportError:
        print(
            'error: make sure you are inside a mamba application root '
            'directory and then run this command again'
        )
        sys.exit(-1)

    twisted_pid = filepath.FilePath('twistd.pid')
    if not twisted_pid.exists():
        print(
            'error: twistd.pid file can\'t be found. You should be in the '
            'applicatin directory in order to stop it'
        )
        sys.exit(-1)

    pid = twisted_pid.open().read()
    print('killing process id {} with SIGINT signal'.format(
        pid).ljust(73), end='')
    try:
        filepath.os.kill(int(pid), signal.SIGINT)
        print('[{}]'.format(darkgreen('Ok')))
    except:
        print('[{}]'.format(darkred('Fail')))
        raise
예제 #5
0
    def _handle_pack_command(self):
        """Pack the current mamba application
        """

        try:
            mamba_services = commons.import_services()
            mamba_services.config.Application('config/application.json')
        except Exception:
            mamba_services_not_found()

        use_egg = self.options.subOptions.opts['egg']
        command = 'bdist_egg' if use_egg else 'sdist'

        try:
            print('Packing {} application into {} format...'.format(
                self.options.subOptions.opts['name'],
                'egg' if use_egg else 'source'
            ).ljust(73), end='')
            Packer().pack_application(
                command,
                self.options.subOptions,
                mamba_services.config.Application()
            )
            print('[{}]'.format(darkgreen('Ok')))
        except:
            print('[{}]'.format(darkred('Fail')))
            raise
            sys.exit(-1)
예제 #6
0
 def wrapper(*args, **kwargs):
     try:
         result = func(*args, **kwargs)
         print('[{}]'.format(darkgreen('Ok')))
         return result
     except:
         print('[{}]'.format(darkred('Fail')))
         raise
예제 #7
0
    def _handle_configure_command(self):
        """Take care of SQL configuration to generate config/database.json file
        """

        try:
            mamba_services = commons.import_services()
        except Exception:
            mamba_services_not_found()

        if not self.options.subOptions.opts['noquestions']:
            query = (
                'You are going to generate (and possible overwrite) a '
                'database.json configuration file for your database. Are you '
                'sure do you want to do that? (Ctrl+c to abort)'
            )
            if commons.Interaction.userquery(query) == 'No':
                print('Skiping...')
                sys.exit(0)

        options = {
            'uri': self.options.subOptions.opts['uri'],
            'min_threads': self.options.subOptions.opts['min-threads'],
            'max_threads': self.options.subOptions.opts['max-threads'],
            'auto_adjust_pool_size': (True if (
                self.options.subOptions.opts['autoadjust-pool'])
                else False
            ),
            'create_table_behaviours': {
                'create_table_if_not_exists': (True if (
                    self.options.subOptions.opts['create-if-not-exists'])
                    else False
                ),
                'drop_table': (True if (
                    self.options.subOptions['drop-table']) else False
                )
            },
            'drop_table_behaviours': {
                'drop_if_exists': (True if(
                    self.options.subOptions.opts['drop-if-exists']) else False
                ),
                'restrict': (False if(
                    self.options.subOptions.opts['non-restrict']) else True
                ),
                'cascade': (True if(
                    self.options.subOptions.opts['cascade']) else False
                )
            }
        }

        try:
            print('Writing databse config file...'.ljust(73), end='')
            mamba_services.config.Database.write(options)
            print('[{}]'.format(darkgreen('Ok')))
        except OSError:
            print('[{}]'.format(darkred('Fail')))
            raise
            sys.exit(-1)
예제 #8
0
def handle_start_command(options):
    """I handle the start command
    """

    if GNU_LINUX or BSD:
        app = config.Application('config/application.json')
        if app.port <= 1024:
            if os.getuid() != 0:
                print(
                    '[{e}]: This application is configured to use a reserved '
                    'port (a port under 1025) only root can open a port from '
                    'this range root access is needed to start this '
                    'application using the {port} port.\n\nTry something '
                    'like: sudo mamba-admin start\n\nYou can also change the '
                    'configuration for this application editing '
                    '\'config/application.json\''.format(
                        e=darkred('ERROR'), port=app.port
                    )
                )
                sys.exit(-1)

    args = ['twistd']
    try:
        app_name = glob.glob(
            'twisted/plugins/*.py')[0].split(os.sep)[-1].split('_')[0]
    except IndexError:
        print(
            'error: twisted directory can\'t be found. You should be in '
            'the application directory in order to start it'
        )
        sys.exit(-1)

    if filepath.exists('twistd.pid'):
        print(
            'error: twistd.pid found, seems like the application is '
            'running already. If the application is not running, please '
            'delete twistd.pid and try again'
        )
        sys.exit(-1)

    if BSD:
        args.append('--reactor=kqueue')

    args.append(app_name)

    if options.subOptions.opts['port']:
        args.append('--port={}'.format(options.subOptions.opts['port']))

    print('starting application {}...'.format(app_name).ljust(73), end='')
    if subprocess.call(args) == 0:
        print('[{}]'.format(darkgreen('Ok')))
        sys.exit(0)
    else:
        print('[{}]'.format(darkred('Fail')))
        sys.exit(-1)
예제 #9
0
파일: routing.py 프로젝트: cypreess/mamba
    def install_routes(self, controller):
        """
        Install all the routes in a controller.

        :param controller: the controller where to fid routes
        :type controller: :class:`~mamba.Controller`
        """

        for func in inspect.getmembers(controller, predicate=inspect.ismethod):
            error = False
            if hasattr(func[1], 'route'):
                route = getattr(func[1], 'route')
                route.url = UrlSanitizer().sanitize_string(
                    controller.get_register_path() + route.url
                )
                route.compile()
                # normalize parameters
                real_args = inspect.getargspec(route.callback)[0]
                if real_args:
                    real_args = real_args[real_args.index('request') + 1:]
                    for arg in real_args:
                        if arg not in route.arguments.keys():
                            green = output.darkgreen
                            log.msg(
                                '{ERROR}: {arg} is not present in the {rout} '
                                'url for function {func_name}. Please, revise '
                                'your @route url string. The paramters names '
                                'in the url string should match the ones in '
                                'the function call. Skipping route registering'
                                '... this route ({route}) shouldn\'t be'
                                ' available at {controller}'.format(
                                    ERROR=output.brown('ERROR'),
                                    rout=green('@route'),
                                    arg=output.darkgreen(arg),
                                    func_name=green(route.callback.__name__),
                                    route=green('@route -> {}'.format(
                                        route.url
                                    )),
                                    controller=green(
                                        controller.__class__.__name__
                                    )
                                )
                            )
                            error = True

                if not error:
                    self.register_route(controller, route)
예제 #10
0
파일: routing.py 프로젝트: olivecoder/mamba
    def install_routes(self, controller):
        """Install all the routes in a controller.

        :param controller: the controller where to fid routes
        :type controller: :class:`~mamba.Controller`
        """

        for func in inspect.getmembers(controller, predicate=inspect.ismethod):
            error = False
            if hasattr(func[1], 'route'):
                route = getattr(func[1], 'route')
                route.url = UrlSanitizer().sanitize_string(
                    controller.get_register_path() + route.url
                )
                route.compile()
                # normalize parameters
                real_args = inspect.getargspec(route.callback)[0]
                if real_args:
                    real_args = real_args[real_args.index('request') + 1:]
                    for arg in real_args:
                        if arg not in route.arguments.keys():
                            green = output.darkgreen
                            log.msg(
                                '{ERROR}: {arg} is not present in the {rout} '
                                'url for function {func_name}. Please, revise '
                                'your @route url string. The paramters names '
                                'in the url string should match the ones in '
                                'the function call. Skipping route registering'
                                '... this route ({route}) shouldn\'t be'
                                ' available at {controller}'.format(
                                    ERROR=output.brown('ERROR'),
                                    rout=green('@route'),
                                    arg=output.darkgreen(arg),
                                    func_name=green(route.callback.__name__),
                                    route=green('@route -> {}'.format(
                                        route.url
                                    )),
                                    controller=green(
                                        controller.__class__.__name__
                                    )
                                )
                            )
                            error = True

                if not error:
                    self.register_route(controller, route, func[0])
예제 #11
0
    def _handle_install_already_packed_application(self, path):
        """Handles the installation of the given installable mamba app
        """

        packer = Packer()
        if not packer.is_mamba_package(path):
            raise usage.UsageError(
                '{} is not a valid mamba package file'.format(path))

        print('Installing {} application in {} store...'.format(
            path.basename(), 'global'
            if not self.options.subOptions['global'] else 'user').ljust(73),
              end='')
        try:
            packer.install_package_file(path, self.options.subOptions)
            print('[{}]'.format(darkgreen('Ok')))
        except:
            print('[{}]'.format(darkred('Fail')))
            raise
예제 #12
0
    def _handle_install_already_packed_application(self, path):
        """Handles the installation of the given installable mamba app
        """

        packer = Packer()
        if not packer.is_mamba_package(path):
            raise usage.UsageError(
                '{} is not a valid mamba package file'.format(path)
            )

        print('Installing {} application in {} store...'.format(
            path.basename(),
            'global' if self.options.subOptions['global'] else 'user'
        ).ljust(73), end='')
        try:
            packer.install_package_file(path, self.options.subOptions)
            print('[{}]'.format(darkgreen('Ok')))
        except:
            print('[{}]'.format(darkred('Fail')))
            raise
예제 #13
0
def handle_stop_command():
    """I handle the stop command
    """
    twisted_pid = filepath.FilePath('twistd.pid')
    if not twisted_pid.exists():
        print(
            'error: twistd.pid file can\'t be found. You should be in the '
            'application directory in order to stop it'
        )
        sys.exit(-1)

    pid = twisted_pid.open().read()
    print('killing process id {} with SIGINT signal'.format(
        pid).ljust(73), end='')
    try:
        filepath.os.kill(int(pid), signal.SIGINT)
        print('[{}]'.format(darkgreen('Ok')))
    except:
        print('[{}]'.format(darkred('Fail')))
        raise
예제 #14
0
    def _handle_install_current_directory(self, mamba_services):
        """Handles the installation of the current directory
        """

        packer = Packer()
        config = mamba_services.config.Application('config/application.json')

        print('Installing {} application in {} store...'.format(
            self.options.subOptions['name'],
            'global' if self.options.subOptions['global'] else 'user'
        ).ljust(73), end='')

        try:
            packer.create_package_directory(
                config.name.lower(), self.options.subOptions, config)
            packer.install_package_directory(self.options.subOptions)
            print('[{}]'.format(darkgreen('Ok')))
        except:
            print('[{}]'.format(darkred('Fail')))
            raise
예제 #15
0
    def _handle_install_current_directory(self, mamba_services):
        """Handles the installation of the current directory
        """

        packer = Packer()
        config = mamba_services.config.Application('config/application.json')

        print('Installing {} application in {} store...'.format(
            self.options.subOptions['name'],
            'global' if self.options.subOptions['global'] else 'user'
        ).ljust(73), end='')

        try:
            packer.create_package_directory(
                config.name.lower(), self.options.subOptions, config)
            packer.install_package_directory(self.options.subOptions)
            print('[{}]'.format(darkgreen('Ok')))
        except:
            print('[{}]'.format(darkred('Fail')))
            raise
예제 #16
0
    def _handle_uninstall_command(self):
        """Uninstall a package using pip (we don't want to reinvent the wheel)
        """

        if not PIP_IS_AVAILABLE:
            raise usage.UsageError('pip is not available')

        try:
            mamba_services = commons.import_services()
            mamba_services.config.Application('config/application.json')
        except Exception:
            mamba_services_not_found()

        name = 'mamba-{}'.format(mamba_services.config.Application(
            'config/application.json').name.lower()
        )
        print('Uninstalling {}...'.format(name).ljust(73), end='')
        try:
            p = subprocess.Popen(
                ['pip', 'uninstall', name],
                stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                stdin=subprocess.PIPE
            )
            p.communicate('y')
            # PROD-3384: previous code was checking stderr for errors but inside our
            # vagrant virtual environments stderr was returning a message telling us
            # to upgrade pip. This was resulting in the user being incorrectly told
            # the uninstall command had failed.
            # Now checking return code from command: should be 0 if the command was
            # successfully executed

            if p.returncode == 0:
                print('[{}]'.format(darkgreen('Ok')))
            else:
                raise Exception(
                    'Unexpected output from pip install command: {}'.format(p.returncode)
                )
        except:
            print('[{}]'.format(darkred('Fail')))
            raise
예제 #17
0
    def _pip_install_package(self):
        """Use pip to install a package.

        Requires package to be in a state which is pip installable, i.e. that a
        setup.py is already specified.
        Note that the legacy code is dynamically generating the setup.py file.
        See: Packer.write_setup_script
        """

        try:
            mamba_services = commons.import_services()
            mamba_services.config.Application('config/application.json')
        except Exception:
            mamba_services_not_found()

        name = 'mamba-{}'.format(
            mamba_services.config.Application('config/application.json').name.lower()
        )

        print('Installing {}...'.format(name).ljust(73), end='')
        try:

            args = ['pip', 'install', '--upgrade']

            if self.options.subOptions['user']:
                args.append(['--user'])

            args.append(os.curdir)

            p = subprocess.call(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

            if p == 0:
                print('[{}]'.format(darkgreen('Ok')))
            else:
                raise Exception('Unexpected output from pip install command: {}'.format(p))
        except:
            print('[{}]'.format(darkred('Fail')))
            raise
예제 #18
0
def handle_start_command(options=None, dropin_cache_wa=False):
    """I handle the start command
    """

    try:
        mamba_services = import_services()
        mamba_services.config.Application('config/application.json')
    except ImportError:
        print(
            'error: make sure you are inside a mamba application root '
            'directory and then run this command again'
        )
        sys.exit(-1)

    if POSIX:
        app = mamba_services.config.Application()
        if app.port is None:
            print(
                'Your application configuration file does not define a valid '
                'port. Is your configuration file valid JSON format?'
            )
            sys.exit(-1)
        elif app.port <= 1024:
            if os.getuid() != 0:
                print(
                    '[{e}]: This application is configured to use a reserved '
                    'port (a port under 1025) only root can open a port from '
                    'this range root access is needed to start this '
                    'application using the {port} port.\n\nTry something '
                    'like: sudo mamba-admin start\n\nYou can also change the '
                    'configuration for this application editing '
                    '\'config/application.json\''.format(
                        e=darkred('ERROR'), port=app.port
                    )
                )
                sys.exit(-1)

    args = ['twistd']
    try:
        app_name = glob.glob(
            'twisted/plugins/*.py')[0].split(os.sep)[-1].rsplit('_', 1)[0]
    except IndexError:
        print(
            'error: twisted directory can\'t be found. You should be in '
            'the application directory in order to start it'
        )
        sys.exit(-1)

    if filepath.exists('twistd.pid'):
        print(
            'error: twistd.pid found, seems like the application is '
            'running already. If the application is not running, please '
            'delete twistd.pid and try again'
        )
        sys.exit(-1)

    # determine if we are running in heroku
    in_heroku = '.heroku' in os.environ.get('PYTHONHOME', '')

    args.append('--nodaemon')
    if not in_heroku:
        if not mamba_services.config.Application().auto_select_reactor:
            args.append(determine_platform_reactor(mamba_services))
        if not mamba_services.config.Application().development:
            args.remove('--nodaemon')
            args.append('--syslog')

    args.append(app_name)

    if options is not None and options.subOptions.opts['port']:
        args.append('--port={}'.format(options.subOptions.opts['port']))

    if in_heroku or mamba_services.config.Application().development:
        os.execlp('twistd', *args)
    else:
        if not dropin_cache_wa:
            print(
                'starting application {}...'.format(app_name).ljust(73), end=''
            )
        proc = subprocess.Popen(
            args, stdin=subprocess.PIPE,
            stdout=subprocess.PIPE, stderr=subprocess.PIPE
        )
        out, err = proc.communicate()
        if not err:
            if 'exception' in out:
                result = darkred('Fail')
                exit_code = -1
            elif 'already installed' in out:
                return handle_start_command(options, True)
            else:
                result = darkgreen('Ok')
                exit_code = 0
        else:
            result = darkred('Fail')
            exit_code = -1

        print('[{}]'.format(result))
        print(err if exit_code == -1 else out)
        sys.exit(exit_code)