Fix: First boot from floppy, not CD-ROM
[ta/remote-installer.git] / src / remoteinstaller / installer / bmc_management / falcon.py
1 # Copyright 2019 Nokia
2 # Copyright 2020 ENEA
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
7 #
8 #     http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15
16 import logging
17 import time
18 from .bmctools import BMC, BMCException
19
20 RAW_CHECK_NFS_SERVICE_STATUS = '0x32 0xd8 0x06 0x01 0x01 0x00'
21
22 RAW_GET_VMEDIA_DEVICE_COUNT = '0x32 0xca %s'     # (type)
23 RAW_SET_VMEDIA_DEVICE_COUNT = '0x32 0xcb %s %s'  # (type, count)
24 ( VMEDIA_DEVICE_TYPE_CD,
25   VMEDIA_DEVICE_TYPE_FD,
26   VMEDIA_DEVICE_TYPE_HD ) = ('0x04', '0x05', '0x06')
27
28 RAW_GET_VMEDIA_MOUNT_STATUS = '0x32 0xca 0x00'
29 RAW_SET_VMEDIA_MOUNT_STATUS = '0x32 0xcb 0x00 %s'
30
31 RAW_GET_VMEDIA_STATUS = '0x32 0xca 0x08'
32 RAW_SET_VMEDIA_STATUS = '0x32 0xcb 0x08 %s'
33 RAW_RESTART_VMEDIA =    '0x32 0xcb 0x0a 0x01'
34
35 # Remote Image Service commands
36 RAW_RESTART_RIS_CD =   '0x32 0x9f 0x01 0x0b 0x01'
37 RAW_SET_RIS_NFS =      '0x32 0x9f 0x01 0x05 0x00 0x6e 0x66 0x73 0x00 0x00 0x00'
38 RAW_SET_RIS_NFS_IP =   '0x32 0x9f 0x01 0x02 0x00 %s'
39 RAW_SET_RIS_NFS_PATH = '0x32 0x9f 0x01 0x01 0x01 %s'
40 RAW_SET_RIS_PROGRESS = '0x32 0x9f 0x01 0x01 0x00 %s'
41 RAW_CLEAR_RIS_CONFIG = '0x32 0x9f 0x01 0x0d'
42 RAW_RESTART_RIS =      '0x32 0x9f 0x08 0x0b'
43
44 RAW_GET_MOUNTED_IMG_COUNT = '0x32 0xd8 0x00 0x01'
45 RAW_SET_IMG_NAME =  '0x32 0xd7 0x01 0x01 0x01 0x01 %s'
46 RAW_STOP_REDIRECT = '0x32 0xd7 0x01 0x01 0x01 0x00 %s'
47
48 class FALCON(BMC):
49     def __init__(self, host, user, passwd, priv_level='ADMINISTRATOR', log_path=None):
50         super(FALCON, self).__init__(host, user, passwd, priv_level, log_path)
51
52     def _clear_ris_configuration(self):
53         # Clear Remote Image Service configuration
54         try:
55             logging.debug('Clear RIS configuration.')
56             self._run_ipmitool_raw_command(RAW_CLEAR_RIS_CONFIG)
57         except Exception as err:
58             logging.warning('Exception when clearing RIS NFS configuration: %s', str(err))
59             return False
60         return True
61
62     def _check_virtual_media_started(self):
63         # Check virtmedia service status
64         try:
65             out = self._run_ipmitool_raw_command(RAW_GET_VMEDIA_STATUS)
66             service_status = out[0]
67             logging.debug('Virtual media service status: %s', service_status)
68         except Exception as err:
69             logging.warning('Exception when checking virtual media service: %s', str(err))
70
71         return service_status == '01'
72
73     def _start_virtual_media(self):
74         # Enable "Remote Media Support" in GUI (p145)
75         try:
76             logging.debug('Start virtual media service')
77             self._run_ipmitool_raw_command(RAW_SET_VMEDIA_STATUS % '0x01')
78         except Exception as err:
79             logging.warning('Exception when starting virtual media service: %s', str(err))
80
81     def _set_setup_nfs(self, nfs_host, mount_path):
82
83         # Set share type NFS
84         try:
85             logging.debug('Virtual media share type to NFS.')
86             self._run_ipmitool_raw_command(RAW_SET_RIS_NFS)
87         except Exception as err:
88             logging.warning('Exception when setting virtual media service type NFS: %s', str(err))
89             return False
90
91         # NFS server IP
92         try:
93             cmd = RAW_SET_RIS_NFS_IP % (self._convert_to_hex(nfs_host, True, 63))
94             logging.debug('Virtual media server "%s"', nfs_host)
95             self._run_ipmitool_raw_command(cmd)
96         except Exception as err:
97             logging.warning('Exception when setting virtual media server: %s', str(err))
98             return False
99
100         # Set NFS Mount Root path
101         try:
102             logging.debug('Virtual media path to "%s"', mount_path)
103
104             self._run_ipmitool_raw_command(RAW_SET_RIS_PROGRESS % '0x00')
105             time.sleep(2)
106             self._run_ipmitool_raw_command(RAW_SET_RIS_PROGRESS % '0x01')
107             time.sleep(2)
108             self._run_ipmitool_raw_command(RAW_SET_RIS_NFS_PATH % (self._convert_to_hex(mount_path, True, 64)))
109             time.sleep(2)
110             self._run_ipmitool_raw_command(RAW_SET_RIS_PROGRESS % '0x00')
111
112         except Exception as err:
113             logging.warning('Exception when setting virtual media path: %s', str(err))
114             return False
115         return True
116
117     def _enable_virtual_media(self):
118         # Speed up things if it service is already running
119         if self._check_virtual_media_started():
120             logging.debug('Virtual media service already running.')
121             return True
122
123         # Just enabling the service does not seem to start it (in all HW)
124         # Resetting it after enabling helps
125         self._start_virtual_media()
126         self._restart_virtual_media_service()
127
128         tries = 60
129         while tries > 0:
130             if self._check_virtual_media_started():
131                 return True
132             time.sleep(5)
133             tries -= 1
134
135         logging.warning('Ensure virtual media service start failed: attempts exceeded.')
136         return False
137
138     def _get_virtual_media_device_count(self, devicetype):
139         try:
140             _num_inst = 0
141             # Get num of enabled devices
142             if devicetype == 'CD':
143                 _devparam = VMEDIA_DEVICE_TYPE_CD
144                 logging.debug('Get virtual CD count')
145             elif devicetype == 'FD':
146                 _devparam = VMEDIA_DEVICE_TYPE_FD
147                 logging.debug('Get virtual FD count')
148             elif devicetype == 'HD':
149                 _devparam = VMEDIA_DEVICE_TYPE_HD
150                 logging.debug('Get virtual HD count')
151             else:
152                 logging.warning('Unknown device type "%s"', devicetype)
153                 return _num_inst
154
155             cmd = RAW_GET_VMEDIA_DEVICE_COUNT % _devparam
156             out = self._run_ipmitool_raw_command(cmd)
157             _num_inst = int(out[0], 16)
158             logging.debug('Number of enabled %s devices is %d', devicetype, _num_inst)
159             return _num_inst
160         except Exception as err:
161             raise BMCException('Exception when getting number of enabled %s devices. error: %s' % (devicetype, str(err)))
162
163     def _set_virtual_media_device_count(self, devicetype, devicecount):
164         if not 0 <= devicecount <= 4:
165             logging.warning('Number of devices must be in range 0 to 4')
166             return False
167
168         if devicetype == 'CD':
169             _devparam = VMEDIA_DEVICE_TYPE_CD
170             logging.debug('Setting virtual CD count to %d', devicecount)
171         elif devicetype == 'HD':
172             _devparam = VMEDIA_DEVICE_TYPE_HD
173             logging.debug('Setting virtual HD count to %d', devicecount)
174         else:
175             logging.warning('Unknown device type "%s"', devicetype)
176             return False
177
178         try:
179             cmd = RAW_SET_VMEDIA_DEVICE_COUNT % (_devparam, hex(devicecount))
180             self._run_ipmitool_raw_command(cmd)
181
182             _conf_device_num = self._get_virtual_media_device_count(devicetype)
183             _tries = 40
184             while _conf_device_num != devicecount and _tries > 0:
185                 logging.debug('Virtual %s count is %d expecting %d', devicetype, _conf_device_num, devicecount)
186                 time.sleep(5)
187                 _conf_device_num = self._get_virtual_media_device_count(devicetype)
188                 _tries = _tries -1
189
190         except Exception as err:
191             raise BMCException('Exception when setting virtual media device count : %s' % str(err))
192         return True
193
194     def _restart_virtual_media_service(self):
195         try:
196             cmd = RAW_RESTART_VMEDIA
197             logging.debug('Restart virtual media service')
198             self._run_ipmitool_raw_command(cmd)
199         except Exception as err:
200             raise BMCException('Exception when restarting virtual media service: %s' % str(err))
201
202     def _restart_ris(self):
203         try:
204             cmd = RAW_RESTART_RIS
205             logging.debug('Restart RIS')
206             self._run_ipmitool_raw_command(cmd)
207         except Exception as err:
208             raise BMCException('Exception when restarting RIS: %s' % str(err))
209
210         return True
211
212     def _restart_ris_cd(self):
213         try:
214             cmd = RAW_RESTART_RIS_CD
215             logging.debug('Restart RIS CD media')
216             self._run_ipmitool_raw_command(cmd)
217         except Exception as err:
218             raise BMCException('Exception when restarting RIS CD media: %s' % str(err))
219
220         return True
221
222     def _check_vmedia_mount_state(self, enabled):
223         expected_state = 'enabled' if enabled else 'disabled'
224         logging.debug('Check if CD/DVD device is %s', expected_state)
225
226         tries = 10
227         while tries > 0:
228             try:
229                 out = self._run_ipmitool_raw_command(RAW_GET_VMEDIA_MOUNT_STATUS)
230                 status = out[0]
231                 logging.debug('Virtual media mount status: %s', status)
232             except Exception as err:
233                 status = None
234                 logging.warning('Exception when checking VMedia mount status: %s', str(err))
235
236             matched_state = (status == '01') if enabled else (status == '00')
237             if matched_state:
238                 # Virtual media mount found in expected state
239                 return True
240
241             tries -= 1
242             time.sleep(6)
243
244         logging.warning('Failed: CD/DVD mount is not %s (attempts exceeded).'
245                         'Ignoring and trying to continue.',
246                         expected_state)
247         return False
248
249     def _toggle_virtual_device(self, enabled):
250         state_raw = '0x01' if enabled else '0x00'
251         state_str = 'enable' if enabled else 'disable'
252
253         logging.debug('Try to %s VMedia mount.', state_str)
254         try:
255             self._run_ipmitool_raw_command(RAW_SET_VMEDIA_MOUNT_STATUS % state_raw)
256             time.sleep(1)
257             return self._check_vmedia_mount_state(enabled)
258         except Exception as err:
259             logging.warning('Exception when tying to %s VMedia mount: %s. Ignoring... ',
260                             state_str, str(err))
261         return True
262
263     def _mount_virtual_device(self):
264         return self._toggle_virtual_device(True)
265
266     def _demount_virtual_device(self):
267         return self._toggle_virtual_device(False)
268
269     def _get_mounted_image_count(self):
270         count = 0
271         try:
272             out = self._run_ipmitool_raw_command(RAW_GET_MOUNTED_IMG_COUNT)
273             count = int(out[0], 16)
274             logging.warning('Available image count: %d', count)
275         except Exception as err:
276             logging.warning('Exception when trying to get the image count: %s', str(err))
277         return count
278
279     def _wait_for_mount_count(self):
280         # Poll until we got some images from server
281         tries = 12
282         while tries > 0:
283             if self._get_mounted_image_count() > 0:
284                 return True
285             tries -= 1
286             logging.debug('Check available images count tries left: %d', tries)
287             time.sleep(10)
288
289         logging.warning('Available images count 0, attempts exceeded.')
290         return False
291
292     def _set_image_name(self, image_filename):
293         try:
294             logging.debug('Setting virtual media image: %s', image_filename)
295             self._run_ipmitool_raw_command(RAW_SET_IMG_NAME % self._convert_to_hex(image_filename, True, 64))
296         except Exception as err:
297             logging.debug('Exception when setting virtual media image: %s', str(err))
298             return False
299         return True
300
301     def _get_bmc_nfs_service_status(self):
302         try:
303             out = self._run_ipmitool_raw_command(RAW_CHECK_NFS_SERVICE_STATUS)
304             _image_name = str(bytearray.fromhex(''.join(out)))
305             logging.debug('Found mounted image: %s', _image_name)
306             return 'mounted'
307         except Exception:
308             return 'nfserror'
309
310     def _stop_remote_redirection(self):
311         _num_inst = self._get_virtual_media_device_count('CD')
312         for driveindex in range(0, _num_inst):
313             cmd = RAW_STOP_REDIRECT % hex(driveindex)
314             logging.debug('Stop redirection CD/DVD drive index %d', driveindex)
315             try:
316                 out = self._run_ipmitool_raw_command(cmd)
317                 logging.debug('ipmitool out = "%s"', out)
318             except Exception as err:
319                 # Drive might not be mounted to start with
320                 logging.debug('Ignoring exception when stopping redirection CD/DVD drive index %d error: %s',
321                               driveindex, str(err))
322
323     def _set_boot_from_virtual_media(self):
324         logging.debug('Set boot from cd (%s), and boot after that', self._host)
325         try:
326             self._run_ipmitool_command('chassis bootdev floppy options=persistent')
327         except Exception as err:
328             raise BMCException('Set Boot to CD failed: %s' % str(err))
329
330     def _detach_virtual_media(self):
331         logging.debug('Detach virtual media')
332
333         #Enable virtual media
334         if not self._enable_virtual_media():
335             raise BMCException("detach_virtual_cd: Failed to enable virtual media")
336
337         # Restart Remote Image Service
338         if not self._restart_ris():
339             raise BMCException("Failed to restart RIS")
340
341         # Stop redirection
342         self._stop_remote_redirection()
343
344         #Clear RIS configuration
345         if not self._clear_ris_configuration():
346             raise BMCException("detach_virtual_cd: Failed to clear RIS configuration")
347
348         #Demount virtual device
349         if not self._demount_virtual_device():
350             raise BMCException('detach_virtual_cd: Exception when disabling CD/DVD virtual media')
351
352         # Reduce the number of virtual devices (both HD and CD default to 4 devices each)
353         if not self._set_virtual_media_device_count('HD', 0):
354             BMCException('Failed to set virtual media device count for HD')
355         if not self._set_virtual_media_device_count('CD', 1):
356             BMCException('Failed to set virtual media device count for CD')
357
358     def attach_virtual_cd(self, nfs_host, nfs_mount, boot_iso_filename):
359         # Detach first
360         self._detach_virtual_media()
361
362         logging.debug('Attach virtual media')
363
364         #Enable virtual media
365         if not self._enable_virtual_media():
366             raise BMCException("Failed to enable virtual media")
367
368         #Enable CD/DVD device
369         if not self._toggle_virtual_device(True):
370             raise BMCException("Failed to enable virtual device")
371
372         #Clear RIS configuration
373         if not self._clear_ris_configuration():
374             raise BMCException("Failed to clear RIS configuration")
375
376         #Setup nfs
377         if not self._set_setup_nfs(nfs_host, nfs_mount):
378             raise BMCException("Failed to setup nfs")
379
380         # Restart Remote Image CD
381         if not self._restart_ris_cd():
382             raise BMCException("Failed to restart RIS CD")
383
384         #Wait for device to be mounted
385         if not self._wait_for_mount_count():
386             raise BMCException("Failed when waiting for the device to appear")
387
388         # Set Image Name
389         time.sleep(5)
390         if not self._set_image_name(boot_iso_filename):
391             raise BMCException("Failed to set image name")
392
393         success = self._wait_for_bmc_nfs_service(90, 'mounted')
394         if success:
395             return True
396         else:
397             raise BMCException('NFS service setup failed')