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)
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)
def _handle_reset_command(self): """Take care of database reset """ mamba_services, db = self._prepare_model_db() if not self.options.subOptions.opts['noquestions']: question = ( 'This operation will {delete} all the data in your database.\n' 'Are you really sure this is what you want to do?'.format( delete=darkred('DELETE') ) ) if commons.Interaction.userquery(question) == 'No': sys.exit(0) reset_data = db.reset(ModelManager()) # PySQLite does not allow us to perform more than one operation if db.backend == 'sqlite': for query in reset_data.split(';'): db.store().execute(query) else: db.store().execute(reset_data) db.store().commit() print('All the data in your database has been reset.') sys.exit(0)
def _handle_reset_command(self): """Take care of database reset """ mamba_services, db = self._prepare_model_db() if not self.options.subOptions.opts['noquestions']: question = ( 'This operation will {delete} all the data in your database.\n' 'Are you really sure this is what you want to do?'.format( delete=darkred('DELETE'))) if commons.Interaction.userquery(question) == 'No': sys.exit(0) reset_data = db.reset(ModelManager()) # PySQLite does not allow us to perform more than one operation if db.backend == 'sqlite': for query in reset_data.split(';'): db.store().execute(query) else: db.store().execute(reset_data) db.store().commit() print('All the data in your database has been reset.') sys.exit(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
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
def wrapper(*args, **kwargs): try: result = func(*args, **kwargs) print('[{}]'.format(darkgreen('Ok'))) return result except: print('[{}]'.format(darkred('Fail'))) raise
def _generate_application_directory(self): """Generates the application directory in the current path """ try: # create project directory directory = filepath.FilePath( '{}/{}'.format(filepath.os.getcwd(), self.app_dir)) if directory.exists() and self.noask is False: print( 'Seems like an application named {} already exists in ' 'your current path.'.format(directory.basename()) ) query = 'Would you like to rename it? (Ctrl+c to abort)' if Interaction.userquery(query) == 'Yes': rnd = str(filepath.random.randrange(1, 10000)) filepath.os.rename( directory.path, '{}{}'.format(directory.path, rnd) ) print('The old directory has been saved as {}'.format( brown('{}{}'.format(directory.path, rnd)) )) else: query = 'The {} directory is going to be {}, Are you sure?' query = query.format( directory.basename(), darkred('deleted') ) if Interaction.userquery(query) == 'Yes': print('Deleting {}...'.format(directory.basename())) directory.remove() else: print('Quitting.') sys.exit(0) elif directory.exists() and self.noask is True: directory.remove() print('Creating {} directory...'.format( directory.basename()).ljust(73), end='' ) directory.createDirectory() except OSError as error: print(darkred(error)) sys.exit(-1)
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)
def _generate_application_directories(self): """Generates the application needed directories """ try: self._generate_directory_helper('application/') self._generate_directory_helper('application/controller') self._generate_directory_helper('application/model') self._generate_directory_helper('application/view') self._generate_directory_helper('application/view/templates') self._generate_directory_helper('application/view/stylesheets') self._generate_directory_helper('twisted') self._generate_directory_helper('twisted/plugins') self._generate_directory_helper('static') self._generate_directory_helper('config') except OSError as error: print(darkred(error)) sys.exit(-1)
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
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
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
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
def _generate_application_directories(self): """Generates the application needed directories """ try: self._generate_directory_helper('application/') self._generate_directory_helper('application/lib') self._generate_directory_helper('application/controller') self._generate_directory_helper('application/model') self._generate_directory_helper('application/view') self._generate_directory_helper('application/view/templates') self._generate_directory_helper('application/view/stylesheets') self._generate_directory_helper('twisted') self._generate_directory_helper('twisted/plugins') self._generate_directory_helper('static') self._generate_directory_helper('config') self._generate_directory_helper('logs') except OSError as error: print(darkred(error)) sys.exit(-1)
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
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
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)