Example #1
0
    def run(self, xmlstr):
        root = ET.fromstring(xmlstr)
        version = None
        sn = None
        actionid = None
        actions = list()
        atype = None
        self._logger.info(__file__ + ":  parsing xml ...")
        for x in root:
            if x.tag == "head":
                version = x.attrib["version"]
                sn = x.attrib["sn"]
                actionid = x.attrib["actionid"]
                atype = x.attrib["actiontype"]
            elif x.tag == "subprocess":
                params = dict()
                for y in x:
                    if y.tag == "args":
                        params[y.tag] = json.loads(y.text)
                    else:
                        params[y.tag] = y.text
                actions.append({"type": x.tag, "params": params})

        if version == "1.0":
            if sn != EdgeConfig.getInstance().sn():
                raise Exception("serial number mismatched")
            if actionid == None or atype == None:
                raise Exception("no action id or action type exist")
            try:
                self.doactions(actionid, atype, actions)
            except Exception as e:
                self._logger.error(traceback.format_exc())
                astderr = type(e).__name__ + ": " + str(e).strip("'")
                report = utils.reportactionresult(sn, actionid, atype, -1, "", astderr)
                utils.http_post(EdgeConfig.getInstance().sms(), EdgeConfig.getInstance().smsport(), "/north/actionresult/", report)
Example #2
0
    def subprocess(self, aid, atype, params):
        env = dict()
        env["SN"] = EdgeConfig.getInstance().sn()
        env["ACTIONID"] = aid
        env["ACTIONTYPE"] = atype
        env["SMS"] = EdgeConfig.getInstance().sms()
        env["SMSPORT"] = str(EdgeConfig.getInstance().smsport())
        env["PYTHONPATH"] = os.environ["PYTHONPATH"]
        env["CONFIGFILE"] = EdgeConfig.getInstance().configfile()
        env["INPUTPORT"] = str(EdgeConfig.getInstance().inputport())
#        try:
#            env.append(params["env"])
#        except:
#            pass

        sp = subprocess.run(params["args"], env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        astdout = sp.stdout.decode()
        astderr = sp.stderr.decode()
        self._logger.info("action stdout: \n%s", astdout)
        self._logger.info("action stderr: \n%s", astderr)
        if sp.returncode != 0:

            report = utils.reportactionresult(env["SN"], aid, atype, sp.returncode, astdout[-100:-1], astderr[-200:-1])
            utils.http_post(EdgeConfig.getInstance().sms(), EdgeConfig.getInstance().smsport(), "/north/actionresult/",
                            report)
def doreport(ret, out, err):
    try:
        report = utils.reportactionresult(os.environ["SN"],
                                          os.environ["ACTIONID"],
                                          os.environ["ACTIONTYPE"], ret, out,
                                          err)
        utils.http_post(os.environ["SMS"], os.environ["SMSPORT"],
                        "/north/actionresult/", report)
    except:
        print("returncode: ", ret)
        print("stdout: ", out)
        print("stderr: ", err)
Example #4
0
    def ready(self, count):
        ip = self.ip()
        if ip is None:
            return False

        opts = {"entry": "httpself", "cmd": "readycheck"}
        try:
            resp = utils.http_post(ip, 11112, "/", opts)
            if resp.getcode() == 200 and resp.read().decode("utf-8") == "OK":
                return True
        except Exception as e:
            self._logger.info(
                f'docker is not ready({ip}:{count}), exceptin {str(e)}')
            #self._logger.info(traceback.format_exc())
            return False
        self._logger.info(
            f'docker is not ready({ip}:{count}), {resp.getcode()}, {resp.read().decode("utf-8")}'
        )
        return False
from edgeutils import utils
import os
import time

# test new simpletun service version
if __name__ == "__main__":
    cwd = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
    assert utils.runningUnderGitProjectRootDirectory(cwd)
    os.chdir(cwd)

    #opts = {"entry": "mainself", "cmd": "pollnotify"}
    #opts = {"entry": "http", "module": "stun", "cmd": "add", "node": "client", "server": "127.0.0.1", "port": "1299",
    #        "tunortap": "tap", "ptunnelip": "192.168.23.19", "tunneltype": "ipsec"}
    #opts = {"entry": "http", "module": "stun", "cmd": "add", "node": "server", "port": "55556",
    #        "tunortap": "tap", "tunnelip": "192.168.2.29", "tunneltype": "ipsec"}
    #opts = {"entry": "http", "module": "stun", "cmd": "delete", "node": "server", "port": "55556",
    #        "tunortap": "tap", "tunnelip": "10.139.47.1", "tunneltype": "ipsec", "remoteip": "10.129.101.99"}

    #opts = {"entry": "http", "module": "network", "cmd": "bridgeadd", "brname": "br0", "intf": "enp1s0"}
    #opts = {"entry": "http", "module": "network", "cmd": "newgateway", "ip": "10.100.20.1/24"}
    opts = {"entry": "httpself", "cmd": "readycheck"}

    #resp = utils.http_post("127.0.0.1", 11112, "/", opts)
    resp = utils.http_post("172.17.0.6", 11112, "/", opts)
    print(__file__, resp.getcode(), resp.read().decode("utf-8"))
    print("end")
Example #6
0
    config["CMD"] = "query"

    try:
        wans, subnets = getwans()
    except:
        wans = dict()
        subnets = []
        pass

    config["wans"] = wans
    try:
        config["subnets"]
    except:
        config["subnets"] = subnets

    version = EdgeConfig.getInstance().edgeversion()
    config["version"] = version["major"] + "." + version["minor"] + "." + version["commit"]
    try:
        os.environ["SN"]
    except:
        # in test environment, just exit, do not report
        print(config)
        print("test environment", file=sys.stderr)
        sys.exit(-1)
    report = utils.reportactionresult(os.environ["SN"], os.environ["ACTIONID"], os.environ["ACTIONTYPE"],
                                          0, str(config), "")
    utils.http_post(os.environ["SMS"], os.environ["SMSPORT"], "/north/actionresult/", report)
    sys.exit(0)


Example #7
0
    cwd = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
    assert utils.runningUnderGitProjectRootDirectory(cwd)
    os.chdir(cwd)

    ec = edgeconfig.EdgeConfig.getInstance()
    ec.loadconfig("./config.json")

    #start http server
    pservertask = Process(target=servertask, args=(ec, ))
    pservertask.start()

    time.sleep(1)
    # we can send pollnotify, if we know edge's ip address to fasten the polling
    print(__file__, ": send pollnotify")
    opts = {"entry": "mainself", "cmd": "notifypoll"}
    resp = utils.http_post("127.0.0.1", ec.inputport(), "/", opts)
    try:
        pservertask.join()
    except KeyboardInterrupt:
        print("test.py is break")
    except Exception as e:
        print("test.py exception", type(e).__name__, str(e))

# test new simpletun service version
if __name__ == "__main__1":
    cwd = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
    assert utils.runningUnderGitProjectRootDirectory(cwd)
    os.chdir(cwd)

    ec = edgeconfig.EdgeConfig.getInstance()
    ec.loadconfig("./config.json")
            }
        else:
            isclient = False
            opts = {
                "entry": "http",
                "module": "stun",
                "cmd": "query",
                "node": "server",
                "port": port
            }
    except:
        doreport(-1, str(sys.argv), "Error Parameters")
        sys.exit(-1)

    out = ""
    resp = utils.http_post("127.0.0.1", 11112, "/", opts)
    out += resp.read().decode("utf-8")

    doreport(0, out, "")
    '''
    sp = subprocess.run(["ping", "-I", tap, "-c", "3", "-W", "3", ip], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    tout = sp.stdout.decode()
    terr = sp.stderr.decode()
    tret = sp.returncode

    out += tout
    if tret != 0:
        doreport(-1, out, terr)
        sys.exit(-1)

    doreport(0, out, "")
Example #9
0
        elif o in "-v":
            verbose = "-v"
        elif o in "-d":
            remove = True
            pass

    int(port)
    inputport = os.environ["INPUTPORT"]  #notifyport
    if remove:
        opts = {
            "entry": "http",
            "module": "stun",
            "cmd": "delete",
            "port": port
        }
        resp = utils.http_post("127.0.0.1", inputport, "/", opts)
        result = ""
        if resp.getcode() == 200:
            result = resp.read().decode("utf-8")
            if result == "OK":
                doreport(0, "OK", "")
                sys.exit(0)
        else:
            result = "post to notifytask fail"
        doreport(0, "NOK", result)
        sys.exit(0)

    if localip == None:
        print("Localip is not provided", file=sys.stderr)
        usage()
        sys.exit(-1)