Beispiel #1
0
    def take_action(self, parsed_args):

        region_name = parsed_args.region_name
        filter_name = parsed_args.filter_name

        if parsed_args.list_app_local:
            print 'List local app....'
            rlt = db.get_app_list(region_name, filter_name)
            return (( 'Name', 'Source Id', 'Region', 'State', 'Create At', 'Change At'), rlt)

        else:
            print 'List remote app....'

            (username, session_id) = utils.load_session()
            if not(username and session_id):
                return (),()

            (project_name, project_id, key_id) = utils.load_current_project()
            if not key_id:
                return (),()

            # get app list
            (err, result) = rpc.app_list(username, session_id, key_id, region_name)

            if err:
                print('Get app list failed')
                utils.hanlde_error(err,result)
            else:
                self.log.debug('> get {0} app list succeed!'.format(len(result)))
                print "App list in %s(%s):" % (project_name,project_id)
                return (('Id', 'Name', 'Region', 'State'),
                    ((app["id"], app["name"], app["region"], app["state"]) for app in result if (filter_name.lower() in app['name'].lower() and app["state"] in ["Running","Stopped"]) )
                )
Beispiel #2
0
    def take_action(self, parsed_args):

        (username, session_id)   = utils.load_session()
        if not(username and session_id):
            return (),()
 
        # get stack list
        (err, result) = rpc.stack_list(username, session_id, parsed_args.region_name)
        if err:
            print('Get stack list failed')
            utils.hanlde_error(err,result)
        else:
            self.log.debug('> get {0} stack(s) list succeed!\n'.format(len(result)))
            print "Stacks:"
            return (('Id', 'Name', 'Region', 'URL'),
                ((stack["id"], stack["name"], stack["region"], constant.IDE_URL + stack['id']) for stack in result if parsed_args.filter_name.lower() in stack['name'].lower() )
            )
Beispiel #3
0
    def take_action(self, parsed_args):

        (username, session_id)   = utils.load_session()
        if not(username and session_id):
            print 'Invalid login, no need logout!'
            return

        while True:
            confirm = raw_input('Are you sure to logout? [Y/n]:')
            if not confirm or confirm.lower() in ['y','n']:
                break

        if not confirm or confirm.lower() == 'y':
            # Logout
            (err, result) = rpc.logout(username, session_id)

            if err:
                utils.hanlde_error(err,result)
            else:
                print('\nLogout Success!')
Beispiel #4
0
    def take_action(self, parsed_args):

        (username, session_id)   = utils.load_session()
        if not(username and session_id):
            return (),()

        # get project list
        (err, result) = rpc.project_list(username, session_id)
        if err:
            print('Get project list failed')
            utils.hanlde_error(err,result)
        else:
            self.log.debug('> get {0} project(s) list succeed!\n'.format(len(result)))

            #set current workspace
            if len(result) > 0:

                home_folder = os.path.expanduser('~')
                project_cfg = home_folder + '/.visualops/project'
                project_name=""
                current_project = None

                if os.path.isfile(project_cfg):
                    (project_name, project_id, key_id) = utils.load_current_project()

                for project in result:
                    if not 'name' in project:
                        my_project = project
                    else:
                        if project['name'] == project_name:
                            current_project = project
                if not current_project:
                    current_project = my_project
                utils.set_current_project(current_project)
                print '\n"%s" is current project' % (current_project["name"] if 'name' in current_project else constant.DEFAULT_PROJECT)
                print 'Please run "visualops project select <project id>" to set current project.\n'

            print "Projects:"
            return (('Id', 'Name', 'URL'),
                ((project["id"], project["name"] if 'name' in project else constant.DEFAULT_PROJECT, constant.IDE_URL + project['id']) for project in result if ( 'name' in project and parsed_args.filter_name.lower() in project['name'].lower()) or (not 'name' in project) )
            )
Beispiel #5
0
    def take_action(self, parsed_args):

        (username, session_id)   = utils.load_session()
        if not(username and session_id):
            return None

        project_id = parsed_args.project_id
        if not project_id:
            print "project_id can not be empty"
            return None

        # get project list
        (err, result) = rpc.project_list(username, session_id, project_id)
        if err:
            print('Get project list failed')
            utils.hanlde_error(err,result)
        else:
            self.log.debug('> get {0} project(s) list succeed!\n'.format(len(result)))

            #set current workspace
            if len(result) == 1:
                current_project = result[0]
                utils.set_current_project(current_project)
                print 'Select "%s" as current project\n' % (current_project["name"] if 'name' in current_project else constant.DEFAULT_PROJECT)
Beispiel #6
0
    def take_action(self, parsed_args):

        print 'Show remote app info....'

        (username, session_id)   = utils.load_session()
        if not(username and session_id):
            return (),()

        (project_name, project_id, key_id) = utils.load_current_project()
        if not key_id:
            return (),()

        app_id = parsed_args.app_id

        print 'Pulling %s from remote ....\n' % app_id
        (err, result) = rpc.app_info(username, session_id, key_id, None, [app_id])

        if err:
            utils.hanlde_error(err,result)
        else:
            if len(result) == 0:
                print('The app does not exist\n')
                return (),()

            self.log.debug('> pull app %s succeed\n' %  app_id )

            app_json = result[0]
            del app_json['layout']
            del app_json['property']

            #generate yaml
            app = {
                'name'  : app_json['name'],
                'region': app_json['region'],
                'hosts' : {},
                'hosts_table' : {},
            }
            for (uid,comp) in app_json['component'].items():
                if unicode(comp['type']) == constant.RESTYPE['INSTANCE']:

                    app['hosts_table'][uid] = comp['name']

                    log_str = '> found instance {0}'.format(comp['name'])

                    if comp['state']:
                        log_str+=': has %s state(s)' % len(comp['state'])
                        hostname = comp['name']
                        container = {}
                        for (idx,state) in enumerate(comp['state']):
                            state_type = state['module']
                            if state_type == 'linux.docker.deploy':
                                container_name = state['parameter']['container']
                                if not container.has_key(state_type):
                                    container[state_type] = {}
                                container[state_type][container_name] = state['parameter']
                        app['hosts'][hostname] = container
                    else:
                        log_str+=': has no state'

                    self.log.debug(log_str)

            app_yaml = utils.dict2yaml(app)
            app_file = os.path.join(os.getcwd(), '%s.yaml' % app_id)
            with open(app_file,'w+') as f:
                f.writelines( app_yaml )

            self.log.debug( '\n> docker state info' )
            self.log.debug( '==============================================================' )
            self.log.debug( app_yaml )
            self.log.debug( '==============================================================' )
            self.app.stdout.write( '> %s is saved to %s\n' % (app_id, app_file) )

            print 'Done!'


            try:
                self.log.debug( "> load data from %s" % app_file )
                stream = open(app_file, 'r')
                app = yaml.load(stream)
            except Exception:
                raise RuntimeError('Load yaml error!')

            config = utils.gen_config(app.get("name","default-app"))
            is_succeed = False
            try:
                app['src_app_id'] = app_id
                app["name"] = config["appname"]
                self.clone_app(config, app)
                #insert app to local db
                db.create_app(config["appname"], config["appname"], app_id, app['region'], base64.b64encode(utils.dict2str(app)) )
                is_succeed = True
            except Result,e:
                print '!!!Expected error occur %s' % str(e.format())
            except Exception,e:
                print '!!!Unexpected error occur %s' % str(e)
Beispiel #7
0
    def take_action(self, parsed_args):

        app_id = parsed_args.app_id

        if parsed_args.info_app_local:
            print 'Show local app info ....'
            (app_info, app_data, container_info) = db.get_app_info( app_id )

            #1. format and output app info
            if not app_info or len(app_info) == 0:
                print "Can not found local app info '%s' " % app_id
                return ((),())
            title  = ['Name','Source Id','Region','State','Create At','Change At']
            header = ['Field','Value']
            app_info = [ title, list(app_info) ] #insert title
            app_info = map(list, zip(*app_info))    #matrix transpose
            print '\nApp info:'
            print utils.print_prettytable(header, app_info)

            #2. format and output app data
            if not app_data or len(app_data) == 0:
                print "Can not found local app data '%s' " % app_id
                return ((),())
            print '\nApp data:'
            print json.dumps(utils.str2dict(base64.b64decode(app_data[0])), indent=4)


            #3. output container info
            if not container_info or len(container_info) ==0:
                print 'No container'
                return ((),())
            print '\nContainer:'
            return (( 'Id', 'Name', 'App Id' ), container_info)

        else:
            print 'Show remote app info....'

            (username, session_id) = utils.load_session()
            if not(username and session_id):
                return (),()

            (project_name, project_id, key_id) = utils.load_current_project()
            if not key_id:
                return (),()

            # get app info
            (err, result) = rpc.app_info(username, session_id, key_id, None, [app_id])

            if err:
                print('Get app info failed')
                utils.hanlde_error(err,result)
            else:
                self.log.debug('> get {0} app(s) info'.format(len(result)))

                if len(result) == 0:
                    return (),()

                app_json = result[0]

                del app_json['layout']
                del app_json['property']

                instance_with_state    = 0
                instance_without_state = 0
                for (uid,comp) in app_json['component'].items():
                    if unicode(comp['type']) == constant.RESTYPE['INSTANCE']:

                        log_str = '> found instance {0}'.format(comp['name'])

                        if comp['state']:
                            log_str+=': has %s state(s)' % len(comp['state'])
                            instance_with_state+=1
                        else:
                            log_str+=': has no state'
                            instance_without_state+=1

                        self.log.debug(log_str)

                print "App Info in %s(%s):" % (project_name,project_id)
                columns = ( 'Id',
                            'Name',
                            'Region',
                            'Version',
                            'Module Tag',
                            'Component',
                            'Instance Total',
                            'Instance With State',
                            'Instance Without State',
                           )
                data = (
                        result[0]['id'],
                        result[0]['name'],
                        result[0]['region'],
                        result[0]['version'],
                        result[0]['agent']['module']['tag'],
                        len(result[0]['component']),
                        instance_with_state+instance_without_state,
                        instance_with_state,
                        instance_without_state,
                        )
                return (columns, data)
Beispiel #8
0
    def take_action(self, parsed_args):

        (username, session_id)   = utils.load_session()
        if not(username and session_id):
            return (),()

        (project_name, project_id, key_id) = utils.load_current_project()
        if not key_id:
            return (),()

        stack_id = parsed_args.stack_id

        print 'Pulling %s from remote ....\n' % stack_id
        (err, result) = rpc.stack_info(username, session_id, key_id, None, [stack_id])

        if err:
            print('Pull stack failed')
            utils.hanlde_error(err,result)
        else:
            if len(result) == 0:
                self.app.stdout.write('The stack does not exist\n')
                return (),()

            self.log.debug('> pull stack %s succeed\n' %  stack_id )

            stack_json = result[0]
            del stack_json['layout']
            del stack_json['property']

            #generate yaml
            app = {
                'name'  : stack_json['name'],
                'region': stack_json['region'],
                'hosts' : {},
                'hosts_table' : {},
            }
            for (uid,comp) in stack_json['component'].items():
                if unicode(comp['type']) == constant.RESTYPE['INSTANCE']:

                    app['hosts_table'][uid] = comp['name']

                    log_str = '> found instance {0}'.format(comp['name'])

                    if comp['state']:
                        log_str+=': has %s state(s)' % len(comp['state'])
                        hostname = comp['name']
                        container = {}
                        for (idx,state) in enumerate(comp['state']):
                            state_type = state['module']
                            if state_type == 'linux.docker.deploy':
                                container_name = state['parameter']['container']
                                if not container.has_key(state_type):
                                    container[state_type] = {}
                                container[state_type][container_name] = state['parameter']
                        app['hosts'][hostname] = container
                    else:
                        log_str+=': has no state'

                    self.log.debug(log_str)

            stack_yaml = utils.dict2yaml(app)
            stack_file = os.path.join(os.getcwd(), '%s.yaml' % stack_id)
            with open(stack_file,'w+') as f:
                f.writelines( stack_yaml )

            self.log.debug( '\n> docker state info' )
            self.log.debug( '==============================================================' )
            self.log.debug( stack_yaml )
            self.log.debug( '==============================================================' )
            self.app.stdout.write( '%s is saved to %s\n' % (stack_id, stack_file) )

            print 'Done!'
Beispiel #9
0
    def take_action(self, parsed_args):

        (username, session_id)   = utils.load_session()
        if not(username and session_id):
            return (),()

        (project_name, project_id, key_id) = utils.load_current_project()
        if not key_id:
            return (),()

        # get stack info
        stack_id = parsed_args.stack_id
        (err, result) = rpc.stack_info(username, session_id, key_id, None, [ stack_id ])

        if err:
            print('Get stack info failed')
            utils.hanlde_error(err,result)
        else:
            self.log.debug('> get {0} stack(s) info'.format(len(result)))

            if len(result) == 0:
                return (),()

            stack_json = result[0]

            del stack_json['layout']
            del stack_json['property']

            instance_with_state    = 0
            instance_without_state = 0
            for (uid,comp) in stack_json['component'].items():
                if unicode(comp['type']) == constant.RESTYPE['INSTANCE']:

                    log_str = '> found instance {0}'.format(comp['name'])

                    if comp['state']:
                        log_str+=': has %s state(s)' % len(comp['state'])
                        instance_with_state+=1
                    else:
                        log_str+=': has no state'
                        instance_without_state+=1

                    self.log.debug(log_str)

            print "Stack Info in %s(%s):" % (project_name,project_id)
            columns = ( 'Id',
                        'Name',
                        'Region',
                        'Version',
                        'Module Tag',
                        'Component',
                        'Instance Total',
                        'Instance With State',
                        'Instance Without State',
                       )
            data = (
                    result[0]['id'],
                    result[0]['name'],
                    result[0]['region'],
                    result[0]['version'],
                    result[0]['agent']['module']['tag'],
                    len(result[0]['component']),
                    instance_with_state+instance_without_state,
                    instance_with_state,
                    instance_without_state,
                    )
            return (columns, data)