-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathredfish_utils.py
3972 lines (3468 loc) · 168 KB
/
redfish_utils.py
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
# Copyright (c) 2017-2018 Dell EMC Inc.
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
from __future__ import absolute_import, division, print_function
__metaclass__ = type
import json
import os
import random
import string
import gzip
import time
from io import BytesIO
from ansible.module_utils.urls import open_url
from ansible.module_utils.common.text.converters import to_native
from ansible.module_utils.common.text.converters import to_text
from ansible.module_utils.common.text.converters import to_bytes
from ansible.module_utils.six import text_type
from ansible.module_utils.six.moves import http_client
from ansible.module_utils.six.moves.urllib.error import URLError, HTTPError
from ansible.module_utils.six.moves.urllib.parse import urlparse
from ansible.module_utils.ansible_release import __version__ as ansible_version
from ansible_collections.community.general.plugins.module_utils.version import LooseVersion
GET_HEADERS = {'accept': 'application/json', 'OData-Version': '4.0'}
POST_HEADERS = {'content-type': 'application/json', 'accept': 'application/json',
'OData-Version': '4.0'}
PATCH_HEADERS = {'content-type': 'application/json', 'accept': 'application/json',
'OData-Version': '4.0'}
PUT_HEADERS = {'content-type': 'application/json', 'accept': 'application/json',
'OData-Version': '4.0'}
DELETE_HEADERS = {'accept': 'application/json', 'OData-Version': '4.0'}
FAIL_MSG = 'Issuing a data modification command without specifying the '\
'ID of the target %(resource)s resource when there is more '\
'than one %(resource)s is no longer allowed. Use the `resource_id` '\
'option to specify the target %(resource)s ID.'
class RedfishUtils(object):
def __init__(self, creds, root_uri, timeout, module, resource_id=None,
data_modification=False, strip_etag_quotes=False, ciphers=None):
self.root_uri = root_uri
self.creds = creds
self.timeout = timeout
self.module = module
self.service_root = '/redfish/v1/'
self.session_service_uri = '/redfish/v1/SessionService'
self.sessions_uri = '/redfish/v1/SessionService/Sessions'
self.resource_id = resource_id
self.data_modification = data_modification
self.strip_etag_quotes = strip_etag_quotes
self.ciphers = ciphers
self._vendor = None
def _auth_params(self, headers):
"""
Return tuple of required authentication params based on the presence
of a token in the self.creds dict. If using a token, set the
X-Auth-Token header in the `headers` param.
:param headers: dict containing headers to send in request
:return: tuple of username, password and force_basic_auth
"""
if self.creds.get('token'):
username = None
password = None
force_basic_auth = False
headers['X-Auth-Token'] = self.creds['token']
else:
username = self.creds['user']
password = self.creds['pswd']
force_basic_auth = True
return username, password, force_basic_auth
def _check_request_payload(self, req_pyld, cur_pyld, uri):
"""
Checks the request payload with the values currently held by the
service. Will check if changes are needed and if properties are
supported by the service.
:param req_pyld: dict containing the properties to apply
:param cur_pyld: dict containing the properties currently set
:param uri: string containing the URI being modified
:return: dict containing response information
"""
change_required = False
for prop in req_pyld:
# Check if the property is supported by the service
if prop not in cur_pyld:
return {'ret': False,
'changed': False,
'msg': '%s does not support the property %s' % (uri, prop),
'changes_required': False}
# Perform additional checks based on the type of property
if isinstance(req_pyld[prop], dict) and isinstance(cur_pyld[prop], dict):
# If the property is a dictionary, check the nested properties
sub_resp = self._check_request_payload(req_pyld[prop], cur_pyld[prop], uri)
if not sub_resp['ret']:
# Unsupported property or other error condition; no change
return sub_resp
if sub_resp['changes_required']:
# Subordinate dictionary requires changes
change_required = True
else:
# For other properties, just compare the values
# Note: This is also a fallthrough for cases where the request
# payload and current settings do not match in their data type.
# There are cases where this can be expected, such as when a
# property is always 'null' in responses, so we want to attempt
# the PATCH request.
# Note: This is also a fallthrough for properties that are
# arrays of objects. Some services erroneously omit properties
# within arrays of objects when not configured, and it is
# expecting the client to provide them anyway.
if req_pyld[prop] != cur_pyld[prop]:
change_required = True
resp = {'ret': True, 'changes_required': change_required}
if not change_required:
# No changes required; all properties set
resp['changed'] = False
resp['msg'] = 'Properties in %s are already set' % uri
return resp
# The following functions are to send GET/POST/PATCH/DELETE requests
def get_request(self, uri, override_headers=None, allow_no_resp=False, timeout=None):
req_headers = dict(GET_HEADERS)
if override_headers:
req_headers.update(override_headers)
username, password, basic_auth = self._auth_params(req_headers)
if timeout is None:
timeout = self.timeout
try:
# Service root is an unauthenticated resource; remove credentials
# in case the caller will be using sessions later.
if uri == (self.root_uri + self.service_root):
basic_auth = False
resp = open_url(uri, method="GET", headers=req_headers,
url_username=username, url_password=password,
force_basic_auth=basic_auth, validate_certs=False,
follow_redirects='all',
use_proxy=True, timeout=timeout, ciphers=self.ciphers)
headers = {k.lower(): v for (k, v) in resp.info().items()}
try:
if headers.get('content-encoding') == 'gzip' and LooseVersion(ansible_version) < LooseVersion('2.14'):
# Older versions of Ansible do not automatically decompress the data
# Starting in 2.14, open_url will decompress the response data by default
data = json.loads(to_native(gzip.open(BytesIO(resp.read()), 'rt', encoding='utf-8').read()))
else:
data = json.loads(to_native(resp.read()))
except Exception as e:
# No response data; this is okay in certain cases
data = None
if not allow_no_resp:
raise
except HTTPError as e:
msg, data = self._get_extended_message(e)
return {'ret': False,
'msg': "HTTP Error %s on GET request to '%s', extended message: '%s'"
% (e.code, uri, msg),
'status': e.code, 'data': data}
except URLError as e:
return {'ret': False, 'msg': "URL Error on GET request to '%s': '%s'"
% (uri, e.reason)}
# Almost all errors should be caught above, but just in case
except Exception as e:
return {'ret': False,
'msg': "Failed GET request to '%s': '%s'" % (uri, to_text(e))}
return {'ret': True, 'data': data, 'headers': headers, 'resp': resp}
def post_request(self, uri, pyld, multipart=False):
req_headers = dict(POST_HEADERS)
username, password, basic_auth = self._auth_params(req_headers)
try:
# When performing a POST to the session collection, credentials are
# provided in the request body. Do not provide the basic auth
# header since this can cause conflicts with some services
if self.sessions_uri is not None and uri == (self.root_uri + self.sessions_uri):
basic_auth = False
if multipart:
# Multipart requests require special handling to encode the request body
multipart_encoder = self._prepare_multipart(pyld)
data = multipart_encoder[0]
req_headers['content-type'] = multipart_encoder[1]
else:
data = json.dumps(pyld)
resp = open_url(uri, data=data,
headers=req_headers, method="POST",
url_username=username, url_password=password,
force_basic_auth=basic_auth, validate_certs=False,
follow_redirects='all',
use_proxy=True, timeout=self.timeout, ciphers=self.ciphers)
try:
data = json.loads(to_native(resp.read()))
except Exception as e:
# No response data; this is okay in many cases
data = None
headers = {k.lower(): v for (k, v) in resp.info().items()}
except HTTPError as e:
msg, data = self._get_extended_message(e)
return {'ret': False,
'msg': "HTTP Error %s on POST request to '%s', extended message: '%s'"
% (e.code, uri, msg),
'status': e.code, 'data': data}
except URLError as e:
return {'ret': False, 'msg': "URL Error on POST request to '%s': '%s'"
% (uri, e.reason)}
# Almost all errors should be caught above, but just in case
except Exception as e:
return {'ret': False,
'msg': "Failed POST request to '%s': '%s'" % (uri, to_text(e))}
return {'ret': True, 'data': data, 'headers': headers, 'resp': resp}
def patch_request(self, uri, pyld, check_pyld=False):
req_headers = dict(PATCH_HEADERS)
r = self.get_request(uri)
if r['ret']:
# Get etag from etag header or @odata.etag property
etag = r['headers'].get('etag')
if not etag:
etag = r['data'].get('@odata.etag')
if etag:
if self.strip_etag_quotes:
etag = etag.strip('"')
req_headers['If-Match'] = etag
if check_pyld:
# Check the payload with the current settings to see if changes
# are needed or if there are unsupported properties
if r['ret']:
check_resp = self._check_request_payload(pyld, r['data'], uri)
if not check_resp.pop('changes_required'):
check_resp['changed'] = False
return check_resp
else:
r['changed'] = False
return r
username, password, basic_auth = self._auth_params(req_headers)
try:
resp = open_url(uri, data=json.dumps(pyld),
headers=req_headers, method="PATCH",
url_username=username, url_password=password,
force_basic_auth=basic_auth, validate_certs=False,
follow_redirects='all',
use_proxy=True, timeout=self.timeout, ciphers=self.ciphers)
except HTTPError as e:
msg, data = self._get_extended_message(e)
return {'ret': False, 'changed': False,
'msg': "HTTP Error %s on PATCH request to '%s', extended message: '%s'"
% (e.code, uri, msg),
'status': e.code, 'data': data}
except URLError as e:
return {'ret': False, 'changed': False,
'msg': "URL Error on PATCH request to '%s': '%s'" % (uri, e.reason)}
# Almost all errors should be caught above, but just in case
except Exception as e:
return {'ret': False, 'changed': False,
'msg': "Failed PATCH request to '%s': '%s'" % (uri, to_text(e))}
return {'ret': True, 'changed': True, 'resp': resp, 'msg': 'Modified %s' % uri}
def put_request(self, uri, pyld):
req_headers = dict(PUT_HEADERS)
r = self.get_request(uri)
if r['ret']:
# Get etag from etag header or @odata.etag property
etag = r['headers'].get('etag')
if not etag:
etag = r['data'].get('@odata.etag')
if etag:
if self.strip_etag_quotes:
etag = etag.strip('"')
req_headers['If-Match'] = etag
username, password, basic_auth = self._auth_params(req_headers)
try:
resp = open_url(uri, data=json.dumps(pyld),
headers=req_headers, method="PUT",
url_username=username, url_password=password,
force_basic_auth=basic_auth, validate_certs=False,
follow_redirects='all',
use_proxy=True, timeout=self.timeout, ciphers=self.ciphers)
except HTTPError as e:
msg, data = self._get_extended_message(e)
return {'ret': False,
'msg': "HTTP Error %s on PUT request to '%s', extended message: '%s'"
% (e.code, uri, msg),
'status': e.code, 'data': data}
except URLError as e:
return {'ret': False, 'msg': "URL Error on PUT request to '%s': '%s'"
% (uri, e.reason)}
# Almost all errors should be caught above, but just in case
except Exception as e:
return {'ret': False,
'msg': "Failed PUT request to '%s': '%s'" % (uri, to_text(e))}
return {'ret': True, 'resp': resp}
def delete_request(self, uri, pyld=None):
req_headers = dict(DELETE_HEADERS)
username, password, basic_auth = self._auth_params(req_headers)
try:
data = json.dumps(pyld) if pyld else None
resp = open_url(uri, data=data,
headers=req_headers, method="DELETE",
url_username=username, url_password=password,
force_basic_auth=basic_auth, validate_certs=False,
follow_redirects='all',
use_proxy=True, timeout=self.timeout, ciphers=self.ciphers)
except HTTPError as e:
msg, data = self._get_extended_message(e)
return {'ret': False,
'msg': "HTTP Error %s on DELETE request to '%s', extended message: '%s'"
% (e.code, uri, msg),
'status': e.code, 'data': data}
except URLError as e:
return {'ret': False, 'msg': "URL Error on DELETE request to '%s': '%s'"
% (uri, e.reason)}
# Almost all errors should be caught above, but just in case
except Exception as e:
return {'ret': False,
'msg': "Failed DELETE request to '%s': '%s'" % (uri, to_text(e))}
return {'ret': True, 'resp': resp}
@staticmethod
def _prepare_multipart(fields):
"""Prepares a multipart body based on a set of fields provided.
Ideally it would have been good to use the existing 'prepare_multipart'
found in ansible.module_utils.urls, but it takes files and encodes them
as Base64 strings, which is not expected by Redfish services. It also
adds escaping of certain bytes in the payload, such as inserting '\r'
any time it finds a standalone '\n', which corrupts the image payload
send to the service. This implementation is simplified to Redfish's
usage and doesn't necessarily represent an exhaustive method of
building multipart requests.
"""
def write_buffer(body, line):
# Adds to the multipart body based on the provided data type
# At this time there is only support for strings, dictionaries, and bytes (default)
if isinstance(line, text_type):
body.append(to_bytes(line, encoding='utf-8'))
elif isinstance(line, dict):
body.append(to_bytes(json.dumps(line), encoding='utf-8'))
else:
body.append(line)
return
# Generate a random boundary marker; may need to consider probing the
# payload for potential conflicts in the future
boundary = ''.join(random.choice(string.digits + string.ascii_letters) for i in range(30))
body = []
for form in fields:
# Fill in the form details
write_buffer(body, '--' + boundary)
# Insert the headers (Content-Disposition and Content-Type)
if 'filename' in fields[form]:
name = os.path.basename(fields[form]['filename']).replace('"', '\\"')
write_buffer(body, u'Content-Disposition: form-data; name="%s"; filename="%s"' % (to_text(form), to_text(name)))
else:
write_buffer(body, 'Content-Disposition: form-data; name="%s"' % form)
write_buffer(body, 'Content-Type: %s' % fields[form]['mime_type'])
write_buffer(body, '')
# Insert the payload; read from the file if not given by the caller
if 'content' not in fields[form]:
with open(to_bytes(fields[form]['filename'], errors='surrogate_or_strict'), 'rb') as f:
fields[form]['content'] = f.read()
write_buffer(body, fields[form]['content'])
# Finalize the entire request
write_buffer(body, '--' + boundary + '--')
write_buffer(body, '')
return (b'\r\n'.join(body), 'multipart/form-data; boundary=' + boundary)
@staticmethod
def _get_extended_message(error):
"""
Get Redfish ExtendedInfo message from response payload if present
:param error: an HTTPError exception
:type error: HTTPError
:return: the ExtendedInfo message if present, else standard HTTP error
:return: the JSON data of the response if present
"""
msg = http_client.responses.get(error.code, '')
data = None
if error.code >= 400:
try:
body = error.read().decode('utf-8')
data = json.loads(body)
ext_info = data['error']['@Message.ExtendedInfo']
# if the ExtendedInfo contains a user friendly message send it
# otherwise try to send the entire contents of ExtendedInfo
try:
msg = ext_info[0]['Message']
except Exception:
msg = str(data['error']['@Message.ExtendedInfo'])
except Exception:
pass
return msg, data
def _init_session(self):
self.module.deprecate("Method _init_session is deprecated and will be removed.", version="11.0.0", collection_name="community.general")
def _get_vendor(self):
# If we got the vendor info once, don't get it again
if self._vendor is not None:
return {'ret': 'True', 'Vendor': self._vendor}
# Find the vendor info from the service root
response = self.get_request(self.root_uri + self.service_root)
if response['ret'] is False:
return {'ret': False, 'Vendor': ''}
data = response['data']
if 'Vendor' in data:
# Extract the vendor string from the Vendor property
self._vendor = data["Vendor"]
return {'ret': True, 'Vendor': data["Vendor"]}
elif 'Oem' in data and len(data['Oem']) > 0:
# Determine the vendor from the OEM object if needed
vendor = list(data['Oem'].keys())[0]
if vendor == 'Hpe' or vendor == 'Hp':
# HPE uses Pascal-casing for their OEM object
# Older systems reported 'Hp' (pre-split)
vendor = 'HPE'
self._vendor = vendor
return {'ret': True, 'Vendor': vendor}
else:
# Could not determine; use an empty string
self._vendor = ''
return {'ret': True, 'Vendor': ''}
def _find_accountservice_resource(self):
response = self.get_request(self.root_uri + self.service_root)
if response['ret'] is False:
return response
data = response['data']
if 'AccountService' not in data:
return {'ret': False, 'msg': "AccountService resource not found"}
else:
account_service = data["AccountService"]["@odata.id"]
response = self.get_request(self.root_uri + account_service)
if response['ret'] is False:
return response
data = response['data']
accounts = data['Accounts']['@odata.id']
if accounts[-1:] == '/':
accounts = accounts[:-1]
self.accounts_uri = accounts
return {'ret': True}
def _find_sessionservice_resource(self):
# Get the service root
response = self.get_request(self.root_uri + self.service_root)
if response['ret'] is False:
return response
data = response['data']
# Check for the session service and session collection. Well-known
# defaults are provided in the constructor, but services that predate
# Redfish 1.6.0 might contain different values.
self.session_service_uri = data.get('SessionService', {}).get('@odata.id')
self.sessions_uri = data.get('Links', {}).get('Sessions', {}).get('@odata.id')
# If one isn't found, return an error
if self.session_service_uri is None:
return {'ret': False, 'msg': "SessionService resource not found"}
if self.sessions_uri is None:
return {'ret': False, 'msg': "SessionCollection resource not found"}
return {'ret': True}
def _get_resource_uri_by_id(self, uris, id_prop):
for uri in uris:
response = self.get_request(self.root_uri + uri)
if response['ret'] is False:
continue
data = response['data']
if id_prop == data.get('Id'):
return uri
return None
def _find_systems_resource(self):
response = self.get_request(self.root_uri + self.service_root)
if response['ret'] is False:
return response
data = response['data']
if 'Systems' not in data:
return {'ret': False, 'msg': "Systems resource not found"}
response = self.get_request(self.root_uri + data['Systems']['@odata.id'])
if response['ret'] is False:
return response
self.systems_uris = [
i['@odata.id'] for i in response['data'].get('Members', [])]
if not self.systems_uris:
return {
'ret': False,
'msg': "ComputerSystem's Members array is either empty or missing"}
self.systems_uri = self.systems_uris[0]
if self.data_modification:
if self.resource_id:
self.systems_uri = self._get_resource_uri_by_id(self.systems_uris,
self.resource_id)
if not self.systems_uri:
return {
'ret': False,
'msg': "System resource %s not found" % self.resource_id}
elif len(self.systems_uris) > 1:
self.module.fail_json(msg=FAIL_MSG % {'resource': 'System'})
return {'ret': True}
def _find_updateservice_resource(self):
response = self.get_request(self.root_uri + self.service_root)
if response['ret'] is False:
return response
data = response['data']
if 'UpdateService' not in data:
return {'ret': False, 'msg': "UpdateService resource not found"}
else:
update = data["UpdateService"]["@odata.id"]
self.update_uri = update
response = self.get_request(self.root_uri + update)
if response['ret'] is False:
return response
data = response['data']
self.firmware_uri = self.software_uri = None
if 'FirmwareInventory' in data:
self.firmware_uri = data['FirmwareInventory'][u'@odata.id']
if 'SoftwareInventory' in data:
self.software_uri = data['SoftwareInventory'][u'@odata.id']
return {'ret': True}
def _find_chassis_resource(self):
response = self.get_request(self.root_uri + self.service_root)
if response['ret'] is False:
return response
data = response['data']
if 'Chassis' not in data:
return {'ret': False, 'msg': "Chassis resource not found"}
chassis = data["Chassis"]["@odata.id"]
response = self.get_request(self.root_uri + chassis)
if response['ret'] is False:
return response
self.chassis_uris = [
i['@odata.id'] for i in response['data'].get('Members', [])]
if not self.chassis_uris:
return {'ret': False,
'msg': "Chassis Members array is either empty or missing"}
self.chassis_uri = self.chassis_uris[0]
if self.data_modification:
if self.resource_id:
self.chassis_uri = self._get_resource_uri_by_id(self.chassis_uris,
self.resource_id)
if not self.chassis_uri:
return {
'ret': False,
'msg': "Chassis resource %s not found" % self.resource_id}
elif len(self.chassis_uris) > 1:
self.module.fail_json(msg=FAIL_MSG % {'resource': 'Chassis'})
return {'ret': True}
def _find_managers_resource(self):
response = self.get_request(self.root_uri + self.service_root)
if response['ret'] is False:
return response
data = response['data']
if 'Managers' not in data:
return {'ret': False, 'msg': "Manager resource not found"}
manager = data["Managers"]["@odata.id"]
response = self.get_request(self.root_uri + manager)
if response['ret'] is False:
return response
self.manager_uris = [
i['@odata.id'] for i in response['data'].get('Members', [])]
if not self.manager_uris:
return {'ret': False,
'msg': "Managers Members array is either empty or missing"}
self.manager_uri = self.manager_uris[0]
if self.data_modification:
if self.resource_id:
self.manager_uri = self._get_resource_uri_by_id(self.manager_uris,
self.resource_id)
if not self.manager_uri:
return {
'ret': False,
'msg': "Manager resource %s not found" % self.resource_id}
elif len(self.manager_uris) > 1:
self.module.fail_json(msg=FAIL_MSG % {'resource': 'Manager'})
return {'ret': True}
def _get_all_action_info_values(self, action):
"""Retrieve all parameter values for an Action from ActionInfo.
Fall back to AllowableValue annotations if no ActionInfo found.
Return the result in an ActionInfo-like dictionary, keyed
by the name of the parameter. """
ai = {}
if '@Redfish.ActionInfo' in action:
ai_uri = action['@Redfish.ActionInfo']
response = self.get_request(self.root_uri + ai_uri)
if response['ret'] is True:
data = response['data']
if 'Parameters' in data:
params = data['Parameters']
ai = {p['Name']: p for p in params if 'Name' in p}
if not ai:
ai = {
k[:-24]: {'AllowableValues': v}
for k, v in action.items()
if k.endswith('@Redfish.AllowableValues')
}
return ai
def _get_allowable_values(self, action, name, default_values=None):
if default_values is None:
default_values = []
ai = self._get_all_action_info_values(action)
allowable_values = ai.get(name, {}).get('AllowableValues')
# fallback to default values
if allowable_values is None:
allowable_values = default_values
return allowable_values
def check_service_availability(self):
"""
Checks if the service is accessible.
:return: dict containing the status of the service
"""
# Get the service root
# Override the timeout since the service root is expected to be readily
# available.
service_root = self.get_request(self.root_uri + self.service_root, timeout=10)
if service_root['ret'] is False:
# Failed, either due to a timeout or HTTP error; not available
return {'ret': True, 'available': False}
# Successfully accessed the service root; available
return {'ret': True, 'available': True}
def get_logs(self):
log_svcs_uri_list = []
list_of_logs = []
properties = ['Severity', 'Created', 'EntryType', 'OemRecordFormat',
'Message', 'MessageId', 'MessageArgs']
# Find LogService
response = self.get_request(self.root_uri + self.manager_uri)
if response['ret'] is False:
return response
data = response['data']
if 'LogServices' not in data:
return {'ret': False, 'msg': "LogServices resource not found"}
# Find all entries in LogServices
logs_uri = data["LogServices"]["@odata.id"]
response = self.get_request(self.root_uri + logs_uri)
if response['ret'] is False:
return response
data = response['data']
for log_svcs_entry in data.get('Members', []):
response = self.get_request(self.root_uri + log_svcs_entry[u'@odata.id'])
if response['ret'] is False:
return response
_data = response['data']
if 'Entries' in _data:
log_svcs_uri_list.append(_data['Entries'][u'@odata.id'])
# For each entry in LogServices, get log name and all log entries
for log_svcs_uri in log_svcs_uri_list:
logs = {}
list_of_log_entries = []
response = self.get_request(self.root_uri + log_svcs_uri)
if response['ret'] is False:
return response
data = response['data']
logs['Description'] = data.get('Description',
'Collection of log entries')
# Get all log entries for each type of log found
for logEntry in data.get('Members', []):
entry = {}
for prop in properties:
if prop in logEntry:
entry[prop] = logEntry.get(prop)
if entry:
list_of_log_entries.append(entry)
log_name = log_svcs_uri.rstrip('/').split('/')[-1]
logs[log_name] = list_of_log_entries
list_of_logs.append(logs)
# list_of_logs[logs{list_of_log_entries[entry{}]}]
return {'ret': True, 'entries': list_of_logs}
def clear_logs(self):
# Find LogService
response = self.get_request(self.root_uri + self.manager_uri)
if response['ret'] is False:
return response
data = response['data']
if 'LogServices' not in data:
return {'ret': False, 'msg': "LogServices resource not found"}
# Find all entries in LogServices
logs_uri = data["LogServices"]["@odata.id"]
response = self.get_request(self.root_uri + logs_uri)
if response['ret'] is False:
return response
data = response['data']
for log_svcs_entry in data[u'Members']:
response = self.get_request(self.root_uri + log_svcs_entry["@odata.id"])
if response['ret'] is False:
return response
_data = response['data']
# Check to make sure option is available, otherwise error is ugly
if "Actions" in _data:
if "#LogService.ClearLog" in _data[u"Actions"]:
self.post_request(self.root_uri + _data[u"Actions"]["#LogService.ClearLog"]["target"], {})
if response['ret'] is False:
return response
return {'ret': True}
def aggregate(self, func, uri_list, uri_name):
ret = True
entries = []
for uri in uri_list:
inventory = func(uri)
ret = inventory.pop('ret') and ret
if 'entries' in inventory:
entries.append(({uri_name: uri},
inventory['entries']))
return dict(ret=ret, entries=entries)
def aggregate_chassis(self, func):
return self.aggregate(func, self.chassis_uris, 'chassis_uri')
def aggregate_managers(self, func):
return self.aggregate(func, self.manager_uris, 'manager_uri')
def aggregate_systems(self, func):
return self.aggregate(func, self.systems_uris, 'system_uri')
def get_storage_controller_inventory(self, systems_uri):
result = {}
controller_list = []
controller_results = []
# Get these entries, but does not fail if not found
properties = ['CacheSummary', 'FirmwareVersion', 'Identifiers',
'Location', 'Manufacturer', 'Model', 'Name', 'Id',
'PartNumber', 'SerialNumber', 'SpeedGbps', 'Status']
key = "Controllers"
deprecated_key = "StorageControllers"
# Find Storage service
response = self.get_request(self.root_uri + systems_uri)
if response['ret'] is False:
return response
data = response['data']
if 'Storage' not in data:
return {'ret': False, 'msg': "Storage resource not found"}
# Get a list of all storage controllers and build respective URIs
storage_uri = data['Storage']["@odata.id"]
response = self.get_request(self.root_uri + storage_uri)
if response['ret'] is False:
return response
result['ret'] = True
data = response['data']
# Loop through Members and their StorageControllers
# and gather properties from each StorageController
if data[u'Members']:
for storage_member in data[u'Members']:
storage_member_uri = storage_member[u'@odata.id']
response = self.get_request(self.root_uri + storage_member_uri)
data = response['data']
if key in data:
controllers_uri = data[key][u'@odata.id']
response = self.get_request(self.root_uri + controllers_uri)
if response['ret'] is False:
return response
result['ret'] = True
data = response['data']
if data[u'Members']:
for controller_member in data[u'Members']:
controller_member_uri = controller_member[u'@odata.id']
response = self.get_request(self.root_uri + controller_member_uri)
if response['ret'] is False:
return response
result['ret'] = True
data = response['data']
controller_result = {}
for property in properties:
if property in data:
controller_result[property] = data[property]
controller_results.append(controller_result)
elif deprecated_key in data:
controller_list = data[deprecated_key]
for controller in controller_list:
controller_result = {}
for property in properties:
if property in controller:
controller_result[property] = controller[property]
controller_results.append(controller_result)
result['entries'] = controller_results
return result
else:
return {'ret': False, 'msg': "Storage resource not found"}
def get_multi_storage_controller_inventory(self):
return self.aggregate_systems(self.get_storage_controller_inventory)
def get_disk_inventory(self, systems_uri):
result = {'entries': []}
controller_list = []
# Get these entries, but does not fail if not found
properties = ['BlockSizeBytes', 'CapableSpeedGbs', 'CapacityBytes',
'EncryptionAbility', 'EncryptionStatus',
'FailurePredicted', 'HotspareType', 'Id', 'Identifiers',
'Links', 'Manufacturer', 'MediaType', 'Model', 'Name',
'PartNumber', 'PhysicalLocation', 'Protocol', 'Revision',
'RotationSpeedRPM', 'SerialNumber', 'Status']
# Find Storage service
response = self.get_request(self.root_uri + systems_uri)
if response['ret'] is False:
return response
data = response['data']
if 'SimpleStorage' not in data and 'Storage' not in data:
return {'ret': False, 'msg': "SimpleStorage and Storage resource \
not found"}
if 'Storage' in data:
# Get a list of all storage controllers and build respective URIs
storage_uri = data[u'Storage'][u'@odata.id']
response = self.get_request(self.root_uri + storage_uri)
if response['ret'] is False:
return response
result['ret'] = True
data = response['data']
if data[u'Members']:
for controller in data[u'Members']:
controller_list.append(controller[u'@odata.id'])
for c in controller_list:
uri = self.root_uri + c
response = self.get_request(uri)
if response['ret'] is False:
return response
data = response['data']
controller_name = 'Controller 1'
storage_id = data['Id']
if 'Controllers' in data:
controllers_uri = data['Controllers'][u'@odata.id']
response = self.get_request(self.root_uri + controllers_uri)
if response['ret'] is False:
return response
result['ret'] = True
cdata = response['data']
if cdata[u'Members']:
controller_member_uri = cdata[u'Members'][0][u'@odata.id']
response = self.get_request(self.root_uri + controller_member_uri)
if response['ret'] is False:
return response
result['ret'] = True
cdata = response['data']
controller_name = cdata['Name']
elif 'StorageControllers' in data:
sc = data['StorageControllers']
if sc:
if 'Name' in sc[0]:
controller_name = sc[0]['Name']
else:
sc_id = sc[0].get('Id', '1')
controller_name = 'Controller %s' % sc_id
drive_results = []
if 'Drives' in data:
for device in data[u'Drives']:
disk_uri = self.root_uri + device[u'@odata.id']
response = self.get_request(disk_uri)
data = response['data']
drive_result = {}
drive_result['RedfishURI'] = data['@odata.id']
for property in properties:
if property in data:
if data[property] is not None:
if property == "Links":
if "Volumes" in data["Links"].keys():
volumes = [v["@odata.id"] for v in data["Links"]["Volumes"]]
drive_result["Volumes"] = volumes
else:
drive_result[property] = data[property]
drive_results.append(drive_result)
drives = {'Controller': controller_name,
'StorageId': storage_id,
'Drives': drive_results}
result["entries"].append(drives)
if 'SimpleStorage' in data:
# Get a list of all storage controllers and build respective URIs
storage_uri = data["SimpleStorage"]["@odata.id"]
response = self.get_request(self.root_uri + storage_uri)
if response['ret'] is False:
return response
result['ret'] = True
data = response['data']
for controller in data[u'Members']:
controller_list.append(controller[u'@odata.id'])
for c in controller_list:
uri = self.root_uri + c
response = self.get_request(uri)
if response['ret'] is False:
return response
data = response['data']
if 'Name' in data:
controller_name = data['Name']
else:
sc_id = data.get('Id', '1')
controller_name = 'Controller %s' % sc_id
drive_results = []
for device in data[u'Devices']:
drive_result = {}
for property in properties:
if property in device:
drive_result[property] = device[property]
drive_results.append(drive_result)
drives = {'Controller': controller_name,
'Drives': drive_results}
result["entries"].append(drives)
return result
def get_multi_disk_inventory(self):
return self.aggregate_systems(self.get_disk_inventory)
def get_volume_inventory(self, systems_uri):
result = {'entries': []}
controller_list = []
volume_list = []
# Get these entries, but does not fail if not found
properties = ['Id', 'Name', 'RAIDType', 'VolumeType', 'BlockSizeBytes',
'Capacity', 'CapacityBytes', 'CapacitySources',
'Encrypted', 'EncryptionTypes', 'Identifiers',
'Operations', 'OptimumIOSizeBytes', 'AccessCapabilities',
'AllocatedPools', 'Status']
# Find Storage service
response = self.get_request(self.root_uri + systems_uri)
if response['ret'] is False:
return response
data = response['data']
if 'SimpleStorage' not in data and 'Storage' not in data:
return {'ret': False, 'msg': "SimpleStorage and Storage resource \
not found"}
if 'Storage' in data:
# Get a list of all storage controllers and build respective URIs
storage_uri = data[u'Storage'][u'@odata.id']
response = self.get_request(self.root_uri + storage_uri)
if response['ret'] is False:
return response
result['ret'] = True
data = response['data']
if data.get('Members'):
for controller in data[u'Members']:
controller_list.append(controller[u'@odata.id'])
for idx, c in enumerate(controller_list):
uri = self.root_uri + c
response = self.get_request(uri)
if response['ret'] is False:
return response
data = response['data']
controller_name = 'Controller %s' % str(idx)
if 'Controllers' in data:
response = self.get_request(self.root_uri + data['Controllers'][u'@odata.id'])
if response['ret'] is False: