def change_group_own(_path):
     code, output = TiServerControl.__exe_cmd(
         "sudo -n chgrp ${USER} -R %s" % _path)
     if code:
         log.error("Change group of %s failed." % _path)
     log.info("Change group of %s successfully.")
     return code
Exemple #2
0
    def main(self, arg, prog, class_name, command):

        # load ti-server info
        self.__load_config(self.TI_CONFIG)

        self.argv = arg
        self.parser = self.get_parser(prog, command)

        if not arg:
            self.do_help([])
            return 0

        args = self.parser.parse_args(arg)

        if args.func == self.do_help:
            self.do_help(args)
            return 0

        sys.path.append(
            os.path.split(os.path.split(os.path.realpath(__file__))[0])[0])
        module_name, class_name = class_name.rsplit('.', 1)
        __import__(module_name)
        module_meta = sys.modules[module_name]
        proxy = getattr(module_meta, class_name)(self.ti_server_url)
        try:
            args.func(proxy, args)
        except Exception as e:
            log.error("execute cmd: %s failed. error: %s, trace: %s" %
                      ("%s %s" %
                       (prog, args.func.__name__), e, traceback.format_exc()))
            print("execute cmd: %s failed. error: %s, trace: %s" %
                  ("%s %s" %
                   (prog, args.func.__name__), e, traceback.format_exc()))
Exemple #3
0
    def https_request(self, method, url, **kwargs):
        """Deal with http request use urllib2

        :param method: str, request method
        :param url: str, server url
        :param kwargs: tuple list, other specified arguments
        :return: urllib2 Response object, response
        """
        if (not method) or (not url):
            raise HTTPException("The input params is null.")
        # replace http protocol to https
        _url = url.strip()
        _url = _url.replace("http://", "https://", 1)
        # judge protocol is https or not
        if not _url.startswith("https://"):
            raise HTTPException("The url is illegal,url=%s." % url)
        req_param = dict()
        url_open_param = dict()
        req_param["url"] = url
        # set request headers
        req_param["headers"] = {"Content-Type": "application/json"}
        if "headers" in kwargs:
            req_param["headers"] = kwargs["headers"]
        # set request body
        if "body" in kwargs:
            if req_param["headers"]["Content-Type"] == "application/gzip":
                req_param["data"] = kwargs["body"]
            else:
                req_param["data"] = \
                    json.dumps(kwargs["body"]).encode(encoding='UTF8')
        # build urllib2 Request object
        req = urllib2.Request(**req_param)
        self._set_method(req, method)
        # set max transfer time
        if "timeout" in kwargs:
            url_open_param["timeout"] = kwargs["timeout"]
        # judge verify exists or not
        if "verify" not in kwargs:
            raise HTTPException("The verify is null")
        # judge ssl verify file exists or not
        ca_path = kwargs["verify"]
        if not ca_path:
            url_open_param["context"] = ssl._create_unverified_context()
        elif self.is_file_exist(ca_path):
            url_open_param["context"] = ca_path
        else:
            raise HTTPException("The verify is illegal . verify=%s " % ca_path)
        # request to server
        try:
            response = urllib2.urlopen(req, **url_open_param)
            res_code = response.code
            res_data = response.read()
        except urllib2.HTTPError as e:
            log.error("http error: %s" % traceback.format_exc())
            res_code = e.getcode()
            res_data = e.read()
        return res_code, res_data
 def run(self):
     args = init_options()
     log.info("input argument: %s" % args)
     if args.config:
         self.__load_config(args.config)
     if args.action:
         action = args.action.lower()
         if action not in self.ACTION_LIST:
             log.error("action to control ti-server invalid.")
             raise Exception("Action to control ti-server invalid.")
         self.operate_ti_server(action)
Exemple #5
0
def main(prog, class_name, command):
    try:
        workspace_path = ""
        try:
            workspace_index = sys.argv.index("--workspace")
            workspace_path = sys.argv[workspace_index + 1]
        except ValueError as e:
            log.error("not an ti run command. workspace set as: %s, error: "
                      "%s" % (workspace_path, e))
        log_path = os.path.join("/root/", workspace_path, "test")
        log.init(log_path)
        sys.exit(Shell().main(sys.argv[1:], prog, class_name, command))
    except Exception as e:
        print("error occurred when execute cmd, error: %s, trace: %s" %
              (e, traceback.format_exc()))
        exit(1)
 def __stop_ti_server(self):
     log.info("begin to stop ti-server..")
     with open(TiServerControl.TI_CTL_LOCK, "r+") as fd:
         fcntl.flock(fd.fileno(), fcntl.LOCK_EX)
         is_run = self.is_ti_server_run()
         if not is_run:
             log.info("ti server is not run, exist ti_server_control")
         else:
             ti_server_pid = self.get_ti_server_pid()
             kill_cmd = "kill -9 %s" % ti_server_pid
             code, output = self.__exe_cmd(kill_cmd)
             if code:
                 log.error("ti server stop failed, code: %s, output: "
                           "%s" % (code, output))
                 raise Exception(output[-1])
             if os.path.exists(self.TI_SERVER_PID):
                 os.remove(self.TI_SERVER_PID)
             log.info("ti server stop successfully.")
Exemple #7
0
 def __load_config(self, config):
     if not os.path.exists(config):
         log.error("ti server configuration file not exist. "
                   "path: %s" % config)
         raise Exception("ti server configuration file not exist. "
                         "path: %s" % config)
     log.info("ti-server config path: %s" % config)
     ti_config = ConfigParser()
     ti_config.read(config)
     if not ti_config.has_section(self.TI_SERVER_SECTION):
         log.error("there is not ti server configuration in config "
                   "file: %s" % config)
         raise NoSectionError(self.TI_SERVER_SECTION)
     for option in self.ti_server_info:
         if not ti_config.has_option(self.TI_SERVER_SECTION, option):
             log.error("there is not ti server %s in config "
                       "file: %s" % (option, config))
             raise NoOptionError(option, self.TI_SERVER_SECTION)
         self.ti_server_info[option] = \
             ti_config.get(self.TI_SERVER_SECTION, option)
     self.ti_server_url = "http://%s:%s" % (self.ti_server_info["host"],
                                            self.ti_server_info["port"])
                            "--action",
                            metavar="",
                            required=True,
                            help="Action to control ti-server")
    parser_sub.add_argument("-c",
                            "--config",
                            metavar="",
                            required=True,
                            help="configuration file of ti-server")
    parsed_args = parser.parse_args()
    return parsed_args


if __name__ == "__main__":
    log.init("ti_server_control")

    ti_server = "ti_server_process.py"
    ti_server_root = TiServerControl.TI_SERVER_ROOT
    log.info("ti_server_root: %s, ti_server: %s" % (ti_server_root, ti_server))

    if not os.path.exists(TiServerControl.TI_CTL_LOCK):
        with open(TiServerControl.TI_CTL_LOCK, "w"):
            TiServerControl.change_group_own(TiServerControl.TI_CTL_LOCK)

    try:
        ti_server_ctl = TiServerControl(ti_server_root, ti_server)
        ti_server_ctl.run()
    except Exception as e:
        log.error("operate ti-server failed. error: %s, trace: %s" %
                  (e, traceback.format_exc()))