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
|
# Copyright 2018-2022 Hewlett Packard Enterprise Development Company, L.P.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
__author__ = 'HPE'
import hashlib
import retrying
from proliantutils import exception
from proliantutils.ilo import common
from proliantutils.ilo import constants
from proliantutils.ilo import firmware_controller
from proliantutils.ilo import mappings
from proliantutils.ilo import operations
from proliantutils import log
from proliantutils import rest
from proliantutils import utils
""" Currently this class supports only secure boot and firmware settings
related API's .
TODO : Add rest of the API's that exists in RIBCL. """
DEVICE_COMMON_TO_RIS = {'NETWORK': 'Pxe',
'CDROM': 'Cd',
'HDD': 'Hdd',
'ISCSI': 'UefiTarget'}
DEVICE_RIS_TO_COMMON = dict(
(v, k) for (k, v) in DEVICE_COMMON_TO_RIS.items())
POWER_STATE = {
'ON': 'On',
'OFF': 'ForceOff',
}
# The PCI standards mention following categories of PCI devices as
# GPU devices.
# Base Class Code 03 indicate VGA devices
# Sub Class Code
# 00h: VGA-compatible controller
# 01h: XGA controller
# 02h: 3D controller
# 80h: Other display controller
# RIS data reports the SubclassCode in integer rather than in hexadecimal form.
CLASSCODE_FOR_GPU_DEVICES = [3]
SUBCLASSCODE_FOR_GPU_DEVICES = [0, 1, 2, 128]
MAX_RETRY_ATTEMPTS = 3 # Maximum number of attempts to be retried
MAX_TIME_BEFORE_RETRY = 7 * 1000 # wait time in milliseconds before retry
LOG = log.get_logger(__name__)
class RISOperations(rest.RestConnectorBase, operations.IloOperations):
"""iLO class for RIS interface of iLO.
Implements the class used for REST based RIS services to talk to the iLO.
"""
def __init__(self, host, login, password, bios_password=None,
cacert=None):
super(RISOperations, self).__init__(host, login, password,
bios_password=bios_password,
cacert=cacert)
def _get_collection(self, collection_uri, request_headers=None):
"""Generator function that returns collection members."""
# get the collection
status, headers, thecollection = self._rest_get(collection_uri)
if status != 200:
msg = self._get_extended_error(thecollection)
raise exception.IloError(msg)
while status < 300:
# verify expected type
# Don't limit to version 0 here as we will rev to 1.0 at some
# point hopefully with minimal changes
ctype = self._get_type(thecollection)
if (ctype not in ['Collection.0', 'Collection.1']):
raise exception.IloError("collection not found")
# if this collection has inline items, return those
# NOTE: Collections are very flexible in how the represent
# members. They can be inline in the collection as members
# of the 'Items' array, or they may be href links in the
# links/Members array. The could actually be both. Typically,
# iLO implements the inline (Items) for only when the collection
# is read only. We have to render it with the href links when an
# array contains PATCHable items because its complex to PATCH
# inline collection members.
if 'Items' in thecollection:
# iterate items
for item in thecollection['Items']:
# if the item has a self uri pointer,
# supply that for convenience.
memberuri = None
if 'links' in item and 'self' in item['links']:
memberuri = item['links']['self']['href']
yield 200, None, item, memberuri
# else walk the member links
elif ('links' in thecollection
and 'Member' in thecollection['links']):
# iterate members
for memberuri in thecollection['links']['Member']:
# for each member return the resource indicated by the
# member link
status, headers, member = self._rest_get(memberuri['href'])
yield status, headers, member, memberuri['href']
# page forward if there are more pages in the collection
if ('links' in thecollection
and 'NextPage' in thecollection['links']):
next_link_uri = (collection_uri + '?page=' + str(
thecollection['links']['NextPage']['page']))
status, headers, thecollection = self._rest_get(next_link_uri)
# else we are finished iterating the collection
else:
break
def _get_type(self, obj):
"""Return the type of an object."""
typever = obj['Type']
typesplit = typever.split('.')
return typesplit[0] + '.' + typesplit[1]
def _operation_allowed(self, headers_dict, operation):
"""Checks if specified operation is allowed on the resource."""
if 'allow' in headers_dict:
if operation in headers_dict['allow']:
return True
return False
def _render_extended_error_message_list(self, extended_error):
"""Parse the ExtendedError object and retruns the message.
Build a list of decoded messages from the extended_error using the
message registries. An ExtendedError JSON object is a response from
the with its own schema. This function knows how to parse the
ExtendedError object and, using any loaded message registries,
render an array of plain language strings that represent
the response.
"""
messages = []
if isinstance(extended_error, dict):
if ('Type' in extended_error
and extended_error['Type'].startswith('ExtendedError.')):
for msg in extended_error['Messages']:
message_id = msg['MessageID']
x = message_id.split('.')
registry = x[0]
msgkey = x[len(x) - 1]
# if the correct message registry is loaded,
# do string resolution
if (registry in self.message_registries and msgkey in
self.message_registries[registry]['Messages']):
rmsgs = self.message_registries[registry]['Messages']
msg_dict = rmsgs[msgkey]
msg_str = message_id + ': ' + msg_dict['Message']
for argn in range(0, msg_dict['NumberOfArgs']):
subst = '%' + str(argn + 1)
m = str(msg['MessageArgs'][argn])
msg_str = msg_str.replace(subst, m)
if ('Resolution' in msg_dict
and msg_dict['Resolution'] != 'None'):
msg_str += ' ' + msg_dict['Resolution']
messages.append(msg_str)
else:
# no message registry, simply return the msg object
# in string form
messages.append(str(message_id))
return messages
def _get_extended_error(self, extended_error):
"""Gets the list of decoded messages from the extended_error."""
return self._render_extended_error_message_list(extended_error)
def _get_host_details(self):
"""Get the system details."""
# Assuming only one system present as part of collection,
# as we are dealing with iLO's here.
status, headers, system = self._rest_get('/rest/v1/Systems/1')
if status < 300:
stype = self._get_type(system)
if stype not in ['ComputerSystem.0', 'ComputerSystem.1']:
msg = "%s is not a valid system type " % stype
raise exception.IloError(msg)
else:
msg = self._get_extended_error(system)
raise exception.IloError(msg)
return system
def _check_bios_resource(self, properties=[]):
"""Check if the bios resource exists."""
system = self._get_host_details()
if ('links' in system['Oem']['Hp']
and 'BIOS' in system['Oem']['Hp']['links']):
# Get the BIOS URI and Settings
bios_uri = system['Oem']['Hp']['links']['BIOS']['href']
status, headers, bios_settings = self._rest_get(bios_uri)
if status >= 300:
msg = self._get_extended_error(bios_settings)
raise exception.IloError(msg)
# If property is not None, check if the bios_property is supported
for property in properties:
if property not in bios_settings:
# not supported on this platform
msg = ('BIOS Property "' + property + '" is not'
' supported on this system.')
raise exception.IloCommandNotSupportedError(msg)
return headers, bios_uri, bios_settings
else:
msg = ('"links/BIOS" section in ComputerSystem/Oem/Hp'
' does not exist')
raise exception.IloCommandNotSupportedError(msg)
def _get_pci_devices(self):
"""Gets the PCI devices.
:returns: PCI devices list if the pci resource exist.
:raises: IloCommandNotSupportedError if the PCI resource
doesn't exist.
:raises: IloError, on an error from iLO.
"""
system = self._get_host_details()
if ('links' in system['Oem']['Hp']
and 'PCIDevices' in system['Oem']['Hp']['links']):
# Get the PCI URI and Settings
pci_uri = system['Oem']['Hp']['links']['PCIDevices']['href']
status, headers, pci_device_list = self._rest_get(pci_uri)
if status >= 300:
msg = self._get_extended_error(pci_device_list)
raise exception.IloError(msg)
return pci_device_list
else:
msg = ('links/PCIDevices section in ComputerSystem/Oem/Hp'
' does not exist')
raise exception.IloCommandNotSupportedError(msg)
def _get_gpu_pci_devices(self):
"""Returns the list of gpu devices."""
pci_device_list = self._get_pci_devices()
gpu_list = []
items = pci_device_list['Items']
for item in items:
if item['ClassCode'] in CLASSCODE_FOR_GPU_DEVICES:
if item['SubclassCode'] in SUBCLASSCODE_FOR_GPU_DEVICES:
gpu_list.append(item)
return gpu_list
def _get_storage_resource(self):
"""Gets the SmartStorage resource if exists.
:raises: IloCommandNotSupportedError if the resource SmartStorage
doesn't exist.
:returns the tuple of SmartStorage URI, Headers and settings.
"""
system = self._get_host_details()
if ('links' in system['Oem']['Hp']
and 'SmartStorage' in system['Oem']['Hp']['links']):
# Get the SmartStorage URI and Settings
storage_uri = system['Oem']['Hp']['links']['SmartStorage']['href']
status, headers, storage_settings = self._rest_get(storage_uri)
if status >= 300:
msg = self._get_extended_error(storage_settings)
raise exception.IloError(msg)
return headers, storage_uri, storage_settings
else:
msg = ('"links/SmartStorage" section in ComputerSystem/Oem/Hp'
' does not exist')
raise exception.IloCommandNotSupportedError(msg)
def _get_array_controller_resource(self):
"""Gets the ArrayController resource if exists.
:raises: IloCommandNotSupportedError if the resource ArrayController
doesn't exist.
:returns the tuple of SmartStorage URI, Headers and settings.
"""
headers, storage_uri, storage_settings = self._get_storage_resource()
# Do not raise exception if there is no ArrayControllers
# as Storage can be zero at any point and if we raise
# exception it might fail get_server_capabilities().
if ('links' in storage_settings
and 'ArrayControllers' in storage_settings['links']):
# Get the ArrayCOntrollers URI and Settings
array_uri = storage_settings['links']['ArrayControllers']['href']
status, headers, array_settings = self._rest_get(array_uri)
if status >= 300:
msg = self._get_extended_error(array_settings)
raise exception.IloError(msg)
return headers, array_uri, array_settings
def _create_list_of_array_controllers(self):
"""Creates the list of Array Controller URIs.
:returns list of ArrayControllers.
"""
headers, array_uri, array_settings = (
self._get_array_controller_resource())
array_uri_links = []
# Do not raise exception if there is no ArrayControllers
# as Storage can be zero at any point and if we raise
# exception it might fail get_server_capabilities().
if ('links' in array_settings
and 'Member' in array_settings['links']):
array_uri_links = array_settings['links']['Member']
return array_uri_links
def _get_drive_type_and_speed(self):
"""Gets the disk drive type.
:returns: A dictionary with the following keys:
- has_rotational: True/False. It is True if atleast one
rotational disk is attached.
- has_ssd: True/False. It is True if at least one SSD disk is
attached.
- drive_rotational_<speed>_rpm: These are set to true as
per the speed of the rotational disks.
:raises: IloCommandNotSupportedError if the PhysicalDrives resource
doesn't exist.
:raises: IloError, on an error from iLO.
"""
disk_details = self._get_physical_drive_resource()
drive_hdd = False
drive_ssd = False
drive_details = {}
speed_const_list = [4800, 5400, 7200, 10000, 15000]
if disk_details:
for item in disk_details:
value = item['MediaType']
if value == "HDD":
drive_hdd = True
speed = item['RotationalSpeedRpm']
if speed in speed_const_list:
var = 'rotational_drive_' + str(speed) + '_rpm'
drive_details.update({var: 'true'})
# Note: RIS returns value as 'SDD' for SSD drives.
else:
drive_ssd = True
if drive_hdd:
drive_details.update({'has_rotational': 'true'})
if drive_ssd:
drive_details.update({'has_ssd': 'true'})
return drive_details if len(drive_details.keys()) > 0 else None
def _get_drive_resource(self, drive_name):
"""Gets the DiskDrive resource if exists.
:param drive_name: can be either "PhysicalDrives" or
"LogicalDrives".
:returns the list of drives.
:raises: IloCommandNotSupportedError if the given drive resource
doesn't exist.
:raises: IloError, on an error from iLO.
"""
disk_details_list = []
array_uri_links = self._create_list_of_array_controllers()
# Do not raise exception if there is no disk/logical drive
# as Storage can be zero at any point and if we raise
# exception it might fail get_server_capabilities().
for array_link in array_uri_links:
_, _, member_settings = (
self._rest_get(array_link['href']))
if ('links' in member_settings
and drive_name in member_settings['links']):
disk_uri = member_settings['links'][drive_name]['href']
headers, disk_member_uri, disk_mem = (
self._rest_get(disk_uri))
if ('links' in disk_mem
and 'Member' in disk_mem['links']):
for disk_link in disk_mem['links']['Member']:
diskdrive_uri = disk_link['href']
_, _, disk_details = (
self._rest_get(diskdrive_uri))
disk_details_list.append(disk_details)
if disk_details_list:
return disk_details_list
def _get_logical_drive_resource(self):
"""Returns the LogicalDrives data."""
return self._get_drive_resource('LogicalDrives')
def _get_physical_drive_resource(self):
"""Returns the PhysicalDrives data."""
return self._get_drive_resource('PhysicalDrives')
def _get_logical_raid_levels(self):
"""Gets the different raid levels configured on a server.
:returns a dictionary of logical_raid_levels set to true.
Example if raid level 1+0 and 6 are configured, it returns
{'logical_raid_level_10': 'true',
'logical_raid_level_6': 'true'}
"""
logical_drive_details = self._get_logical_drive_resource()
raid_level = {}
if logical_drive_details:
for item in logical_drive_details:
if 'Raid' in item:
raid_level_var = "logical_raid_level_" + item['Raid']
raid_level.update({raid_level_var: 'true'})
return raid_level if len(raid_level.keys()) > 0 else None
def _is_raid_supported(self):
"""Get the RAID support on the server.
This method returns the raid support on the physical server. It
checks for the list of array controllers configured to the Smart
Storage. If one or more array controllers available then raid
is supported by the server. If none, raid is not supported.
:return: Raid support as a dictionary with true/false as its value.
"""
header, uri, array_resource = self._get_array_controller_resource()
return True if array_resource['Total'] > 0 else False
def _get_bios_settings_resource(self, data):
"""Get the BIOS settings resource."""
try:
bios_settings_uri = data['links']['Settings']['href']
except KeyError:
msg = ('BIOS Settings resource not found.')
raise exception.IloError(msg)
status, headers, bios_settings = self._rest_get(bios_settings_uri)
if status != 200:
msg = self._get_extended_error(bios_settings)
raise exception.IloError(msg)
return headers, bios_settings_uri, bios_settings
def _validate_if_patch_supported(self, headers, uri):
"""Check if the PATCH Operation is allowed on the resource."""
if not self._operation_allowed(headers, 'PATCH'):
msg = ('PATCH Operation not supported on the resource "%s"' % uri)
raise exception.IloError(msg)
def _get_bios_setting(self, bios_property):
"""Retrieves bios settings of the server."""
headers, bios_uri, bios_settings = self._check_bios_resource([
bios_property])
return bios_settings[bios_property]
def _get_bios_hash_password(self, bios_password):
"""Get the hashed BIOS password."""
request_headers = {}
if bios_password:
bios_password_hash = hashlib.sha256((bios_password.encode()).
hexdigest().upper())
request_headers['X-HPRESTFULAPI-AuthToken'] = bios_password_hash
return request_headers
def _change_bios_setting(self, properties):
"""Change the bios settings to specified values."""
keys = properties.keys()
# Check if the BIOS resource/property exists.
headers, bios_uri, settings = self._check_bios_resource(keys)
if not self._operation_allowed(headers, 'PATCH'):
headers, bios_uri, _ = self._get_bios_settings_resource(settings)
self._validate_if_patch_supported(headers, bios_uri)
request_headers = self._get_bios_hash_password(self.bios_password)
status, headers, response = self._rest_patch(bios_uri, request_headers,
properties)
if status >= 300:
msg = self._get_extended_error(response)
raise exception.IloError(msg)
def _get_iscsi_settings_resource(self, data):
"""Get the iscsi settings resoure.
:param data: Existing iscsi settings of the server.
:returns: headers, iscsi_settings url and
iscsi settings as a dictionary.
:raises: IloCommandNotSupportedError, if resource is not found.
:raises: IloError, on an error from iLO.
"""
try:
iscsi_settings_uri = data['links']['Settings']['href']
except KeyError:
msg = ('iscsi settings resource not found.')
raise exception.IloCommandNotSupportedError(msg)
status, headers, iscsi_settings = self._rest_get(iscsi_settings_uri)
if status != 200:
msg = self._get_extended_error(iscsi_settings)
raise exception.IloError(msg)
return headers, iscsi_settings_uri, iscsi_settings
def _get_bios_boot_resource(self, data):
"""Get the Boot resource like BootSources.
:param data: Existing Bios settings of the server.
:returns: boot settings.
:raises: IloCommandNotSupportedError, if resource is not found.
:raises: IloError, on an error from iLO.
"""
try:
boot_uri = data['links']['Boot']['href']
except KeyError:
msg = ('Boot resource not found.')
raise exception.IloCommandNotSupportedError(msg)
status, headers, boot_settings = self._rest_get(boot_uri)
if status != 200:
msg = self._get_extended_error(boot_settings)
raise exception.IloError(msg)
return boot_settings
def _get_bios_mappings_resource(self, data):
"""Get the Mappings resource.
:param data: Existing Bios settings of the server.
:returns: mappings settings.
:raises: IloCommandNotSupportedError, if resource is not found.
:raises: IloError, on an error from iLO.
"""
try:
map_uri = data['links']['Mappings']['href']
except KeyError:
msg = ('Mappings resource not found.')
raise exception.IloCommandNotSupportedError(msg)
status, headers, map_settings = self._rest_get(map_uri)
if status != 200:
msg = self._get_extended_error(map_settings)
raise exception.IloError(msg)
return map_settings
def _check_iscsi_rest_patch_allowed(self):
"""Checks if patch is supported on iscsi.
:returns: iscsi url.
:raises: IloError, on an error from iLO.
:raises: IloCommandNotSupportedError, if the command is not supported
on the server.
"""
headers, bios_uri, bios_settings = self._check_bios_resource()
# Check if the bios resource exists.
if('links' in bios_settings and 'iScsi' in bios_settings['links']):
iscsi_uri = bios_settings['links']['iScsi']['href']
status, headers, settings = self._rest_get(iscsi_uri)
if status != 200:
msg = self._get_extended_error(settings)
raise exception.IloError(msg)
if not self._operation_allowed(headers, 'PATCH'):
headers, iscsi_uri, settings = (
self._get_iscsi_settings_resource(settings))
self._validate_if_patch_supported(headers, iscsi_uri)
return iscsi_uri
else:
msg = ('"links/iScsi" section in bios'
' does not exist')
raise exception.IloCommandNotSupportedError(msg)
def _get_uefi_device_path_by_mac(self, mac):
"""Return uefi device path of mac.
:param mac: Mac address.
:returns: Uefi Device path.
Ex. 'PciRoot(0x0)/Pci(0x2,0x3)/Pci(0x0,0x0)'
"""
adapter_uri = '/rest/v1/Systems/1/NetworkAdapters'
for status, headers, member, memberuri in (
self._get_collection(adapter_uri)):
if status < 300 and member.get('PhysicalPorts'):
for port in member.get('PhysicalPorts'):
if port['MacAddress'].lower() == mac.lower():
return port['UEFIDevicePath']
def _get_nic_association_name_by_mac(self, mac):
"""Return nic association name by mac address
:param mac: Mac address.
:returns: Nic association name. Ex. NicBoot1
"""
headers, bios_uri, bios_settings = self._check_bios_resource()
mappings = (
self._get_bios_mappings_resource(
bios_settings).get('BiosPciSettingsMappings'))
correlatable_id = self._get_uefi_device_path_by_mac(mac)
for mapping in mappings:
for subinstance in mapping['Subinstances']:
for association in subinstance['Associations']:
if subinstance.get('CorrelatableID') == correlatable_id:
return [name for name in subinstance[
'Associations'] if 'NicBoot' in name][0]
def _get_all_macs(self):
"""Return list of macs available on system
:returns: List of macs
"""
macs = []
adapter_uri = '/rest/v1/Systems/1/NetworkAdapters'
for status, headers, member, memberuri in (
self._get_collection(adapter_uri)):
if status < 300 and member.get('PhysicalPorts'):
for port in member.get('PhysicalPorts'):
macs.append(port['MacAddress'].lower())
return macs
def _validate_macs(self, macs):
"""Validate given macs are there in system
:param macs: List of macs
:raises: InvalidInputError, if macs not valid
"""
macs_available = self._get_all_macs()
if not set(macs).issubset(macs_available):
msg = ("Given macs: %(macs)s not found in the system"
% {'macs': list(set(macs) - set(macs_available))})
raise exception.InvalidInputError(msg)
def _change_iscsi_settings(self, iscsi_info, macs=[]):
"""Change iSCSI settings.
:param macs: List of target macs for iSCSI.
:param iscsi_info: A dictionary that contains information of iSCSI
target like target_name, lun, ip_address, port etc.
:raises: IloError, on an error from iLO.
"""
iscsi_uri = self._check_iscsi_rest_patch_allowed()
association_names = []
if macs:
self._validate_macs(macs)
association_names = [
self._get_nic_association_name_by_mac(mac) for mac in macs]
else:
# Get the Mappings resource.
headers, bios_uri, bios_settings = self._check_bios_resource()
map_settings = self._get_bios_mappings_resource(bios_settings)
for mapping in map_settings['BiosPciSettingsMappings']:
for subinstance in mapping['Subinstances']:
for association in subinstance['Associations']:
if 'NicBoot' in association:
association_names.append(association)
if not association_names:
msg = ('No macs were found on the system')
raise exception.IloError(msg)
iscsi_infos = []
for association_name in association_names:
data = iscsi_info.copy()
data['iSCSIBootAttemptName'] = association_name
data['iSCSINicSource'] = association_name
data['iSCSIBootAttemptInstance'] = (
association_names.index(association_name) + 1)
iscsi_infos.append(data)
iscsi_data = {'iSCSIBootSources': iscsi_infos}
status, headers, response = self._rest_patch(iscsi_uri,
None, iscsi_data)
if status >= 300:
msg = self._get_extended_error(response)
raise exception.IloError(msg)
def _change_secure_boot_settings(self, property, value):
"""Change secure boot settings on the server."""
system = self._get_host_details()
# find the BIOS URI
if ('links' not in system['Oem']['Hp']
or 'SecureBoot' not in system['Oem']['Hp']['links']):
msg = (' "SecureBoot" resource or feature is not '
'supported on this system')
raise exception.IloCommandNotSupportedError(msg)
secure_boot_uri = system['Oem']['Hp']['links']['SecureBoot']['href']
# Change the property required
new_secure_boot_settings = {}
new_secure_boot_settings[property] = value
# perform the patch
status, headers, response = self._rest_patch(
secure_boot_uri, None, new_secure_boot_settings)
if status >= 300:
msg = self._get_extended_error(response)
raise exception.IloError(msg)
# Change the bios setting as a workaround to enable secure boot
# Can be removed when fixed for Gen9 snap2
val = self._get_bios_setting('CustomPostMessage')
val = val.rstrip() if val.endswith(" ") else val + " "
self._change_bios_setting({'CustomPostMessage': val})
def _is_boot_mode_uefi(self):
"""Checks if the system is in uefi boot mode.
:return: 'True' if the boot mode is uefi else 'False'
:raises: IloError, on an error from iLO.
:raises: IloCommandNotSupportedError, if the command is not supported
on the server.
"""
boot_mode = self.get_current_boot_mode()
if boot_mode == 'UEFI':
return True
else:
return False
def get_product_name(self):
"""Gets the product name of the server.
:returns: server model name.
:raises: IloError, on an error from iLO.
"""
system = self._get_host_details()
return system['Model']
def get_secure_boot_mode(self):
"""Get the status of secure boot.
:returns: True, if enabled, else False
:raises: IloError, on an error from iLO.
:raises: IloCommandNotSupportedError, if the command is not supported
on the server.
"""
system = self._get_host_details()
if ('links' not in system['Oem']['Hp']
or 'SecureBoot' not in system['Oem']['Hp']['links']):
msg = ('"SecureBoot" resource or feature is not supported'
' on this system')
raise exception.IloCommandNotSupportedError(msg)
secure_boot_uri = system['Oem']['Hp']['links']['SecureBoot']['href']
# get the Secure Boot object
status, headers, secure_boot_settings = self._rest_get(secure_boot_uri)
if status >= 300:
msg = self._get_extended_error(secure_boot_settings)
raise exception.IloError(msg)
return secure_boot_settings['SecureBootCurrentState']
def set_secure_boot_mode(self, secure_boot_enable):
"""Enable/Disable secure boot on the server.
:param secure_boot_enable: True, if secure boot needs to be
enabled for next boot, else False.
:raises: IloError, on an error from iLO.
:raises: IloCommandNotSupportedError, if the command is not supported
on the server.
"""
if self._is_boot_mode_uefi():
self._change_secure_boot_settings('SecureBootEnable',
secure_boot_enable)
else:
msg = ('System is not in UEFI boot mode. "SecureBoot" related '
'resources cannot be changed.')
raise exception.IloCommandNotSupportedInBiosError(msg)
def reset_secure_boot_keys(self):
"""Reset secure boot keys to manufacturing defaults.
:raises: IloError, on an error from iLO.
:raises: IloCommandNotSupportedError, if the command is not supported
on the server.
"""
if self._is_boot_mode_uefi():
self._change_secure_boot_settings('ResetToDefaultKeys', True)
else:
msg = ('System is not in UEFI boot mode. "SecureBoot" related '
'resources cannot be changed.')
raise exception.IloCommandNotSupportedInBiosError(msg)
def clear_secure_boot_keys(self):
"""Reset all keys.
:raises: IloError, on an error from iLO.
:raises: IloCommandNotSupportedError, if the command is not supported
on the server.
"""
if self._is_boot_mode_uefi():
self._change_secure_boot_settings('ResetAllKeys', True)
else:
msg = ('System is not in UEFI boot mode. "SecureBoot" related '
'resources cannot be changed.')
raise exception.IloCommandNotSupportedInBiosError(msg)
def get_host_power_status(self):
"""Request the power state of the server.
:returns: Power State of the server, 'ON' or 'OFF'
:raises: IloError, on an error from iLO.
"""
data = self._get_host_details()
return data['Power'].upper()
def _perform_power_op(self, oper):
"""Perform requested power operation.
:param oper: Type of power button press to simulate.
Supported values: 'ON', 'ForceOff', 'ForceRestart' and
'Nmi'
:raises: IloError, on an error from iLO.
"""
power_settings = {"Action": "Reset",
"ResetType": oper}
systems_uri = "/rest/v1/Systems/1"
status, headers, response = self._rest_post(systems_uri, None,
power_settings)
if status >= 300:
msg = self._get_extended_error(response)
raise exception.IloError(msg)
def reset_server(self):
"""Resets the server.
:raises: IloError, on an error from iLO.
"""
self._perform_power_op("ForceRestart")
def _press_pwr_btn(self, pushType="Press"):
"""Simulates a physical press of the server power button.
:param pushType: Type of power button press to simulate
Supported values are: 'Press' and 'PressAndHold'
:raises: IloError, on an error from iLO.
"""
power_settings = {"Action": "PowerButton",
"Target": "/Oem/Hp",
"PushType": pushType}
systems_uri = "/rest/v1/Systems/1"
status, headers, response = self._rest_post(systems_uri, None,
power_settings)
if status >= 300:
msg = self._get_extended_error(response)
raise exception.IloError(msg)
def press_pwr_btn(self):
"""Simulates a physical press of the server power button.
:raises: IloError, on an error from iLO.
"""
self._press_pwr_btn()
def hold_pwr_btn(self):
"""Simulate a physical press and hold of the server power button.
:raises: IloError, on an error from iLO.
"""
self._press_pwr_btn(pushType="PressAndHold")
@retrying.retry(
stop_max_attempt_number=MAX_RETRY_ATTEMPTS,
retry_on_result=lambda state: state != 'ON',
wait_fixed=MAX_TIME_BEFORE_RETRY
)
def _retry_until_powered_on(self, power):
"""This method retries power on operation.
:param: power : target power state
"""
# If the system is in the same power state as
# requested by the user, it gives the error
# InvalidOperationForSystemState. To avoid this error
# the power state is checked before power on
# operation is performed.
status = self.get_host_power_status()
if (status != power):
self._perform_power_op(POWER_STATE[power])
return self.get_host_power_status()
else:
return status
def set_host_power(self, power):
"""Toggle the power button of server.
:param power: 'ON' or 'OFF'
:raises: IloError, on an error from iLO.
"""
power = power.upper()
if (power is not None) and (power not in POWER_STATE):
msg = ("Invalid input '%(pow)s'. "
"The expected input is ON or OFF." %
{'pow': power})
raise exception.IloInvalidInputError(msg)
# Check current power status, do not act if it's in requested state.
cur_status = self.get_host_power_status()
if cur_status == power:
LOG.debug(self._("Node is already in '%(power)s' power state."),
{'power': power})
return
if power == 'ON' and 'PROLIANT BL' in self.get_product_name().upper():
self._retry_until_powered_on(power)
else:
self._perform_power_op(POWER_STATE[power])
def get_http_boot_url(self):
"""Request the http boot url from system in uefi boot mode.
:returns: URL for http boot
:raises: IloError, on an error from iLO.
:raises: IloCommandNotSupportedInBiosError, if the system is
in the bios boot mode.
"""
if(self._is_boot_mode_uefi() is True):
return self._get_bios_setting('UefiShellStartupUrl')
else:
msg = 'get_http_boot_url is not supported in the BIOS boot mode'
raise exception.IloCommandNotSupportedInBiosError(msg)
def set_http_boot_url(self, url):
"""Set url to the UefiShellStartupUrl to the system in uefi boot mode.
:param url: URL for http boot
:raises: IloError, on an error from iLO.
:raises: IloCommandNotSupportedInBiosError, if the system is
in the bios boot mode.
"""
if(self._is_boot_mode_uefi() is True):
self._change_bios_setting({'UefiShellStartupUrl': url})
else:
msg = 'set_http_boot_url is not supported in the BIOS boot mode'
raise exception.IloCommandNotSupportedInBiosError(msg)
def set_iscsi_info(self, target_name, lun, ip_address,
port='3260', auth_method=None, username=None,
password=None, macs=[]):
"""Set iSCSI details of the system in UEFI boot mode.
The initiator system is set with the target details like
IQN, LUN, IP, Port etc.
:param target_name: Target Name for iscsi.
:param lun: logical unit number.
:param ip_address: IP address of the target.
:param port: port of the target.
:param auth_method : either None or CHAP.
:param username: CHAP Username for authentication.
:param password: CHAP secret.
:param macs: List of target macs for iSCSI.
:raises: IloError, on an error from iLO.
:raises: IloCommandNotSupportedInBiosError, if the system is
in the BIOS boot mode.
"""
if(self._is_boot_mode_uefi() is True):
iscsi_info = {}
iscsi_info['iSCSITargetName'] = target_name
iscsi_info['iSCSIBootLUN'] = lun
iscsi_info['iSCSITargetIpAddress'] = ip_address
iscsi_info['iSCSITargetTcpPort'] = int(port)
iscsi_info['iSCSITargetInfoViaDHCP'] = False
iscsi_info['iSCSIBootEnable'] = 'Enabled'
if (auth_method == 'CHAP'):
iscsi_info['iSCSIAuthenticationMethod'] = 'Chap'
iscsi_info['iSCSIChapUsername'] = username
iscsi_info['iSCSIChapSecret'] = password
self._change_iscsi_settings(iscsi_info, macs)
else:
msg = 'iSCSI boot is not supported in the BIOS boot mode'
raise exception.IloCommandNotSupportedInBiosError(msg)
def unset_iscsi_info(self, macs=[]):
"""Disable iSCSI boot option in UEFI boot mode.
:param macs: List of target macs for iSCSI.
:raises: IloError, on an error from iLO.
:raises: IloCommandNotSupportedInBiosError, if the system is
in the BIOS boot mode.
"""
if(self._is_boot_mode_uefi() is True):
iscsi_info = {'iSCSIBootEnable': 'Disabled'}
self._change_iscsi_settings(iscsi_info, macs)
else:
msg = 'iSCSI boot is not supported in the BIOS boot mode'
raise exception.IloCommandNotSupportedInBiosError(msg)
def get_iscsi_initiator_info(self):
"""Give iSCSI initiator information of iLO.
:returns: iSCSI initiator information.
:raises: IloError, on an error from iLO.
:raises: IloCommandNotSupportedError, if the system is
in the bios boot mode.
"""
headers, bios_uri, bios_settings = self._check_bios_resource()
if('links' in bios_settings and 'iScsi' in bios_settings['links']):
iscsi_uri = bios_settings['links']['iScsi']['href']
status, headers, iscsi_settings = self._rest_get(iscsi_uri)
if status != 200:
msg = self._get_extended_error(iscsi_settings)
raise exception.IloError(msg)
return iscsi_settings['iSCSIInitiatorName']
else:
msg = ('"links/iScsi" section in bios '
'does not exist')
raise exception.IloCommandNotSupportedError(msg)
def set_iscsi_initiator_info(self, initiator_iqn):
"""Set iSCSI initiator information in iLO.
:param initiator_iqn: Initiator iqn for iLO.
:raises: IloError, on an error from iLO.
:raises: IloCommandNotSupportedError, if the system is
in the bios boot mode.
"""
if(self._is_boot_mode_uefi() is True):
iscsi_uri = self._check_iscsi_rest_patch_allowed()
initiator_info = {'iSCSIInitiatorName': initiator_iqn}
status, headers, response = self._rest_patch(iscsi_uri,
None, initiator_info)
if status >= 300:
msg = self._get_extended_error(response)
raise exception.IloError(msg)
else:
msg = 'iSCSI initiator cannot be set in the BIOS boot mode'
raise exception.IloCommandNotSupportedError(msg)
def get_current_boot_mode(self):
"""Retrieves the current boot mode of the server.
:returns: Current boot mode, LEGACY or UEFI.
:raises: IloError, on an error from iLO.
"""
boot_mode = self._get_bios_setting('BootMode')
if boot_mode == 'LegacyBios':
boot_mode = 'legacy'
return boot_mode.upper()
def get_pending_boot_mode(self):
"""Retrieves the pending boot mode of the server.
Gets the boot mode to be set on next reset.
:returns: either LEGACY or UEFI.
:raises: IloError, on an error from iLO.
"""
headers, uri, bios_settings = self._check_bios_resource(['BootMode'])
_, _, settings = self._get_bios_settings_resource(bios_settings)
boot_mode = settings.get('BootMode')
if boot_mode == 'LegacyBios':
boot_mode = 'legacy'
return boot_mode.upper()
def set_pending_boot_mode(self, boot_mode):
"""Sets the boot mode of the system for next boot.
:param boot_mode: either 'uefi' or 'legacy'.
:raises: IloInvalidInputError, on an invalid input.
:raises: IloError, on an error from iLO.
:raises: IloCommandNotSupportedError, if the command is not supported
on the server.
"""
boot_mode = boot_mode.lower()
if boot_mode not in ['uefi', 'legacy']:
msg = 'Invalid Boot mode specified'
raise exception.IloInvalidInputError(msg)
boot_properties = {'BootMode': boot_mode}
if boot_mode == 'legacy':
boot_properties['BootMode'] = 'LegacyBios'
else:
# If Boot Mode is 'Uefi' set the UEFIOptimizedBoot first.
boot_properties['UefiOptimizedBoot'] = "Enabled"
# Change the Boot Mode
self._change_bios_setting(boot_properties)
def get_supported_boot_mode(self):
"""Retrieves the supported boot mode.
:returns: any one of the following proliantutils.ilo.constants:
SUPPORTED_BOOT_MODE_LEGACY_BIOS_ONLY,
SUPPORTED_BOOT_MODE_UEFI_ONLY,
SUPPORTED_BOOT_MODE_LEGACY_BIOS_AND_UEFI
"""
system = self._get_host_details()
bios_uefi_class_val = 0 # value for bios_only boot mode
if ('Bios' in system['Oem']['Hp']
and 'UefiClass' in system['Oem']['Hp']['Bios']):
bios_uefi_class_val = (system['Oem']['Hp']
['Bios']['UefiClass'])
return mappings.GET_SUPPORTED_BOOT_MODE_RIS_MAP.get(
bios_uefi_class_val)
def reset_ilo_credential(self, password):
"""Resets the iLO password.
:param password: The password to be set.
:raises: IloError, if account not found or on an error from iLO.
:raises: IloCommandNotSupportedError, if the command is not supported
on the server.
"""
acc_uri = '/rest/v1/AccountService/Accounts'
for status, hds, account, memberuri in self._get_collection(acc_uri):
if account['UserName'] == self.login:
mod_user = {}
mod_user['Password'] = password
status, headers, response = self._rest_patch(memberuri,
None, mod_user)
if status != 200:
msg = self._get_extended_error(response)
raise exception.IloError(msg)
return
msg = "iLO Account with specified username is not found."
raise exception.IloError(msg)
def _get_ilo_details(self):
"""Gets iLO details
:raises: IloError, on an error from iLO.
:raises: IloConnectionError, if iLO is not up after reset.
:raises: IloCommandNotSupportedError, if the command is not supported
on the server.
"""
manager_uri = '/rest/v1/Managers/1'
status, headers, manager = self._rest_get(manager_uri)
if status != 200:
msg = self._get_extended_error(manager)
raise exception.IloError(msg)
# verify expected type
mtype = self._get_type(manager)
if (mtype not in ['Manager.0', 'Manager.1']):
msg = "%s is not a valid Manager type " % mtype
raise exception.IloError(msg)
return manager, manager_uri
def reset_ilo(self):
"""Resets the iLO.
:raises: IloError, on an error from iLO.
:raises: IloConnectionError, if iLO is not up after reset.
:raises: IloCommandNotSupportedError, if the command is not supported
on the server.
"""
manager, reset_uri = self._get_ilo_details()
action = {'Action': 'Reset'}
# perform the POST
status, headers, response = self._rest_post(reset_uri, None, action)
if(status != 200):
msg = self._get_extended_error(response)
raise exception.IloError(msg)
# Check if the iLO is up again.
common.wait_for_ilo_after_reset(self)
def reset_bios_to_default(self):
"""Resets the BIOS settings to default values.
:raises: IloError, on an error from iLO.
:raises: IloCommandNotSupportedError, if the command is not supported
on the server.
"""
# Check if the BIOS resource if exists.
headers_bios, bios_uri, bios_settings = self._check_bios_resource()
# Get the BaseConfig resource.
try:
base_config_uri = bios_settings['links']['BaseConfigs']['href']
except KeyError:
msg = ("BaseConfigs resource not found. Couldn't apply the BIOS "
"Settings.")
raise exception.IloCommandNotSupportedError(msg)
# Check if BIOS resource supports patch, else get the settings
if not self._operation_allowed(headers_bios, 'PATCH'):
headers, bios_uri, _ = self._get_bios_settings_resource(
bios_settings)
self._validate_if_patch_supported(headers, bios_uri)
status, headers, config = self._rest_get(base_config_uri)
if status != 200:
msg = self._get_extended_error(config)
raise exception.IloError(msg)
new_bios_settings = {}
for cfg in config['BaseConfigs']:
default_settings = cfg.get('default', None)
if default_settings is not None:
new_bios_settings = default_settings
break
else:
msg = ("Default Settings not found in 'BaseConfigs' resource.")
raise exception.IloCommandNotSupportedError(msg)
request_headers = self._get_bios_hash_password(self.bios_password)
status, headers, response = self._rest_patch(bios_uri, request_headers,
new_bios_settings)
if status >= 300:
msg = self._get_extended_error(response)
raise exception.IloError(msg)
def _get_ilo_firmware_version(self):
"""Gets the ilo firmware version for server capabilities
:returns: a dictionary of iLO firmware version.
"""
manager, reset_uri = self._get_ilo_details()
ilo_firmware_version = manager['Firmware']['Current']['VersionString']
return {'ilo_firmware_version': ilo_firmware_version}
def get_ilo_firmware_version_as_major_minor(self):
"""Gets the ilo firmware version for server capabilities
:returns: String with the format "<major>.<minor>" or None.
"""
try:
manager, reset_uri = self._get_ilo_details()
ilo_fw_ver_str = (
manager['Oem']['Hp']['Firmware']['Current']['VersionString']
)
return common.get_major_minor(ilo_fw_ver_str)
except Exception:
return None
def _is_sriov_enabled(self):
"""Return sriov enabled or not"""
return (self._get_bios_setting('Sriov') == 'Enabled')
def get_server_capabilities(self):
"""Gets server properties which can be used for scheduling
:returns: a dictionary of hardware properties like firmware
versions, server model.
:raises: IloError, if iLO returns an error in command execution.
"""
capabilities = {}
system = self._get_host_details()
capabilities['server_model'] = system['Model']
rom_firmware_version = (
system['Oem']['Hp']['Bios']['Current']['VersionString'])
capabilities['rom_firmware_version'] = rom_firmware_version
capabilities.update(self._get_ilo_firmware_version())
capabilities.update(self._get_number_of_gpu_devices_connected())
drive_details = self._get_drive_type_and_speed()
if drive_details is not None:
capabilities.update(drive_details)
raid_details = self._get_logical_raid_levels()
if raid_details is not None:
capabilities.update(raid_details)
if self._is_raid_supported():
capabilities['hardware_supports_raid'] = 'true'
boot_modes = common.get_supported_boot_modes(
self.get_supported_boot_mode())
capabilities.update({
'boot_mode_bios': boot_modes.boot_mode_bios,
'boot_mode_uefi': boot_modes.boot_mode_uefi})
if self._get_tpm_capability():
capabilities['trusted_boot'] = 'true'
if self._get_cpu_virtualization():
capabilities['cpu_vt'] = 'true'
if self._get_nvdimm_n_status():
capabilities['nvdimm_n'] = 'true'
try:
self._check_iscsi_rest_patch_allowed()
capabilities['iscsi_boot'] = 'true'
except exception.IloError:
# If an error is raised dont populate the capability
# iscsi_boot
pass
try:
self.get_secure_boot_mode()
capabilities['secure_boot'] = 'true'
except exception.IloCommandNotSupportedError:
# If an error is raised dont populate the capability
# secure_boot
pass
if self._is_sriov_enabled():
capabilities['sriov_enabled'] = 'true'
return capabilities
def activate_license(self, key):
"""Activates iLO license.
:param key: iLO license key.
:raises: IloError, on an error from iLO.
:raises: IloCommandNotSupportedError, if the command is not supported
on the server.
"""
manager, uri = self._get_ilo_details()
try:
lic_uri = manager['Oem']['Hp']['links']['LicenseService']['href']
except KeyError:
msg = ('"LicenseService" section in Manager/Oem/Hp does not exist')
raise exception.IloCommandNotSupportedError(msg)
lic_key = {}
lic_key['LicenseKey'] = key
# Perform POST to activate license
status, headers, response = self._rest_post(lic_uri, None, lic_key)
if status >= 300:
msg = self._get_extended_error(response)
raise exception.IloError(msg)
def _get_vm_device_status(self, device='FLOPPY'):
"""Returns the given virtual media device status and device URI
:param device: virtual media device to be queried
:returns json format virtual media device status and its URI
:raises: IloError, on an error from iLO.
:raises: IloCommandNotSupportedError, if the command is not supported
on the server.
"""
valid_devices = {'FLOPPY': 'floppy',
'CDROM': 'cd'}
# Check if the input is valid
if device not in valid_devices:
raise exception.IloInvalidInputError(
"Invalid device. Valid devices: FLOPPY or CDROM.")
manager, uri = self._get_ilo_details()
try:
vmedia_uri = manager['links']['VirtualMedia']['href']
except KeyError:
msg = '"VirtualMedia" section in Manager/links does not exist'
raise exception.IloCommandNotSupportedError(msg)
for status, hds, vmed, memberuri in self._get_collection(vmedia_uri):
status, headers, response = self._rest_get(memberuri)
if status != 200:
msg = self._get_extended_error(response)
raise exception.IloError(msg)
if (valid_devices[device] in
[item.lower() for item in response['MediaTypes']]):
vm_device_uri = response['links']['self']['href']
return response, vm_device_uri
# Requested device not found
msg = ('Virtualmedia device "' + device + '" is not'
' found on this system.')
raise exception.IloError(msg)
def get_vm_status(self, device='FLOPPY'):
"""Returns the virtual media drive status.
:param device: virtual media device to be queried
:returns device status in dictionary form
:raises: IloError, on an error from iLO.
:raises: IloCommandNotSupportedError, if the command is not supported
on the server.
"""
response, vm_device_uri = self._get_vm_device_status(device)
# Create RIBCL equivalent response
# RIBCL provides this data in VM status
# VM_APPLET = CONNECTED | DISCONNECTED
# DEVICE = FLOPPY | CDROM
# BOOT_OPTION = BOOT_ALWAYS | BOOT_ONCE | NO_BOOT
# WRITE_PROTECT = YES | NO
# IMAGE_INSERTED = YES | NO
response_data = {}
if response.get('WriteProtected', False):
response_data['WRITE_PROTECT'] = 'YES'
else:
response_data['WRITE_PROTECT'] = 'NO'
if response.get('BootOnNextServerReset', False):
response_data['BOOT_OPTION'] = 'BOOT_ONCE'
else:
response_data['BOOT_OPTION'] = 'BOOT_ALWAYS'
if response.get('Inserted', False):
response_data['IMAGE_INSERTED'] = 'YES'
else:
response_data['IMAGE_INSERTED'] = 'NO'
if response.get('ConnectedVia') == 'NotConnected':
response_data['VM_APPLET'] = 'DISCONNECTED'
# When media is not connected, it's NO_BOOT
response_data['BOOT_OPTION'] = 'NO_BOOT'
else:
response_data['VM_APPLET'] = 'CONNECTED'
response_data['IMAGE_URL'] = response['Image']
response_data['DEVICE'] = device
# FLOPPY cannot be a boot device
if ((response_data['BOOT_OPTION'] == 'BOOT_ONCE')
and (response_data['DEVICE'] == 'FLOPPY')):
response_data['BOOT_OPTION'] = 'NO_BOOT'
return response_data
def set_vm_status(self, device='FLOPPY',
boot_option='BOOT_ONCE', write_protect='YES'):
"""Sets the Virtual Media drive status
It sets the boot option for virtual media device.
Note: boot option can be set only for CD device.
:param device: virual media device
:param boot_option: boot option to set on the virtual media device
:param write_protect: set the write protect flag on the vmedia device
Note: It's ignored. In RIS it is read-only.
:raises: IloError, on an error from iLO.
:raises: IloCommandNotSupportedError, if the command is not supported
on the server.
"""
# CONNECT is a RIBCL call. There is no such property to set in RIS.
if boot_option == 'CONNECT':
return
boot_option_map = {'BOOT_ONCE': True,
'BOOT_ALWAYS': False,
'NO_BOOT': False
}
if boot_option not in boot_option_map:
msg = ('Virtualmedia boot option "' + boot_option + '" is '
'invalid.')
raise exception.IloInvalidInputError(msg)
response, vm_device_uri = self._get_vm_device_status(device)
# Update required property
vm_settings = {}
vm_settings['Oem'] = (
{'Hp': {'BootOnNextServerReset': boot_option_map[boot_option]}})
# perform the patch operation
status, headers, response = self._rest_patch(
vm_device_uri, None, vm_settings)
if status >= 300:
msg = self._get_extended_error(response)
raise exception.IloError(msg)
def insert_virtual_media(self, url, device='FLOPPY'):
"""Notifies iLO of the location of a virtual media diskette image.
:param url: URL to image
:param device: virual media device
:raises: IloError, on an error from iLO.
:raises: IloCommandNotSupportedError, if the command is not supported
on the server.
"""
# Validate url
utils.validate_href(url)
response, vm_device_uri = self._get_vm_device_status(device)
# Eject media if there is one. RIBCL was tolerant enough to overwrite
# existing media, RIS is not. This check is to take care of that
# assumption.
if response.get('Inserted', False):
self.eject_virtual_media(device)
# Update required property
vm_settings = {}
vm_settings['Image'] = url
# Perform the patch operation
status, headers, response = self._rest_patch(
vm_device_uri, None, vm_settings)
if status >= 300:
msg = self._get_extended_error(response)
raise exception.IloError(msg)
def eject_virtual_media(self, device='FLOPPY'):
"""Ejects the Virtual Media image if one is inserted.
:param device: virual media device
:raises: IloError, on an error from iLO.
:raises: IloCommandNotSupportedError, if the command is not supported
on the server.
"""
response, vm_device_uri = self._get_vm_device_status(device)
# Check if virtual media is connected.
if response.get('Inserted') is False:
return
# Update required property
vm_settings = {}
vm_settings['Image'] = None
# perform the patch operation
status, headers, response = self._rest_patch(
vm_device_uri, None, vm_settings)
if status >= 300:
msg = self._get_extended_error(response)
raise exception.IloError(msg)
def _get_persistent_boot_devices(self):
"""Get details of persistent boot devices, its order
:returns: List of dictionary of boot sources and
list of boot device order
:raises: IloError, on an error from iLO.
:raises: IloCommandNotSupportedError, if the command is not supported
on the server.
"""
# Check if the BIOS resource if exists.
headers_bios, bios_uri, bios_settings = self._check_bios_resource()
# Get the Boot resource.
boot_settings = self._get_bios_boot_resource(bios_settings)
# Get the BootSources resource
try:
boot_sources = boot_settings['BootSources']
except KeyError:
msg = ("BootSources resource not found.")
raise exception.IloError(msg)
try:
boot_order = boot_settings['PersistentBootConfigOrder']
except KeyError:
msg = ("PersistentBootConfigOrder resource not found.")
raise exception.IloCommandNotSupportedError(msg)
return boot_sources, boot_order
def get_persistent_boot_device(self):
"""Get current persistent boot device set for the host
:returns: persistent boot device for the system
:raises: IloError, on an error from iLO.
:raises: IloCommandNotSupportedError, if the command is not supported
on the server.
"""
system = self._get_host_details()
try:
# Return boot device if it is persistent.
if system['Boot']['BootSourceOverrideEnabled'] == 'Continuous':
device = system['Boot']['BootSourceOverrideTarget']
if device in DEVICE_RIS_TO_COMMON:
return DEVICE_RIS_TO_COMMON[device]
return device
except KeyError as e:
msg = "get_persistent_boot_device failed with the KeyError:%s"
raise exception.IloError((msg) % e)
# Check if we are in BIOS boot mode.
# There is no resource to fetch boot device order for BIOS boot mode
if not self._is_boot_mode_uefi():
return None
# Get persistent boot device order for UEFI
boot_sources, boot_devices = self._get_persistent_boot_devices()
boot_string = ""
try:
for source in boot_sources:
if (source["StructuredBootString"] == boot_devices[0]):
boot_string = source["BootString"]
break
except KeyError as e:
msg = "get_persistent_boot_device failed with the KeyError:%s"
raise exception.IloError((msg) % e)
if 'HP iLO Virtual USB CD' in boot_string:
return 'CDROM'
elif ('NIC' in boot_string
or 'PXE' in boot_string
or "iSCSI" in boot_string):
return 'NETWORK'
elif common.isDisk(boot_string):
return 'HDD'
else:
return None
def _update_persistent_boot(self, device_type=[], persistent=False):
"""Changes the persistent boot device order in BIOS boot mode for host
Note: It uses first boot device from the device_type and ignores rest.
:param device_type: ordered list of boot devices
:param persistent: Boolean flag to indicate if the device to be set as
a persistent boot device
:raises: IloError, on an error from iLO.
:raises: IloCommandNotSupportedError, if the command is not supported
on the server.
"""
tenure = 'Once'
new_device = device_type[0]
# If it is a standard device, we need to convert in RIS convention
if device_type[0].upper() in DEVICE_COMMON_TO_RIS:
new_device = DEVICE_COMMON_TO_RIS[device_type[0].upper()]
if persistent:
tenure = 'Continuous'
systems_uri = "/rest/v1/Systems/1"
# Need to set this option first if device is 'UefiTarget'
if new_device == 'UefiTarget':
system = self._get_host_details()
uefi_devices = (
system['Boot']['UefiTargetBootSourceOverrideSupported'])
iscsi_device = None
for device in uefi_devices:
if device is not None and 'iSCSI' in device:
iscsi_device = device
break
if iscsi_device is None:
msg = 'No UEFI iSCSI bootable device found'
raise exception.IloError(msg)
new_boot_settings = {}
new_boot_settings['Boot'] = {'UefiTargetBootSourceOverride':
iscsi_device}
status, headers, response = self._rest_patch(systems_uri, None,
new_boot_settings)
if status >= 300:
msg = self._get_extended_error(response)
raise exception.IloError(msg)
new_boot_settings = {}
new_boot_settings['Boot'] = {'BootSourceOverrideEnabled': tenure,
'BootSourceOverrideTarget': new_device}
status, headers, response = self._rest_patch(systems_uri, None,
new_boot_settings)
if status >= 300:
msg = self._get_extended_error(response)
raise exception.IloError(msg)
def update_persistent_boot(self, device_type=[]):
"""Changes the persistent boot device order for the host
:param device_type: ordered list of boot devices
:raises: IloError, on an error from iLO.
:raises: IloCommandNotSupportedError, if the command is not supported
on the server.
"""
# Check if the input is valid
for item in device_type:
if item.upper() not in DEVICE_COMMON_TO_RIS:
raise exception.IloInvalidInputError("Invalid input. Valid "
"devices: NETWORK, HDD,"
" ISCSI or CDROM.")
self._update_persistent_boot(device_type, persistent=True)
def set_one_time_boot(self, device):
"""Configures a single boot from a specific device.
:param device: Device to be set as a one time boot device
:raises: IloError, on an error from iLO.
:raises: IloCommandNotSupportedError, if the command is not supported
on the server.
"""
self._update_persistent_boot([device], persistent=False)
def get_one_time_boot(self):
"""Retrieves the current setting for the one time boot.
:returns: Returns the first boot device that would be used in next
boot. Returns 'Normal' is no device is set.
:raises: IloError, on an error from iLO.
:raises: IloCommandNotSupportedError, if the command is not supported
on the server.
"""
system = self._get_host_details()
try:
if system['Boot']['BootSourceOverrideEnabled'] == 'Once':
device = system['Boot']['BootSourceOverrideTarget']
if device in DEVICE_RIS_TO_COMMON:
return DEVICE_RIS_TO_COMMON[device]
return device
else:
# value returned by RIBCL if one-time boot setting are absent
return 'Normal'
except KeyError as e:
msg = "get_one_time_boot failed with the KeyError:%s"
raise exception.IloError((msg) % e)
def _get_firmware_update_service_resource(self):
"""Gets the firmware update service uri.
:returns: firmware update service uri
:raises: IloError, on an error from iLO.
:raises: IloConnectionError, if not able to reach iLO.
:raises: IloCommandNotSupportedError, for not finding the uri
"""
manager, uri = self._get_ilo_details()
try:
fw_uri = manager['Oem']['Hp']['links']['UpdateService']['href']
except KeyError:
msg = ("Firmware Update Service resource not found.")
raise exception.IloCommandNotSupportedError(msg)
return fw_uri
@firmware_controller.check_firmware_update_component
def update_firmware(self, file_url, component_type):
"""Updates the given firmware on the server for the given component.
:param file_url: location of the raw firmware file. Extraction of the
firmware file (if in compact format) is expected to
happen prior to this invocation.
:param component_type: Type of component to be applied to.
:raises: InvalidInputError, if the validation of the input fails
:raises: IloError, on an error from iLO
:raises: IloConnectionError, if not able to reach iLO.
:raises: IloCommandNotSupportedError, if the command is
not supported on the server
"""
fw_update_uri = self._get_firmware_update_service_resource()
action_data = {
'Action': 'InstallFromURI',
'FirmwareURI': file_url,
}
# perform the POST
LOG.debug(self._('Flashing firmware file: %s ...'), file_url)
status, headers, response = self._rest_post(
fw_update_uri, None, action_data)
if status != 200:
msg = self._get_extended_error(response)
raise exception.IloError(msg)
# wait till the firmware update completes.
common.wait_for_ris_firmware_update_to_complete(self)
try:
state, percent = self.get_firmware_update_progress()
except exception.IloError:
msg = 'Status of firmware update not known'
LOG.debug(self._(msg)) # noqa
return
if state == "ERROR":
msg = 'Unable to update firmware'
LOG.debug(self._(msg)) # noqa
raise exception.IloError(msg)
elif state == "UNKNOWN":
msg = 'Status of firmware update not known'
LOG.debug(self._(msg)) # noqa
else: # "COMPLETED" | "IDLE"
LOG.info(self._('Flashing firmware file: %s ... done'), file_url)
def get_firmware_update_progress(self):
"""Get the progress of the firmware update.
:returns: firmware update state, one of the following values:
"IDLE", "UPLOADING", "PROGRESSING", "COMPLETED", "ERROR".
If the update resource is not found, then "UNKNOWN".
:returns: firmware update progress percent
:raises: IloError, on an error from iLO.
:raises: IloConnectionError, if not able to reach iLO.
"""
try:
fw_update_uri = self._get_firmware_update_service_resource()
except exception.IloError as e:
LOG.debug(self._('Progress of firmware update not known: %s'),
str(e))
return "UNKNOWN", "UNKNOWN"
# perform the GET
status, headers, response = self._rest_get(fw_update_uri)
if status != 200:
msg = self._get_extended_error(response)
raise exception.IloError(msg)
fw_update_state = response.get('State')
fw_update_progress_percent = response.get('ProgressPercent')
LOG.debug(self._('Flashing firmware file ... in progress %d%%'),
fw_update_progress_percent)
return fw_update_state, fw_update_progress_percent
def _get_number_of_gpu_devices_connected(self):
"""get the number of GPU devices connected."""
gpu_devices = self._get_gpu_pci_devices()
gpu_devices_count = len(gpu_devices)
return {'pci_gpu_devices': gpu_devices_count}
def _get_tpm_capability(self):
"""Retrieves if server is TPM capable or not.
:returns True if TPM is Present else False
"""
tpm_values = {"NotPresent": False,
"PresentDisabled": True,
"PresentEnabled": True}
try:
tpm_state = self._get_bios_setting('TpmState')
except exception.IloCommandNotSupportedError:
tpm_state = "NotPresent"
tpm_result = tpm_values[tpm_state]
return tpm_result
def _get_cpu_virtualization(self):
"""get cpu virtualization status."""
try:
cpu_vt = self._get_bios_setting('ProcVirtualization')
except exception.IloCommandNotSupportedError:
return False
if cpu_vt == 'Enabled':
vt_status = True
else:
vt_status = False
return vt_status
def _get_nvdimm_n_status(self):
"""Get status of NVDIMM_N.
:returns: True if NVDIMM_N is present and enabled, False otherwise.
"""
try:
nvdimm_n_status = self._get_bios_setting('NvDimmNMemFunctionality')
if nvdimm_n_status == 'Enabled':
nvn_status = True
else:
nvn_status = False
except exception.IloCommandNotSupportedError:
nvn_status = False
return nvn_status
def inject_nmi(self):
"""Inject NMI, Non Maskable Interrupt.
Inject NMI (Non Maskable Interrupt) for a node immediately.
:raises: IloError, on an error from iLO
"""
cur_status = self.get_host_power_status()
if cur_status != 'ON':
raise exception.IloError("Server is not in powered on state.")
self._perform_power_op("Nmi")
def get_host_post_state(self):
"""Get the current state of system POST.
Retrieves current state of system POST.
:returns: POST state of the server. The valida states are:-
null, Unknown, Reset, PowerOff, InPost,
InPostDiscoveryComplete and FinishedPost.
:raises: IloError, on an error from iLO
"""
system = self._get_host_details()
if 'PostState' in system['Oem']['Hp']:
return system['Oem']['Hp']['PostState']
raise exception.IloError("Attribute 'Oem/Hp/PostState' "
"not found on system.")
def get_current_bios_settings(self, only_allowed_settings=False):
"""Get current BIOS settings.
:param: only_allowed_settings: True when only allowed BIOS settings
are to be returned. If False, All the BIOS settings supported
by iLO are returned.
:return: a dictionary of current BIOS settings is returned. Depending
on the 'only_allowed_settings', either only the allowed
settings are returned or all the supported settings are
returned.
:raises: IloError, on an error from iLO.
:raises: IloCommandNotSupportedError, if the command is not supported
on the server.
"""
headers, bios_uri, bios_settings = self._check_bios_resource()
# Remove the "links" section
bios_settings.pop("links", None)
if only_allowed_settings:
return utils.apply_bios_properties_filter(
bios_settings, constants.SUPPORTED_BIOS_PROPERTIES)
return bios_settings
def get_pending_bios_settings(self, only_allowed_settings=False):
"""Get current BIOS settings.
:param: only_allowed_settings: True when only allowed BIOS settings
are to be returned. If False, All the BIOS settings supported
by iLO are returned.
:return: a dictionary of pending BIOS settings. Depending
on the 'only_allowed_settings', either only the allowed
settings are returned or all the supported settings are
returned.
:raises: IloError, on an error from iLO.
:raises: IloCommandNotSupportedError, if the command is not supported
on the server.
"""
headers, bios_uri, bios_settings = self._check_bios_resource()
try:
settings_config_uri = bios_settings['links']['Settings']['href']
except KeyError:
msg = ("Settings resource not found. Couldn't get pending BIOS "
"Settings.")
raise exception.IloCommandNotSupportedError(msg)
status, headers, config = self._rest_get(settings_config_uri)
if status != 200:
msg = self._get_extended_error(config)
raise exception.IloError(msg)
# Remove the "links" section
config.pop("links", None)
if only_allowed_settings:
return utils.apply_bios_properties_filter(
config, constants.SUPPORTED_BIOS_PROPERTIES)
return config
def set_bios_settings(self, data=None, only_allowed_settings=False):
"""Sets current BIOS settings to the provided data.
:param: only_allowed_settings: True when only allowed BIOS settings
are to be set. If False, all the BIOS settings supported by
iLO and present in the 'data' are set.
:param: data: a dictionary of BIOS settings to be applied. Depending
on the 'only_allowed_settings', either only the allowed
settings are set or all the supported settings that are in
the 'data' are set.
:raises: IloError, on an error from iLO.
:raises: IloCommandNotSupportedError, if the command is not supported
on the server.
"""
if not data:
raise exception.IloError("Could not apply settings with"
" empty data")
if only_allowed_settings:
unsupported_settings = [key for key in data if key not in (
constants.SUPPORTED_BIOS_PROPERTIES)]
if unsupported_settings:
msg = ("Could not apply settings as one or more settings are"
" not supported. Unsupported settings are %s."
" Supported settings are %s." % (
unsupported_settings,
constants.SUPPORTED_BIOS_PROPERTIES))
raise exception.IloError(msg)
self._change_bios_setting(data)
def get_default_bios_settings(self, only_allowed_settings=False):
"""Get default BIOS settings.
:param: only_allowed_settings: True when only allowed BIOS settings
are to be returned. If False, All the BIOS settings supported
by iLO are returned.
:return: a dictionary of default BIOS settings(factory settings).
Depending on the 'only_allowed_settings', either only the
allowed settings are returned or all the supported settings
are returned.
:raises: IloError, on an error from iLO.
:raises: IloCommandNotSupportedError, if the command is not supported
on the server.
"""
headers_bios, bios_uri, bios_settings = self._check_bios_resource()
# Get the BaseConfig resource.
try:
base_config_uri = bios_settings['links']['BaseConfigs']['href']
except KeyError:
msg = ("BaseConfigs resource not found. Couldn't apply the BIOS "
"Settings.")
raise exception.IloCommandNotSupportedError(msg)
status, headers, config = self._rest_get(base_config_uri)
if status != 200:
msg = self._get_extended_error(config)
raise exception.IloError(msg)
for cfg in config['BaseConfigs']:
default_settings = cfg.get('default')
if default_settings:
break
else:
msg = ("Default BIOS Settings not found in 'BaseConfigs' "
"resource.")
raise exception.IloCommandNotSupportedError(msg)
if only_allowed_settings:
return utils.apply_bios_properties_filter(
default_settings, constants.SUPPORTED_BIOS_PROPERTIES)
return default_settings
def _raise_command_not_supported(self, method):
platform = self.get_product_name()
msg = ("`%(method)s` is not supported on %(platform)s" %
{'method': method, 'platform': platform})
raise (exception.IloCommandNotSupportedError(msg))
def read_raid_configuration(self, raid_config=None):
"""Read the logical drives from the system
Read raid configuration of the hardware.
:param raid_config: None in case of post-delete read or in case of
post-create a dictionary containing target raid
configuration data. This data stucture should be as
follows:
raid_config = {'logical_disks': [{'raid_level': 1,
'size_gb': 100, 'physical_disks': ['6I:1:5'],
'controller': 'HPE Smart Array P408i-a SR Gen10'},
<info-for-logical-disk-2>]}
:raises: IloCommandNotSupportedError, if the command is not supported
on the server.
"""
self._raise_command_not_supported("read_raid_configuration")
def delete_raid_configuration(self):
"""Delete the raid configuration on the hardware.
Loops through each SmartStorageConfig controller and clears the
raid configuration.
:raises: IloCommandNotSupportedError
"""
self._raise_command_not_supported("delete_raid_configuration")
def create_raid_configuration(self, raid_config):
"""Create the raid configuration on the hardware.
Based on user raid_config input, it will create raid
:param raid_config: A dictionary containing target raid configuration
data. This data stucture should be as follows:
raid_config = {'logical_disks': [{'raid_level': 1,
'size_gb': 100, 'physical_disks': ['6I:1:5'],
'controller': 'HPE Smart Array P408i-a SR Gen10'},
<info-for-logical-disk-2>]}
:raises: IloCommandNotSupportedError
"""
self._raise_command_not_supported("create_raid_configuration")
def get_bios_settings_result(self):
"""Gets the result of the bios settings applied
:raises: IloError, on an error from iLO.
:raises: IloCommandNotSupportedError, if the command is
not supported on the server.
"""
headers, bios_uri, bios_settings = self._check_bios_resource()
settings_result = bios_settings.get("SettingsResult").get("Messages")
status = "failed" if len(settings_result) > 1 else "success"
return {"status": status, "results": settings_result}
def create_csr(self, path, csr_params):
"""Creates the Certificate Signing Request.
:param path: directory to store csr file.
:param csr_params: A dictionary containing all the necessary
information required to create CSR.
:raises: IloError, on an error from iLO.
"""
self._raise_command_not_supported("create_csr")
def add_https_certificate(self, cert_file):
"""Adds the signed https certificate to the iLO.
:param cert_file: Signed HTTPS certificate file.
:raises: IloError, on an error from iLO.
"""
self._raise_command_not_supported("add_https_certificate")
|