source: ogClient-Git/src/linux/ogOperations.py @ ffbcf7e

Last change on this file since ffbcf7e was ffbcf7e, checked in by OpenGnSys Support Team <soporte-og@…>, 5 years ago

Check return code on restore image command

When restore image command was sent and the restoration failed, you
could see in WebConsole? the image as restored and the command completed,
as it if had not failed. This happened because ogClient did not check
the return code of restoration script.

This commit adds return code check on restore image. So, when return
code is a non-zero value ogClient responses with an error 500. When
ogServer receives this error response, it did not set in the database
the image as restored and command as completed without errors.

  • Property mode set to 100644
File size: 9.2 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 os
10import json
11import subprocess
12from src.ogClient import ogClient
13
14OG_SHELL = '/bin/bash'
15
16class OgLinuxOperations:
17    def __init__(self, config):
18        self._url = config['opengnsys']['url']
19        self._url_log = config['opengnsys']['url_log']
20
21    def _restartBrowser(self, url):
22        try:
23            proc = subprocess.call(["pkill", "-9", "browser"])
24            proc = subprocess.Popen(["browser", "-qws", url])
25        except:
26            raise ValueError('Error: cannot restart browser')
27
28    def parseGetConf(self, out):
29        parsed = {'serial_number': '',
30              'disk_setup': '',
31              'partition_setup': list()}
32        configs = out.split('\n')
33        for line in configs[:-1]:
34            if 'ser=' in line:
35                parsed['serial_number'] = line.partition('ser=')[2]
36            else:
37                part_setup = {}
38                params = dict(param.split('=') for param in line.split('\t'))
39                # Parse partition configuration.
40                part_setup['disk'] = params['disk']
41                part_setup['partition'] = params['par']
42                part_setup['code'] = params['cpt']
43                part_setup['filesystem'] = params['fsi']
44                part_setup['os'] = params['soi']
45                part_setup['size'] = params['tam']
46                part_setup['used_size'] = params['uso']
47                if part_setup['partition'] == '0':
48                    parsed['disk_setup'] = part_setup
49                else:
50                    parsed['partition_setup'].append(part_setup)
51        return parsed
52
53    def poweroff(self):
54        if os.path.exists('/scripts/oginit'):
55            cmd = f'source {ogClient.OG_PATH}etc/preinit/loadenviron.sh; ' \
56                  f'{ogClient.OG_PATH}scripts/poweroff'
57            subprocess.call([cmd], shell=True, executable=OG_SHELL)
58        else:
59            subprocess.call(['/sbin/poweroff'])
60
61    def reboot(self):
62        if os.path.exists('/scripts/oginit'):
63            cmd = f'source {ogClient.OG_PATH}etc/preinit/loadenviron.sh; ' \
64                  f'{ogClient.OG_PATH}scripts/reboot'
65            subprocess.call([cmd], shell=True, executable=OG_SHELL)
66        else:
67            subprocess.call(['/sbin/reboot'])
68
69    def shellrun(self, request, ogRest):
70        cmd = request.getrun()
71        cmds = cmd.split(";|\n\r")
72
73        self._restartBrowser(self._url_log)
74
75        try:
76            ogRest.proc = subprocess.Popen(cmds,
77                               stdout=subprocess.PIPE,
78                               shell=True,
79                               executable=OG_SHELL)
80            (output, error) = ogRest.proc.communicate()
81        except:
82            raise ValueError('Error: Incorrect command value')
83
84        cmd_get_conf = f'{ogClient.OG_PATH}interfaceAdm/getConfiguration'
85        result = subprocess.check_output([cmd_get_conf], shell=True)
86        self._restartBrowser(self._url)
87
88        return output.decode('utf-8')
89
90    def session(self, request, ogRest):
91        disk = request.getDisk()
92        partition = request.getPartition()
93        cmd = f'{ogClient.OG_PATH}interfaceAdm/IniciarSesion {disk} {partition}'
94
95        try:
96            ogRest.proc = subprocess.Popen([cmd],
97                               stdout=subprocess.PIPE,
98                               shell=True,
99                               executable=OG_SHELL)
100            (output, error) = ogRest.proc.communicate()
101        except:
102            raise ValueError('Error: Incorrect command value')
103
104        return output.decode('utf-8')
105
106    def software(self, request, path, ogRest):
107        disk = request.getDisk()
108        partition = request.getPartition()
109
110        self._restartBrowser(self._url_log)
111
112        try:
113            cmd = f'{ogClient.OG_PATH}interfaceAdm/InventarioSoftware {disk} ' \
114                  f'{partition} {path}'
115
116            ogRest.proc = subprocess.Popen([cmd],
117                               stdout=subprocess.PIPE,
118                               shell=True,
119                               executable=OG_SHELL)
120            (output, error) = ogRest.proc.communicate()
121        except:
122            raise ValueError('Error: Incorrect command value')
123
124        self._restartBrowser(self._url)
125
126        software = ''
127        with open(path, 'r') as f:
128            software = f.read()
129        return software
130
131    def hardware(self, path, ogRest):
132        self._restartBrowser(self._url_log)
133
134        try:
135            cmd = f'{ogClient.OG_PATH}interfaceAdm/InventarioHardware {path}'
136            ogRest.proc = subprocess.Popen([cmd],
137                               stdout=subprocess.PIPE,
138                               shell=True,
139                               executable=OG_SHELL)
140            (output, error) = ogRest.proc.communicate()
141        except:
142            raise ValueError('Error: Incorrect command value')
143
144        self._restartBrowser(self._url)
145
146        return output.decode('utf-8')
147
148    def setup(self, request, ogRest):
149        disk = request.getDisk()
150        cache = request.getCache()
151        cache_size = request.getCacheSize()
152        partlist = request.getPartitionSetup()
153        cfg = f'dis={disk}*che={cache}*tch={cache_size}!'
154
155        for part in partlist:
156            cfg += f'par={part["partition"]}*cpt={part["code"]}*' \
157                   f'sfi={part["filesystem"]}*tam={part["size"]}*' \
158                   f'ope={part["format"]}%'
159
160            if ogRest.terminated:
161                break
162
163        cmd = f'{ogClient.OG_PATH}interfaceAdm/Configurar {disk} {cfg}'
164        try:
165            ogRest.proc = subprocess.Popen([cmd],
166                               stdout=subprocess.PIPE,
167                               shell=True,
168                               executable=OG_SHELL)
169            (output, error) = ogRest.proc.communicate()
170        except:
171            raise ValueError('Error: Incorrect command value')
172
173        cmd_get_conf = f'{ogClient.OG_PATH}interfaceAdm/getConfiguration'
174        result = subprocess.check_output([cmd_get_conf], shell=True)
175        self._restartBrowser(self._url)
176
177        return self.parseGetConf(result.decode('utf-8'))
178
179    def image_restore(self, request, ogRest):
180        disk = request.getDisk()
181        partition = request.getPartition()
182        name = request.getName()
183        repo = request.getRepo()
184        ctype = request.getType()
185        profile = request.getProfile()
186        cid = request.getId()
187        cmd = f'{ogClient.OG_PATH}interfaceAdm/RestaurarImagen {disk} {partition} ' \
188              f'{name} {repo} {ctype}'
189
190        self._restartBrowser(self._url_log)
191
192        try:
193            ogRest.proc = subprocess.Popen([cmd],
194                               stdout=subprocess.PIPE,
195                               shell=True,
196                               executable=OG_SHELL)
197            (output, error) = ogRest.proc.communicate()
198            if (ogRest.proc.returncode):
199                raise Exception
200        except:
201            raise ValueError('Error: Incorrect command value')
202
203        cmd_get_conf = f'{ogClient.OG_PATH}interfaceAdm/getConfiguration'
204        result = subprocess.check_output([cmd_get_conf], shell=True)
205        self._restartBrowser(self._url)
206
207        return output.decode('utf-8')
208
209    def image_create(self, path, request, ogRest):
210        disk = request.getDisk()
211        partition = request.getPartition()
212        name = request.getName()
213        repo = request.getRepo()
214        cmd_software = f'{ogClient.OG_PATH}interfaceAdm/InventarioSoftware {disk} ' \
215                   f'{partition} {path}'
216        cmd_create_image = f'{ogClient.OG_PATH}interfaceAdm/CrearImagen {disk} ' \
217                   f'{partition} {name} {repo}'
218
219        self._restartBrowser(self._url_log)
220
221        try:
222            ogRest.proc = subprocess.Popen([cmd_software],
223                               stdout=subprocess.PIPE,
224                               shell=True,
225                               executable=OG_SHELL)
226            (output, error) = ogRest.proc.communicate()
227        except:
228            raise ValueError('Error: Incorrect command value')
229
230        if ogRest.terminated:
231            return
232
233        try:
234            ogRest.proc = subprocess.Popen([cmd_create_image],
235                               stdout=subprocess.PIPE,
236                               shell=True,
237                               executable=OG_SHELL)
238            ogRest.proc.communicate()
239        except:
240            raise ValueError('Error: Incorrect command value')
241
242        self._restartBrowser(self._url)
243
244        return output.decode('utf-8')
245
246    def refresh(self, ogRest):
247        self._restartBrowser(self._url_log)
248
249        try:
250            cmd = f'{ogClient.OG_PATH}interfaceAdm/getConfiguration'
251            ogRest.proc = subprocess.Popen([cmd],
252                               stdout=subprocess.PIPE,
253                               shell=True,
254                               executable=OG_SHELL)
255            (output, error) = ogRest.proc.communicate()
256        except:
257            raise ValueError('Error: Incorrect command value')
258
259        self._restartBrowser(self._url)
260
261        return self.parseGetConf(output.decode('utf-8'))
Note: See TracBrowser for help on using the repository browser.