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
|
# Copyright 2018-2022 Hewlett Packard Enterprise Development LP
#
# 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'
from base64 import b64decode
import json
import os
import re
import subprocess
import tempfile
from OpenSSL.crypto import FILETYPE_ASN1
from OpenSSL.crypto import load_certificate
import retrying
from six.moves.urllib import parse
import sushy
from sushy import utils
from proliantutils import exception
from proliantutils.ilo import common
from proliantutils.ilo import constants as ilo_cons
from proliantutils.ilo import firmware_controller
from proliantutils.ilo import operations
from proliantutils import log
from proliantutils.redfish import main
from proliantutils.redfish.resources import gpu_common
from proliantutils.redfish.resources.manager import constants as mgr_cons
from proliantutils.redfish.resources.system import constants as sys_cons
from proliantutils.redfish.resources.system.storage \
import common as common_storage
from proliantutils.redfish import utils as rf_utils
from proliantutils import utils as common_utils
"""
Class specific for Redfish APIs.
"""
MAX_RETRY_ATTEMPTS = 3 # Maximum number of attempts to be retried
MAX_TIME_BEFORE_RETRY = 7 * 1000 # wait time in milliseconds before retry
GET_POWER_STATE_MAP = {
sushy.SYSTEM_POWER_STATE_ON: 'ON',
sushy.SYSTEM_POWER_STATE_POWERING_ON: 'PoweringOn',
sushy.SYSTEM_POWER_STATE_OFF: 'OFF',
sushy.SYSTEM_POWER_STATE_POWERING_OFF: 'PoweringOff'
}
POWER_RESET_MAP = {
'ON': sushy.RESET_ON,
'OFF': sushy.RESET_FORCE_OFF,
}
DEVICE_COMMON_TO_REDFISH = {
'NETWORK': sushy.BOOT_SOURCE_TARGET_PXE,
'HDD': sushy.BOOT_SOURCE_TARGET_HDD,
'CDROM': sushy.BOOT_SOURCE_TARGET_CD,
'ISCSI': sushy.BOOT_SOURCE_TARGET_UEFI_TARGET,
'UEFIHTTP': sushy.BOOT_SOURCE_TARGET_UEFI_HTTP,
'NONE': sushy.BOOT_SOURCE_TARGET_NONE
}
DEVICE_REDFISH_TO_COMMON = {v: k for k, v in DEVICE_COMMON_TO_REDFISH.items()}
BOOT_MODE_MAP = {
sys_cons.BIOS_BOOT_MODE_LEGACY_BIOS: 'LEGACY',
sys_cons.BIOS_BOOT_MODE_UEFI: 'UEFI'
}
BOOT_MODE_MAP_REV = (
utils.revert_dictionary(BOOT_MODE_MAP))
PERSISTENT_BOOT_MAP = {
sushy.BOOT_SOURCE_TARGET_PXE: 'NETWORK',
sushy.BOOT_SOURCE_TARGET_HDD: 'HDD',
sushy.BOOT_SOURCE_TARGET_CD: 'CDROM',
sushy.BOOT_SOURCE_TARGET_UEFI_TARGET: 'NETWORK',
sushy.BOOT_SOURCE_TARGET_UEFI_HTTP: 'UEFIHTTP',
sushy.BOOT_SOURCE_TARGET_NONE: 'NONE'
}
GET_SECUREBOOT_CURRENT_BOOT_MAP = {
sys_cons.SECUREBOOT_CURRENT_BOOT_ENABLED: True,
sys_cons.SECUREBOOT_CURRENT_BOOT_DISABLED: False
}
GET_POST_STATE_MAP = {
sys_cons.POST_STATE_NULL: 'Null',
sys_cons.POST_STATE_UNKNOWN: 'Unknown',
sys_cons.POST_STATE_RESET: 'Reset',
sys_cons.POST_STATE_POWEROFF: 'PowerOff',
sys_cons.POST_STATE_INPOST: 'InPost',
sys_cons.POST_STATE_INPOSTDISCOVERY: 'InPostDiscoveryComplete',
sys_cons.POST_STATE_FINISHEDPOST: 'FinishedPost'
}
# Assuming only one system and one manager present as part of
# collection, as we are dealing with iLO's here.
PROLIANT_MANAGER_ID = '1'
PROLIANT_SYSTEM_ID = '1'
PROLIANT_CHASSIS_ID = '1'
BOOT_OPTION_MAP = {'BOOT_ONCE': True,
'BOOT_ALWAYS': False,
'NO_BOOT': False}
VIRTUAL_MEDIA_MAP = {'FLOPPY': mgr_cons.VIRTUAL_MEDIA_FLOPPY,
'CDROM': mgr_cons.VIRTUAL_MEDIA_CD}
SUPPORTED_BOOT_MODE_MAP = {
sys_cons.SUPPORTED_LEGACY_BIOS_ONLY: (
ilo_cons.SUPPORTED_BOOT_MODE_LEGACY_BIOS_ONLY),
sys_cons.SUPPORTED_UEFI_ONLY: ilo_cons.SUPPORTED_BOOT_MODE_UEFI_ONLY,
sys_cons.SUPPORTED_LEGACY_BIOS_AND_UEFI: (
ilo_cons.SUPPORTED_BOOT_MODE_LEGACY_BIOS_AND_UEFI)
}
_CERTIFICATE_PATTERN = (
r'-----BEGIN CERTIFICATE-----.*?-----END CERTIFICATE-----')
LOG = log.get_logger(__name__)
# Copied from ironic/drivers/modules/redfish/inspect.py
CPU_ARCH_MAP = {
sushy.PROCESSOR_ARCH_x86: 'x86_64',
sushy.PROCESSOR_ARCH_IA_64: 'ia64',
sushy.PROCESSOR_ARCH_ARM: 'arm',
sushy.PROCESSOR_ARCH_MIPS: 'mips',
sushy.PROCESSOR_ARCH_OEM: 'oem'
}
class RedfishOperations(operations.IloOperations):
"""Operations supported on redfish based hardware.
This class holds APIs which are currently supported via Redfish mode
of operation. This is a growing list which needs to be updated as and when
the existing API/s (of its cousin RIS and RIBCL interfaces) are migrated.
For operations currently supported on the client object, please refer:
*proliantutils.ilo.client.SUPPORTED_REDFISH_METHODS*
"""
def __init__(self, redfish_controller_ip, username, password,
bios_password=None, cacert=None, root_prefix='/redfish/v1/'):
"""A class representing supported RedfishOperations
:param redfish_controller_ip: The ip address of the Redfish controller.
:param username: User account with admin/server-profile access
privilege
:param password: User account password
:param bios_password: bios password
:param cacert: a path to a CA_BUNDLE file or directory with
certificates of trusted CAs. If set to None, the driver will
ignore verifying the SSL certificate; if it's a path the driver
will use the specified certificate or one of the certificates in
the directory. Defaults to None.
:param root_prefix: The default URL prefix. This part includes
the root service and version. Defaults to /redfish/v1
"""
super(RedfishOperations, self).__init__()
address = ('https://' + redfish_controller_ip)
LOG.debug('Redfish address: %s', address)
verify = False if cacert is None else cacert
# for error reporting purpose
self.host = redfish_controller_ip
self._root_prefix = root_prefix
self._username = username
try:
self._sushy = main.HPESushy(
address, username=username, password=password,
root_prefix=root_prefix, verify=verify)
except sushy.exceptions.SushyError as e:
msg = (self._('The Redfish controller at "%(controller)s" has '
'thrown error. Error %(error)s') %
{'controller': address, 'error': str(e)})
LOG.debug(msg)
raise exception.IloConnectionError(msg)
def __del__(self):
try:
if self._sushy:
self._sushy.close()
except AttributeError:
pass
def _get_sushy_system(self, system_id):
"""Get the sushy system for system_id
:param system_id: The identity of the System resource
:returns: the Sushy system instance
:raises: IloError
"""
system_url = parse.urljoin(self._sushy.get_system_collection_path(),
system_id)
try:
return self._sushy.get_system(system_url)
except sushy.exceptions.SushyError as e:
msg = (self._('The Redfish System "%(system)s" was not found. '
'Error %(error)s') %
{'system': system_id, 'error': str(e)})
LOG.debug(msg)
raise exception.IloError(msg)
def _get_sushy_manager(self, manager_id):
"""Get the sushy Manager for manager_id
:param manager_id: The identity of the Manager resource
:returns: the Sushy Manager instance
:raises: IloError
"""
manager_url = parse.urljoin(self._sushy.get_manager_collection_path(),
manager_id)
try:
return self._sushy.get_manager(manager_url)
except sushy.exceptions.SushyError as e:
msg = (self._('The Redfish Manager "%(manager)s" was not found. '
'Error %(error)s') %
{'manager': manager_id, 'error': str(e)})
LOG.debug(msg)
raise exception.IloError(msg)
def _get_sushy_chassis(self, chassis_id):
"""Get the sushy chassis for chassis_id
:param chassis_id: The identity of the Chassis resource
:returns: the Sushy Chassis instance
:raises: IloError
"""
chassis_url = parse.urljoin(self._sushy.get_chassis_collection_path(),
chassis_id)
try:
return self._sushy.get_chassis(chassis_url)
except sushy.exceptions.SushyError as e:
msg = (self._('The Redfish Chassis "%(chassis)s" was not found. '
'Error %(error)s') %
{'chassis': chassis_id, 'error': str(e)})
LOG.debug(msg)
raise exception.IloError(msg)
def get_product_name(self):
"""Gets the product name of the server.
:returns: server model name.
:raises: IloError, on an error from iLO.
"""
sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)
return sushy_system.model
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.
"""
sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)
return GET_POWER_STATE_MAP.get(sushy_system.power_state)
def _perform_power_op(self, power):
"""This method performs power operation.
:param: power : target power state
"""
sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)
try:
sushy_system.reset_system(POWER_RESET_MAP[power])
except sushy.exceptions.SushyError as e:
msg = (self._('The Redfish controller failed to set power state '
'of server to %(target_value)s. Error %(error)s') %
{'target_value': power, 'error': str(e)})
LOG.debug(msg)
raise exception.IloError(msg)
@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()
allowed_states = ['ON', 'PoweringOn']
if power == "OFF":
allowed_states = ['OFF', 'PoweringOff']
if (status != power or status not in allowed_states or status is None):
self._perform_power_op(power)
return self.get_host_power_status()
else:
return status
def reset_server(self):
"""Resets the server.
:raises: IloError, on an error from iLO.
"""
sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)
try:
sushy_system.reset_system(sushy.RESET_FORCE_RESTART)
except sushy.exceptions.SushyError as e:
msg = (self._('The Redfish controller failed to reset server. '
'Error %(error)s') %
{'error': str(e)})
LOG.debug(msg)
raise exception.IloError(msg)
def set_host_power(self, target_value):
"""Sets the power state of the system.
:param target_value: The target value to be set. Value can be:
'ON' or 'OFF'.
:raises: IloError, on an error from iLO.
:raises: InvalidInputError, if the target value is not
allowed.
"""
if target_value not in POWER_RESET_MAP:
msg = ('The parameter "%(parameter)s" value "%(target_value)s" is '
'invalid. Valid values are: %(valid_power_values)s' %
{'parameter': 'target_value', 'target_value': target_value,
'valid_power_values': POWER_RESET_MAP.keys()})
raise exception.InvalidInputError(msg)
# Check current power status, do not act if it's in requested state.
current_power_status = self.get_host_power_status()
if current_power_status == target_value:
LOG.debug(self._("Node is already in '%(target_value)s' power "
"state."), {'target_value': target_value})
return
try:
self._retry_until_powered_on(target_value)
except sushy.exceptions.SushyError as e:
msg = (self._('The Redfish controller failed to set power state '
'of server to %(target_value)s. Error %(error)s') %
{'target_value': target_value, 'error': str(e)})
LOG.debug(msg)
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.
"""
sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)
try:
sushy_system.push_power_button(sys_cons.PUSH_POWER_BUTTON_PRESS)
except sushy.exceptions.SushyError as e:
msg = (self._('The Redfish controller failed to press power button'
' of server. Error %(error)s') %
{'error': str(e)})
LOG.debug(msg)
raise exception.IloError(msg)
def hold_pwr_btn(self):
"""Simulate a physical press and hold of the server power button.
:raises: IloError, on an error from iLO.
"""
sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)
try:
sushy_system.push_power_button(
sys_cons.PUSH_POWER_BUTTON_PRESS_AND_HOLD)
except sushy.exceptions.SushyError as e:
msg = (self._('The Redfish controller failed to press and hold '
'power button of server. Error %(error)s') %
{'error': str(e)})
LOG.debug(msg)
raise exception.IloError(msg)
def activate_license(self, key):
"""Activates iLO license.
:param key: iLO license key.
:raises: IloError, on an error from iLO.
"""
sushy_manager = self._get_sushy_manager(PROLIANT_MANAGER_ID)
try:
sushy_manager.set_license(key)
except sushy.exceptions.SushyError as e:
msg = (self._('The Redfish controller failed to update '
'the license. Error %(error)s') %
{'error': str(e)})
LOG.debug(msg)
raise exception.IloError(msg)
def get_one_time_boot(self):
"""Retrieves the current setting for the one time boot.
:returns: Returns boot device that would be used in next
boot. Returns 'Normal' if no device is set.
"""
sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)
if (sushy_system.boot.enabled == sushy.BOOT_SOURCE_ENABLED_ONCE):
return DEVICE_REDFISH_TO_COMMON.get(sushy_system.boot.target)
else:
# value returned by RIBCL if one-time boot setting are absent
return 'Normal'
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.
"""
sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)
try:
return BOOT_MODE_MAP.get(
sushy_system.bios_settings.pending_settings.boot_mode)
except sushy.exceptions.SushyError as e:
msg = (self._('The pending BIOS Settings was not found. Error '
'%(error)s') %
{'error': str(e)})
LOG.debug(msg)
raise exception.IloError(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.
"""
sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)
try:
return BOOT_MODE_MAP.get(sushy_system.bios_settings.boot_mode)
except sushy.exceptions.SushyError as e:
msg = (self._('The current BIOS Settings was not found. Error '
'%(error)s') %
{'error': str(e)})
LOG.debug(msg)
raise exception.IloError(msg)
def _validate_virtual_media(self, device):
"""Check if the device is valid device.
:param device: virtual media device
:raises: IloInvalidInputError, if the device is not valid.
"""
if device not in VIRTUAL_MEDIA_MAP:
msg = (self._("Invalid device '%s'. Valid devices: FLOPPY or "
"CDROM.")
% device)
LOG.debug(msg)
raise exception.IloInvalidInputError(msg)
def eject_virtual_media(self, device):
"""Ejects the Virtual Media image if one is inserted.
:param device: virual media device
:raises: IloError, on an error from iLO.
:raises: IloInvalidInputError, if the device is not valid.
"""
self._validate_virtual_media(device)
manager = self._get_sushy_manager(PROLIANT_MANAGER_ID)
try:
vmedia_device = (
manager.virtual_media.get_member_device(
VIRTUAL_MEDIA_MAP[device]))
if not vmedia_device.inserted:
LOG.debug(self._("No media available in the device '%s' to "
"perform eject operation.") % device)
return
LOG.debug(self._("Ejecting the media image '%(url)s' from the "
"device %(device)s.") %
{'url': vmedia_device.image, 'device': device})
vmedia_device.eject_media()
except sushy.exceptions.SushyError as e:
msg = (self._("The Redfish controller failed to eject the virtual"
" media device '%(device)s'. Error %(error)s.") %
{'device': device, 'error': str(e)})
LOG.debug(msg)
raise exception.IloError(msg)
def insert_virtual_media(self, url, device):
"""Inserts the Virtual Media image to the device.
:param url: URL to image
:param device: virual media device
:raises: IloError, on an error from iLO.
:raises: IloInvalidInputError, if the device is not valid.
"""
# Validate url
common_utils.validate_href(url)
self._validate_virtual_media(device)
manager = self._get_sushy_manager(PROLIANT_MANAGER_ID)
try:
vmedia_device = (
manager.virtual_media.get_member_device(
VIRTUAL_MEDIA_MAP[device]))
if vmedia_device.inserted:
vmedia_device.eject_media()
LOG.debug(self._("Inserting the image url '%(url)s' to the "
"device %(device)s.") %
{'url': url, 'device': device})
vmedia_device.insert_media(url)
except sushy.exceptions.SushyError as e:
msg = (self._("The Redfish controller failed to insert the media "
"url %(url)s in the virtual media device "
"'%(device)s'. Error %(error)s.") %
{'url': url, 'device': device, 'error': str(e)})
LOG.debug(msg)
raise exception.IloError(msg)
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 Redfish it is read-only.
:raises: IloError, on an error from iLO.
:raises: IloInvalidInputError, if the device is not valid.
"""
# CONNECT is a RIBCL call. There is no such property to set in Redfish.
if boot_option == 'CONNECT':
return
self._validate_virtual_media(device)
if boot_option not in BOOT_OPTION_MAP:
msg = (self._("Virtual media boot option '%s' is invalid.")
% boot_option)
LOG.debug(msg)
raise exception.IloInvalidInputError(msg)
manager = self._get_sushy_manager(PROLIANT_MANAGER_ID)
try:
vmedia_device = (
manager.virtual_media.get_member_device(
VIRTUAL_MEDIA_MAP[device]))
vmedia_device.set_vm_status(BOOT_OPTION_MAP[boot_option])
except sushy.exceptions.SushyError as e:
msg = (self._("The Redfish controller failed to set the virtual "
"media status for '%(device)s'. Error %(error)s") %
{'device': device, 'error': str(e)})
LOG.debug(msg)
raise exception.IloError(msg)
@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: IloError, on an error from iLO.
"""
try:
update_service_inst = self._sushy.get_update_service()
update_service_inst.flash_firmware(self, file_url)
except sushy.exceptions.SushyError as e:
msg = (self._('The Redfish controller failed to update firmware '
'with firmware %(file)s Error %(error)s') %
{'file': file_url, 'error': str(e)})
LOG.debug(msg)
raise exception.IloError(msg)
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'
"""
boot_mode = self.get_current_boot_mode()
return (boot_mode == BOOT_MODE_MAP.get(sys_cons.BIOS_BOOT_MODE_UEFI))
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.
"""
sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)
# Return boot device if it is persistent.
if ((sushy_system.
boot.enabled) == sushy.BOOT_SOURCE_ENABLED_CONTINUOUS):
return PERSISTENT_BOOT_MAP.get(sushy_system.boot.target)
# 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
try:
boot_device = (sushy_system.bios_settings.boot_settings.
get_persistent_boot_device())
return PERSISTENT_BOOT_MAP.get(boot_device)
except sushy.exceptions.SushyError as e:
msg = (self._("The Redfish controller is unable to get "
"persistent boot device. Error %(error)s") %
{'error': str(e)})
LOG.debug(msg)
raise exception.IloError(msg)
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.
"""
sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)
if boot_mode.upper() not in BOOT_MODE_MAP_REV.keys():
msg = (('Invalid Boot mode: "%(boot_mode)s" specified, valid boot '
'modes are either "uefi" or "legacy"')
% {'boot_mode': boot_mode})
raise exception.IloInvalidInputError(msg)
try:
sushy_system.bios_settings.pending_settings.set_pending_boot_mode(
BOOT_MODE_MAP_REV.get(boot_mode.upper()))
except sushy.exceptions.SushyError as e:
msg = (self._('The Redfish controller failed to set '
'pending boot mode to %(boot_mode)s. '
'Error: %(error)s') %
{'boot_mode': boot_mode, 'error': str(e)})
LOG.debug(msg)
raise exception.IloError(msg)
def update_persistent_boot(self, devices=[]):
"""Changes the persistent boot device order for the host
:param devices: ordered list of boot devices
:raises: IloError, on an error from iLO.
:raises: IloInvalidInputError, if the given input is not valid.
"""
sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)
# Check if the input is valid
for item in devices:
if item.upper() not in DEVICE_COMMON_TO_REDFISH:
msg = (self._('Invalid input "%(device)s". Valid devices: '
'NETWORK, HDD, ISCSI, UEFIHTTP or CDROM.') %
{'device': item})
raise exception.IloInvalidInputError(msg)
try:
sushy_system.update_persistent_boot(
devices, persistent=True)
except sushy.exceptions.SushyError as e:
msg = (self._('The Redfish controller failed to update '
'persistent boot device %(devices)s.'
'Error: %(error)s') %
{'devices': devices, 'error': str(e)})
LOG.debug(msg)
raise exception.IloError(msg)
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: IloInvalidInputError, if the given input is not valid.
"""
sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)
# Check if the input is valid
if device.upper() not in DEVICE_COMMON_TO_REDFISH:
msg = (self._('Invalid input "%(device)s". Valid devices: '
'NETWORK, HDD, ISCSI, UEFIHTTP or CDROM.') %
{'device': device})
raise exception.IloInvalidInputError(msg)
try:
sushy_system.update_persistent_boot(
[device], persistent=False)
except sushy.exceptions.SushyError as e:
msg = (self._('The Redfish controller failed to set '
'one time boot device %(device)s. '
'Error: %(error)s') %
{'device': device, 'error': str(e)})
LOG.debug(msg)
raise exception.IloError(msg)
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.
"""
try:
acc_service = self._sushy.get_account_service()
member = acc_service.accounts.get_member_details(self._username)
if member is None:
msg = (self._("No account found with username: %s")
% self._username)
LOG.debug(msg)
raise exception.IloError(msg)
member.update_credentials(password)
except sushy.exceptions.SushyError as e:
msg = (self._('The Redfish controller failed to update '
'credentials for %(username)s. Error %(error)s') %
{'username': self._username, 'error': str(e)})
LOG.debug(msg)
raise exception.IloError(msg)
def get_supported_boot_mode(self):
"""Get the system supported boot modes.
:return: 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
:raises: IloError, if account not found or on an error from iLO.
"""
sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)
try:
return SUPPORTED_BOOT_MODE_MAP.get(
sushy_system.supported_boot_mode)
except sushy.exceptions.SushyError as e:
msg = (self._('The Redfish controller failed to get the '
'supported boot modes. Error: %s') % e)
LOG.debug(msg)
raise exception.IloError(msg)
def _update_security_parameter(self, sec_param, ignore=False):
"""Sets the ignore flag for the security parameter.
:param sec_param: Name of the security parameter.
:param ignore : True when security parameter needs to be ignored.
If passed False, security param will not be ignored.
If nothing passed default will be False.
"""
sushy_manager = self._get_sushy_manager(PROLIANT_MANAGER_ID)
try:
security_params = (
sushy_manager.securityservice.securityparamscollectionuri)
param_members = security_params.get_members()
for param in param_members:
if sec_param in param.name:
param.update_security_param_ignore_status(ignore)
break
else:
msg = (self._('Specified parameter "%(param)s" is not '
'a Security Dashboard Parameter.') %
{'param': sec_param})
raise exception.IloInvalidInputError(msg)
except sushy.exceptions.SushyError as e:
msg = (self._("The Redfish controller is unable to update "
"resource or its member. Error "
"%(error)s)") % {'error': str(e)})
LOG.debug(msg)
raise exception.IloError(msg)
def update_password_complexity(self, enable=True, ignore=False):
"""Update the Password_Complexity security param.
:param enable: A boolean param, True when Password_Complexity needs
to be enabled. If passed False, Password_Complexity security
param will be disabled. If nothing passed default will be True.
:param ignore : A boolean param, True when Password_Complexity needs
to be ignored. If passed False, Password_Complexity security
param will not be ignored. If nothing passed default will be
False.
:raises: IloError, on an error from iLO.
"""
acc_service = self._sushy.get_account_service()
try:
self._update_security_parameter(sec_param="Password Complexity",
ignore=ignore)
acc_service.update_enforce_passwd_complexity(enable)
except sushy.exceptions.SushyError as e:
msg = (self._('The Redfish controller failed to update the '
'security dashboard parameter '
'``Password_Complexity``. '
'Error %(error)s') % {'error': str(e)})
LOG.debug(msg)
raise exception.IloError(msg)
def update_require_login_for_ilo_rbsu(self, enable=True, ignore=False):
"""Update the RequiredLoginForiLORBSU security param.
:param enable: A boolean param, True when RequiredLoginForiLORBSU
needs to be enabled. If passed False, RequiredLoginForiLORBSU
security param will be disabled. If nothing passed default
will be True.
:param ignore : A boolean param, True when RequiredLoginForiLORBSU
needs to be ignored. If passed False, RequiredLoginForiLORBSU
security param will not be ignored. If nothing passed default
will be False.
:raises: IloError, on an error from iLO.
"""
sushy_manager = self._get_sushy_manager(PROLIANT_MANAGER_ID)
try:
self._update_security_parameter(sec_param="Require Login",
ignore=ignore)
sushy_manager.update_login_for_ilo_rbsu(enable)
except sushy.exceptions.SushyError as e:
msg = (self._('The Redfish controller failed to update the '
'security dashboard parameter '
'``RequiredLoginForiLORBSU``. '
'Error %(error)s') % {'error': str(e)})
LOG.debug(msg)
raise exception.IloError(msg)
def update_require_host_authentication(self, enable=True, ignore=False):
"""Update the RequireHostAuthentication security param.
:param enable: A boolean param, True when RequireHostAuthentication
needs to be enabled. If passed False, RequireHostAuthentication
security param will be disabled. If nothing passed
default will be True.
:param ignore : A boolean param, True when RequireHostAuthentication
needs to be ignored. If passed False, RequireHostAuthentication
security param will not be ignored. If nothing passed
default will be False.
:raises: IloError, on an error from iLO.
"""
sushy_manager = self._get_sushy_manager(PROLIANT_MANAGER_ID)
try:
self._update_security_parameter(sec_param="Host Authentication",
ignore=ignore)
sushy_manager.update_host_authentication(enable)
except sushy.exceptions.SushyError as e:
msg = (self._('The Redfish controller failed to update the '
'security dashboard paramater '
'``RequireHostAuthentication``. '
'Error %(error)s') % {'error': str(e)})
LOG.debug(msg)
raise exception.IloError(msg)
def update_minimum_password_length(self, passwd_length=None, ignore=False):
"""Update the MinPasswordLength security param.
:param passwd_length: Minimum lenght of password used. If nothing
passed default will be None.
:param ignore : A boolean param, True when MinPasswordLength needs to
be ignored. If passed False, MinPasswordLength security param
will not be ignored. If nothing passed default will be False.
"""
acc_service = self._sushy.get_account_service()
try:
self._update_security_parameter(sec_param="Minimum",
ignore=ignore)
acc_service.update_min_passwd_length(passwd_length)
except sushy.exceptions.SushyError as e:
msg = (self._('The Redfish controller failed to update the '
'security dashboard paramater '
'``MinPasswordLength``. '
'Error %(error)s') % {'error': str(e)})
LOG.debug(msg)
raise exception.IloError(msg)
def update_ipmi_over_lan(self, enable=False, ignore=False):
"""Update the IPMI/DCMI_Over_LAN security param.
:param enable: A boolean param, True when IPMI/DCMI_Over_LAN needs to
be enabled. If passed False, IPMI/DCMI_Over_LAN security param
will be disabled. If nothing passed default will be False.
:param ignore : A boolean param, True when IPMI/DCMI_Over_LAN needs to
be ignored. If passed False, IPMI/DCMI_Over_LAN security param
will not be ignored. If nothing passed default will be False.
:raises: IloError, on an error from iLO.
"""
sushy_manager = self._get_sushy_manager(PROLIANT_MANAGER_ID)
try:
self._update_security_parameter(sec_param="IPMI", ignore=ignore)
sushy_manager.networkprotocol.update_ipmi_enabled(enable)
except sushy.exceptions.SushyError as e:
msg = (self._('The Redfish controller failed to update the '
'security dashboard paramater '
'``IPMI/DCMI_Over_LAN``. '
'Error %(error)s') % {'error': str(e)})
LOG.debug(msg)
raise exception.IloError(msg)
def update_authentication_failure_logging(self, logging_threshold=None,
ignore=False):
"""Update the Authentication_failure_Logging security param.
:param logging_threshold: Value of authenication failure logging
threshold. If nothing passed default will be None.
:param ignore : A boolean param, True when
Authentication_failure_Logging needs to be ignored. If passed
False, Authentication_failure_Logging security param will not
be ignored. If nothing passed default will be False.
:raises: IloError, on an error from iLO.
"""
acc_service = self._sushy.get_account_service()
try:
self._update_security_parameter(sec_param="Failure Logging",
ignore=ignore)
acc_service.update_auth_failure_logging(logging_threshold)
except sushy.exceptions.SushyError as e:
msg = (self._('The Redfish controller failed to update the '
'security dashboard paramater '
'``Authentication_failure_Logging``. '
'Error %(error)s') % {'error': str(e)})
LOG.debug(msg)
raise exception.IloError(msg)
def update_secure_boot(self, enable=True, ignore=False):
"""Update Secure_Boot security param on the server.
:param enable: A boolean param, True when Secure_Boot needs to be
enabled. If passed False, Secure_Boot security param will
be disabled. If nothing passed default will be True.
:param ignore : A boolean param, True when Secure_boot needs to be
ignored. If passed False, Secure_boot security param will
not be ignored. If nothing passed default will be False.
:raises: IloError, on an error from iLO.
"""
try:
self._update_security_parameter(sec_param="Secure Boot",
ignore=ignore)
self.set_secure_boot_mode(enable)
except sushy.exceptions.SushyError as e:
msg = (self._('The Redfish controller failed to update the '
'security dashboard paramater ``Secure_boot``. '
'Error %(error)s') % {'error': str(e)})
LOG.debug(msg)
raise exception.IloError(msg)
def _create_csr(self, csr_params):
"""Creates the Certificate Signing Request.
:param csr_params: A dictionary containing all the necessary
information required to create CSR.
:raises: IloError, on an error from iLO.
"""
sushy_man = self._get_sushy_manager(PROLIANT_MANAGER_ID)
try:
cert_request = (
sushy_man.securityservice.https_certificate_uri.generate_csr(
csr_params))
(fd, temp_file) = tempfile.mkstemp(suffix='.csr')
with open(temp_file, 'w') as f:
f.write(cert_request)
return temp_file
except sushy.exceptions.SushyError as e:
msg = (self._('The Redfish controller failed to create the '
'certificate signing request. '
'Error %(error)s') % {'error': str(e)})
LOG.debug(msg)
raise exception.IloError(msg)
def add_ssl_certificate(self, csr_params, signed_cert,
private_key, pass_phrase):
"""Creates CSR and adds the signed SSL certificate to the iLO.
:param csr_params: A dictionary containing all the necessary
information required to create CSR.
:param signed_cert: signed certificate which will be used
to sign the created CSR.
:param private_key: private key.
:param pass_phrase: Pass phrase for the private key.
:raises: IloError, on an error from iLO.
"""
csr_file = self._create_csr(csr_params)
(fd, temp_file) = tempfile.mkstemp(suffix='.ext')
(fd, https_cert_file) = tempfile.mkstemp(suffix='.crt')
(fd, ss_cert_file) = tempfile.mkstemp(suffix='.crt')
with open(signed_cert, 'r') as f:
data = json.dumps(f.read())
p = re.sub(r"\"", "", data)
q = re.sub(r"\\n", "\r\n", p).rstrip()
c_list = re.findall(_CERTIFICATE_PATTERN, q, re.DOTALL)
if len(c_list) == 0:
msg = (self._("No valid certificate in %(cert_file)s.") %
{"cert_file": signed_cert})
LOG.debug(msg)
raise exception.InvalidParameterValueError(msg)
ss_cert = c_list[0]
with open(ss_cert_file, 'w') as f:
f.write(ss_cert)
content = [
"authorityKeyIdentifier = keyid,issuer\n",
"basicConstraints = CA:true,pathlen:1\n",
"keyUsage = digitalSignature,keyEncipherment,keyCertSign,cRLSign",
"\nextendedKeyUsage = clientAuth,serverAuth\n",
"subjectKeyIdentifier = hash"]
with open(temp_file, 'w') as f:
f.writelines(content)
cert_cmd = (
"openssl x509 -req -days 365 -in %(csr_file)s -extfile"
" %(tempfile)s -CA %(cert)s -CAkey %(p_key)s -passin "
" pass:%(pphrase)s -CAcreateserial -out %(cert_file)s"
% {'csr_file': csr_file, 'tempfile': temp_file,
'cert': ss_cert_file, 'p_key': private_key,
'pphrase': pass_phrase, 'cert_file': https_cert_file})
try:
process = subprocess.Popen(cert_cmd, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, shell=True)
out, err = process.communicate()
except Exception as e:
msg = (self._("Failed to create HTTPS certificate. "
"error: %(err)s") % {"err": e})
LOG.debug(msg)
raise exception.CertificateCreationError(msg)
self._add_https_certificate(https_cert_file)
def _add_https_certificate(self, cert_file):
"""Adds the signed https certificate to the iLO.
:param certificate: Signed HTTPS certificate file.
:raises: IloError, on an error from iLO.
"""
sushy_man = self._get_sushy_manager(PROLIANT_MANAGER_ID)
try:
with open(cert_file, 'r') as f:
data = json.dumps(f.read())
p = re.sub(r"\"", "", data)
q = re.sub(r"\\n", "\r\n", p).rstrip()
c_list = re.findall(_CERTIFICATE_PATTERN, q, re.DOTALL)
if len(c_list) == 0:
msg = (self._("No valid certificate in %(cert_file)s.") %
{"cert_file": cert_file})
LOG.debug(msg)
raise exception.IloError(msg)
cert = c_list[0]
sushy_man.securityservice.https_certificate_uri.import_certificate(
cert)
common.wait_for_ilo_after_reset(self)
except sushy.exceptions.SushyError as e:
msg = (self._('The Redfish controller failed to import the '
'given certificate. '
'Error: %(error)s') % {'error': str(e)})
LOG.debug(msg)
raise exception.IloError(msg)
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.
"""
sushy_man = self._get_sushy_manager(PROLIANT_MANAGER_ID)
try:
cert_request = (
sushy_man.securityservice.https_certificate_uri.generate_csr(
csr_params))
if not os.path.exists(path):
os.makedirs(path, 0o755)
csr_file_name = os.path.basename(path)
csr_file = os.path.join(path, csr_file_name + '.csr')
with open(csr_file, 'w') as f:
f.write(cert_request)
os.chmod(csr_file, 0o755)
except sushy.exceptions.SushyError as e:
msg = (self._('The Redfish controller failed to create the '
'certificate signing request. '
'Error %(error)s') % {'error': str(e)})
LOG.debug(msg)
raise exception.IloError(msg)
def add_https_certificate(self, cert_file):
"""Adds the signed https certificate to the iLO.
:param certificate: Signed HTTPS certificate file.
:raises: IloError, on an error from iLO.
"""
sushy_man = self._get_sushy_manager(PROLIANT_MANAGER_ID)
try:
with open(cert_file, 'r') as f:
data = json.dumps(f.read())
p = re.sub(r"\"", "", data)
q = re.sub(r"\\n", "\r\n", p).rstrip()
c_list = re.findall(_CERTIFICATE_PATTERN, q, re.DOTALL)
if len(c_list) == 0:
msg = (self._("No valid certificate in %(cert_file)s.") %
{"cert_file": cert_file})
LOG.debug(msg)
raise exception.IloError(msg)
cert = c_list[0]
sushy_man.securityservice.https_certificate_uri.import_certificate(
cert)
common.wait_for_ilo_after_reset(self)
except sushy.exceptions.SushyError as e:
msg = (self._('The Redfish controller failed to import the '
'given certificate. '
'Error: %(error)s') % {'error': str(e)})
LOG.debug(msg)
raise exception.IloError(msg)
def get_security_dashboard_values(self):
"""Gets all the parameters related to security dashboard.
:return: a dictionary of the security dashboard values
with their security status and security parameters
with their complete details and security status.
:raises: IloError, if security dashboard or their params
not found or on an error from iLO.
"""
sec_capabilities = {}
sushy_manager = self._get_sushy_manager(PROLIANT_MANAGER_ID)
try:
security_dashboard = (
sushy_manager.securityservice.securitydashboard)
security_params = (
security_dashboard.securityparamscollectionuri)
if security_dashboard.server_configuration_lock_status:
sec_capabilities.update(
{'server_configuration_lock_status': (
security_dashboard.server_configuration_lock_status)})
sec_capabilities.update(
{'overall_security_status': (
security_dashboard.overall_status)})
security_parameters = {}
param_members = security_params.get_members()
for param in param_members:
param_dict = {param.name: {'security_status': param.status,
'state': param.state,
'ignore': param.ignore}}
if param.description:
param_dict[param.name].update(
{'description': param.description})
if param.recommended_action:
param_dict[param.name].update(
{'recommended_action': param.recommended_action})
security_parameters.update(param_dict)
sec_capabilities.update(
{'security_parameters': security_parameters})
except sushy.exceptions.SushyError as e:
msg = (self._("The Redfish controller is unable to get "
"resource or its members. Error "
"%(error)s)") % {'error': str(e)})
LOG.debug(msg)
raise exception.IloError(msg)
return sec_capabilities
def _parse_security_dashboard_values_for_capabilities(self):
"""Parses the security dashboard parameters.
:returns: a dictionary of only those security parameters and their
security status which are applicable for ironic.
"""
values = self.get_security_dashboard_values()
ironic_sec_capabilities = {}
ironic_sec_capabilities.update(
{'overall_security_status': values.get('overall_security_status')})
param_values = values.get('security_parameters')
p_map = {'Last Firmware Scan Result': 'last_firmware_scan_result',
'Security Override Switch': 'security_override_switch'}
p_keys = p_map.keys()
for p_key, p_val in param_values.items():
if p_key in p_keys:
p_dict = {p_map.get(p_key): p_val.get('security_status')}
ironic_sec_capabilities.update(p_dict)
return ironic_sec_capabilities
def get_server_capabilities(self):
"""Returns the server capabilities
raises: IloError on an error from iLO.
"""
capabilities = {}
sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)
sushy_manager = self._get_sushy_manager(PROLIANT_MANAGER_ID)
sushy_chassis = self._get_sushy_chassis(PROLIANT_CHASSIS_ID)
try:
count = len(sushy_system.pci_devices.gpu_devices)
boot_mode = rf_utils.get_supported_boot_mode(
sushy_system.supported_boot_mode)
capabilities.update(
{'pci_gpu_devices': count,
'ilo_firmware_version': sushy_manager.firmware_version,
'rom_firmware_version': sushy_system.rom_version,
'server_model': sushy_system.model,
'nic_capacity': sushy_system.pci_devices.max_nic_capacity,
'boot_mode_bios': boot_mode.boot_mode_bios,
'boot_mode_uefi': boot_mode.boot_mode_uefi})
tpm_state = sushy_system.bios_settings.tpm_state
all_key_to_value_expression_tuples = [
('sriov_enabled',
sushy_system.bios_settings.sriov == sys_cons.SRIOV_ENABLED),
('cpu_vt',
sushy_system.bios_settings.cpu_vt == (
sys_cons.CPUVT_ENABLED)),
('trusted_boot',
(tpm_state == sys_cons.TPM_PRESENT_ENABLED
or tpm_state == sys_cons.TPM_PRESENT_DISABLED)),
('secure_boot', self._has_secure_boot()),
('iscsi_boot',
(sushy_system.bios_settings.iscsi_resource.
is_iscsi_boot_supported())),
('hardware_supports_raid',
len(sushy_system.smart_storage.array_controllers.
members_identities) > 0),
('has_ssd',
common_storage.has_ssd(sushy_system)),
('has_rotational',
common_storage.has_rotational(sushy_system)),
('has_nvme_ssd',
common_storage.has_nvme_ssd(sushy_system))
]
all_key_to_value_expression_tuples += (
[('logical_raid_level_' + x, True)
for x in sushy_system.smart_storage.logical_raid_levels])
all_key_to_value_expression_tuples += (
[('drive_rotational_' + str(x) + '_rpm', True)
for x in
common_storage.get_drive_rotational_speed_rpm(sushy_system)])
capabilities.update(
{key: 'true'
for (key, value) in all_key_to_value_expression_tuples
if value})
memory_data = sushy_system.memory.details()
if memory_data.has_nvdimm_n:
capabilities.update(
{'persistent_memory': (
json.dumps(memory_data.has_persistent_memory)),
'nvdimm_n': (
json.dumps(memory_data.has_nvdimm_n)),
'logical_nvdimm_n': (
json.dumps(memory_data.has_logical_nvdimm_n))})
gpu_capabilities = gpu_common.gpu_capabilities(sushy_system,
sushy_chassis)
for member in gpu_capabilities:
for key in member:
capabilities.update(member.get(key))
capabilities.update(
self._parse_security_dashboard_values_for_capabilities())
except sushy.exceptions.SushyError as e:
msg = (self._("The Redfish controller is unable to get "
"resource or its members. Error "
"%(error)s)") % {'error': str(e)})
LOG.debug(msg)
raise exception.IloError(msg)
return capabilities
def reset_bios_to_default(self):
"""Resets the BIOS settings to default values.
:raises: IloError, on an error from iLO.
"""
sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)
try:
sushy_system.bios_settings.update_bios_to_default()
except sushy.exceptions.SushyError as e:
msg = (self._("The Redfish controller is unable to update bios "
"settings to default Error %(error)s") %
{'error': str(e)})
LOG.debug(msg)
raise exception.IloError(msg)
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.
"""
sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)
try:
secure_boot_enabled = GET_SECUREBOOT_CURRENT_BOOT_MAP.get(
sushy_system.secure_boot.current_boot)
except sushy.exceptions.SushyError as e:
msg = (self._('The Redfish controller failed to provide '
'information about secure boot on the server. '
'Error: %(error)s') %
{'error': str(e)})
LOG.debug(msg)
raise exception.IloCommandNotSupportedError(msg)
if secure_boot_enabled:
LOG.debug(self._("Secure boot is Enabled"))
else:
LOG.debug(self._("Secure boot is Disabled"))
return secure_boot_enabled
def _has_secure_boot(self):
try:
self._get_sushy_system(PROLIANT_SYSTEM_ID).secure_boot
except (exception.MissingAttributeError, sushy.exceptions.SushyError):
return False
return True
def set_secure_boot_mode(self, secure_boot_enable):
"""Enable/Disable secure boot on the server.
Resetting the server post updating this settings is needed
from the caller side to make this into effect.
: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():
sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)
try:
sushy_system.secure_boot.enable_secure_boot(secure_boot_enable)
except exception.InvalidInputError as e:
msg = (self._('Invalid input. Error %(error)s')
% {'error': str(e)})
LOG.debug(msg)
raise exception.IloError(msg)
except sushy.exceptions.SushyError as e:
msg = (self._('The Redfish controller failed to set secure '
'boot settings on the server. Error: %(error)s')
% {'error': str(e)})
LOG.debug(msg)
raise exception.IloError(msg)
else:
msg = (self._('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():
sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)
try:
sushy_system.secure_boot.reset_keys(
sys_cons.SECUREBOOT_RESET_KEYS_DEFAULT)
except sushy.exceptions.SushyError as e:
msg = (self._('The Redfish controller failed to reset secure '
'boot keys on the server. Error %(error)s')
% {'error': str(e)})
LOG.debug(msg)
raise exception.IloError(msg)
else:
msg = (self._('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():
sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)
try:
sushy_system.secure_boot.reset_keys(
sys_cons.SECUREBOOT_RESET_KEYS_DELETE_ALL)
except sushy.exceptions.SushyError as e:
msg = (self._('The Redfish controller failed to clear secure '
'boot keys on the server. Error %(error)s')
% {'error': str(e)})
LOG.debug(msg)
raise exception.IloError(msg)
else:
msg = (self._('System is not in UEFI boot mode. "SecureBoot" '
'related resources cannot be changed.'))
raise exception.IloCommandNotSupportedInBiosError(msg)
def get_essential_properties(self):
"""Constructs the dictionary of essential properties
Constructs the dictionary of essential properties, named
cpu, cpu_arch, local_gb, memory_mb. The MACs are also returned
as part of this method.
"""
sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)
try:
# TODO(nisha): Add local_gb here and return after
# local_gb changes are merged.
# local_gb = sushy_system.storage_summary
prop = {'memory_mb': (sushy_system.memory_summary.size_gib * 1024),
'cpus': sushy_system.processors.summary.count,
'cpu_arch': CPU_ARCH_MAP.get(
sushy_system.processors.summary.architecture),
'local_gb': common_storage.get_local_gb(sushy_system)}
return {'properties': prop,
'macs': sushy_system.ethernet_interfaces.summary}
except sushy.exceptions.SushyError as e:
msg = (self._('The Redfish controller failed to get the '
'resource data. Error %(error)s')
% {'error': str(e)})
LOG.debug(msg)
raise exception.IloError(msg)
def _change_iscsi_target_settings(self, iscsi_info, macs=[]):
"""Change iSCSI target settings.
:param macs: List of target mac 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.
"""
sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)
association_names = []
try:
if macs:
sushy_system.validate_macs(macs)
association_names = [
sushy_system.get_nic_association_name_by_mac(
mac) for mac in macs]
else:
pci_settings_map = (
sushy_system.bios_settings.
bios_mappings.pci_settings_mappings)
for mapping in pci_settings_map:
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)
# Set iSCSI info to all nics
iscsi_infos = []
for association_name in association_names:
data = iscsi_info.copy()
data['iSCSIAttemptName'] = association_name
data['iSCSINicSource'] = association_name
data['iSCSIAttemptInstance'] = (
association_names.index(association_name) + 1)
iscsi_infos.append(data)
iscsi_data = {'iSCSISources': iscsi_infos}
except sushy.exceptions.SushyError as e:
msg = (self._('The Redfish controller failed to get the '
'bios mappings. Error %(error)s')
% {'error': str(e)})
LOG.debug(msg)
raise exception.IloError(msg)
try:
(sushy_system.bios_settings.iscsi_resource.
iscsi_settings.update_iscsi_settings(iscsi_data))
except sushy.exceptions.SushyError as e:
msg = (self._("The Redfish controller is failed to update iSCSI "
"settings. Error %(error)s") %
{'error': str(e)})
LOG.debug(msg)
raise exception.IloError(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: IloCommandNotSupportedInBiosError, if the system is
in the bios boot mode.
"""
if(self._is_boot_mode_uefi()):
iscsi_info = {}
iscsi_info['iSCSITargetName'] = target_name
iscsi_info['iSCSILUN'] = lun
iscsi_info['iSCSITargetIpAddress'] = ip_address
iscsi_info['iSCSITargetTcpPort'] = int(port)
iscsi_info['iSCSITargetInfoViaDHCP'] = False
iscsi_info['iSCSIConnection'] = 'Enabled'
if (auth_method == 'CHAP'):
iscsi_info['iSCSIAuthenticationMethod'] = 'Chap'
iscsi_info['iSCSIChapUsername'] = username
iscsi_info['iSCSIChapSecret'] = password
self._change_iscsi_target_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: IloCommandNotSupportedInBiosError, if the system is
in the BIOS boot mode.
"""
if(self._is_boot_mode_uefi()):
iscsi_info = {'iSCSIConnection': 'Disabled'}
self._change_iscsi_target_settings(iscsi_info, macs)
else:
msg = 'iSCSI boot is not supported in the BIOS boot mode'
raise exception.IloCommandNotSupportedInBiosError(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: IloCommandNotSupportedInBiosError, if the system is
in the BIOS boot mode.
"""
sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)
if(self._is_boot_mode_uefi()):
iscsi_data = {'iSCSIInitiatorName': initiator_iqn}
try:
(sushy_system.bios_settings.iscsi_resource.
iscsi_settings.update_iscsi_settings(iscsi_data))
except sushy.exceptions.SushyError as e:
msg = (self._("The Redfish controller has failed to update "
"iSCSI settings. Error %(error)s") %
{'error': str(e)})
LOG.debug(msg)
raise exception.IloError(msg)
else:
msg = 'iSCSI initiator cannot be updated in 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: IloCommandNotSupportedInBiosError, if the system is
in the BIOS boot mode.
"""
sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)
if(self._is_boot_mode_uefi()):
try:
iscsi_initiator = (
sushy_system.bios_settings.iscsi_resource.iscsi_initiator)
except sushy.exceptions.SushyError as e:
msg = (self._('The Redfish controller has failed to get the '
'iSCSI initiator. Error %(error)s')
% {'error': str(e)})
LOG.debug(msg)
raise exception.IloError(msg)
return iscsi_initiator
else:
msg = 'iSCSI initiator cannot be retrieved in BIOS boot mode'
raise exception.IloCommandNotSupportedInBiosError(msg)
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
"""
sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)
if sushy_system.power_state != sushy.SYSTEM_POWER_STATE_ON:
raise exception.IloError("Server is not in powered on state.")
try:
sushy_system.reset_system(sushy.RESET_NMI)
except sushy.exceptions.SushyError as e:
msg = (self._('The Redfish controller failed to inject nmi to '
'server. Error %(error)s') % {'error': str(e)})
LOG.debug(msg)
raise exception.IloError(msg)
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
"""
sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)
return GET_POST_STATE_MAP.get(sushy_system.post_state)
def read_raid_configuration(self, raid_config=None):
"""Read the logical drives from the system
: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: IloError, on an error from iLO.
:returns: A dictionary containing list of logical disks
"""
sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)
return sushy_system.read_raid(raid_config=raid_config)
def delete_raid_configuration(self):
"""Delete the raid configuration on the hardware."""
sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)
sushy_system.delete_raid()
def do_disk_erase(self, disk_type, pattern=None):
"""Perform the out-of-band sanitize disk erase on the hardware.
:param disk_type: Media type of disk drives either 'HDD' or 'SSD'.
:param pattern: Erase pattern, if nothing passed default
('overwrite' for 'HDD', and 'block' for 'SSD') will
be used.
:raises: IloError, on an error from iLO.
"""
sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)
sushy_system.do_disk_erase(disk_type, pattern)
def has_disk_erase_completed(self):
"""Get out-of-band sanitize disk erase status.
:returns: True if disk erase completed on all controllers
otherwise False
"""
sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)
return sushy_system.has_disk_erase_completed()
def do_one_button_secure_erase(self):
"""Perform the one button secure erase on the hardware.
The One-button secure erase process resets iLO and deletes all licenses
stored there, resets BIOS settings, and deletes all AHS and warranty
data stored on the system. It also erases supported non-volatile
storage data and deletes any deployment settings profiles.
:raises: IloError, on an error from iLO.
"""
sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)
sushy_system.do_one_button_secure_erase()
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
"""
sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)
try:
current_settings = sushy_system.bios_settings.json
except sushy.exceptions.SushyError as e:
msg = (self._('The current BIOS Settings were not found. Error '
'%(error)s') %
{'error': str(e)})
LOG.debug(msg)
raise exception.IloError(msg)
attributes = current_settings.get("Attributes")
if only_allowed_settings and attributes:
return common_utils.apply_bios_properties_filter(
attributes, ilo_cons.SUPPORTED_REDFISH_BIOS_PROPERTIES)
return attributes
def get_pending_bios_settings(self, only_allowed_settings=False):
"""Get pending 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 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.
"""
sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)
try:
settings = sushy_system.bios_settings.pending_settings.json
except sushy.exceptions.SushyError as e:
msg = (self._('The pending BIOS Settings were not found. Error '
'%(error)s') %
{'error': str(e)})
LOG.debug(msg)
raise exception.IloError(msg)
attributes = settings.get("Attributes")
if only_allowed_settings and attributes:
return common_utils.apply_bios_properties_filter(
attributes, ilo_cons.SUPPORTED_REDFISH_BIOS_PROPERTIES)
return attributes
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")
sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)
if only_allowed_settings:
unsupported_settings = [key for key in data if key not in (
ilo_cons.SUPPORTED_REDFISH_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,
ilo_cons.SUPPORTED_REDFISH_BIOS_PROPERTIES))
raise exception.IloError(msg)
try:
settings_required = sushy_system.bios_settings.pending_settings
settings_required.update_bios_data_by_patch(data)
except sushy.exceptions.SushyError as e:
msg = (self._('The pending BIOS Settings resource not found.'
' Error %(error)s') %
{'error': str(e)})
LOG.debug(msg)
raise exception.IloError(msg)
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.
"""
sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)
try:
settings = sushy_system.bios_settings.default_settings
except sushy.exceptions.SushyError as e:
msg = (self._('The default BIOS Settings were not found. Error '
'%(error)s') %
{'error': str(e)})
LOG.debug(msg)
raise exception.IloError(msg)
if only_allowed_settings:
return common_utils.apply_bios_properties_filter(
settings, ilo_cons.SUPPORTED_REDFISH_BIOS_PROPERTIES)
return settings
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: IloError, on an error from iLO.
"""
sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)
sushy_system.create_raid(raid_config)
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.
"""
sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)
try:
settings_result = sushy_system.bios_settings.messages
except sushy.exceptions.SushyError as e:
msg = (self._('The BIOS Settings results were not found. Error '
'%(error)s') %
{'error': str(e)})
LOG.debug(msg)
raise exception.IloError(msg)
status = "failed" if len(settings_result) > 1 else "success"
return {"status": status, "results": settings_result}
def get_available_disk_types(self):
"""Get the list of all disk type available in server
:returns: A list containing disk types
:raises: IloError, on an error from iLO.
"""
sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)
return sushy_system.get_disk_types()
def get_http_boot_url(self):
"""Sets current BIOS settings to the provided data.
:raises: IloError, on an error from iLO.
:return: Returns the setting 'UrlBootFile' if set previously.
"""
sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)
url = None
try:
settings = sushy_system.bios_settings.json
attributes = settings.get('Attributes')
url = attributes.get('UrlBootFile')
except sushy.exceptions.SushyError as e:
msg = (self._('The attribute "UrlBootFile" not found.'
' Error %(error)s') %
{'error': str(e)})
LOG.debug(msg)
raise exception.IloError(msg)
return url
def set_http_boot_url(self, url, is_dhcp_enabled=True):
"""Sets HTTP boot URL to boot from it.
:param: url: HTTP URL of the image to be booted on the iLO.
:param: is_dhcp_enabled: True if no static IP is set on the node and
preferred to use DHCP service running in the network.
If False, the MAC is expected to be configured with static IP.
:raises: IloError, on an error from iLO.
"""
if not url:
raise exception.IloError("Could not set http url with"
" empty URL")
data = {
'PreBootNetwork': 'Auto',
'UrlBootFile': url,
'Dhcpv4': 'Enabled' if is_dhcp_enabled else 'Disabled'
}
sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)
try:
settings_required = sushy_system.bios_settings.pending_settings
settings_required.update_bios_data_by_post(data)
except sushy.exceptions.SushyError as e:
msg = (self._('Could not set HTTPS URL on the iLO.'
' Error %(error)s') %
{'error': str(e)})
LOG.debug(msg)
raise exception.IloError(msg)
def add_tls_certificate(self, cert_file_list):
"""Adds the TLS certificates to the iLO.
:param cert_file_list: List of TLS certificate files
:raises: IloError, on an error from iLO.
:raises: IloCommandNotSupportedError, if the command is
not supported on the server.
"""
sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)
if(self._is_boot_mode_uefi()):
cert_list = []
for cert_file in cert_file_list:
with open(cert_file, 'r') as f:
data = json.dumps(f.read())
p = re.sub(r"\"", "", data)
q = re.sub(r"\\n", "\r\n", p).rstrip()
c_list = re.findall(_CERTIFICATE_PATTERN, q, re.DOTALL)
if len(c_list) == 0:
LOG.warning("Could not find any valid certificate in "
"%(cert_file)s. Ignoring." %
{"cert_file": cert_file})
continue
for content in c_list:
cert = {}
cert['X509Certificate'] = content
cert_list.append(cert)
if len(cert_list) == 0:
msg = (self._("No valid certificate in %(cert_file_list)s.") %
{"cert_file_list": cert_file_list})
LOG.debug(msg)
raise exception.IloError(msg)
cert_dict = {}
cert_dict['NewCertificates'] = cert_list
try:
(sushy_system.bios_settings.tls_config.
tls_config_settings.add_tls_certificate(cert_dict))
except sushy.exceptions.SushyError as e:
msg = (self._("The Redfish controller has failed to upload "
"TLS certificate. Error %(error)s") %
{'error': str(e)})
LOG.debug(msg)
raise exception.IloError(msg)
else:
msg = 'TLS certificate cannot be upload in BIOS boot mode'
raise exception.IloCommandNotSupportedInBiosError(msg)
def _get_fps_from_file(self, cert_file):
"""Gets the finger prints from the certificate file.
Parse the file passed in to get the certificates. For each certificate,
find the fingerprint by calculating the digest of base64 decoded
content. Finally return the list of the fingerprints.
:param cert_file: TLS certificate file containing one or more
certificates.
:return: Returns the list of FPs for the certificates in the file.
"""
fp_list = []
with open(cert_file, 'r') as f:
data = json.dumps(f.read())
p = re.sub(r"\"", "", data)
q = re.sub(r"\\n", "\r\n", p).rstrip()
c_list = re.findall(_CERTIFICATE_PATTERN, q, re.DOTALL)
if len(c_list) == 0:
LOG.warning("Could not find any valid certificate in "
"%(cert_file)s. Ignoring." %
{"cert_file": cert_file})
return fp_list
for content in c_list:
pem_lines = [line.strip() for line in (
content.strip().split('\n'))]
try:
der_data = b64decode(''.join(pem_lines[1:-1]))
except ValueError:
LOG.warning("Illegal base64 encountered "
"in the certificate.")
else:
cert = load_certificate(FILETYPE_ASN1, der_data)
fp = cert.digest('sha256').decode('ascii')
fp_list.append(fp)
return fp_list
def remove_tls_certificate(self, cert_file_list=[],
excl_cert_file_list=[]):
"""Removes the TLS CA certificates from the iLO.
:param cert_file_list: List of TLS CA certificate files
:param excl_cert_file_list: List of TLS CA certificate files to be
retained on the iLO. These certificates will not be
removed from the iLO.
:raises: IloError, on an error from iLO.
:raises: IloCommandNotSupportedError, if the command is
not supported on the server.
"""
sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)
if not self._is_boot_mode_uefi():
msg = 'TLS certificates cannot be removed in BIOS boot mode'
raise exception.IloCommandNotSupportedInBiosError(msg)
cert_dict = {}
del_cert_list = []
exc_fp_list = []
for exc_cert_file in excl_cert_file_list:
efp_list = self._get_fps_from_file(exc_cert_file)
exc_fp_list.extend(efp_list)
LOG.debug("Excluding certificates with FingerPrints: %(exc_fp_list)s",
{'exc_fp_list': exc_fp_list})
if not cert_file_list:
tls_certificates = (sushy_system.bios_settings.tls_config.
tls_certificates)
for cert in tls_certificates:
fp = cert.get("FingerPrint")
if fp not in exc_fp_list:
cert_fp = {
"FingerPrint": fp
}
del_cert_list.append(cert_fp)
else:
all_fp_list = []
for cert_file in cert_file_list:
afp_list = self._get_fps_from_file(cert_file)
all_fp_list.extend(afp_list)
final_fp_set = set(all_fp_list) - set(exc_fp_list)
for fp in final_fp_set:
cert_fp = {
"FingerPrint": fp
}
del_cert_list.append(cert_fp)
if len(del_cert_list) == 0:
msg = (self._("No valid certificate in %(cert_file_list)s.") %
{"cert_file_list": cert_file_list})
raise exception.IloError(msg)
cert_dict.update({"DeleteCertificates": del_cert_list})
try:
(sushy_system.bios_settings.tls_config.
tls_config_settings.remove_tls_certificate(cert_dict))
except sushy.exceptions.SushyError as e:
msg = (self._("The Redfish controller has failed to remove "
"TLS certificate. Error %(error)s") %
{'error': str(e)})
LOG.debug(msg)
raise exception.IloError(msg)
|