Ejemplo n.º 1
0
class RemoveCommand(Command):
    def __init__(self, api_url):
        super(RemoveCommand, self).__init__()
        self.hippoServingService = HippoServingService(api_url)

    def verify_args(self, **kwargs):
        return kwargs

    def execute(self, **kwargs):

        try:
            inputs = self.verify_args(**kwargs)
            hippo_id = inputs.get(CliBeanColumn.ID.value)
            force = inputs.get(CliBeanColumn.FORCE.value)
            del_service = inputs.get(CliBeanColumn.DEL_SERVICE.value)
            request_entity = HippoInstanceRequest(id=hippo_id)
            # stop service
            if force:
                stop_success, stop_resp = self.hippoServingService.stop_service(
                    request_entity)
                if stop_success:
                    print('stop {} success'.format(hippo_id))
            if del_service:
                is_success, status_resp = self.hippoServingService.get_service_status(
                    request_entity)
            # unregister service
            is_success, resp = self.hippoServingService.remove_service(
                request_entity)
            if not is_success:
                raise Exception('message: {}\n reason: {}'.format(
                    resp.get('message'), resp.get('reason')))
            self.output(resp)

            # delete service plugin from project
            if del_service:
                self._execute(status_resp)
        except Exception as e:
            self.logger.error('Remove {} service failed'.format(hippo_id))
            self.logger.error(e.message)
            self.logger.debug(traceback.format_exc())

    def _execute(self, status_resp):
        # 1. get project_home, service name by hippo http
        project_home = status_resp[HippoColumn.CONFIG.value][
            HippoColumn.PATH.value]
        service_name = status_resp[HippoColumn.CONFIG.value][
            HippoColumn.SERVICENAME.value]

        # 2. delete service plugin
        hippo_build_service = HippoBuildService()

        delete_service = hippo_build_service.delete_service(
            service_name=service_name, project_home=project_home)
        if delete_service.status != 0:
            raise Exception("Delete {} Service plugin : {}".format(
                service_name, delete_service.stderr))
Ejemplo n.º 2
0
class StopCommand(Command):
    def __init__(self, api_host):
        super(StopCommand, self).__init__()
        self.hippoServingService = HippoServingService(api_host)

    def verify_args(self, **kwargs):
        return kwargs

    def execute(self, **kwargs):
        try:
            inputs = self.verify_args(**kwargs)
            hippo_id = inputs.get(CliBeanColumn.ID.value)
            # call http
            request_entity = HippoInstanceRequest(id=hippo_id)
            is_success, resp = self.hippoServingService.stop_service(
                request_entity)

            if not is_success:
                raise Exception('message: {}\n reason: {}'.format(resp.get('message'),resp.get('reason')))
            output_dict = self.refactor_result(resp)
            self.output(output_dict)

        except Exception as e:
            self.logger.error('Stop {} service failed'.format(hippo_id))
            self.logger.error(e.message)
            self.logger.debug(traceback.format_exc())
Ejemplo n.º 3
0
 def __init__(self, api_url):
     super(RemoveCommand, self).__init__()
     self.hippoServingService = HippoServingService(api_url)
Ejemplo n.º 4
0
 def __init__(self, api_url):
     super(RegisterCommand, self).__init__()
     self.hippoBuildService = HippoBuildService()
     self.hippoServingService = HippoServingService(api_url)
Ejemplo n.º 5
0
class RegisterCommand(Command):
    def __init__(self, api_url):
        super(RegisterCommand, self).__init__()
        self.hippoBuildService = HippoBuildService()
        self.hippoServingService = HippoServingService(api_url)

    def verify_args(self, **kwargs):
        project_home = kwargs.get(CliBeanColumn.PROJECT_HOME.value)
        service_name = kwargs.get(CliBeanColumn.SERVICE_NAME.value)
        run_cmd = kwargs.get(CliBeanColumn.RUN_CMD.value)

        if service_name is None:
            service_name = os.path.basename(project_home)
            kwargs[CliBeanColumn.SERVICE_NAME.value] = service_name
        if run_cmd is not None:
            run_cmd = '\"{}\"'.format(run_cmd)
            kwargs[CliBeanColumn.RUN_CMD.value] = run_cmd

        return kwargs

    def set_authkey(self, api_url):
        is_success, sshkey_result = self.hippoServingService.get_sshkey()
        sshkey = sshkey_result['key']
        if not is_success:
            raise Exception('message: {}\n reason: {}'.format(sshkey_result.get('message'),sshkey_result.get('reason')))
        # check authorized_keys exists
        auth_file = os.path.expanduser('~/.ssh/authorized_keys')
        if not os.path.exists(auth_file):
            with open(auth_file, 'w'):
                pass
            self.logger.info("create {}".format(auth_file))

        exists_key = list()
        with open(auth_file) as f:
            for line in f:
                exists_key.append(line.replace('\n',''))
        if sshkey not in exists_key:
            self.logger.info(
                "Add hippo manager ({}) ssh key to lcoal".format(api_url))
            self.logger.info(sshkey)
            with open(auth_file, 'a') as f:
                f.write(sshkey+'\n')
            self.logger.info('Set Authkey Success')
            print()

    def execute(self, **kwargs):
        inputs = self.verify_args(**kwargs)
        project_home = inputs.get(CliBeanColumn.PROJECT_HOME.value)
        service_name = inputs.get(CliBeanColumn.SERVICE_NAME.value)
        client_ip = inputs.get(CliBeanColumn.CLIENT_IP.value)
        run_cmd = inputs.get(CliBeanColumn.RUN_CMD.value)
        user = inputs.get(CliBeanColumn.USER.value)
        api_url = inputs.get(CliBeanColumn.API_URL.value)

        try:
            check_service = self.hippoBuildService.check_service(
                service_name=service_name, project_home=project_home)

            # 若 Project 未裝 plugin ,則先進行安裝
            if check_service.status != 0:
                create_service = self.hippoBuildService.create_service(
                    service_name=service_name, project_home=project_home,  cmd=run_cmd)
                print("Install {0} Hippo Plugin to {1}:{2} ".format(
                    service_name, client_ip, project_home))
                self.logger.info('==== create service ====')
                self.logger.info(create_service.stdout)

                double_check_service = self.hippoBuildService.check_service(
                    service_name=service_name, project_home=project_home)

                if double_check_service.status != 0:
                    raise Exception("Service plugin not found : {}".format(
                        double_check_service.stderr))
            conf_name = '{}-env.conf'.format(service_name)
            conf_path = os.path.join(
                project_home, 'hippo', 'etc', service_name, conf_name)

            cprint('Please confirm that the {} file is filled in correctly'.format(
                conf_path), 'green')
            cprint('================{} Header ====================='.format(
                conf_name), 'blue')
            common_util.print_by_file(conf_path, 'blue')
            cprint('================{} Footer =====================\n'.format(
                conf_name), 'blue')
            # TODO
            self.set_authkey(api_url)
            # call http
            register_request = HippoInstanceRequest(
                clientIP=client_ip, path=project_home, serviceName=service_name, user=user)
            is_success, resp = self.hippoServingService.register_service(
                register_request)

            if not is_success:
                raise Exception('message: {}\n reason: {}'.format(resp.get('message'),resp.get('reason')))
            self.output(resp)

        except Exception as e:
            self.logger.error(
                'Register {} service failed'.format(service_name))
            self.logger.error(e.message)
            self.logger.debug(traceback.format_exc())
Ejemplo n.º 6
0
 def __init__(self, api_host):
     super(StopCommand, self).__init__()
     self.hippoServingService = HippoServingService(api_host)
Ejemplo n.º 7
0
class StatusCommand(Command, object):
    def __init__(self, api_url):
        super(StatusCommand, self).__init__()
        self.hippoServingService = HippoServingService(api_url)

    def verify_args(self, **kwargs):
        return kwargs

    def execute(self, **kwargs):
        inputs = self.verify_args(**kwargs)
        hippo_id = inputs.get(CliBeanColumn.ID.value)
        try:
            # call http
            request_entity = HippoInstanceRequest(
                id=hippo_id)
            is_success, resp = self.hippoServingService.get_service_status(
                request_entity)

            if not is_success:
                raise Exception('message: {}\n reason: {}'.format(resp.get('message'),resp.get('reason')))
            output_dict = self.refactor_result(resp)
            self.output(output_dict)

        except Exception as e:
            self.logger.error('Get {} service status failed'.format(hippo_id))
            self.logger.error(e.message)
            self.logger.debug(traceback.format_exc())

    def execute_node(self, **kwargs):
        try:
            inputs = self.verify_args(**kwargs)
            user = inputs.get(CliBeanColumn.USER.value)
            client_ip = inputs.get(CliBeanColumn.CLIENT_IP.value)

            request_entity = HippoInstanceRequest(
                user=user, clientIP=client_ip)

            # call http
            is_success, resp = self.hippoServingService.get_node_status(
                request_entity)

            if not is_success:
                raise Exception(resp.get('message'))

            output_dict = self.refactor_node_result(resp)
            oeder_dict = self.output(output_dict)
        except Exception as e:
            self.logger.error('Get Node status failed')
            self.logger.error(e.message)
            self.logger.debug(traceback.format_exc())

    def execute_cluster(self, **kwargs):
        try:
            inputs = self.verify_args(**kwargs)
            user = inputs.get(CliBeanColumn.USER.value)
            client_ip = inputs.get(CliBeanColumn.CLIENT_IP.value)

            request_entity = HippoInstanceRequest(
                user=user, clientIP=client_ip)
            # call http
            is_success, resp = self.hippoServingService.get_cluster_status(
                request_entity)

            if not is_success:
                raise Exception(resp.get('message'))

            output_dict = self.refactor_cluster_result(resp)
            oeder_dict = self.output(output_dict)
        except Exception as e:
            self.logger.error('Get Node status failed')
            self.logger.error(e.message)
            self.logger.debug(traceback.format_exc())

    def refactor_cluster_result(self, resp):
        node_list = []
        for node in resp:
            node_info = self.refactor_node_result(node)
            node_list.append(node_info)
        return node_list

    def refactor_node_result(self, resp):
        node_dict = {}
        service_list = []

        for k, v in resp.items():
            if k == HippoNodeColumn.INSTANCES.value:
                for instance in v:
                    service_info = self.refactor_result(instance)
                    service_list.append(service_info)
                v = service_list
            elif k == HippoNodeColumn.SNAPSHOTTIME.value:
                v = datetime.datetime.fromtimestamp(
                    v / 1000.0).strftime("%Y-%m-%d %H:%M:%S")

            node_dict.setdefault(k, v)

        # order
        output_dict_ordered = self.order_dict(node_dict, HippoNodeColumn)
        return output_dict_ordered