File: redfish_utils.py

package info (click to toggle)
ansible 12.0.0%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 420,012 kB
  • sloc: python: 4,118,863; javascript: 16,878; xml: 5,260; sh: 4,634; cs: 3,510; makefile: 597; sql: 85; ansic: 14
file content (4019 lines) | stat: -rw-r--r-- 172,456 bytes parent folder | download | duplicates (2)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
# -*- 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 time
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

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.'

# Use together with the community.general.redfish docs fragment
REDFISH_COMMON_ARGUMENT_SPEC = {
    "validate_certs": {
        "type": "bool",
        "default": False,
    },
    "ca_path": {
        "type": "path",
    },
    "ciphers": {
        "type": "list",
        "elements": "str",
    },
}


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 if ciphers is not None else module.params.get("ciphers")
        self._vendor = None
        self.validate_certs = module.params.get("validate_certs", False)
        self.ca_path = module.params.get("ca_path")

    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

    def _request(self, uri, **kwargs):
        kwargs.setdefault("validate_certs", self.validate_certs)
        kwargs.setdefault("follow_redirects", "all")
        kwargs.setdefault("use_proxy", True)
        kwargs.setdefault("timeout", self.timeout)
        kwargs.setdefault("ciphers", self.ciphers)
        kwargs.setdefault("ca_path", self.ca_path)
        resp = open_url(uri, **kwargs)
        headers = {k.lower(): v for (k, v) in resp.info().items()}
        return resp, headers

    # 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, headers = self._request(
                uri,
                method="GET",
                headers=req_headers,
                url_username=username,
                url_password=password,
                force_basic_auth=basic_auth,
                timeout=timeout,
            )
            try:
                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, headers = self._request(
                uri,
                data=data,
                headers=req_headers,
                method="POST",
                url_username=username,
                url_password=password,
                force_basic_auth=basic_auth,
            )
            try:
                data = json.loads(to_native(resp.read()))
            except Exception as e:
                # No response data; this is okay in many cases
                data = None
        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, dummy = self._request(
                uri,
                data=json.dumps(pyld),
                headers=req_headers,
                method="PATCH",
                url_username=username,
                url_password=password,
                force_basic_auth=basic_auth,
            )
        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, dummy = self._request(
                uri,
                data=json.dumps(pyld),
                headers=req_headers,
                method="PUT",
                url_username=username,
                url_password=password,
                force_basic_auth=basic_auth,
            )
        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, dummy = self._request(
                uri,
                data=data,
                headers=req_headers,
                method="DELETE",
                url_username=username,
                url_password=password,
                force_basic_auth=basic_auth,
            )
        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 _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:
                            return response
                        c_data = response['data']

                        if c_data.get('Members') and c_data['Members']:
                            response = self.get_request(self.root_uri + c_data['Members'][0][u'@odata.id'])
                            if response['ret'] is False:
                                return response
                            member_data = response['data']

                            if member_data:
                                if 'Name' in member_data:
                                    controller_name = member_data['Name']
                                else:
                                    controller_id = member_data.get('Id', '1')
                                    controller_name = 'Controller %s' % controller_id
                    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
                    volume_results = []
                    volume_list = []
                    if 'Volumes' in data:
                        # Get a list of all volumes and build respective URIs
                        volumes_uri = data[u'Volumes'][u'@odata.id']
                        response = self.get_request(self.root_uri + volumes_uri)
                        data = response['data']

                        if data.get('Members'):
                            for volume in data[u'Members']:
                                volume_list.append(volume[u'@odata.id'])
                            for v in volume_list:
                                uri = self.root_uri + v
                                response = self.get_request(uri)
                                if response['ret'] is False:
                                    return response
                                data = response['data']

                                volume_result = {}
                                for property in properties:
                                    if property in data:
                                        if data[property] is not None:
                                            volume_result[property] = data[property]

                                # Get related Drives Id
                                drive_id_list = []
                                if 'Links' in data:
                                    if 'Drives' in data[u'Links']:
                                        for link in data[u'Links'][u'Drives']:
                                            drive_id_link = link[u'@odata.id']
                                            drive_id = drive_id_link.rstrip('/').split('/')[-1]
                                            drive_id_list.append({'Id': drive_id})
                                        volume_result['Linked_drives'] = drive_id_list
                                volume_results.append(volume_result)
                    volumes = {'Controller': controller_name,
                               'Volumes': volume_results}
                    result["entries"].append(volumes)
        else:
            return {'ret': False, 'msg': "Storage resource not found"}

        return result

    def get_multi_volume_inventory(self):
        return self.aggregate_systems(self.get_volume_inventory)

    def manage_system_indicator_led(self, command):
        return self.manage_indicator_led(command, self.systems_uri)

    def manage_chassis_indicator_led(self, command):
        return self.manage_indicator_led(command, self.chassis_uri)

    def manage_indicator_led(self, command, resource_uri=None):
        # If no resource is specified; default to the Chassis resource
        if resource_uri is None:
            resource_uri = self.chassis_uri

        # Perform a PATCH on the IndicatorLED property based on the requested command
        payloads = {'IndicatorLedOn': 'Lit', 'IndicatorLedOff': 'Off', "IndicatorLedBlink": 'Blinking'}
        if command not in payloads.keys():
            return {'ret': False, 'msg': 'Invalid command (%s)' % command}
        payload = {'IndicatorLED': payloads[command]}
        resp = self.patch_request(self.root_uri + resource_uri, payload, check_pyld=True)
        if resp['ret'] and resp['changed']:
            resp['msg'] = 'Set IndicatorLED to %s' % payloads[command]
        return resp

    def _map_reset_type(self, reset_type, allowable_values):
        equiv_types = {
            'On': 'ForceOn',
            'ForceOn': 'On',
            'ForceOff': 'GracefulShutdown',
            'GracefulShutdown': 'ForceOff',
            'GracefulRestart': 'ForceRestart',
            'ForceRestart': 'GracefulRestart'
        }

        if reset_type in allowable_values:
            return reset_type
        if reset_type not in equiv_types:
            return reset_type
        mapped_type = equiv_types[reset_type]
        if mapped_type in allowable_values:
            return mapped_type
        return reset_type

    def manage_system_power(self, command):
        return self.manage_power(command, self.systems_uri,
                                 '#ComputerSystem.Reset')

    def manage_manager_power(self, command, wait=False, wait_timeout=120):
        return self.manage_power(command, self.manager_uri,
                                 '#Manager.Reset', wait, wait_timeout)

    def manage_power(self, command, resource_uri, action_name, wait=False,
                     wait_timeout=120):
        key = "Actions"
        reset_type_values = ['On', 'ForceOff', 'GracefulShutdown',
                             'GracefulRestart', 'ForceRestart', 'Nmi',
                             'ForceOn', 'PushPowerButton', 'PowerCycle',
                             'FullPowerCycle']

        # command should be PowerOn, PowerForceOff, etc.
        if not command.startswith('Power'):
            return {'ret': False, 'msg': 'Invalid Command (%s)' % command}

        # Commands (except PowerCycle) will be stripped of the 'Power' prefix
        if command == 'PowerCycle':
            reset_type = command
        else:
            reset_type = command[5:]

        # map Reboot to a ResetType that does a reboot
        if reset_type == 'Reboot':
            reset_type = 'GracefulRestart'

        if reset_type not in reset_type_values:
            return {'ret': False, 'msg': 'Invalid Command (%s)' % command}

        # read the resource and get the current power state
        response = self.get_request(self.root_uri + resource_uri)
        if response['ret'] is False:
            return response
        data = response['data']
        power_state = data.get('PowerState')

        # if power is already in target state, nothing to do
        if power_state == "On" and reset_type in ['On', 'ForceOn']:
            return {'ret': True, 'changed': False}
        if power_state == "Off" and reset_type in ['GracefulShutdown', 'ForceOff']:
            return {'ret': True, 'changed': False}

        # get the reset Action and target URI
        if key not in data or action_name not in data[key]:
            return {'ret': False, 'msg': 'Action %s not found' % action_name}
        reset_action = data[key][action_name]
        if 'target' not in reset_action:
            return {'ret': False,
                    'msg': 'target URI missing from Action %s' % action_name}
        action_uri = reset_action['target']

        # get AllowableValues
        ai = self._get_all_action_info_values(reset_action)
        allowable_values = ai.get('ResetType', {}).get('AllowableValues', [])

        # map ResetType to an allowable value if needed
        if reset_type not in allowable_values:
            reset_type = self._map_reset_type(reset_type, allowable_values)

        # define payload
        payload = {'ResetType': reset_type}

        # POST to Action URI
        response = self.post_request(self.root_uri + action_uri, payload)
        if response['ret'] is False:
            return response

        # If requested to wait for the service to be available again, block
        # until it is ready
        if wait:
            elapsed_time = 0
            start_time = time.time()
            # Start with a large enough sleep.  Some services will process new
            # requests while in the middle of shutting down, thus breaking out
            # early.
            time.sleep(30)

            # Periodically check for the service's availability.
            while elapsed_time <= wait_timeout:
                status = self.check_service_availability()
                if status['available']:
                    # It is available; we are done
                    break
                time.sleep(5)
                elapsed_time = time.time() - start_time

            if elapsed_time > wait_timeout:
                # Exhausted the wait timer; error
                return {'ret': False, 'changed': True,
                        'msg': 'The service did not become available after %d seconds' % wait_timeout}
        return {'ret': True, 'changed': True}

    def manager_reset_to_defaults(self, command):
        return self.reset_to_defaults(command, self.manager_uri,
                                      '#Manager.ResetToDefaults')

    def reset_to_defaults(self, command, resource_uri, action_name):
        key = "Actions"
        reset_type_values = ['ResetAll',
                             'PreserveNetworkAndUsers',
                             'PreserveNetwork']

        if command not in reset_type_values:
            return {'ret': False, 'msg': 'Invalid Command (%s)' % command}

        # read the resource and get the current power state
        response = self.get_request(self.root_uri + resource_uri)
        if response['ret'] is False:
            return response
        data = response['data']

        # get the reset Action and target URI
        if key not in data or action_name not in data[key]:
            return {'ret': False, 'msg': 'Action %s not found' % action_name}
        reset_action = data[key][action_name]
        if 'target' not in reset_action:
            return {'ret': False,
                    'msg': 'target URI missing from Action %s' % action_name}
        action_uri = reset_action['target']

        # get AllowableValues
        ai = self._get_all_action_info_values(reset_action)
        allowable_values = ai.get('ResetType', {}).get('AllowableValues', [])

        # map ResetType to an allowable value if needed
        if allowable_values and command not in allowable_values:
            return {'ret': False,
                    'msg': 'Specified reset type (%s) not supported '
                           'by service. Supported types: %s' %
                           (command, allowable_values)}

        # define payload
        payload = {'ResetType': command}

        # POST to Action URI
        response = self.post_request(self.root_uri + action_uri, payload)
        if response['ret'] is False:
            return response
        return {'ret': True, 'changed': True}

    def _find_account_uri(self, username=None, acct_id=None, password_change_uri=None):
        if not any((username, acct_id)):
            return {'ret': False, 'msg':
                    'Must provide either account_id or account_username'}

        if password_change_uri:
            # Password change required; go directly to the specified URI
            response = self.get_request(self.root_uri + password_change_uri)
            if response['ret'] is False:
                return response
            data = response['data']
            headers = response['headers']
            if username:
                if username == data.get('UserName'):
                    return {'ret': True, 'data': data,
                            'headers': headers, 'uri': password_change_uri}
            if acct_id:
                if acct_id == data.get('Id'):
                    return {'ret': True, 'data': data,
                            'headers': headers, 'uri': password_change_uri}
        else:
            # Walk the accounts collection to find the desired user
            response = self.get_request(self.root_uri + self.accounts_uri)
            if response['ret'] is False:
                return response
            data = response['data']

            uris = [a.get('@odata.id') for a in data.get('Members', []) if
                    a.get('@odata.id')]
            for uri in uris:
                response = self.get_request(self.root_uri + uri)
                if response['ret'] is False:
                    continue
                data = response['data']
                headers = response['headers']
                if username:
                    if username == data.get('UserName'):
                        return {'ret': True, 'data': data,
                                'headers': headers, 'uri': uri}
                if acct_id:
                    if acct_id == data.get('Id'):
                        return {'ret': True, 'data': data,
                                'headers': headers, 'uri': uri}

        return {'ret': False, 'no_match': True, 'msg':
                'No account with the given account_id or account_username found'}

    def _find_empty_account_slot(self):
        response = self.get_request(self.root_uri + self.accounts_uri)
        if response['ret'] is False:
            return response
        data = response['data']

        uris = [a.get('@odata.id') for a in data.get('Members', []) if
                a.get('@odata.id')]
        if uris:
            # first slot may be reserved, so move to end of list
            uris += [uris.pop(0)]
        for uri in uris:
            response = self.get_request(self.root_uri + uri)
            if response['ret'] is False:
                continue
            data = response['data']
            headers = response['headers']
            if data.get('UserName') == "" and not data.get('Enabled', True):
                return {'ret': True, 'data': data,
                        'headers': headers, 'uri': uri}

        return {'ret': False, 'no_match': True, 'msg':
                'No empty account slot found'}

    def list_users(self):
        result = {}
        # listing all users has always been slower than other operations, why?
        user_list = []
        users_results = []
        # Get these entries, but does not fail if not found
        properties = ['Id', 'Name', 'UserName', 'RoleId', 'Locked', 'Enabled',
                      'AccountTypes', 'OEMAccountTypes']

        response = self.get_request(self.root_uri + self.accounts_uri)
        if response['ret'] is False:
            return response
        result['ret'] = True
        data = response['data']

        for users in data.get('Members', []):
            user_list.append(users[u'@odata.id'])   # user_list[] are URIs

        # for each user, get details
        for uri in user_list:
            user = {}
            response = self.get_request(self.root_uri + uri)
            if response['ret'] is False:
                return response
            data = response['data']

            for property in properties:
                if property in data:
                    user[property] = data[property]

            # Filter out empty account slots
            # An empty account slot can be detected if the username is an empty
            # string and if the account is disabled
            if user.get('UserName', '') == '' and not user.get('Enabled', False):
                continue

            users_results.append(user)
        result["entries"] = users_results
        return result

    def add_user_via_patch(self, user):
        if user.get('account_id'):
            # If Id slot specified, use it
            response = self._find_account_uri(acct_id=user.get('account_id'))
        else:
            # Otherwise find first empty slot
            response = self._find_empty_account_slot()

        if not response['ret']:
            return response
        uri = response['uri']
        payload = {}
        if user.get('account_username'):
            payload['UserName'] = user.get('account_username')
        if user.get('account_password'):
            payload['Password'] = user.get('account_password')
        if user.get('account_roleid'):
            payload['RoleId'] = user.get('account_roleid')
        if user.get('account_accounttypes'):
            payload['AccountTypes'] = user.get('account_accounttypes')
        if user.get('account_oemaccounttypes'):
            payload['OEMAccountTypes'] = user.get('account_oemaccounttypes')
        return self.patch_request(self.root_uri + uri, payload, check_pyld=True)

    def add_user(self, user):
        if not user.get('account_username'):
            return {'ret': False, 'msg':
                    'Must provide account_username for AddUser command'}

        response = self._find_account_uri(username=user.get('account_username'))
        if response['ret']:
            # account_username already exists, nothing to do
            return {'ret': True, 'changed': False}

        response = self.get_request(self.root_uri + self.accounts_uri)
        if not response['ret']:
            return response
        headers = response['headers']

        if 'allow' in headers:
            methods = [m.strip() for m in headers.get('allow').split(',')]
            if 'POST' not in methods:
                # if Allow header present and POST not listed, add via PATCH
                return self.add_user_via_patch(user)

        payload = {}
        if user.get('account_username'):
            payload['UserName'] = user.get('account_username')
        if user.get('account_password'):
            payload['Password'] = user.get('account_password')
        if user.get('account_roleid'):
            payload['RoleId'] = user.get('account_roleid')
        if user.get('account_accounttypes'):
            payload['AccountTypes'] = user.get('account_accounttypes')
        if user.get('account_oemaccounttypes'):
            payload['OEMAccountTypes'] = user.get('account_oemaccounttypes')
        if user.get('account_id'):
            payload['Id'] = user.get('account_id')

        response = self.post_request(self.root_uri + self.accounts_uri, payload)
        if not response['ret']:
            if response.get('status') == 405:
                # if POST returned a 405, try to add via PATCH
                return self.add_user_via_patch(user)
            else:
                return response
        return {'ret': True}

    def enable_user(self, user):
        response = self._find_account_uri(username=user.get('account_username'),
                                          acct_id=user.get('account_id'))
        if not response['ret']:
            return response
        uri = response['uri']

        payload = {'Enabled': True}
        return self.patch_request(self.root_uri + uri, payload, check_pyld=True)

    def delete_user_via_patch(self, user, uri=None, data=None):
        if not uri:
            response = self._find_account_uri(username=user.get('account_username'),
                                              acct_id=user.get('account_id'))
            if not response['ret']:
                return response
            uri = response['uri']
            data = response['data']

        payload = {'UserName': ''}
        if data.get('Enabled', False):
            payload['Enabled'] = False
        return self.patch_request(self.root_uri + uri, payload, check_pyld=True)

    def delete_user(self, user):
        response = self._find_account_uri(username=user.get('account_username'),
                                          acct_id=user.get('account_id'))
        if not response['ret']:
            if response.get('no_match'):
                # account does not exist, nothing to do
                return {'ret': True, 'changed': False}
            else:
                # some error encountered
                return response

        uri = response['uri']
        headers = response['headers']
        data = response['data']

        if 'allow' in headers:
            methods = [m.strip() for m in headers.get('allow').split(',')]
            if 'DELETE' not in methods:
                # if Allow header present and DELETE not listed, del via PATCH
                return self.delete_user_via_patch(user, uri=uri, data=data)

        response = self.delete_request(self.root_uri + uri)
        if not response['ret']:
            if response.get('status') == 405:
                # if DELETE returned a 405, try to delete via PATCH
                return self.delete_user_via_patch(user, uri=uri, data=data)
            else:
                return response
        return {'ret': True}

    def disable_user(self, user):
        response = self._find_account_uri(username=user.get('account_username'),
                                          acct_id=user.get('account_id'))
        if not response['ret']:
            return response

        uri = response['uri']
        payload = {'Enabled': False}
        return self.patch_request(self.root_uri + uri, payload, check_pyld=True)

    def update_user_role(self, user):
        if not user.get('account_roleid'):
            return {'ret': False, 'msg':
                    'Must provide account_roleid for UpdateUserRole command'}

        response = self._find_account_uri(username=user.get('account_username'),
                                          acct_id=user.get('account_id'))
        if not response['ret']:
            return response

        uri = response['uri']
        payload = {'RoleId': user['account_roleid']}
        return self.patch_request(self.root_uri + uri, payload, check_pyld=True)

    def update_user_password(self, user):
        if not user.get('account_password'):
            return {'ret': False, 'msg':
                    'Must provide account_password for UpdateUserPassword command'}

        response = self._find_account_uri(username=user.get('account_username'),
                                          acct_id=user.get('account_id'),
                                          password_change_uri=user.get('account_passwordchangerequired'))
        if not response['ret']:
            return response

        uri = response['uri']
        payload = {'Password': user['account_password']}
        return self.patch_request(self.root_uri + uri, payload, check_pyld=True)

    def update_user_name(self, user):
        if not user.get('account_updatename'):
            return {'ret': False, 'msg':
                    'Must provide account_updatename for UpdateUserName command'}

        response = self._find_account_uri(username=user.get('account_username'),
                                          acct_id=user.get('account_id'))
        if not response['ret']:
            return response

        uri = response['uri']
        payload = {'UserName': user['account_updatename']}
        return self.patch_request(self.root_uri + uri, payload, check_pyld=True)

    def update_accountservice_properties(self, user):
        account_properties = user.get('account_properties')
        if account_properties is None:
            return {'ret': False, 'msg':
                    'Must provide account_properties for UpdateAccountServiceProperties command'}

        # Find the AccountService resource
        response = self.get_request(self.root_uri + self.service_root)
        if response['ret'] is False:
            return response
        data = response['data']
        accountservice_uri = data.get("AccountService", {}).get("@odata.id")
        if accountservice_uri is None:
            return {'ret': False, 'msg': "AccountService resource not found"}

        # Perform a PATCH on the AccountService resource with the requested properties
        resp = self.patch_request(self.root_uri + accountservice_uri, account_properties, check_pyld=True)
        if resp['ret'] and resp['changed']:
            resp['msg'] = 'Modified account service'
        return resp

    def update_user_accounttypes(self, user):
        account_types = user.get('account_accounttypes')
        oemaccount_types = user.get('account_oemaccounttypes')
        if account_types is None and oemaccount_types is None:
            return {'ret': False, 'msg':
                    'Must provide account_accounttypes or account_oemaccounttypes for UpdateUserAccountTypes command'}

        response = self._find_account_uri(username=user.get('account_username'),
                                          acct_id=user.get('account_id'))
        if not response['ret']:
            return response

        uri = response['uri']
        payload = {}
        if user.get('account_accounttypes'):
            payload['AccountTypes'] = user.get('account_accounttypes')
        if user.get('account_oemaccounttypes'):
            payload['OEMAccountTypes'] = user.get('account_oemaccounttypes')

        return self.patch_request(self.root_uri + uri, payload, check_pyld=True)

    def check_password_change_required(self, return_data):
        """
        Checks a response if a user needs to change their password

        :param return_data: The return data for a failed request
        :return: None or the URI of the account to update
        """
        uri = None
        if 'data' in return_data:
            # Find the extended messages in the response payload
            extended_messages = return_data['data'].get('error', {}).get('@Message.ExtendedInfo', [])
            if len(extended_messages) == 0:
                extended_messages = return_data['data'].get('@Message.ExtendedInfo', [])
            # Go through each message and look for Base.1.X.PasswordChangeRequired
            for message in extended_messages:
                message_id = message.get('MessageId')
                if message_id is None:
                    # While this is invalid, treat the lack of a MessageId as "no message"
                    continue
                if message_id.startswith('Base.1.') and message_id.endswith('.PasswordChangeRequired'):
                    # Password change required; get the URI of the user account
                    uri = message['MessageArgs'][0]
                    break
        return uri

    def get_sessions(self):
        result = {}
        # listing all users has always been slower than other operations, why?
        session_list = []
        sessions_results = []
        # Get these entries, but does not fail if not found
        properties = ['Description', 'Id', 'Name', 'UserName']

        response = self.get_request(self.root_uri + self.sessions_uri)
        if response['ret'] is False:
            return response
        result['ret'] = True
        data = response['data']

        for sessions in data[u'Members']:
            session_list.append(sessions[u'@odata.id'])   # session_list[] are URIs

        # for each session, get details
        for uri in session_list:
            session = {}
            response = self.get_request(self.root_uri + uri)
            if response['ret'] is False:
                return response
            data = response['data']

            for property in properties:
                if property in data:
                    session[property] = data[property]

            sessions_results.append(session)
        result["entries"] = sessions_results
        return result

    def clear_sessions(self):
        response = self.get_request(self.root_uri + self.sessions_uri)
        if response['ret'] is False:
            return response
        data = response['data']

        # if no active sessions, return as success
        if data['Members@odata.count'] == 0:
            return {'ret': True, 'changed': False, 'msg': "There are no active sessions"}

        # loop to delete every active session
        for session in data[u'Members']:
            response = self.delete_request(self.root_uri + session[u'@odata.id'])
            if response['ret'] is False:
                return response

        return {'ret': True, 'changed': True, 'msg': "Cleared all sessions successfully"}

    def create_session(self):
        if not self.creds.get('user') or not self.creds.get('pswd'):
            return {'ret': False, 'msg':
                    'Must provide the username and password parameters for '
                    'the CreateSession command'}

        payload = {
            'UserName': self.creds['user'],
            'Password': self.creds['pswd']
        }
        response = self.post_request(self.root_uri + self.sessions_uri, payload)
        if response['ret'] is False:
            return response

        headers = response['headers']
        if 'x-auth-token' not in headers:
            return {'ret': False, 'msg':
                    'The service did not return the X-Auth-Token header in '
                    'the response from the Sessions collection POST'}

        if 'location' not in headers:
            self.module.warn(
                'The service did not return the Location header for the '
                'session URL in the response from the Sessions collection '
                'POST')
            session_uri = None
        else:
            session_uri = urlparse(headers.get('location')).path

        session = dict()
        session['token'] = headers.get('x-auth-token')
        session['uri'] = session_uri
        return {'ret': True, 'changed': True, 'session': session,
                'msg': 'Session created successfully'}

    def delete_session(self, session_uri):
        if not session_uri:
            return {'ret': False, 'msg':
                    'Must provide the session_uri parameter for the '
                    'DeleteSession command'}

        response = self.delete_request(self.root_uri + session_uri)
        if response['ret'] is False:
            return response

        return {'ret': True, 'changed': True,
                'msg': 'Session deleted successfully'}

    def get_firmware_update_capabilities(self):
        result = {}
        response = self.get_request(self.root_uri + self.update_uri)
        if response['ret'] is False:
            return response

        result['ret'] = True

        result['entries'] = {}

        data = response['data']

        result['multipart_supported'] = 'MultipartHttpPushUri' in data

        if "Actions" in data:
            actions = data['Actions']
            if len(actions) > 0:
                for key in actions.keys():
                    action = actions.get(key)
                    if 'title' in action:
                        title = action['title']
                    else:
                        title = key
                    result['entries'][title] = action.get('TransferProtocol@Redfish.AllowableValues',
                                                          ["Key TransferProtocol@Redfish.AllowableValues not found"])
            else:
                return {'ret': "False", 'msg': "Actions list is empty."}
        else:
            return {'ret': "False", 'msg': "Key Actions not found."}
        return result

    def _software_inventory(self, uri):
        result = {}
        result['entries'] = []

        while uri:
            response = self.get_request(self.root_uri + uri)
            if response['ret'] is False:
                return response
            result['ret'] = True

            data = response['data']
            if data.get('Members@odata.nextLink'):
                uri = data.get('Members@odata.nextLink')
            else:
                uri = None

            for member in data[u'Members']:
                fw_uri = self.root_uri + member[u'@odata.id']
                # Get details for each software or firmware member
                response = self.get_request(fw_uri)
                if response['ret'] is False:
                    return response
                result['ret'] = True
                data = response['data']
                software = {}
                # Get these standard properties if present
                for key in ['Name', 'Id', 'Status', 'Version', 'Updateable',
                            'SoftwareId', 'LowestSupportedVersion', 'Manufacturer',
                            'ReleaseDate']:
                    if key in data:
                        software[key] = data.get(key)
                result['entries'].append(software)

        return result

    def get_firmware_inventory(self):
        if self.firmware_uri is None:
            return {'ret': False, 'msg': 'No FirmwareInventory resource found'}
        else:
            return self._software_inventory(self.firmware_uri)

    def get_software_inventory(self):
        if self.software_uri is None:
            return {'ret': False, 'msg': 'No SoftwareInventory resource found'}
        else:
            return self._software_inventory(self.software_uri)

    def _operation_results(self, response, data, handle=None):
        """
        Builds the results for an operation from task, job, or action response.

        :param response: HTTP response object
        :param data: HTTP response data
        :param handle: The task or job handle that was last used
        :return: dict containing operation results
        """

        operation_results = {'status': None, 'messages': [], 'handle': None, 'ret': True,
                             'resets_requested': []}

        if response.status == 204:
            # No content; successful, but nothing to return
            # Use the Redfish "Completed" enum from TaskState for the operation status
            operation_results['status'] = 'Completed'
        else:
            # Parse the response body for details

            # Determine the next handle, if any
            operation_results['handle'] = handle
            if response.status == 202:
                # Task generated; get the task monitor URI
                operation_results['handle'] = response.getheader('Location', handle)

            # Pull out the status and messages based on the body format
            if data is not None:
                response_type = data.get('@odata.type', '')
                if response_type.startswith('#Task.') or response_type.startswith('#Job.'):
                    # Task and Job have similar enough structures to treat the same
                    operation_results['status'] = data.get('TaskState', data.get('JobState'))
                    operation_results['messages'] = data.get('Messages', [])
                else:
                    # Error response body, which is a bit of a misnomer since it is used in successful action responses
                    operation_results['status'] = 'Completed'
                    if response.status >= 400:
                        operation_results['status'] = 'Exception'
                    operation_results['messages'] = data.get('error', {}).get('@Message.ExtendedInfo', [])
            else:
                # No response body (or malformed); build based on status code
                operation_results['status'] = 'Completed'
                if response.status == 202:
                    operation_results['status'] = 'New'
                elif response.status >= 400:
                    operation_results['status'] = 'Exception'

            # Clear out the handle if the operation is complete
            if operation_results['status'] in ['Completed', 'Cancelled', 'Exception', 'Killed']:
                operation_results['handle'] = None

            # Scan the messages to see if next steps are needed
            for message in operation_results['messages']:
                message_id = message.get('MessageId')
                if message_id is None:
                    # While this is invalid, treat the lack of a MessageId as "no message"
                    continue

                if message_id.startswith('Update.1.') and message_id.endswith('.OperationTransitionedToJob'):
                    # Operation rerouted to a job; update the status and handle
                    operation_results['status'] = 'New'
                    operation_results['handle'] = message['MessageArgs'][0]
                    operation_results['resets_requested'] = []
                    # No need to process other messages in this case
                    break

                if message_id.startswith('Base.1.') and message_id.endswith('.ResetRequired'):
                    # A reset to some device is needed to continue the update
                    reset = {'uri': message['MessageArgs'][0], 'type': message['MessageArgs'][1]}
                    operation_results['resets_requested'].append(reset)

        return operation_results

    def simple_update(self, update_opts):
        image_uri = update_opts.get('update_image_uri')
        protocol = update_opts.get('update_protocol')
        targets = update_opts.get('update_targets')
        creds = update_opts.get('update_creds')
        apply_time = update_opts.get('update_apply_time')

        if not image_uri:
            return {'ret': False, 'msg':
                    'Must specify update_image_uri for the SimpleUpdate command'}

        response = self.get_request(self.root_uri + self.update_uri)
        if response['ret'] is False:
            return response
        data = response['data']
        if 'Actions' not in data:
            return {'ret': False, 'msg': 'Service does not support SimpleUpdate'}
        if '#UpdateService.SimpleUpdate' not in data['Actions']:
            return {'ret': False, 'msg': 'Service does not support SimpleUpdate'}
        action = data['Actions']['#UpdateService.SimpleUpdate']
        if 'target' not in action:
            return {'ret': False, 'msg': 'Service does not support SimpleUpdate'}
        update_uri = action['target']
        if protocol:
            default_values = ['CIFS', 'FTP', 'SFTP', 'HTTP', 'HTTPS', 'NSF',
                              'SCP', 'TFTP', 'OEM', 'NFS']
            allowable_values = self._get_allowable_values(action,
                                                          'TransferProtocol',
                                                          default_values)
            if protocol not in allowable_values:
                return {'ret': False,
                        'msg': 'Specified update_protocol (%s) not supported '
                               'by service. Supported protocols: %s' %
                               (protocol, allowable_values)}
        if targets:
            allowable_values = self._get_allowable_values(action, 'Targets')
            if allowable_values:
                for target in targets:
                    if target not in allowable_values:
                        return {'ret': False,
                                'msg': 'Specified target (%s) not supported '
                                       'by service. Supported targets: %s' %
                                       (target, allowable_values)}

        payload = {
            'ImageURI': image_uri
        }
        if protocol:
            payload["TransferProtocol"] = protocol
        if targets:
            payload["Targets"] = targets
        if creds:
            if creds.get('username'):
                payload["Username"] = creds.get('username')
            if creds.get('password'):
                payload["Password"] = creds.get('password')
        if apply_time:
            payload["@Redfish.OperationApplyTime"] = apply_time
        response = self.post_request(self.root_uri + update_uri, payload)
        if response['ret'] is False:
            return response
        return {'ret': True, 'changed': True,
                'msg': "SimpleUpdate requested",
                'update_status': self._operation_results(response['resp'], response['data'])}

    def multipath_http_push_update(self, update_opts):
        """
        Provides a software update via the URI specified by the
        MultipartHttpPushUri property.  Callers should adjust the 'timeout'
        variable in the base object to accommodate the size of the image and
        speed of the transfer.  For example, a 200MB image will likely take
        more than the default 10 second timeout.

        :param update_opts: The parameters for the update operation
        :return: dict containing the response of the update request
        """
        image_file = update_opts.get('update_image_file')
        targets = update_opts.get('update_targets')
        apply_time = update_opts.get('update_apply_time')
        oem_params = update_opts.get('update_oem_params')
        custom_oem_header = update_opts.get('update_custom_oem_header')
        custom_oem_mime_type = update_opts.get('update_custom_oem_mime_type')
        custom_oem_params = update_opts.get('update_custom_oem_params')

        # Ensure the image file is provided
        if not image_file:
            return {'ret': False, 'msg':
                    'Must specify update_image_file for the MultipartHTTPPushUpdate command'}
        if not os.path.isfile(image_file):
            return {'ret': False, 'msg':
                    'Must specify a valid file for the MultipartHTTPPushUpdate command'}
        try:
            with open(image_file, 'rb') as f:
                image_payload = f.read()
        except Exception as e:
            return {'ret': False, 'msg':
                    'Could not read file %s' % image_file}

        # Check that multipart HTTP push updates are supported
        response = self.get_request(self.root_uri + self.update_uri)
        if response['ret'] is False:
            return response
        data = response['data']
        if 'MultipartHttpPushUri' not in data:
            return {'ret': False, 'msg': 'Service does not support MultipartHttpPushUri'}
        update_uri = data['MultipartHttpPushUri']

        # Assemble the JSON payload portion of the request
        payload = {}
        if targets:
            payload["Targets"] = targets
        if apply_time:
            payload["@Redfish.OperationApplyTime"] = apply_time
        if oem_params:
            payload["Oem"] = oem_params
        multipart_payload = {
            'UpdateParameters': {'content': json.dumps(payload), 'mime_type': 'application/json'},
            'UpdateFile': {'filename': image_file, 'content': image_payload, 'mime_type': 'application/octet-stream'}
        }
        if custom_oem_params:
            multipart_payload[custom_oem_header] = {'content': custom_oem_params}
            if custom_oem_mime_type:
                multipart_payload[custom_oem_header]['mime_type'] = custom_oem_mime_type

        response = self.post_request(self.root_uri + update_uri, multipart_payload, multipart=True)
        if response['ret'] is False:
            return response
        return {'ret': True, 'changed': True,
                'msg': "MultipartHTTPPushUpdate requested",
                'update_status': self._operation_results(response['resp'], response['data'])}

    def get_update_status(self, update_handle):
        """
        Gets the status of an update operation.

        :param handle: The task or job handle tracking the update
        :return: dict containing the response of the update status
        """

        if not update_handle:
            return {'ret': False, 'msg': 'Must provide a handle tracking the update.'}

        # Get the task or job tracking the update
        response = self.get_request(self.root_uri + update_handle, allow_no_resp=True)
        if response['ret'] is False:
            return response

        # Inspect the response to build the update status
        return self._operation_results(response['resp'], response['data'], update_handle)

    def perform_requested_update_operations(self, update_handle):
        """
        Performs requested operations to allow the update to continue.

        :param handle: The task or job handle tracking the update
        :return: dict containing the result of the operations
        """

        # Get the current update status
        update_status = self.get_update_status(update_handle)
        if update_status['ret'] is False:
            return update_status

        changed = False

        # Perform any requested updates
        for reset in update_status['resets_requested']:
            resp = self.post_request(self.root_uri + reset['uri'], {'ResetType': reset['type']})
            if resp['ret'] is False:
                # Override the 'changed' indicator since other resets may have
                # been successful
                resp['changed'] = changed
                return resp
            changed = True

        msg = 'No operations required for the update'
        if changed:
            # Will need to consider finetuning this message if the scope of the
            # requested operations grow over time
            msg = 'One or more components reset to continue the update'
        return {'ret': True, 'changed': changed, 'msg': msg}

    def get_bios_attributes(self, systems_uri):
        result = {}
        bios_attributes = {}
        key = "Bios"

        # Search for 'key' entry and extract URI from it
        response = self.get_request(self.root_uri + systems_uri)
        if response['ret'] is False:
            return response
        result['ret'] = True
        data = response['data']

        if key not in data:
            return {'ret': False, 'msg': "Key %s not found" % key}

        bios_uri = data[key]["@odata.id"]

        response = self.get_request(self.root_uri + bios_uri)
        if response['ret'] is False:
            return response
        result['ret'] = True
        data = response['data']
        for attribute in data[u'Attributes'].items():
            bios_attributes[attribute[0]] = attribute[1]
        result["entries"] = bios_attributes
        return result

    def get_multi_bios_attributes(self):
        return self.aggregate_systems(self.get_bios_attributes)

    def _get_boot_options_dict(self, boot):
        # Get these entries from BootOption, if present
        properties = ['DisplayName', 'BootOptionReference']

        # Retrieve BootOptions if present
        if 'BootOptions' in boot and '@odata.id' in boot['BootOptions']:
            boot_options_uri = boot['BootOptions']["@odata.id"]
            # Get BootOptions resource
            response = self.get_request(self.root_uri + boot_options_uri)
            if response['ret'] is False:
                return {}
            data = response['data']

            # Retrieve Members array
            if 'Members' not in data:
                return {}
            members = data['Members']
        else:
            members = []

        # Build dict of BootOptions keyed by BootOptionReference
        boot_options_dict = {}
        for member in members:
            if '@odata.id' not in member:
                return {}
            boot_option_uri = member['@odata.id']
            response = self.get_request(self.root_uri + boot_option_uri)
            if response['ret'] is False:
                return {}
            data = response['data']
            if 'BootOptionReference' not in data:
                return {}
            boot_option_ref = data['BootOptionReference']

            # fetch the props to display for this boot device
            boot_props = {}
            for prop in properties:
                if prop in data:
                    boot_props[prop] = data[prop]

            boot_options_dict[boot_option_ref] = boot_props

        return boot_options_dict

    def get_boot_order(self, systems_uri):
        result = {}

        # Retrieve System resource
        response = self.get_request(self.root_uri + systems_uri)
        if response['ret'] is False:
            return response
        result['ret'] = True
        data = response['data']

        # Confirm needed Boot properties are present
        if 'Boot' not in data or 'BootOrder' not in data['Boot']:
            return {'ret': False, 'msg': "Key BootOrder not found"}

        boot = data['Boot']
        boot_order = boot['BootOrder']
        boot_options_dict = self._get_boot_options_dict(boot)

        # Build boot device list
        boot_device_list = []
        for ref in boot_order:
            boot_device_list.append(
                boot_options_dict.get(ref, {'BootOptionReference': ref}))

        result["entries"] = boot_device_list
        return result

    def get_multi_boot_order(self):
        return self.aggregate_systems(self.get_boot_order)

    def get_boot_override(self, systems_uri):
        result = {}

        properties = ["BootSourceOverrideEnabled", "BootSourceOverrideTarget",
                      "BootSourceOverrideMode", "UefiTargetBootSourceOverride", "BootSourceOverrideTarget@Redfish.AllowableValues"]

        response = self.get_request(self.root_uri + systems_uri)
        if response['ret'] is False:
            return response
        result['ret'] = True
        data = response['data']

        if 'Boot' not in data:
            return {'ret': False, 'msg': "Key Boot not found"}

        boot = data['Boot']

        boot_overrides = {}
        if "BootSourceOverrideEnabled" in boot:
            if boot["BootSourceOverrideEnabled"] is not False:
                for property in properties:
                    if property in boot:
                        if boot[property] is not None:
                            boot_overrides[property] = boot[property]
        else:
            return {'ret': False, 'msg': "No boot override is enabled."}

        result['entries'] = boot_overrides
        return result

    def get_multi_boot_override(self):
        return self.aggregate_systems(self.get_boot_override)

    def set_bios_default_settings(self):
        # Find the Bios resource from the requested ComputerSystem resource
        response = self.get_request(self.root_uri + self.systems_uri)
        if response['ret'] is False:
            return response
        data = response['data']
        bios_uri = data.get('Bios', {}).get('@odata.id')
        if bios_uri is None:
            return {'ret': False, 'msg': 'Bios resource not found'}

        # Find the URI of the ResetBios action
        response = self.get_request(self.root_uri + bios_uri)
        if response['ret'] is False:
            return response
        data = response['data']
        reset_bios_uri = data.get('Actions', {}).get('#Bios.ResetBios', {}).get('target')
        if reset_bios_uri is None:
            return {'ret': False, 'msg': 'ResetBios action not found'}

        # Perform the ResetBios action
        response = self.post_request(self.root_uri + reset_bios_uri, {})
        if response['ret'] is False:
            return response
        return {'ret': True, 'changed': True, 'msg': "BIOS set to default settings"}

    def set_boot_override(self, boot_opts):
        # Extract the requested boot override options
        bootdevice = boot_opts.get('bootdevice')
        uefi_target = boot_opts.get('uefi_target')
        boot_next = boot_opts.get('boot_next')
        override_enabled = boot_opts.get('override_enabled')
        boot_override_mode = boot_opts.get('boot_override_mode')
        if not bootdevice and override_enabled != 'Disabled':
            return {'ret': False,
                    'msg': "bootdevice option required for temporary boot override"}

        # Get the current boot override options from the Boot property
        response = self.get_request(self.root_uri + self.systems_uri)
        if response['ret'] is False:
            return response
        data = response['data']
        boot = data.get('Boot')
        if boot is None:
            return {'ret': False, 'msg': "Boot property not found"}
        cur_override_mode = boot.get('BootSourceOverrideMode')

        # Check if the requested target is supported by the system
        if override_enabled != 'Disabled':
            annotation = 'BootSourceOverrideTarget@Redfish.AllowableValues'
            if annotation in boot:
                allowable_values = boot[annotation]
                if isinstance(allowable_values, list) and bootdevice not in allowable_values:
                    return {'ret': False,
                            'msg': "Boot device %s not in list of allowable values (%s)" %
                                   (bootdevice, allowable_values)}

        # Build the request payload based on the desired boot override options
        if override_enabled == 'Disabled':
            payload = {
                'Boot': {
                    'BootSourceOverrideEnabled': override_enabled,
                    'BootSourceOverrideTarget': 'None'
                }
            }
        elif bootdevice == 'UefiTarget':
            if not uefi_target:
                return {'ret': False,
                        'msg': "uefi_target option required to SetOneTimeBoot for UefiTarget"}
            payload = {
                'Boot': {
                    'BootSourceOverrideEnabled': override_enabled,
                    'BootSourceOverrideTarget': bootdevice,
                    'UefiTargetBootSourceOverride': uefi_target
                }
            }
            # If needed, also specify UEFI mode
            if cur_override_mode == 'Legacy':
                payload['Boot']['BootSourceOverrideMode'] = 'UEFI'
        elif bootdevice == 'UefiBootNext':
            if not boot_next:
                return {'ret': False,
                        'msg': "boot_next option required to SetOneTimeBoot for UefiBootNext"}
            payload = {
                'Boot': {
                    'BootSourceOverrideEnabled': override_enabled,
                    'BootSourceOverrideTarget': bootdevice,
                    'BootNext': boot_next
                }
            }
            # If needed, also specify UEFI mode
            if cur_override_mode == 'Legacy':
                payload['Boot']['BootSourceOverrideMode'] = 'UEFI'
        else:
            payload = {
                'Boot': {
                    'BootSourceOverrideEnabled': override_enabled,
                    'BootSourceOverrideTarget': bootdevice
                }
            }
            if boot_override_mode:
                payload['Boot']['BootSourceOverrideMode'] = boot_override_mode

        # Apply the requested boot override request
        resp = self.patch_request(self.root_uri + self.systems_uri, payload, check_pyld=True)
        if resp['ret'] is False:
            # WORKAROUND
            # Older Dell systems do not allow BootSourceOverrideEnabled to be
            # specified with UefiTarget as the target device
            vendor = self._get_vendor()['Vendor']
            if vendor == 'Dell':
                if bootdevice == 'UefiTarget' and override_enabled != 'Disabled':
                    payload['Boot'].pop('BootSourceOverrideEnabled', None)
                    resp = self.patch_request(self.root_uri + self.systems_uri, payload, check_pyld=True)
        if resp['ret'] and resp['changed']:
            resp['msg'] = 'Updated the boot override settings'
        return resp

    def set_bios_attributes(self, attributes):
        # Find the Bios resource from the requested ComputerSystem resource
        response = self.get_request(self.root_uri + self.systems_uri)
        if response['ret'] is False:
            return response
        data = response['data']
        bios_uri = data.get('Bios', {}).get('@odata.id')
        if bios_uri is None:
            return {'ret': False, 'msg': 'Bios resource not found'}

        # Get the current BIOS settings
        response = self.get_request(self.root_uri + bios_uri)
        if response['ret'] is False:
            return response
        data = response['data']

        # Make a copy of the attributes dict
        attrs_to_patch = dict(attributes)
        # List to hold attributes not found
        attrs_bad = {}

        # Check the attributes
        for attr_name, attr_value in attributes.items():
            # Check if attribute exists
            if attr_name not in data[u'Attributes']:
                # Remove and proceed to next attribute if this isn't valid
                attrs_bad.update({attr_name: attr_value})
                del attrs_to_patch[attr_name]
                continue

            # If already set to requested value, remove it from PATCH payload
            if data[u'Attributes'][attr_name] == attr_value:
                del attrs_to_patch[attr_name]

        warning = ""
        if attrs_bad:
            warning = "Unsupported attributes %s" % (attrs_bad)

        # Return success w/ changed=False if no attrs need to be changed
        if not attrs_to_patch:
            return {'ret': True, 'changed': False,
                    'msg': "BIOS attributes already set",
                    'warning': warning}

        # Get the SettingsObject URI to apply the attributes
        set_bios_attr_uri = data.get("@Redfish.Settings", {}).get("SettingsObject", {}).get("@odata.id")
        if set_bios_attr_uri is None:
            return {'ret': False, 'msg': "Settings resource for BIOS attributes not found."}

        # Construct payload and issue PATCH command
        payload = {"Attributes": attrs_to_patch}

        # WORKAROUND
        # Dell systems require manually setting the apply time to "OnReset"
        # to spawn a proprietary job to apply the BIOS settings
        vendor = self._get_vendor()['Vendor']
        if vendor == 'Dell':
            payload.update({"@Redfish.SettingsApplyTime": {"ApplyTime": "OnReset"}})

        response = self.patch_request(self.root_uri + set_bios_attr_uri, payload)
        if response['ret'] is False:
            return response
        return {'ret': True, 'changed': True,
                'msg': "Modified BIOS attributes %s. A reboot is required" % (attrs_to_patch),
                'warning': warning}

    def set_boot_order(self, boot_list):
        if not boot_list:
            return {'ret': False,
                    'msg': "boot_order list required for SetBootOrder command"}

        systems_uri = self.systems_uri
        response = self.get_request(self.root_uri + systems_uri)
        if response['ret'] is False:
            return response
        data = response['data']

        # Confirm needed Boot properties are present
        if 'Boot' not in data or 'BootOrder' not in data['Boot']:
            return {'ret': False, 'msg': "Key BootOrder not found"}

        boot = data['Boot']
        boot_order = boot['BootOrder']
        boot_options_dict = self._get_boot_options_dict(boot)

        # Verify the requested boot options are valid
        if boot_options_dict:
            boot_option_references = boot_options_dict.keys()
            for ref in boot_list:
                if ref not in boot_option_references:
                    return {'ret': False,
                            'msg': "BootOptionReference %s not found in BootOptions" % ref}

        # Apply the boot order
        payload = {
            'Boot': {
                'BootOrder': boot_list
            }
        }
        resp = self.patch_request(self.root_uri + systems_uri, payload, check_pyld=True)
        if resp['ret'] and resp['changed']:
            resp['msg'] = 'Modified the boot order'
        return resp

    def set_default_boot_order(self):
        systems_uri = self.systems_uri
        response = self.get_request(self.root_uri + systems_uri)
        if response['ret'] is False:
            return response
        data = response['data']

        # get the #ComputerSystem.SetDefaultBootOrder Action and target URI
        action = '#ComputerSystem.SetDefaultBootOrder'
        if 'Actions' not in data or action not in data['Actions']:
            return {'ret': False, 'msg': 'Action %s not found' % action}
        if 'target' not in data['Actions'][action]:
            return {'ret': False,
                    'msg': 'target URI missing from Action %s' % action}
        action_uri = data['Actions'][action]['target']

        # POST to Action URI
        payload = {}
        response = self.post_request(self.root_uri + action_uri, payload)
        if response['ret'] is False:
            return response
        return {'ret': True, 'changed': True,
                'msg': "BootOrder set to default"}

    def get_chassis_inventory(self):
        result = {}
        chassis_results = []

        # Get these entries, but does not fail if not found
        properties = ['Name', 'Id', 'ChassisType', 'PartNumber', 'AssetTag',
                      'Manufacturer', 'IndicatorLED', 'SerialNumber', 'Model']

        # Go through list
        for chassis_uri in self.chassis_uris:
            response = self.get_request(self.root_uri + chassis_uri)
            if response['ret'] is False:
                return response
            result['ret'] = True
            data = response['data']
            chassis_result = {}
            for property in properties:
                if property in data:
                    chassis_result[property] = data[property]
            chassis_results.append(chassis_result)

        result["entries"] = chassis_results
        return result

    def get_fan_inventory(self):
        result = {}
        fan_results = []
        key = "Thermal"
        # Get these entries, but does not fail if not found
        properties = ['Name', 'FanName', 'Reading', 'ReadingUnits', 'Status']

        # Go through list
        for chassis_uri in self.chassis_uris:
            response = self.get_request(self.root_uri + chassis_uri)
            if response['ret'] is False:
                return response
            result['ret'] = True
            data = response['data']
            if key in data:
                # match: found an entry for "Thermal" information = fans
                thermal_uri = data[key]["@odata.id"]
                response = self.get_request(self.root_uri + thermal_uri)
                if response['ret'] is False:
                    return response
                result['ret'] = True
                data = response['data']

                # Checking if fans are present
                if u'Fans' in data:
                    for device in data[u'Fans']:
                        fan = {}
                        for property in properties:
                            if property in device:
                                fan[property] = device[property]
                        fan_results.append(fan)
                else:
                    return {'ret': False, 'msg': "No Fans present"}
        result["entries"] = fan_results
        return result

    def get_chassis_power(self):
        result = {}
        key = "Power"

        # Get these entries, but does not fail if not found
        properties = ['Name', 'PowerAllocatedWatts',
                      'PowerAvailableWatts', 'PowerCapacityWatts',
                      'PowerConsumedWatts', 'PowerMetrics',
                      'PowerRequestedWatts', 'RelatedItem', 'Status']

        chassis_power_results = []
        # Go through list
        for chassis_uri in self.chassis_uris:
            chassis_power_result = {}
            response = self.get_request(self.root_uri + chassis_uri)
            if response['ret'] is False:
                return response
            result['ret'] = True
            data = response['data']
            if key in data:
                response = self.get_request(self.root_uri + data[key]['@odata.id'])
                data = response['data']
                if 'PowerControl' in data:
                    if len(data['PowerControl']) > 0:
                        data = data['PowerControl'][0]
                        for property in properties:
                            if property in data:
                                chassis_power_result[property] = data[property]
                chassis_power_results.append(chassis_power_result)

        if len(chassis_power_results) > 0:
            result['entries'] = chassis_power_results
            return result
        else:
            return {'ret': False, 'msg': 'Power information not found.'}

    def get_chassis_thermals(self):
        result = {}
        sensors = []
        key = "Thermal"

        # Get these entries, but does not fail if not found
        properties = ['Name', 'PhysicalContext', 'UpperThresholdCritical',
                      'UpperThresholdFatal', 'UpperThresholdNonCritical',
                      'LowerThresholdCritical', 'LowerThresholdFatal',
                      'LowerThresholdNonCritical', 'MaxReadingRangeTemp',
                      'MinReadingRangeTemp', 'ReadingCelsius', 'RelatedItem',
                      'SensorNumber', 'Status']

        # Go through list
        for chassis_uri in self.chassis_uris:
            response = self.get_request(self.root_uri + chassis_uri)
            if response['ret'] is False:
                return response
            result['ret'] = True
            data = response['data']
            if key in data:
                thermal_uri = data[key]["@odata.id"]
                response = self.get_request(self.root_uri + thermal_uri)
                if response['ret'] is False:
                    return response
                result['ret'] = True
                data = response['data']
                if "Temperatures" in data:
                    for sensor in data[u'Temperatures']:
                        sensor_result = {}
                        for property in properties:
                            if property in sensor:
                                if sensor[property] is not None:
                                    sensor_result[property] = sensor[property]
                        sensors.append(sensor_result)

        if sensors is None:
            return {'ret': False, 'msg': 'Key Temperatures was not found.'}

        result['entries'] = sensors
        return result

    def get_cpu_inventory(self, systems_uri):
        result = {}
        cpu_list = []
        cpu_results = []
        key = "Processors"
        # Get these entries, but does not fail if not found
        properties = ['Id', 'Name', 'Manufacturer', 'Model', 'MaxSpeedMHz',
                      'ProcessorArchitecture', 'TotalCores', 'TotalThreads', 'Status']

        # Search for 'key' entry and extract URI from it
        response = self.get_request(self.root_uri + systems_uri)
        if response['ret'] is False:
            return response
        result['ret'] = True
        data = response['data']

        if key not in data:
            return {'ret': False, 'msg': "Key %s not found" % key}

        processors_uri = data[key]["@odata.id"]

        # Get a list of all CPUs and build respective URIs
        response = self.get_request(self.root_uri + processors_uri)
        if response['ret'] is False:
            return response
        result['ret'] = True
        data = response['data']

        for cpu in data[u'Members']:
            cpu_list.append(cpu[u'@odata.id'])

        for c in cpu_list:
            cpu = {}
            uri = self.root_uri + c
            response = self.get_request(uri)
            if response['ret'] is False:
                return response
            data = response['data']

            for property in properties:
                if property in data:
                    cpu[property] = data[property]

            cpu_results.append(cpu)
        result["entries"] = cpu_results
        return result

    def get_multi_cpu_inventory(self):
        return self.aggregate_systems(self.get_cpu_inventory)

    def get_memory_inventory(self, systems_uri):
        result = {}
        memory_list = []
        memory_results = []
        key = "Memory"
        # Get these entries, but does not fail if not found
        properties = ['Id', 'SerialNumber', 'MemoryDeviceType', 'PartNumber',
                      'MemoryLocation', 'RankCount', 'CapacityMiB', 'OperatingMemoryModes', 'Status', 'Manufacturer', 'Name']

        # Search for 'key' entry and extract URI from it
        response = self.get_request(self.root_uri + systems_uri)
        if response['ret'] is False:
            return response
        result['ret'] = True
        data = response['data']

        if key not in data:
            return {'ret': False, 'msg': "Key %s not found" % key}

        memory_uri = data[key]["@odata.id"]

        # Get a list of all DIMMs and build respective URIs
        response = self.get_request(self.root_uri + memory_uri)
        if response['ret'] is False:
            return response
        result['ret'] = True
        data = response['data']

        for dimm in data[u'Members']:
            memory_list.append(dimm[u'@odata.id'])

        for m in memory_list:
            dimm = {}
            uri = self.root_uri + m
            response = self.get_request(uri)
            if response['ret'] is False:
                return response
            data = response['data']

            if "Status" in data:
                if "State" in data["Status"]:
                    if data["Status"]["State"] == "Absent":
                        continue
            else:
                continue

            for property in properties:
                if property in data:
                    dimm[property] = data[property]

            memory_results.append(dimm)
        result["entries"] = memory_results
        return result

    def get_multi_memory_inventory(self):
        return self.aggregate_systems(self.get_memory_inventory)

    def get_nic(self, resource_uri):
        result = {}
        properties = ['Name', 'Id', 'Description', 'FQDN', 'IPv4Addresses', 'IPv6Addresses',
                      'NameServers', 'MACAddress', 'PermanentMACAddress',
                      'SpeedMbps', 'MTUSize', 'AutoNeg', 'Status', 'LinkStatus']
        response = self.get_request(self.root_uri + resource_uri)
        if response['ret'] is False:
            return response
        result['ret'] = True
        data = response['data']
        nic = {}
        for property in properties:
            if property in data:
                nic[property] = data[property]
        result['entries'] = nic
        return result

    def get_nic_inventory(self, resource_uri):
        result = {}
        nic_list = []
        nic_results = []
        key = "EthernetInterfaces"

        response = self.get_request(self.root_uri + resource_uri)
        if response['ret'] is False:
            return response
        result['ret'] = True
        data = response['data']

        if key not in data:
            return {'ret': False, 'msg': "Key %s not found" % key}

        ethernetinterfaces_uri = data[key]["@odata.id"]

        # Get a list of all network controllers and build respective URIs
        response = self.get_request(self.root_uri + ethernetinterfaces_uri)
        if response['ret'] is False:
            return response
        result['ret'] = True
        data = response['data']

        for nic in data[u'Members']:
            nic_list.append(nic[u'@odata.id'])

        for n in nic_list:
            nic = self.get_nic(n)
            if nic['ret']:
                nic_results.append(nic['entries'])
        result["entries"] = nic_results
        return result

    def get_multi_nic_inventory(self, resource_type):
        ret = True
        entries = []

        #  Given resource_type, use the proper URI
        if resource_type == 'Systems':
            resource_uris = self.systems_uris
        elif resource_type == 'Manager':
            resource_uris = self.manager_uris

        for resource_uri in resource_uris:
            inventory = self.get_nic_inventory(resource_uri)
            ret = inventory.pop('ret') and ret
            if 'entries' in inventory:
                entries.append(({'resource_uri': resource_uri},
                                inventory['entries']))
        return dict(ret=ret, entries=entries)

    def get_virtualmedia(self, resource_uri):
        result = {}
        virtualmedia_list = []
        virtualmedia_results = []
        key = "VirtualMedia"
        # Get these entries, but does not fail if not found
        properties = ['Description', 'ConnectedVia', 'Id', 'MediaTypes',
                      'Image', 'ImageName', 'Name', 'WriteProtected',
                      'TransferMethod', 'TransferProtocolType']

        response = self.get_request(self.root_uri + resource_uri)
        if response['ret'] is False:
            return response
        result['ret'] = True
        data = response['data']

        if key not in data:
            return {'ret': False, 'msg': "Key %s not found" % key}

        virtualmedia_uri = data[key]["@odata.id"]

        # Get a list of all virtual media and build respective URIs
        response = self.get_request(self.root_uri + virtualmedia_uri)
        if response['ret'] is False:
            return response
        result['ret'] = True
        data = response['data']

        for virtualmedia in data[u'Members']:
            virtualmedia_list.append(virtualmedia[u'@odata.id'])

        for n in virtualmedia_list:
            virtualmedia = {}
            uri = self.root_uri + n
            response = self.get_request(uri)
            if response['ret'] is False:
                return response
            data = response['data']

            for property in properties:
                if property in data:
                    virtualmedia[property] = data[property]

            virtualmedia_results.append(virtualmedia)
        result["entries"] = virtualmedia_results
        return result

    def get_multi_virtualmedia(self, resource_type='Manager'):
        ret = True
        entries = []

        #  Given resource_type, use the proper URI
        if resource_type == 'Systems':
            resource_uris = self.systems_uris
        elif resource_type == 'Manager':
            resource_uris = self.manager_uris

        for resource_uri in resource_uris:
            virtualmedia = self.get_virtualmedia(resource_uri)
            ret = virtualmedia.pop('ret') and ret
            if 'entries' in virtualmedia:
                entries.append(({'resource_uri': resource_uri},
                               virtualmedia['entries']))
        return dict(ret=ret, entries=entries)

    @staticmethod
    def _find_empty_virt_media_slot(resources, media_types,
                                    media_match_strict=True, vendor=''):
        for uri, data in resources.items():
            # check MediaTypes
            if 'MediaTypes' in data and media_types:
                if not set(media_types).intersection(set(data['MediaTypes'])):
                    continue
            else:
                if media_match_strict:
                    continue
            # Base on current Lenovo server capability, filter out slot RDOC1/2 and Remote1/2/3/4 which are not supported to Insert/Eject.
            if vendor == 'Lenovo' and ('RDOC' in uri or 'Remote' in uri):
                continue
            # if ejected, 'Inserted' should be False and 'ImageName' cleared
            if (not data.get('Inserted', False) and
                    not data.get('ImageName')):
                return uri, data
        return None, None

    @staticmethod
    def _virt_media_image_inserted(resources, image_url):
        for uri, data in resources.items():
            if data.get('Image'):
                if urlparse(image_url) == urlparse(data.get('Image')):
                    if data.get('Inserted', False) and data.get('ImageName'):
                        return True
        return False

    @staticmethod
    def _find_virt_media_to_eject(resources, image_url):
        matched_uri, matched_data = None, None
        for uri, data in resources.items():
            if data.get('Image'):
                if urlparse(image_url) == urlparse(data.get('Image')):
                    matched_uri, matched_data = uri, data
                    if data.get('Inserted', True) and data.get('ImageName', 'x'):
                        return uri, data, True
        return matched_uri, matched_data, False

    def _read_virt_media_resources(self, uri_list):
        resources = {}
        headers = {}
        for uri in uri_list:
            response = self.get_request(self.root_uri + uri)
            if response['ret'] is False:
                continue
            resources[uri] = response['data']
            headers[uri] = response['headers']
        return resources, headers

    @staticmethod
    def _insert_virt_media_payload(options, param_map, data, ai):
        payload = {
            'Image': options.get('image_url')
        }
        for param, option in param_map.items():
            if options.get(option) is not None and param in data:
                allowable = ai.get(param, {}).get('AllowableValues', [])
                if allowable and options.get(option) not in allowable:
                    return {'ret': False,
                            'msg': "Value '%s' specified for option '%s' not "
                                   "in list of AllowableValues %s" % (
                                       options.get(option), option,
                                       allowable)}
                payload[param] = options.get(option)
        return payload

    def virtual_media_insert_via_patch(self, options, param_map, uri, data, image_only=False):
        # get AllowableValues
        ai = {
            k[:-24]: {'AllowableValues': v}
            for k, v in data.items()
            if k.endswith('@Redfish.AllowableValues')
        }
        # construct payload
        payload = self._insert_virt_media_payload(options, param_map, data, ai)
        if 'Inserted' not in payload and not image_only:
            # Add Inserted to the payload if needed
            payload['Inserted'] = True

        # PATCH the resource
        resp = self.patch_request(self.root_uri + uri, payload, check_pyld=True)
        if resp['ret'] is False:
            # WORKAROUND
            # Older HPE systems with iLO 4 and Supermicro do not support
            # specifying Inserted or WriteProtected
            vendor = self._get_vendor()['Vendor']
            if vendor == 'HPE' or vendor == 'Supermicro':
                payload.pop('Inserted', None)
                payload.pop('WriteProtected', None)
                resp = self.patch_request(self.root_uri + uri, payload, check_pyld=True)
        if resp['ret'] and resp['changed']:
            resp['msg'] = 'VirtualMedia inserted'
        return resp

    def virtual_media_insert(self, options, resource_type='Manager'):
        param_map = {
            'Inserted': 'inserted',
            'WriteProtected': 'write_protected',
            'UserName': 'username',
            'Password': 'password',
            'TransferProtocolType': 'transfer_protocol_type',
            'TransferMethod': 'transfer_method'
        }
        image_url = options.get('image_url')
        if not image_url:
            return {'ret': False,
                    'msg': "image_url option required for VirtualMediaInsert"}
        media_types = options.get('media_types')

        # locate and read the VirtualMedia resources
        #  Given resource_type, use the proper URI
        if resource_type == 'Systems':
            resource_uri = self.systems_uri
        elif resource_type == 'Manager':
            resource_uri = self.manager_uri
        response = self.get_request(self.root_uri + resource_uri)
        if response['ret'] is False:
            return response
        data = response['data']
        if 'VirtualMedia' not in data:
            return {'ret': False, 'msg': "VirtualMedia resource not found"}

        virt_media_uri = data["VirtualMedia"]["@odata.id"]
        response = self.get_request(self.root_uri + virt_media_uri)
        if response['ret'] is False:
            return response
        data = response['data']
        virt_media_list = []
        for member in data[u'Members']:
            virt_media_list.append(member[u'@odata.id'])
        resources, headers = self._read_virt_media_resources(virt_media_list)

        # see if image already inserted; if so, nothing to do
        if self._virt_media_image_inserted(resources, image_url):
            return {'ret': True, 'changed': False,
                    'msg': "VirtualMedia '%s' already inserted" % image_url}

        # find an empty slot to insert the media
        # try first with strict media_type matching
        vendor = self._get_vendor()['Vendor']
        uri, data = self._find_empty_virt_media_slot(
            resources, media_types, media_match_strict=True, vendor=vendor)
        if not uri:
            # if not found, try without strict media_type matching
            uri, data = self._find_empty_virt_media_slot(
                resources, media_types, media_match_strict=False, vendor=vendor)
        if not uri:
            return {'ret': False,
                    'msg': "Unable to find an available VirtualMedia resource "
                           "%s" % ('supporting ' + str(media_types)
                                   if media_types else '')}

        # confirm InsertMedia action found
        if ('Actions' not in data or
                '#VirtualMedia.InsertMedia' not in data['Actions']):
            # try to insert via PATCH if no InsertMedia action found
            h = headers[uri]
            if 'allow' in h:
                methods = [m.strip() for m in h.get('allow').split(',')]
                if 'PATCH' not in methods:
                    # if Allow header present and PATCH missing, return error
                    return {'ret': False,
                            'msg': "%s action not found and PATCH not allowed"
                            % '#VirtualMedia.InsertMedia'}
            return self.virtual_media_insert_via_patch(options, param_map,
                                                       uri, data)

        # get the action property
        action = data['Actions']['#VirtualMedia.InsertMedia']
        if 'target' not in action:
            return {'ret': False,
                    'msg': "target URI missing from Action "
                           "#VirtualMedia.InsertMedia"}
        action_uri = action['target']
        # get ActionInfo or AllowableValues
        ai = self._get_all_action_info_values(action)
        # construct payload
        payload = self._insert_virt_media_payload(options, param_map, data, ai)
        # POST to action
        response = self.post_request(self.root_uri + action_uri, payload)
        if response['ret'] is False and ('Inserted' in payload or 'WriteProtected' in payload):
            # WORKAROUND
            # Older HPE systems with iLO 4 and Supermicro do not support
            # specifying Inserted or WriteProtected
            vendor = self._get_vendor()['Vendor']
            if vendor == 'HPE' or vendor == 'Supermicro':
                payload.pop('Inserted', None)
                payload.pop('WriteProtected', None)
                response = self.post_request(self.root_uri + action_uri, payload)
        if response['ret'] is False:
            return response
        return {'ret': True, 'changed': True, 'msg': "VirtualMedia inserted"}

    def virtual_media_eject_via_patch(self, uri, image_only=False):
        # construct payload
        payload = {
            'Inserted': False,
            'Image': None
        }

        # Inserted is not writable
        if image_only:
            del payload['Inserted']

        # PATCH resource
        resp = self.patch_request(self.root_uri + uri, payload, check_pyld=True)
        if resp['ret'] is False and 'Inserted' in payload:
            # WORKAROUND
            # Older HPE systems with iLO 4 and Supermicro do not support
            # specifying Inserted
            vendor = self._get_vendor()['Vendor']
            if vendor == 'HPE' or vendor == 'Supermicro':
                payload.pop('Inserted', None)
                resp = self.patch_request(self.root_uri + uri, payload, check_pyld=True)
        if resp['ret'] and resp['changed']:
            resp['msg'] = 'VirtualMedia ejected'
        return resp

    def virtual_media_eject(self, options, resource_type='Manager'):
        image_url = options.get('image_url')
        if not image_url:
            return {'ret': False,
                    'msg': "image_url option required for VirtualMediaEject"}

        # locate and read the VirtualMedia resources
        # Given resource_type, use the proper URI
        if resource_type == 'Systems':
            resource_uri = self.systems_uri
        elif resource_type == 'Manager':
            resource_uri = self.manager_uri
        response = self.get_request(self.root_uri + resource_uri)
        if response['ret'] is False:
            return response
        data = response['data']
        if 'VirtualMedia' not in data:
            return {'ret': False, 'msg': "VirtualMedia resource not found"}

        virt_media_uri = data["VirtualMedia"]["@odata.id"]
        response = self.get_request(self.root_uri + virt_media_uri)
        if response['ret'] is False:
            return response
        data = response['data']
        virt_media_list = []
        for member in data[u'Members']:
            virt_media_list.append(member[u'@odata.id'])
        resources, headers = self._read_virt_media_resources(virt_media_list)

        # find the VirtualMedia resource to eject
        uri, data, eject = self._find_virt_media_to_eject(resources, image_url)
        if uri and eject:
            if ('Actions' not in data or
                    '#VirtualMedia.EjectMedia' not in data['Actions']):
                # try to eject via PATCH if no EjectMedia action found
                h = headers[uri]
                if 'allow' in h:
                    methods = [m.strip() for m in h.get('allow').split(',')]
                    if 'PATCH' not in methods:
                        # if Allow header present and PATCH missing, return error
                        return {'ret': False,
                                'msg': "%s action not found and PATCH not allowed"
                                       % '#VirtualMedia.EjectMedia'}
                return self.virtual_media_eject_via_patch(uri)
            else:
                # POST to the EjectMedia Action
                action = data['Actions']['#VirtualMedia.EjectMedia']
                if 'target' not in action:
                    return {'ret': False,
                            'msg': "target URI property missing from Action "
                                   "#VirtualMedia.EjectMedia"}
                action_uri = action['target']
                # empty payload for Eject action
                payload = {}
                # POST to action
                response = self.post_request(self.root_uri + action_uri,
                                             payload)
                if response['ret'] is False:
                    return response
                return {'ret': True, 'changed': True,
                        'msg': "VirtualMedia ejected"}
        elif uri and not eject:
            # already ejected: return success but changed=False
            return {'ret': True, 'changed': False,
                    'msg': "VirtualMedia image '%s' already ejected" %
                           image_url}
        else:
            # return failure (no resources matching image_url found)
            return {'ret': False, 'changed': False,
                    'msg': "No VirtualMedia resource found with image '%s' "
                           "inserted" % image_url}

    def get_psu_inventory(self):
        result = {}
        psu_list = []
        psu_results = []
        key = "PowerSupplies"
        # Get these entries, but does not fail if not found
        properties = ['Name', 'Model', 'SerialNumber', 'PartNumber', 'Manufacturer',
                      'FirmwareVersion', 'PowerCapacityWatts', 'PowerSupplyType',
                      'Status']

        # Get a list of all Chassis and build URIs, then get all PowerSupplies
        # from each Power entry in the Chassis
        for chassis_uri in self.chassis_uris:
            response = self.get_request(self.root_uri + chassis_uri)
            if response['ret'] is False:
                return response

            result['ret'] = True
            data = response['data']

            if 'Power' in data:
                power_uri = data[u'Power'][u'@odata.id']
            else:
                continue

            response = self.get_request(self.root_uri + power_uri)
            data = response['data']

            if key not in data:
                return {'ret': False, 'msg': "Key %s not found" % key}

            psu_list = data[key]
            for psu in psu_list:
                psu_not_present = False
                psu_data = {}
                for property in properties:
                    if property in psu:
                        if psu[property] is not None:
                            if property == 'Status':
                                if 'State' in psu[property]:
                                    if psu[property]['State'] == 'Absent':
                                        psu_not_present = True
                            psu_data[property] = psu[property]
                if psu_not_present:
                    continue
                psu_results.append(psu_data)

        result["entries"] = psu_results
        if not result["entries"]:
            return {'ret': False, 'msg': "No PowerSupply objects found"}
        return result

    def get_multi_psu_inventory(self):
        return self.aggregate_systems(self.get_psu_inventory)

    def get_system_inventory(self, systems_uri):
        result = {}
        inventory = {}
        # Get these entries, but does not fail if not found
        properties = ['Status', 'HostName', 'PowerState', 'BootProgress', 'Model', 'Manufacturer',
                      'PartNumber', 'SystemType', 'AssetTag', 'ServiceTag',
                      'SerialNumber', 'SKU', 'BiosVersion', 'MemorySummary',
                      'ProcessorSummary', 'TrustedModules', 'Name', 'Id']

        response = self.get_request(self.root_uri + systems_uri)
        if response['ret'] is False:
            return response
        result['ret'] = True
        data = response['data']

        for property in properties:
            if property in data:
                inventory[property] = data[property]

        result["entries"] = inventory
        return result

    def get_multi_system_inventory(self):
        return self.aggregate_systems(self.get_system_inventory)

    def get_network_protocols(self):
        result = {}
        service_result = {}
        # Find NetworkProtocol
        response = self.get_request(self.root_uri + self.manager_uri)
        if response['ret'] is False:
            return response
        data = response['data']
        if 'NetworkProtocol' not in data:
            return {'ret': False, 'msg': "NetworkProtocol resource not found"}
        networkprotocol_uri = data["NetworkProtocol"]["@odata.id"]

        response = self.get_request(self.root_uri + networkprotocol_uri)
        if response['ret'] is False:
            return response
        data = response['data']
        protocol_services = ['SNMP', 'VirtualMedia', 'Telnet', 'SSDP', 'IPMI', 'SSH',
                             'KVMIP', 'NTP', 'HTTP', 'HTTPS', 'DHCP', 'DHCPv6', 'RDP',
                             'RFB']
        for protocol_service in protocol_services:
            if protocol_service in data.keys():
                service_result[protocol_service] = data[protocol_service]

        result['ret'] = True
        result["entries"] = service_result
        return result

    def set_network_protocols(self, manager_services):
        # Check input data validity
        protocol_services = ['SNMP', 'VirtualMedia', 'Telnet', 'SSDP', 'IPMI', 'SSH',
                             'KVMIP', 'NTP', 'HTTP', 'HTTPS', 'DHCP', 'DHCPv6', 'RDP',
                             'RFB']
        protocol_state_onlist = ['true', 'True', True, 'on', 1]
        protocol_state_offlist = ['false', 'False', False, 'off', 0]
        payload = {}
        for service_name in manager_services.keys():
            if service_name not in protocol_services:
                return {'ret': False, 'msg': "Service name %s is invalid" % service_name}
            payload[service_name] = {}
            for service_property in manager_services[service_name].keys():
                value = manager_services[service_name][service_property]
                if service_property in ['ProtocolEnabled', 'protocolenabled']:
                    if value in protocol_state_onlist:
                        payload[service_name]['ProtocolEnabled'] = True
                    elif value in protocol_state_offlist:
                        payload[service_name]['ProtocolEnabled'] = False
                    else:
                        return {'ret': False, 'msg': "Value of property %s is invalid" % service_property}
                elif service_property in ['port', 'Port']:
                    if isinstance(value, int):
                        payload[service_name]['Port'] = value
                    elif isinstance(value, str) and value.isdigit():
                        payload[service_name]['Port'] = int(value)
                    else:
                        return {'ret': False, 'msg': "Value of property %s is invalid" % service_property}
                else:
                    payload[service_name][service_property] = value

        # Find the ManagerNetworkProtocol resource
        response = self.get_request(self.root_uri + self.manager_uri)
        if response['ret'] is False:
            return response
        data = response['data']
        networkprotocol_uri = data.get("NetworkProtocol", {}).get("@odata.id")
        if networkprotocol_uri is None:
            return {'ret': False, 'msg': "NetworkProtocol resource not found"}

        # Modify the ManagerNetworkProtocol resource
        resp = self.patch_request(self.root_uri + networkprotocol_uri, payload, check_pyld=True)
        if resp['ret'] and resp['changed']:
            resp['msg'] = 'Modified manager network protocol settings'
        return resp

    @staticmethod
    def to_singular(resource_name):
        if resource_name.endswith('ies'):
            resource_name = resource_name[:-3] + 'y'
        elif resource_name.endswith('s'):
            resource_name = resource_name[:-1]
        return resource_name

    def get_health_resource(self, subsystem, uri, health, expanded):
        status = 'Status'

        if expanded:
            d = expanded
        else:
            r = self.get_request(self.root_uri + uri)
            if r.get('ret'):
                d = r.get('data')
            else:
                return

        if 'Members' in d:  # collections case
            for m in d.get('Members'):
                u = m.get('@odata.id')
                r = self.get_request(self.root_uri + u)
                if r.get('ret'):
                    p = r.get('data')
                    if p:
                        e = {self.to_singular(subsystem.lower()) + '_uri': u,
                             status: p.get(status,
                                           "Status not available")}
                        health[subsystem].append(e)
        else:  # non-collections case
            e = {self.to_singular(subsystem.lower()) + '_uri': uri,
                 status: d.get(status,
                               "Status not available")}
            health[subsystem].append(e)

    def get_health_subsystem(self, subsystem, data, health):
        if subsystem in data:
            sub = data.get(subsystem)
            if isinstance(sub, list):
                for r in sub:
                    if '@odata.id' in r:
                        uri = r.get('@odata.id')
                        expanded = None
                        if '#' in uri and len(r) > 1:
                            expanded = r
                        self.get_health_resource(subsystem, uri, health, expanded)
            elif isinstance(sub, dict):
                if '@odata.id' in sub:
                    uri = sub.get('@odata.id')
                    self.get_health_resource(subsystem, uri, health, None)
        elif 'Members' in data:
            for m in data.get('Members'):
                u = m.get('@odata.id')
                r = self.get_request(self.root_uri + u)
                if r.get('ret'):
                    d = r.get('data')
                    self.get_health_subsystem(subsystem, d, health)

    def get_health_report(self, category, uri, subsystems):
        result = {}
        health = {}
        status = 'Status'

        # Get health status of top level resource
        response = self.get_request(self.root_uri + uri)
        if response['ret'] is False:
            return response
        result['ret'] = True
        data = response['data']
        health[category] = {status: data.get(status, "Status not available")}

        # Get health status of subsystems
        for sub in subsystems:
            d = None
            if sub.startswith('Links.'):  # ex: Links.PCIeDevices
                sub = sub[len('Links.'):]
                d = data.get('Links', {})
            elif '.' in sub:  # ex: Thermal.Fans
                p, sub = sub.split('.')
                u = data.get(p, {}).get('@odata.id')
                if u:
                    r = self.get_request(self.root_uri + u)
                    if r['ret']:
                        d = r['data']
                if not d:
                    continue
            else:  # ex: Memory
                d = data
            health[sub] = []
            self.get_health_subsystem(sub, d, health)
            if not health[sub]:
                del health[sub]

        result["entries"] = health
        return result

    def get_system_health_report(self, systems_uri):
        subsystems = ['Processors', 'Memory', 'SimpleStorage', 'Storage',
                      'EthernetInterfaces', 'NetworkInterfaces.NetworkPorts',
                      'NetworkInterfaces.NetworkDeviceFunctions']
        return self.get_health_report('System', systems_uri, subsystems)

    def get_multi_system_health_report(self):
        return self.aggregate_systems(self.get_system_health_report)

    def get_chassis_health_report(self, chassis_uri):
        subsystems = ['Power.PowerSupplies', 'Thermal.Fans',
                      'Links.PCIeDevices']
        return self.get_health_report('Chassis', chassis_uri, subsystems)

    def get_multi_chassis_health_report(self):
        return self.aggregate_chassis(self.get_chassis_health_report)

    def get_manager_health_report(self, manager_uri):
        subsystems = []
        return self.get_health_report('Manager', manager_uri, subsystems)

    def get_multi_manager_health_report(self):
        return self.aggregate_managers(self.get_manager_health_report)

    def set_manager_nic(self, nic_addr, nic_config):
        # Get the manager ethernet interface uri
        nic_info = self.get_manager_ethernet_uri(nic_addr)

        if nic_info.get('nic_addr') is None:
            return nic_info
        else:
            target_ethernet_uri = nic_info['nic_addr']
            target_ethernet_current_setting = nic_info['ethernet_setting']

        # Convert input to payload and check validity
        # Note: Some properties in the EthernetInterface resource are arrays of
        # objects.  The call into this module expects a flattened view, meaning
        # the user specifies exactly one object for an array property.  For
        # example, if a user provides IPv4StaticAddresses in the request to this
        # module, it will turn that into an array of one member.  This pattern
        # should be avoided for future commands in this module, but needs to be
        # preserved here for backwards compatibility.
        payload = {}
        for property in nic_config.keys():
            value = nic_config[property]
            if property in target_ethernet_current_setting and isinstance(value, dict) and isinstance(target_ethernet_current_setting[property], list):
                payload[property] = list()
                payload[property].append(value)
            else:
                payload[property] = value

        # Modify the EthernetInterface resource
        resp = self.patch_request(self.root_uri + target_ethernet_uri, payload, check_pyld=True)
        if resp['ret'] and resp['changed']:
            resp['msg'] = 'Modified manager NIC'
        return resp

    # A helper function to get the EthernetInterface URI
    def get_manager_ethernet_uri(self, nic_addr='null'):
        # Get EthernetInterface collection
        response = self.get_request(self.root_uri + self.manager_uri)
        if not response['ret']:
            return response
        data = response['data']
        if 'EthernetInterfaces' not in data:
            return {'ret': False, 'msg': "EthernetInterfaces resource not found"}
        ethernetinterfaces_uri = data["EthernetInterfaces"]["@odata.id"]
        response = self.get_request(self.root_uri + ethernetinterfaces_uri)
        if not response['ret']:
            return response
        data = response['data']
        uris = [a.get('@odata.id') for a in data.get('Members', []) if
                a.get('@odata.id')]

        # Find target EthernetInterface
        target_ethernet_uri = None
        target_ethernet_current_setting = None
        if nic_addr == 'null':
            # Find root_uri matched EthernetInterface when nic_addr is not specified
            nic_addr = (self.root_uri).split('/')[-1]
            nic_addr = nic_addr.split(':')[0]  # split port if existing
        for uri in uris:
            response = self.get_request(self.root_uri + uri)
            if not response['ret']:
                return response
            data = response['data']
            data_string = json.dumps(data)
            if nic_addr.lower() in data_string.lower():
                target_ethernet_uri = uri
                target_ethernet_current_setting = data
                break

        nic_info = {}
        nic_info['nic_addr'] = target_ethernet_uri
        nic_info['ethernet_setting'] = target_ethernet_current_setting

        if target_ethernet_uri is None:
            return {}
        else:
            return nic_info

    def set_hostinterface_attributes(self, hostinterface_config, hostinterface_id=None):
        if hostinterface_config is None:
            return {'ret': False, 'msg':
                    'Must provide hostinterface_config for SetHostInterface command'}

        # Find the HostInterfaceCollection resource
        response = self.get_request(self.root_uri + self.manager_uri)
        if response['ret'] is False:
            return response
        data = response['data']
        hostinterfaces_uri = data.get("HostInterfaces", {}).get("@odata.id")
        if hostinterfaces_uri is None:
            return {'ret': False, 'msg': "HostInterface resource not found"}
        response = self.get_request(self.root_uri + hostinterfaces_uri)
        if response['ret'] is False:
            return response
        data = response['data']
        uris = [a.get('@odata.id') for a in data.get('Members', []) if a.get('@odata.id')]

        # Capture list of URIs that match a specified HostInterface resource Id
        if hostinterface_id:
            matching_hostinterface_uris = [uri for uri in uris if hostinterface_id in uri.rstrip('/').split('/')[-1]]
        if hostinterface_id and matching_hostinterface_uris:
            hostinterface_uri = list.pop(matching_hostinterface_uris)
        elif hostinterface_id and not matching_hostinterface_uris:
            return {'ret': False, 'msg': "HostInterface ID %s not present." % hostinterface_id}
        elif len(uris) == 1:
            hostinterface_uri = list.pop(uris)
        else:
            return {'ret': False, 'msg': "HostInterface ID not defined and multiple interfaces detected."}

        # Modify the HostInterface resource
        resp = self.patch_request(self.root_uri + hostinterface_uri, hostinterface_config, check_pyld=True)
        if resp['ret'] and resp['changed']:
            resp['msg'] = 'Modified host interface'
        return resp

    def get_hostinterfaces(self):
        result = {}
        hostinterface_results = []
        properties = ['Id', 'Name', 'Description', 'HostInterfaceType', 'Status',
                      'InterfaceEnabled', 'ExternallyAccessible', 'AuthenticationModes',
                      'AuthNoneRoleId', 'CredentialBootstrapping']
        manager_uri_list = self.manager_uris
        for manager_uri in manager_uri_list:
            response = self.get_request(self.root_uri + manager_uri)
            if response['ret'] is False:
                return response

            result['ret'] = True
            data = response['data']
            hostinterfaces_uri = data.get("HostInterfaces", {}).get("@odata.id")
            if hostinterfaces_uri is None:
                continue

            response = self.get_request(self.root_uri + hostinterfaces_uri)
            data = response['data']

            if 'Members' in data:
                for hostinterface in data['Members']:
                    hostinterface_uri = hostinterface['@odata.id']
                    hostinterface_response = self.get_request(self.root_uri + hostinterface_uri)
                    # dictionary for capturing individual HostInterface properties
                    hostinterface_data_temp = {}
                    if hostinterface_response['ret'] is False:
                        return hostinterface_response
                    hostinterface_data = hostinterface_response['data']
                    for property in properties:
                        if property in hostinterface_data:
                            if hostinterface_data[property] is not None:
                                hostinterface_data_temp[property] = hostinterface_data[property]
                    # Check for the presence of a ManagerEthernetInterface
                    # object, a link to a _single_ EthernetInterface that the
                    # BMC uses to communicate with the host.
                    if 'ManagerEthernetInterface' in hostinterface_data:
                        interface_uri = hostinterface_data['ManagerEthernetInterface']['@odata.id']
                        interface_response = self.get_nic(interface_uri)
                        if interface_response['ret'] is False:
                            return interface_response
                        hostinterface_data_temp['ManagerEthernetInterface'] = interface_response['entries']

                    # Check for the presence of a HostEthernetInterfaces
                    # object, a link to a _collection_ of EthernetInterfaces
                    # that the host uses to communicate with the BMC.
                    if 'HostEthernetInterfaces' in hostinterface_data:
                        interfaces_uri = hostinterface_data['HostEthernetInterfaces']['@odata.id']
                        interfaces_response = self.get_request(self.root_uri + interfaces_uri)
                        if interfaces_response['ret'] is False:
                            return interfaces_response
                        interfaces_data = interfaces_response['data']
                        if 'Members' in interfaces_data:
                            for interface in interfaces_data['Members']:
                                interface_uri = interface['@odata.id']
                                interface_response = self.get_nic(interface_uri)
                                if interface_response['ret'] is False:
                                    return interface_response
                                # Check if this is the first
                                # HostEthernetInterfaces item and create empty
                                # list if so.
                                if 'HostEthernetInterfaces' not in hostinterface_data_temp:
                                    hostinterface_data_temp['HostEthernetInterfaces'] = []

                                hostinterface_data_temp['HostEthernetInterfaces'].append(interface_response['entries'])

                    hostinterface_results.append(hostinterface_data_temp)
            else:
                continue
        result["entries"] = hostinterface_results
        if not result["entries"]:
            return {'ret': False, 'msg': "No HostInterface objects found"}
        return result

    def get_manager_inventory(self, manager_uri):
        result = {}
        inventory = {}
        # Get these entries, but does not fail if not found
        properties = ['Id', 'FirmwareVersion', 'ManagerType', 'Manufacturer', 'Model',
                      'PartNumber', 'PowerState', 'SerialNumber', 'ServiceIdentification',
                      'Status', 'UUID']

        response = self.get_request(self.root_uri + manager_uri)
        if response['ret'] is False:
            return response
        result['ret'] = True
        data = response['data']

        for property in properties:
            if property in data:
                inventory[property] = data[property]

        result["entries"] = inventory
        return result

    def get_multi_manager_inventory(self):
        return self.aggregate_managers(self.get_manager_inventory)

    def get_service_identification(self, manager):
        result = {}
        if manager is None:
            if len(self.manager_uris) == 1:
                manager = self.manager_uris[0].rstrip('/').split('/')[-1]
            elif len(self.manager_uris) > 1:
                entries = self.get_multi_manager_inventory()['entries']
                managers = [m[0]['manager_uri'] for m in entries if m[1].get('ServiceIdentification')]
                if len(managers) == 1:
                    manager = managers[0].rstrip('/').split('/')[-1]
                else:
                    self.module.fail_json(msg=[
                        "Multiple managers with ServiceIdentification were found: %s" % str(managers),
                        "Please specify by using the 'manager' parameter in your playbook"])
            elif len(self.manager_uris) == 0:
                self.module.fail_json(msg="No manager identities were found")
        response = self.get_request(self.root_uri + '/redfish/v1/Managers/' + manager, override_headers=None)
        try:
            result['service_identification'] = response['data']['ServiceIdentification']
        except Exception as e:
            self.module.fail_json(msg="Service ID not found for manager %s" % manager)
        result['ret'] = True
        return result

    def set_service_identification(self, service_id):
        data = {"ServiceIdentification": service_id}
        resp = self.patch_request(self.root_uri + '/redfish/v1/Managers/' + self.resource_id, data, check_pyld=True)
        return resp

    def set_session_service(self, sessions_config):
        if sessions_config is None:
            return {'ret': False, 'msg':
                    'Must provide sessions_config for SetSessionService command'}

        resp = self.patch_request(self.root_uri + self.session_service_uri, sessions_config, check_pyld=True)
        if resp['ret'] and resp['changed']:
            resp['msg'] = 'Modified session service'
        return resp

    def verify_bios_attributes(self, bios_attributes):
        # This method verifies BIOS attributes against the provided input
        server_bios = self.get_bios_attributes(self.systems_uri)
        if server_bios["ret"] is False:
            return server_bios

        bios_dict = {}
        wrong_param = {}

        # Verify bios_attributes with BIOS settings available in the server
        for key, value in bios_attributes.items():
            if key in server_bios["entries"]:
                if server_bios["entries"][key] != value:
                    bios_dict.update({key: value})
            else:
                wrong_param.update({key: value})

        if wrong_param:
            return {
                "ret": False,
                "msg": "Wrong parameters are provided: %s" % wrong_param
            }

        if bios_dict:
            return {
                "ret": False,
                "msg": "BIOS parameters are not matching: %s" % bios_dict
            }

        return {
            "ret": True,
            "changed": False,
            "msg": "BIOS verification completed"
        }

    def enable_secure_boot(self):
        # This function enable Secure Boot on an OOB controller

        response = self.get_request(self.root_uri + self.systems_uri)
        if response["ret"] is False:
            return response

        server_details = response["data"]
        secure_boot_url = server_details["SecureBoot"]["@odata.id"]

        response = self.get_request(self.root_uri + secure_boot_url)
        if response["ret"] is False:
            return response

        body = {}
        body["SecureBootEnable"] = True

        return self.patch_request(self.root_uri + secure_boot_url, body, check_pyld=True)

    def set_secure_boot(self, secure_boot_enable):
        # This function enable Secure Boot on an OOB controller

        response = self.get_request(self.root_uri + self.systems_uri)
        if response["ret"] is False:
            return response

        server_details = response["data"]
        secure_boot_url = server_details["SecureBoot"]["@odata.id"]

        response = self.get_request(self.root_uri + secure_boot_url)
        if response["ret"] is False:
            return response

        body = {}
        body["SecureBootEnable"] = secure_boot_enable

        return self.patch_request(self.root_uri + secure_boot_url, body, check_pyld=True)

    def get_hpe_thermal_config(self):
        result = {}
        key = "Thermal"
        # Go through list
        for chassis_uri in self.chassis_uris:
            response = self.get_request(self.root_uri + chassis_uri)
            if response['ret'] is False:
                return response
            result['ret'] = True
            data = response['data']
            val = data.get('Oem', {}).get('Hpe', {}).get('ThermalConfiguration')
            if val is not None:
                return {"ret": True, "current_thermal_config": val}
        return {"ret": False}

    def get_hpe_fan_percent_min(self):
        result = {}
        key = "Thermal"
        # Go through list
        for chassis_uri in self.chassis_uris:
            response = self.get_request(self.root_uri + chassis_uri)
            if response['ret'] is False:
                return response
            data = response['data']
            val = data.get('Oem', {}).get('Hpe', {}).get('FanPercentMinimum')
            if val is not None:
                return {"ret": True, "fan_percent_min": val}
        return {"ret": False}

    def delete_volumes(self, storage_subsystem_id, volume_ids):
        # Find the Storage resource from the requested ComputerSystem resource
        response = self.get_request(self.root_uri + self.systems_uri)
        if response['ret'] is False:
            return response
        data = response['data']
        storage_uri = data.get('Storage', {}).get('@odata.id')
        if storage_uri is None:
            return {'ret': False, 'msg': 'Storage resource not found'}

        # Get Storage Collection
        response = self.get_request(self.root_uri + storage_uri)
        if response['ret'] is False:
            return response
        data = response['data']

        # Collect Storage Subsystems
        self.storage_subsystems_uris = [i['@odata.id'] for i in response['data'].get('Members', [])]
        if not self.storage_subsystems_uris:
            return {
                'ret': False,
                'msg': "StorageCollection's Members array is either empty or missing"}

        # Matching Storage Subsystem ID with user input
        self.storage_subsystem_uri = ""
        for storage_subsystem_uri in self.storage_subsystems_uris:
            if storage_subsystem_uri.rstrip('/').split('/')[-1] == storage_subsystem_id:
                self.storage_subsystem_uri = storage_subsystem_uri

        if not self.storage_subsystem_uri:
            return {
                'ret': False,
                'msg': "Provided Storage Subsystem ID %s does not exist on the server" % storage_subsystem_id}

        # Get Volume Collection
        response = self.get_request(self.root_uri + self.storage_subsystem_uri)
        if response['ret'] is False:
            return response
        data = response['data']

        response = self.get_request(self.root_uri + data['Volumes']['@odata.id'])
        if response['ret'] is False:
            return response
        data = response['data']

        # Collect Volumes
        self.volume_uris = [i['@odata.id'] for i in response['data'].get('Members', [])]
        if not self.volume_uris:
            return {
                'ret': True, 'changed': False,
                'msg': "VolumeCollection's Members array is either empty or missing"}

        # Delete each volume
        for volume in self.volume_uris:
            if volume.rstrip('/').split('/')[-1] in volume_ids:
                response = self.delete_request(self.root_uri + volume)
                if response['ret'] is False:
                    return response

        return {'ret': True, 'changed': True,
                'msg': "The following volumes were deleted: %s" % str(volume_ids)}

    def create_volume(self, volume_details, storage_subsystem_id, storage_none_volume_deletion=False):
        # Find the Storage resource from the requested ComputerSystem resource
        response = self.get_request(self.root_uri + self.systems_uri)
        if response['ret'] is False:
            return response
        data = response['data']
        storage_uri = data.get('Storage', {}).get('@odata.id')
        if storage_uri is None:
            return {'ret': False, 'msg': 'Storage resource not found'}

        # Get Storage Collection
        response = self.get_request(self.root_uri + storage_uri)
        if response['ret'] is False:
            return response
        data = response['data']

        # Collect Storage Subsystems
        self.storage_subsystems_uris = [i['@odata.id'] for i in response['data'].get('Members', [])]
        if not self.storage_subsystems_uris:
            return {
                'ret': False,
                'msg': "StorageCollection's Members array is either empty or missing"}

        # Matching Storage Subsystem ID with user input
        self.storage_subsystem_uri = ""
        for storage_subsystem_uri in self.storage_subsystems_uris:
            if storage_subsystem_uri.rstrip('/').split('/')[-1] == storage_subsystem_id:
                self.storage_subsystem_uri = storage_subsystem_uri

        if not self.storage_subsystem_uri:
            return {
                'ret': False,
                'msg': "Provided Storage Subsystem ID %s does not exist on the server" % storage_subsystem_id}

        # Validate input parameters
        required_parameters = ['RAIDType', 'Drives']
        allowed_parameters = ['CapacityBytes', 'DisplayName', 'InitializeMethod', 'MediaSpanCount',
                              'Name', 'ReadCachePolicy', 'StripSizeBytes', 'VolumeUsage', 'WriteCachePolicy']

        for parameter in required_parameters:
            if not volume_details.get(parameter):
                return {
                    'ret': False,
                    'msg': "%s are required parameter to create a volume" % str(required_parameters)}

        # Navigate to the volume uri of the correct storage subsystem
        response = self.get_request(self.root_uri + self.storage_subsystem_uri)
        if response['ret'] is False:
            return response
        data = response['data']

        # Deleting any volumes of RAIDType None present on the Storage Subsystem
        if storage_none_volume_deletion:
            response = self.get_request(self.root_uri + data['Volumes']['@odata.id'])
            if response['ret'] is False:
                return response
            volume_data = response['data']

            if "Members" in volume_data:
                for member in volume_data["Members"]:
                    response = self.get_request(self.root_uri + member['@odata.id'])
                    if response['ret'] is False:
                        return response
                    member_data = response['data']

                    if member_data["RAIDType"] == "None":
                        response = self.delete_request(self.root_uri + member['@odata.id'])
                        if response['ret'] is False:
                            return response

        # Construct payload and issue POST command to create volume
        volume_details["Links"] = {}
        volume_details["Links"]["Drives"] = []
        for drive in volume_details["Drives"]:
            volume_details["Links"]["Drives"].append({"@odata.id": drive})
        del volume_details["Drives"]
        payload = volume_details
        response = self.post_request(self.root_uri + data['Volumes']['@odata.id'], payload)
        if response['ret'] is False:
            return response

        return {'ret': True, 'changed': True,
                'msg': "Volume Created"}

    def get_bios_registries(self):
        # Get /redfish/v1
        response = self.get_request(self.root_uri + self.systems_uri)
        if not response["ret"]:
            return response

        server_details = response["data"]

        # Get Registries URI
        if "Bios" not in server_details:
            msg = "Getting BIOS URI failed, Key 'Bios' not found in /redfish/v1/Systems/1/ response: %s"
            return {
                "ret": False,
                "msg": msg % str(server_details)
            }

        bios_uri = server_details["Bios"]["@odata.id"]
        bios_resp = self.get_request(self.root_uri + bios_uri)
        if not bios_resp["ret"]:
            return bios_resp

        bios_data = bios_resp["data"]
        attribute_registry = bios_data["AttributeRegistry"]

        reg_uri = self.root_uri + self.service_root + "Registries/" + attribute_registry
        reg_resp = self.get_request(reg_uri)
        if not reg_resp["ret"]:
            return reg_resp

        reg_data = reg_resp["data"]

        # Get BIOS attribute registry URI
        lst = []

        # Get the location URI
        response = self.check_location_uri(reg_data, reg_uri)
        if not response["ret"]:
            return response

        rsp_data, rsp_uri = response["rsp_data"], response["rsp_uri"]

        if "RegistryEntries" not in rsp_data:
            return {
                "msg": "'RegistryEntries' not present in %s response, %s" % (rsp_uri, str(rsp_data)),
                "ret": False
            }

        return {
            "bios_registry": rsp_data,
            "bios_registry_uri": rsp_uri,
            "ret": True
        }

    def check_location_uri(self, resp_data, resp_uri):
        # Get the location URI response
        # return {"msg": self.creds, "ret": False}
        vendor = self._get_vendor()['Vendor']
        rsp_uri = ""
        for loc in resp_data['Location']:
            if loc['Language'].startswith("en"):
                rsp_uri = loc['Uri']
                if vendor == 'HPE':
                    # WORKAROUND
                    # HPE systems with iLO 4 will have BIOS Attribute Registries location URI as a dictionary with key 'extref'
                    # Hence adding condition to fetch the Uri
                    if isinstance(loc['Uri'], dict) and "extref" in loc['Uri'].keys():
                        rsp_uri = loc['Uri']['extref']
        if not rsp_uri:
            msg = "Language 'en' not found in BIOS Attribute Registries location, URI: %s, response: %s"
            return {
                "ret": False,
                "msg": msg % (resp_uri, str(resp_data))
            }

        res = self.get_request(self.root_uri + rsp_uri)
        if res['ret'] is False:
            # WORKAROUND
            # HPE systems with iLO 4 or iLO5 compresses (gzip) for some URIs
            # Hence adding encoding to the header
            if vendor == 'HPE':
                override_headers = {"Accept-Encoding": "gzip"}
                res = self.get_request(self.root_uri + rsp_uri, override_headers=override_headers)
        if res['ret']:
            return {
                "ret": True,
                "rsp_data": res["data"],
                "rsp_uri": rsp_uri
            }
        return res

    def get_accountservice_properties(self):
        # Find the AccountService resource
        response = self.get_request(self.root_uri + self.service_root)
        if response['ret'] is False:
            return response
        data = response['data']
        accountservice_uri = data.get("AccountService", {}).get("@odata.id")
        if accountservice_uri is None:
            return {'ret': False, 'msg': "AccountService resource not found"}

        response = self.get_request(self.root_uri + accountservice_uri)
        if response['ret'] is False:
            return response
        return {
            'ret': True,
            'entries': response['data']
        }

    def get_power_restore_policy(self, systems_uri):
        # Retrieve System resource
        response = self.get_request(self.root_uri + systems_uri)
        if response['ret'] is False:
            return response
        return {
            'ret': True,
            'entries': response['data']['PowerRestorePolicy']
        }

    def get_multi_power_restore_policy(self):
        return self.aggregate_systems(self.get_power_restore_policy)

    def set_power_restore_policy(self, policy):
        body = {'PowerRestorePolicy': policy}
        return self.patch_request(self.root_uri + self.systems_uri, body, check_pyld=True)