-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandler.py
More file actions
108 lines (94 loc) · 2.81 KB
/
Copy pathhandler.py
File metadata and controls
108 lines (94 loc) · 2.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
import subprocess
import time
import json
processes = dict()
result = dict()
def handle(req):
"""handle a request to the function
Args:
req (str): request body
"""
req_object = json.loads(str(req, encoding = "utf-8"))
if req_object.get("action") is None:
res = json.dumps({
"retCode": -1,
"message": "Invalid action."
})
action = req_object["action"]
if action == "RunCommand":
if req_object.get("command") is None or req_object.get("path") is None:
res = json.dumps({
"retCode": -1,
"message": "Command or path is missing."
})
return res
command = req_object["command"]
path = req_object["path"]
args = ""
if req_object.get("args") is not None:
args = req_object["args"]
args_array = args.split(" ")
id = run_command(command, path, args_array)
if id is None:
res = json.dumps({
"retCode": -1,
"message": "Action failed."
})
return res
else:
res = json.dumps({
"retcode": 0,
"id": id,
})
return res
if action == "GetStatus":
if req_object.get("id") is None:
res = json.dumps({
"retcode": -1,
})
return res
code, out, err = check(req_object["id"])
if code is None:
if err is not None:
res = json.dumps({
"retcode": -1,
"code": code,
"stdout": out,
"stderr": err,
})
return res
res = json.dumps({
"retcode": 1,
"code": code,
"stdout": out,
"stderr": err,
})
return res
else:
res = json.dumps({
"retcode": 0,
"code": code,
"stdout": out,
"stderr": err,
})
return res
return json.dumps({
"retcode": -1,
"message": "Invalid action."
})
def run_command(command, path, args):
proc = subprocess.Popen([command, path] + args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
processes[proc.pid] = proc
return proc.pid
def check(id):
if processes.get(id) is None:
return None, None, "Invalid ID."
else:
proc = processes[id]
return_code = proc.poll()
if return_code is None:
return None, None, None
else:
out, err = proc.communicate()
processes.pop(id, None)
return return_code, str(out, encoding = "utf-8"), str(err, encoding = "utf-8")