source: ogClient-Git/src/ogRest.py @ b5e182f

Last change on this file since b5e182f was b5e182f, checked in by Alvaro Neira Ayuso <alvaroneay@…>, 5 years ago

Add Refresh command

This patch allows us to execute refresh command using ogClient. This command
gets all the configuration in our machine and send this information to the
server. The format of the message that ogClient will send to the server will be:

{"disk": "1", "partition_setup": [{"partition": "1", "code": "LINUX",
"filesystem": "NTFS", "size": "498688", "format": "0"}, {"partition": "2",
"code": "LINUX", "filesystem": "NTFS", "size": "498688", "format": "0"},
{"partition": "3", "code": "LINUX", "filesystem": "NTFS", "size": "498688",
"format": "0"}]}

  • Property mode set to 100644
File size: 8.4 KB
Line 
1#
2# Copyright (C) 2020 Soleta Networks <info@soleta.eu>
3#
4# This program is free software: you can redistribute it and/or modify it under
5# the terms of the GNU Affero General Public License as published by the
6# Free Software Foundation, version 3.
7#
8
9import threading
10import platform
11import time
12from enum import Enum
13import json
14import queue
15import sys
16import os
17import signal
18
19from src.HTTPParser import *
20
21if platform.system() == 'Linux':
22        from src.linux import ogOperations
23
24class jsonResponse():
25        def __init__(self):
26                self.jsontree = {}
27
28        def addElement(self, key, value):
29                self.jsontree[key] = value
30
31        def dumpMsg(self):
32                return json.dumps(self.jsontree)
33
34class restResponse():
35        def getResponse(response, jsonResp=None):
36                msg = ''
37                if response == ogResponses.BAD_REQUEST:
38                        msg = 'HTTP/1.0 400 Bad Request'
39                elif response == ogResponses.IN_PROGRESS:
40                        msg = 'HTTP/1.0 202 Accepted'
41                elif response == ogResponses.OK:
42                        msg = 'HTTP/1.0 200 OK'
43                elif response == ogResponses.INTERNAL_ERR:
44                        msg = 'HTTP/1.0 500 Internal Server Error'
45                elif response == ogResponses.UNAUTHORIZED:
46                        msg = 'HTTP/1.0 401 Unauthorized'
47                else:
48                        return msg
49
50                msg += '\r\n'
51
52                if jsonResp:
53                        msg += 'Content-Length:' + str(len(jsonResp.dumpMsg()))
54                        msg += '\r\nContent-Type:application/json'
55                        msg += '\r\n\r\n' + jsonResp.dumpMsg()
56                else:
57                        msg += '\r\n'
58
59                return msg
60
61class ogThread():
62        # Executing cmd thread
63        def execcmd(client, httpparser, ogRest):
64                if httpparser.getCMD() == None:
65                        client.send(restResponse.getResponse(ogResponses.BAD_REQUEST))
66                        return
67
68                try:
69                        shellout = ogOperations.execCMD(httpparser, ogRest)
70                except ValueError as err:
71                        client.send(restResponse.getResponse(ogResponses.BAD_REQUEST))
72                        return
73
74                if httpparser.getEcho():
75                        jsonResp = jsonResponse()
76                        jsonResp.addElement('out', shellout)
77                        client.send(restResponse.getResponse(ogResponses.OK, jsonResp))
78                else:
79                        client.send(restResponse.getResponse(ogResponses.OK))
80
81        # Powering off thread
82        def poweroff():
83                time.sleep(2)
84                ogOperations.poweroff()
85
86        # Rebooting thread
87        def reboot():
88                ogOperations.reboot()
89
90        # Process session
91        def procsession(client, httpparser, ogRest):
92                try:
93                        ogOperations.procsession(httpparser, ogRest)
94                except ValueError as err:
95                        client.send(restResponse.getResponse(ogResponses.INTERNAL_ERR))
96                        return
97
98                client.send(restResponse.getResponse(ogResponses.OK))
99
100        # Process software
101        def procsoftware(client, httpparser, path, ogRest):
102                try:
103                        ogOperations.procsoftware(httpparser, path, ogRest)
104                except ValueError as err:
105                        client.send(restResponse.getResponse(ogResponses.INTERNAL_ERR))
106                        return
107
108                jsonResp = jsonResponse()
109                jsonResp.addElement('disk', httpparser.getDisk())
110                jsonResp.addElement('partition', httpparser.getPartition())
111
112                f = open(path, "r")
113                lines = f.readlines()
114                f.close()
115                jsonResp.addElement('software', lines[0])
116
117                client.send(restResponse.getResponse(ogResponses.OK, jsonResp))
118
119        # Process hardware
120        def prochardware(client, path, ogRest):
121                try:
122                        ogOperations.prochardware(path, ogRest)
123                except ValueError as err:
124                        client.send(restResponse.getResponse(ogResponses.INTERNAL_ERR))
125                        return
126
127                jsonResp = jsonResponse()
128                f = open(path, "r")
129                lines = f.readlines()
130                f.close()
131                jsonResp.addElement('hardware', lines[0])
132                client.send(restResponse.getResponse(ogResponses.OK, jsonResp))
133
134        # Process setup
135        def procsetup(client, httpparser, ogRest):
136                jsonResp = jsonResponse()
137                jsonResp.addElement('disk', httpparser.getDisk())
138                jsonResp.addElement('cache', httpparser.getCache())
139                jsonResp.addElement('cache_size', httpparser.getCacheSize())
140                listconfig = ogOperations.procsetup(httpparser, ogRest)
141                jsonResp.addElement('partition_setup', listconfig)
142                client.send(restResponse.getResponse(ogResponses.OK, jsonResp))
143
144        # Process image restore
145        def procirestore(client, httpparser, ogRest):
146                try:
147                        ogOperations.procirestore(httpparser, ogRest)
148                except ValueError as err:
149                        client.send(restResponse.getResponse(ogResponses.INTERNAL_ERR))
150                        return
151
152                client.send(restResponse.getResponse(ogResponses.OK))
153
154        # Process image create
155        def procicreate(client, path, httpparser, ogRest):
156                try:
157                        ogOperations.procicreate(path, httpparser, ogRest)
158                except ValueError as err:
159                        client.send(restResponse.getResponse(ogResponses.INTERNAL_ERR))
160                        return
161
162                f = open(path, "r")
163                lines = f.readlines()
164                f.close()
165                jsonResp.addElement('software', lines[0])
166                client.send(restResponse.getResponse(ogResponses.OK, jsonResp))
167
168        # Process refresh
169        def procrefresh(client, ogRest):
170                try:
171                        out = ogOperations.procrefresh(ogRest)
172                except ValueError as err:
173                        client.send(restResponse.getResponse(ogResponses.INTERNAL_ERR))
174                        return
175
176                jsonResp = jsonResponse()
177                jsonResp.addElement('disk', out[0])
178                jsonResp.addElement('partition_setup', out[1])
179
180                client.send(restResponse.getResponse(ogResponses.OK, jsonResp))
181
182class ogResponses(Enum):
183        BAD_REQUEST=0
184        IN_PROGRESS=1
185        OK=2
186        INTERNAL_ERR=3
187        UNAUTHORIZED=4
188
189class ogRest():
190        def __init__(self):
191                self.proc = None
192                self.terminated = False
193
194        def processOperation(self, httpparser, client):
195                op = httpparser.getRequestOP()
196                URI = httpparser.getURI()
197
198                if (not "stop" in URI and not self.proc == None and self.proc.poll() == None):
199                        client.send(restResponse.getResponse(ogResponses.UNAUTHORIZED))
200                        return
201
202                if ("GET" in op):
203                        if "hardware" in URI:
204                                self.process_hardware(client)
205                        elif ("run/schedule" in URI):
206                                self.process_schedule(client)
207                        else:
208                                client.send(restResponse.getResponse(ogResponses.BAD_REQUEST))
209                elif ("POST" in op):
210                        if ("poweroff" in URI):
211                                self.process_poweroff(client)
212                        elif "probe" in URI:
213                                self.process_probe(client)
214                        elif ("reboot" in URI):
215                                self.process_reboot(client)
216                        elif ("shell/run" in URI):
217                                self.process_shellrun(client, httpparser)
218                        elif ("session" in URI):
219                                self.process_session(client, httpparser)
220                        elif ("software" in URI):
221                                self.process_software(client, httpparser)
222                        elif ("setup" in URI):
223                                self.process_setup(client, httpparser)
224                        elif ("image/restore" in URI):
225                                self.process_irestore(client, httpparser)
226                        elif ("stop" in URI):
227                                self.process_stop(client)
228                        elif ("image/create" in URI):
229                                self.process_icreate(client, httpparser)
230                        elif ("refresh" in URI):
231                                self.process_refresh(client)
232                        else:
233                                client.send(restResponse.getResponse(ogResponses.BAD_REQUEST))
234                else:
235                        client.send(restResponse.getResponse(ogResponses.BAD_REQUEST))
236
237                return 0
238
239        def process_reboot(self, client):
240                client.send(restResponse.getResponse(ogResponses.IN_PROGRESS))
241                client.disconnect()
242                threading.Thread(target=ogThread.reboot).start()
243
244        def process_poweroff(self, client):
245                client.send(restResponse.getResponse(ogResponses.IN_PROGRESS))
246                client.disconnect()
247                threading.Thread(target=ogThread.poweroff).start()
248
249        def process_probe(self, client):
250                jsonResp = jsonResponse()
251                jsonResp.addElement('status', 'OPG')
252                client.send(restResponse.getResponse(ogResponses.OK, jsonResp))
253
254        def process_shellrun(self, client, httpparser):
255                threading.Thread(target=ogThread.execcmd, args=(client, httpparser, self,)).start()
256
257        def process_session(self, client, httpparser):
258                threading.Thread(target=ogThread.procsession, args=(client, httpparser, self,)).start()
259
260        def process_software(self, client, httpparser):
261                path = '/tmp/CSft-' + client.ip + '-' + httpparser.getPartition()
262                threading.Thread(target=ogThread.procsoftware, args=(client, httpparser, path, self,)).start()
263
264        def process_hardware(self, client):
265                path = '/tmp/Chrd-' + client.ip
266                threading.Thread(target=ogThread.prochardware, args=(client, path, self,)).start()
267
268        def process_schedule(self, client):
269                client.send(restResponse.getResponse(ogResponses.OK))
270
271        def process_setup(self, client, httpparser):
272                threading.Thread(target=ogThread.procsetup, args=(client, httpparser, self,)).start()
273
274        def process_irestore(self, client, httpparser):
275                threading.Thread(target=ogThread.procirestore, args=(client, httpparser, self,)).start()
276
277        def process_stop(self, client):
278                client.disconnect()
279                if self.proc == None:
280                        return
281
282                if self.proc.poll() == None:
283                        os.killpg(os.getpgid(self.proc.pid), signal.SIGTERM)
284                        self.terminated = True
285                        sys.exit(0)
286
287        def process_icreate(self, client, httpparser):
288                path = '/tmp/CSft-' + client.ip + '-' + httpparser.getPartition()
289                threading.Thread(target=ogThread.procicreate, args=(client, path, httpparser, self,)).start()
290
291        def process_refresh(self, client):
292                threading.Thread(target=ogThread.procrefresh, args=(client, self,)).start()
Note: See TracBrowser for help on using the repository browser.