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
|
# Copyright 2011 Justin Santa Barbara
# Copyright 2012 Hewlett-Packard 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.
import base64
import errno
import glob
import io
import os
import shutil
import subprocess
import tarfile
import tempfile
import time
from unittest import mock
from oslo_concurrency import processutils
import requests
import testtools
from ironic_python_agent import errors
from ironic_python_agent import hardware
from ironic_python_agent.tests.unit import base
from ironic_python_agent import utils
@mock.patch('shutil.rmtree', autospec=True)
@mock.patch.object(utils, 'execute', autospec=True)
@mock.patch('tempfile.mkdtemp', autospec=True)
class MountedTestCase(base.IronicAgentTest):
def test_temporary(self, mock_temp, mock_execute, mock_rmtree):
with utils.mounted('/dev/fake') as path:
self.assertIs(path, mock_temp.return_value)
mock_execute.assert_has_calls([
mock.call("mount", '/dev/fake', mock_temp.return_value,
attempts=1, delay_on_retry=True),
mock.call("umount", mock_temp.return_value,
attempts=3, delay_on_retry=True),
])
mock_rmtree.assert_called_once_with(mock_temp.return_value)
def test_with_dest(self, mock_temp, mock_execute, mock_rmtree):
with utils.mounted('/dev/fake', '/mnt/fake') as path:
self.assertEqual('/mnt/fake', path)
mock_execute.assert_has_calls([
mock.call("mount", '/dev/fake', '/mnt/fake',
attempts=1, delay_on_retry=True),
mock.call("umount", '/mnt/fake',
attempts=3, delay_on_retry=True),
])
self.assertFalse(mock_temp.called)
self.assertFalse(mock_rmtree.called)
def test_with_opts(self, mock_temp, mock_execute, mock_rmtree):
with utils.mounted('/dev/fake', '/mnt/fake',
opts=['ro', 'foo=bar']) as path:
self.assertEqual('/mnt/fake', path)
mock_execute.assert_has_calls([
mock.call("mount", '/dev/fake', '/mnt/fake', '-o', 'ro,foo=bar',
attempts=1, delay_on_retry=True),
mock.call("umount", '/mnt/fake',
attempts=3, delay_on_retry=True),
])
def test_with_type(self, mock_temp, mock_execute, mock_rmtree):
with utils.mounted('/dev/fake', '/mnt/fake',
fs_type='iso9660') as path:
self.assertEqual('/mnt/fake', path)
mock_execute.assert_has_calls([
mock.call("mount", '/dev/fake', '/mnt/fake', '-t', 'iso9660',
attempts=1, delay_on_retry=True),
mock.call("umount", '/mnt/fake',
attempts=3, delay_on_retry=True),
])
def test_failed_to_mount(self, mock_temp, mock_execute, mock_rmtree):
mock_execute.side_effect = OSError
self.assertRaises(OSError, utils.mounted('/dev/fake').__enter__)
mock_execute.assert_called_once_with("mount", '/dev/fake',
mock_temp.return_value,
attempts=1,
delay_on_retry=True)
mock_rmtree.assert_called_once_with(mock_temp.return_value)
def test_failed_to_unmount(self, mock_temp, mock_execute, mock_rmtree):
mock_execute.side_effect = [('', ''),
processutils.ProcessExecutionError]
with utils.mounted('/dev/fake', '/mnt/fake') as path:
self.assertEqual('/mnt/fake', path)
mock_execute.assert_has_calls([
mock.call("mount", '/dev/fake', '/mnt/fake',
attempts=1, delay_on_retry=True),
mock.call("umount", '/mnt/fake',
attempts=3, delay_on_retry=True),
])
self.assertFalse(mock_rmtree.called)
class GetAgentParamsTestCase(base.IronicAgentTest):
@mock.patch('oslo_log.log.getLogger', autospec=True)
@mock.patch('builtins.open', autospec=True)
def test__read_params_from_file_fail(self, logger_mock, open_mock):
open_mock.side_effect = Exception
params = utils._read_params_from_file('file-path')
self.assertEqual({}, params)
@mock.patch('builtins.open', autospec=True)
def test__read_params_from_file(self, open_mock):
kernel_line = 'api-url=http://localhost:9999 baz foo=bar\n'
open_mock.return_value.__enter__ = lambda s: s
open_mock.return_value.__exit__ = mock.Mock()
read_mock = open_mock.return_value.read
read_mock.return_value = kernel_line
params = utils._read_params_from_file('file-path')
open_mock.assert_called_once_with('file-path')
read_mock.assert_called_once_with()
self.assertEqual('http://localhost:9999', params['api-url'])
self.assertEqual('bar', params['foo'])
self.assertNotIn('baz', params)
@mock.patch.object(utils, '_set_cached_params', autospec=True)
@mock.patch.object(utils, '_read_params_from_file', autospec=True)
@mock.patch.object(utils, '_get_cached_params', autospec=True)
def test_get_agent_params_kernel_cmdline(self, get_cache_mock,
read_params_mock,
set_cache_mock):
get_cache_mock.return_value = {}
expected_params = {'a': 'b'}
read_params_mock.return_value = expected_params
returned_params = utils.get_agent_params()
read_params_mock.assert_called_once_with('/proc/cmdline')
self.assertEqual(expected_params, returned_params)
set_cache_mock.assert_called_once_with(expected_params)
@mock.patch.object(utils, '_set_cached_params', autospec=True)
@mock.patch.object(utils, '_get_vmedia_params', autospec=True)
@mock.patch.object(utils, '_read_params_from_file', autospec=True)
@mock.patch.object(utils, '_get_cached_params', autospec=True)
def test_get_agent_params_vmedia(self, get_cache_mock,
read_params_mock,
get_vmedia_params_mock,
set_cache_mock):
get_cache_mock.return_value = {}
kernel_params = {'boot_method': 'vmedia'}
vmedia_params = {'a': 'b'}
expected_params = dict(
list(kernel_params.items()) + list(vmedia_params.items()))
read_params_mock.return_value = kernel_params
get_vmedia_params_mock.return_value = vmedia_params
returned_params = utils.get_agent_params()
read_params_mock.assert_called_once_with('/proc/cmdline')
self.assertEqual(expected_params, returned_params)
# Make sure information is cached
set_cache_mock.assert_called_once_with(expected_params)
@mock.patch.object(utils, '_set_cached_params', autospec=True)
@mock.patch.object(utils, '_get_cached_params', autospec=True)
def test_get_agent_params_from_cache(self, get_cache_mock,
set_cache_mock):
get_cache_mock.return_value = {'a': 'b'}
returned_params = utils.get_agent_params()
expected_params = {'a': 'b'}
self.assertEqual(expected_params, returned_params)
self.assertEqual(0, set_cache_mock.call_count)
@mock.patch('builtins.open', autospec=True)
@mock.patch.object(glob, 'glob', autospec=True)
def test__get_vmedia_device(self, glob_mock, open_mock):
glob_mock.return_value = ['/sys/class/block/sda/device/model',
'/sys/class/block/sdb/device/model',
'/sys/class/block/sdc/device/model']
fobj_mock = mock.MagicMock()
mock_file_handle = mock.MagicMock()
mock_file_handle.__enter__.return_value = fobj_mock
open_mock.return_value = mock_file_handle
fobj_mock.read.side_effect = ['scsi disk', Exception, 'Virtual Media']
vmedia_device_returned = utils._get_vmedia_device()
self.assertEqual('sdc', vmedia_device_returned)
@mock.patch.object(utils, 'execute', autospec=True)
def test__find_vmedia_device_by_labels_handles_exec_error(self,
execute_mock):
execute_mock.side_effect = processutils.ProcessExecutionError
self.assertIsNone(utils._find_vmedia_device_by_labels(['l1', 'l2']))
execute_mock.assert_called_once_with('lsblk', '-p', '-P',
'-oKNAME,LABEL')
@mock.patch.object(utils, 'execute', autospec=True)
def test__find_vmedia_device_by_labels(self, execute_mock):
# NOTE(TheJulia): Case is intentionally mixed here to ensure
# proper matching occurs
disk_list = ('KNAME="/dev/sda" LABEL=""\n'
'KNAME="/dev/sda2" LABEL="Meow"\n'
'KNAME="/dev/sda3" LABEL="Recovery HD"\n'
'KNAME="/dev/sda1" LABEL="EFI"\n'
'KNAME="/dev/sdb" LABEL=""\n'
'KNAME="/dev/sdb1" LABEL=""\n'
'KNAME="/dev/sdb2" LABEL=""\n'
'KNAME="/dev/sdc" LABEL="meow"\n')
invalid_disk = ('KNAME="sda1" SIZE="1610612736" TYPE="part" TRAN=""\n'
'KNAME="sda" SIZE="1610612736" TYPE="disk" '
'TRAN="sata"\n')
valid_disk = ('KNAME="sdc" SIZE="1610612736" TYPE="disk" TRAN="usb"\n')
execute_mock.side_effect = [
(disk_list, ''),
(invalid_disk, ''),
(valid_disk, ''),
]
self.assertEqual('/dev/sdc',
utils._find_vmedia_device_by_labels(['cat', 'meOw']))
execute_mock.assert_has_calls([
mock.call('lsblk', '-p', '-P', '-oKNAME,LABEL'),
mock.call('lsblk', '-n', '-s', '-P', '-b',
'-oKNAME,TRAN,TYPE,SIZE', '/dev/sda2'),
mock.call('lsblk', '-n', '-s', '-P', '-b',
'-oKNAME,TRAN,TYPE,SIZE', '/dev/sdc'),
])
@mock.patch.object(utils, 'execute', autospec=True)
def test__find_vmedia_device_by_labels_not_found(self, execute_mock):
disk_list = ('KNAME="/dev/sdb" LABEL="evil"\n'
'KNAME="/dev/sdb1" LABEL="banana"\n'
'KNAME="/dev/sdb2" LABEL=""\n')
execute_mock.return_value = (disk_list, '')
self.assertIsNone(utils._find_vmedia_device_by_labels(['l1', 'l2']))
execute_mock.assert_called_once_with('lsblk', '-p', '-P',
'-oKNAME,LABEL')
@mock.patch.object(utils, '_check_vmedia_device', autospec=True)
@mock.patch.object(utils, '_find_vmedia_device_by_labels', autospec=True)
@mock.patch.object(utils, '_read_params_from_file', autospec=True)
@mock.patch.object(utils, 'mounted', autospec=True)
def test__get_vmedia_params(self, mount_mock, read_params_mock, find_mock,
check_vmedia_mock):
check_vmedia_mock.return_value = True
find_mock.return_value = '/dev/fake'
mount_mock.return_value.__enter__.return_value = '/tempdir'
expected_params = {'a': 'b'}
read_params_mock.return_value = expected_params
returned_params = utils._get_vmedia_params()
mount_mock.assert_called_once_with('/dev/fake')
read_params_mock.assert_called_once_with("/tempdir/parameters.txt")
self.assertEqual(expected_params, returned_params)
@mock.patch.object(utils, '_check_vmedia_device', autospec=True)
@mock.patch.object(utils, '_find_vmedia_device_by_labels', autospec=True)
@mock.patch.object(utils, '_get_vmedia_device', autospec=True)
@mock.patch.object(utils, '_read_params_from_file', autospec=True)
@mock.patch.object(utils, 'mounted', autospec=True)
def test__get_vmedia_params_by_device(self, mount_mock, read_params_mock,
get_device_mock, find_mock,
check_vmedia_mock):
check_vmedia_mock.return_value = True
find_mock.return_value = None
mount_mock.return_value.__enter__.return_value = '/tempdir'
expected_params = {'a': 'b'}
read_params_mock.return_value = expected_params
get_device_mock.return_value = "sda"
returned_params = utils._get_vmedia_params()
mount_mock.assert_called_once_with('/dev/sda')
read_params_mock.assert_called_once_with("/tempdir/parameters.txt")
self.assertEqual(expected_params, returned_params)
check_vmedia_mock.assert_called_with('/dev/sda')
@mock.patch.object(utils, '_check_vmedia_device', autospec=True)
@mock.patch.object(utils, '_find_vmedia_device_by_labels', autospec=True)
@mock.patch.object(utils, '_get_vmedia_device', autospec=True)
@mock.patch.object(utils, '_read_params_from_file', autospec=True)
@mock.patch.object(utils, 'mounted', autospec=True)
def test__get_vmedia_params_by_device_device_invalid(
self, mount_mock, read_params_mock,
get_device_mock, find_mock,
check_vmedia_mock):
check_vmedia_mock.return_value = False
find_mock.return_value = None
expected_params = {}
read_params_mock.return_value = expected_params
get_device_mock.return_value = "sda"
returned_params = utils._get_vmedia_params()
mount_mock.assert_not_called()
read_params_mock.assert_not_called
self.assertEqual(expected_params, returned_params)
check_vmedia_mock.assert_called_with('/dev/sda')
@mock.patch.object(utils, '_find_vmedia_device_by_labels', autospec=True)
@mock.patch.object(utils, '_get_vmedia_device', autospec=True)
def test__get_vmedia_params_cannot_find_dev(self, get_device_mock,
find_mock):
find_mock.return_value = None
get_device_mock.return_value = None
self.assertEqual({}, utils._get_vmedia_params())
class TestFailures(testtools.TestCase):
def test_get_error(self):
f = utils.AccumulatedFailures()
self.assertFalse(f)
self.assertIsNone(f.get_error())
f.add('foo')
f.add('%s', 'bar')
f.add(RuntimeError('baz'))
self.assertTrue(f)
exp = ('The following errors were encountered:\n* foo\n* bar\n* baz')
self.assertEqual(exp, f.get_error())
def test_raise(self):
class FakeException(Exception):
pass
f = utils.AccumulatedFailures(exc_class=FakeException)
self.assertIsNone(f.raise_if_needed())
f.add('foo')
self.assertRaisesRegex(FakeException, 'foo', f.raise_if_needed)
class TestUtils(base.IronicAgentTest):
def _get_journalctl_output(self, mock_execute, lines=None, units=None):
contents = b'Krusty Krab'
mock_execute.return_value = (contents, '')
data = utils.get_journalctl_output(lines=lines, units=units)
cmd = ['journalctl', '--full', '--no-pager', '-b']
if lines is not None:
cmd.extend(['-n', str(lines)])
if units is not None:
[cmd.extend(['-u', u]) for u in units]
mock_execute.assert_called_once_with(*cmd, binary=True,
log_stdout=False)
self.assertEqual(contents, data.read())
@mock.patch.object(utils, 'execute', autospec=True)
def test_get_journalctl_output(self, mock_execute):
self._get_journalctl_output(mock_execute)
@mock.patch.object(utils, 'execute', autospec=True)
def test_get_journalctl_output_with_lines(self, mock_execute):
self._get_journalctl_output(mock_execute, lines=123)
@mock.patch.object(utils, 'execute', autospec=True)
def test_get_journalctl_output_with_units(self, mock_execute):
self._get_journalctl_output(mock_execute, units=['fake-unit1',
'fake-unit2'])
@mock.patch.object(utils, 'execute', autospec=True)
def test_get_journalctl_output_fail(self, mock_execute):
mock_execute.side_effect = processutils.ProcessExecutionError()
self.assertRaises(errors.CommandExecutionError,
self._get_journalctl_output, mock_execute)
def test_gzip_and_b64encode(self):
contents = b'Squidward Tentacles'
io_dict = {'fake-name': io.BytesIO(bytes(contents))}
data = utils.gzip_and_b64encode(io_dict=io_dict)
self.assertIsInstance(data, str)
res = io.BytesIO(base64.b64decode(data))
with tarfile.open(fileobj=res) as tar:
members = [(m.name, m.size) for m in tar]
self.assertEqual([('fake-name', len(contents))], members)
member = tar.extractfile('fake-name')
self.assertEqual(contents, member.read())
@mock.patch.object(utils, 'execute', autospec=True)
def test_get_command_output(self, mock_execute):
contents = b'Sandra Sandy Cheeks'
mock_execute.return_value = (contents, '')
data = utils.get_command_output(['foo'])
mock_execute.assert_called_once_with(
'foo', binary=True, log_stdout=False)
self.assertEqual(contents, data.read())
@mock.patch.object(subprocess, 'check_call', autospec=True)
def test_guess_root_disk_primary_sort(self, mock_call):
block_devices = [
hardware.BlockDevice(name='/dev/sdc',
model='too small',
size=4294967295,
rotational=True),
hardware.BlockDevice(name='/dev/sda',
model='bigger than sdb',
size=21474836480,
rotational=True),
hardware.BlockDevice(name='/dev/sdb',
model='',
size=10737418240,
rotational=True),
hardware.BlockDevice(name='/dev/sdd',
model='bigger than sdb',
size=21474836480,
rotational=True),
]
device = utils.guess_root_disk(block_devices)
self.assertEqual(device.name, '/dev/sdb')
@mock.patch.object(subprocess, 'check_call', autospec=True)
def test_guess_root_disk_secondary_sort(self, mock_call):
block_devices = [
hardware.BlockDevice(name='/dev/sdc',
model='_',
size=10737418240,
rotational=True),
hardware.BlockDevice(name='/dev/sdb',
model='_',
size=10737418240,
rotational=True),
hardware.BlockDevice(name='/dev/sda',
model='_',
size=10737418240,
rotational=True),
hardware.BlockDevice(name='/dev/sdd',
model='_',
size=10737418240,
rotational=True),
]
device = utils.guess_root_disk(block_devices)
self.assertEqual(device.name, '/dev/sda')
@mock.patch.object(subprocess, 'check_call', autospec=True)
def test_guess_root_disk_disks_too_small(self, mock_call):
block_devices = [
hardware.BlockDevice(name='/dev/sda',
model='too small',
size=4294967295,
rotational=True),
hardware.BlockDevice(name='/dev/sdb',
model='way too small',
size=1,
rotational=True),
]
self.assertRaises(errors.DeviceNotFound,
utils.guess_root_disk, block_devices)
@mock.patch.object(subprocess, 'check_call', autospec=True)
def test_is_journalctl_present(self, mock_call):
self.assertTrue(utils.is_journalctl_present())
@mock.patch.object(subprocess, 'check_call', autospec=True)
def test_is_journalctl_present_false(self, mock_call):
os_error = OSError()
os_error.errno = errno.ENOENT
mock_call.side_effect = os_error
self.assertFalse(utils.is_journalctl_present())
@mock.patch.object(utils, 'gzip_and_b64encode', autospec=True)
@mock.patch.object(hardware, 'dispatch_to_all_managers', autospec=True)
@mock.patch.object(utils, 'is_journalctl_present', autospec=True)
@mock.patch.object(utils, 'get_journalctl_output', autospec=True)
def test_collect_system_logs_journald(
self, mock_logs, mock_journalctl, mock_dispatch, mock_gzip_b64):
mock_journalctl.return_value = True
ret = 'Patrick Star'
mock_gzip_b64.return_value = ret
logs_string = utils.collect_system_logs()
self.assertEqual(ret, logs_string)
mock_logs.assert_called_once_with(lines=None)
mock_gzip_b64.assert_called_once_with(
io_dict=mock.ANY, file_list=[])
mock_dispatch.assert_called_once_with('collect_system_logs',
mock.ANY, [])
@mock.patch.object(utils, 'gzip_and_b64encode', autospec=True)
@mock.patch.object(hardware, 'dispatch_to_all_managers', autospec=True)
@mock.patch.object(utils, 'is_journalctl_present', autospec=True)
@mock.patch.object(utils, 'get_journalctl_output', autospec=True)
def test_collect_system_logs_journald_with_logfile(
self, mock_logs, mock_journalctl, mock_dispatch, mock_gzip_b64):
tmp = tempfile.NamedTemporaryFile()
self.addCleanup(lambda: tmp.close())
self.config(log_file=tmp.name)
mock_journalctl.return_value = True
ret = 'Patrick Star'
mock_gzip_b64.return_value = ret
logs_string = utils.collect_system_logs()
self.assertEqual(ret, logs_string)
mock_logs.assert_called_once_with(lines=None)
mock_gzip_b64.assert_called_once_with(
io_dict=mock.ANY, file_list=[tmp.name])
mock_dispatch.assert_called_once_with('collect_system_logs',
mock.ANY, [tmp.name])
@mock.patch.object(utils, 'gzip_and_b64encode', autospec=True)
@mock.patch.object(hardware, 'dispatch_to_all_managers', autospec=True)
@mock.patch.object(utils, 'is_journalctl_present', autospec=True)
def test_collect_system_logs_non_journald(
self, mock_journalctl, mock_dispatch, mock_gzip_b64):
mock_journalctl.return_value = False
ret = 'SpongeBob SquarePants'
mock_gzip_b64.return_value = ret
logs_string = utils.collect_system_logs()
self.assertEqual(ret, logs_string)
mock_gzip_b64.assert_called_once_with(
io_dict=mock.ANY, file_list=['/var/log'])
mock_dispatch.assert_called_once_with('collect_system_logs',
mock.ANY, ['/var/log'])
@mock.patch.object(utils, 'gzip_and_b64encode', autospec=True)
@mock.patch.object(hardware, 'dispatch_to_all_managers', autospec=True)
@mock.patch.object(utils, 'is_journalctl_present', autospec=True)
def test_collect_system_logs_non_journald_with_logfile(
self, mock_journalctl, mock_dispatch, mock_gzip_b64):
tmp = tempfile.NamedTemporaryFile()
self.addCleanup(lambda: tmp.close())
self.config(log_file=tmp.name)
mock_journalctl.return_value = False
ret = 'SpongeBob SquarePants'
mock_gzip_b64.return_value = ret
logs_string = utils.collect_system_logs()
self.assertEqual(ret, logs_string)
mock_gzip_b64.assert_called_once_with(
io_dict=mock.ANY, file_list=['/var/log', tmp.name])
mock_dispatch.assert_called_once_with('collect_system_logs',
mock.ANY, ['/var/log', tmp.name])
def test_get_ssl_client_options(self):
# defaults
conf = mock.Mock(insecure=False, cafile=None,
keyfile=None, certfile=None)
self.assertEqual((True, None), utils.get_ssl_client_options(conf))
# insecure=True overrides cafile
conf = mock.Mock(insecure=True, cafile='spam',
keyfile=None, certfile=None)
self.assertEqual((False, None), utils.get_ssl_client_options(conf))
# cafile returned as verify when not insecure
conf = mock.Mock(insecure=False, cafile='spam',
keyfile=None, certfile=None)
self.assertEqual(('spam', None), utils.get_ssl_client_options(conf))
# only both certfile and keyfile produce non-None result
conf = mock.Mock(insecure=False, cafile=None,
keyfile=None, certfile='ham')
self.assertEqual((True, None), utils.get_ssl_client_options(conf))
conf = mock.Mock(insecure=False, cafile=None,
keyfile='ham', certfile=None)
self.assertEqual((True, None), utils.get_ssl_client_options(conf))
conf = mock.Mock(insecure=False, cafile=None,
keyfile='spam', certfile='ham')
self.assertEqual((True, ('ham', 'spam')),
utils.get_ssl_client_options(conf))
def test_device_extractor(self):
self.assertEqual(
'md0',
utils.extract_device('md0p1')
)
self.assertEqual(
'/dev/md0',
utils.extract_device('/dev/md0p1')
)
self.assertEqual(
'sda',
utils.extract_device('sda12')
)
self.assertEqual(
'/dev/sda',
utils.extract_device('/dev/sda12')
)
self.assertEqual(
'nvme0n1',
utils.extract_device('nvme0n1p12')
)
self.assertEqual(
'/dev/nvme0n1',
utils.extract_device('/dev/nvme0n1p12')
)
self.assertEqual(
'/dev/hello',
utils.extract_device('/dev/hello42')
)
self.assertIsNone(
utils.extract_device('/dev/sda')
)
self.assertIsNone(
utils.extract_device('whatevernotmatchin12a')
)
def test_extract_capability_from_dict(self):
expected_dict = {"hello": "world"}
root = {"capabilities": expected_dict}
self.assertDictEqual(
expected_dict,
utils.parse_capabilities(root))
def test_extract_capability_from_json_string(self):
root = {'capabilities': '{"test": "world"}'}
self.assertDictEqual(
{"test": "world"},
utils.parse_capabilities(root))
def test_extract_capability_from_old_format_caps(self):
root = {'capabilities': 'test:world:2,hello:test1,badformat'}
self.assertDictEqual(
{'hello': 'test1'},
utils.parse_capabilities(root))
@mock.patch.object(os.path, 'isdir', return_value=True, autospec=True)
def test_boot_mode_fallback_uefi(self, mock_os):
node = {}
boot_mode = utils.get_node_boot_mode(node)
self.assertEqual('uefi', boot_mode)
mock_os.assert_called_once_with('/sys/firmware/efi')
@mock.patch.object(os.path, 'isdir', return_value=False, autospec=True)
def test_boot_mode_fallback_bios(self, mock_os):
node = {}
boot_mode = utils.get_node_boot_mode(node)
self.assertEqual('bios', boot_mode)
mock_os.assert_called_once_with('/sys/firmware/efi')
@mock.patch.object(os.path, 'isdir', return_value=False, autospec=True)
def test_boot_mode_from_driver_internal_info(self, mock_os):
node = {
'driver_internal_info': {
'deploy_boot_mode': 'uefi'
},
}
boot_mode = utils.get_node_boot_mode(node)
self.assertEqual('uefi', boot_mode)
mock_os.assert_called_once_with('/sys/firmware/efi')
@mock.patch.object(os.path, 'isdir', return_value=False, autospec=True)
def test_boot_mode_from_properties_str(self, mock_os):
node = {
'driver_internal_info': {
'deploy_boot_mode': 'bios'
},
'properties': {
'capabilities': 'boot_mode:uefi'
}
}
boot_mode = utils.get_node_boot_mode(node)
self.assertEqual('uefi', boot_mode)
mock_os.assert_called_once_with('/sys/firmware/efi')
@mock.patch.object(os.path, 'isdir', return_value=False, autospec=True)
def test_boot_mode_from_properties_dict(self, mock_os):
node = {
'driver_internal_info': {
'deploy_boot_mode': 'bios'
},
'properties': {
'capabilities': {
'boot_mode': 'uefi'
}
}
}
boot_mode = utils.get_node_boot_mode(node)
self.assertEqual('uefi', boot_mode)
mock_os.assert_called_once_with('/sys/firmware/efi')
@mock.patch.object(os.path, 'isdir', return_value=False, autospec=True)
def test_boot_mode_from_properties_json_str(self, mock_os):
node = {
'driver_internal_info': {
'deploy_boot_mode': 'bios'
},
'properties': {
'capabilities': '{"boot_mode": "uefi"}'
}
}
boot_mode = utils.get_node_boot_mode(node)
self.assertEqual('uefi', boot_mode)
mock_os.assert_called_once_with('/sys/firmware/efi')
@mock.patch.object(os.path, 'isdir', return_value=False, autospec=True)
def test_boot_mode_override_with_instance_info(self, mock_os):
node = {
'driver_internal_info': {
'deploy_boot_mode': 'bios'
},
'properties': {
'capabilities': {
'boot_mode': 'bios'
}
},
'instance_info': {
'deploy_boot_mode': 'uefi'
}
}
boot_mode = utils.get_node_boot_mode(node)
self.assertEqual('uefi', boot_mode)
mock_os.assert_called_once_with('/sys/firmware/efi')
@mock.patch.object(os.path, 'isdir', return_value=False, autospec=True)
def test_boot_mode_implicit_with_secure_boot(self, mock_os):
node = {
'driver_internal_info': {
'deploy_boot_mode': 'bios'
},
'properties': {
'capabilities': {
'boot_mode': 'bios',
'secure_boot': 'TrUe'
}
},
'instance_info': {
'deploy_boot_mode': 'bios'
}
}
boot_mode = utils.get_node_boot_mode(node)
self.assertEqual('uefi', boot_mode)
mock_os.assert_has_calls([])
@mock.patch.object(os.path, 'isdir', return_value=False, autospec=True)
def test_secure_boot_overriden_with_instance_info_caps(self, mock_os):
node = {
'driver_internal_info': {
'deploy_boot_mode': 'bios'
},
'properties': {
'capabilities': {
'boot_mode': 'bios',
'secure_boot': 'false'
}
},
'instance_info': {
'deploy_boot_mode': 'bios',
'capabilities': {
'secure_boot': 'true'
}
}
}
boot_mode = utils.get_node_boot_mode(node)
self.assertEqual('uefi', boot_mode)
mock_os.assert_has_calls([])
@mock.patch.object(os.path, 'isdir', return_value=True, autospec=True)
def test_boot_mode_invalid_cap(self, mock_os):
# In case of invalid boot mode specified we fallback to ramdisk boot
# mode
node = {
'driver_internal_info': {
'deploy_boot_mode': 'bios'
},
'properties': {
'capabilities': {
'boot_mode': 'sfkshfks'
}
}
}
boot_mode = utils.get_node_boot_mode(node)
self.assertEqual('uefi', boot_mode)
mock_os.assert_called_once_with('/sys/firmware/efi')
@mock.patch.object(utils, 'get_node_boot_mode', return_value='bios',
autospec=True)
def test_specified_partition_table_type(self, mock_boot_mode):
node = {}
label = utils.get_partition_table_type_from_specs(node)
self.assertEqual('msdos', label)
mock_boot_mode.assert_called_once_with(node)
@mock.patch.object(utils, 'get_node_boot_mode', return_value='uefi',
autospec=True)
def test_specified_partition_table_type_gpt(self, mock_boot_mode):
node = {}
label = utils.get_partition_table_type_from_specs(node)
self.assertEqual('gpt', label)
mock_boot_mode.assert_called_once_with(node)
@mock.patch.object(utils, 'get_node_boot_mode', return_value='bios',
autospec=True)
def test_specified_partition_table_type_with_disk_label(self,
mock_boot_mode):
node = {
'properties': {
'capabilities': 'disk_label:gpt'
}
}
label = utils.get_partition_table_type_from_specs(node)
self.assertEqual('gpt', label)
mock_boot_mode.assert_has_calls([])
@mock.patch.object(utils, 'get_node_boot_mode', return_value='bios',
autospec=True)
def test_specified_partition_table_type_with_instance_disk_label(
self, mock_boot_mode):
# In case of invalid boot mode specified we fallback to ramdisk boot
# mode
node = {
'instance_info': {
'capabilities': 'disk_label:gpt'
}
}
label = utils.get_partition_table_type_from_specs(node)
self.assertEqual('gpt', label)
mock_boot_mode.assert_has_calls([])
@mock.patch.object(utils, 'get_node_boot_mode', return_value='uefi',
autospec=True)
def test_specified_partition_table_type_disk_label_ignored_with_uefi(
self, mock_boot_mode):
# In case of invalid boot mode specified we fallback to ramdisk boot
# mode
node = {
'instance_info': {
'capabilities': 'disk_label:msdos'
}
}
label = utils.get_partition_table_type_from_specs(node)
self.assertEqual('gpt', label)
mock_boot_mode.assert_has_calls([])
class TestRemoveKeys(testtools.TestCase):
def test_remove_keys(self):
value = {'system_logs': 'abcd',
'key': 'value',
'other': [{'configdrive': 'foo'}, 'string', 0]}
expected = {'system_logs': '<...>',
'key': 'value',
'other': [{'configdrive': '<...>'}, 'string', 0]}
self.assertEqual(expected, utils.remove_large_keys(value))
@mock.patch.object(utils, 'execute', autospec=True)
class TestClockSyncUtils(base.IronicAgentTest):
def test_determine_time_method_none(self, mock_execute):
mock_execute.side_effect = OSError
self.assertIsNone(utils.determine_time_method())
def test_determine_time_method_ntpdate(self, mock_execute):
mock_execute.side_effect = [
OSError, # No chronyd found
('', ''), # Returns nothing on ntpdate call
]
calls = [mock.call('chronyd', '-h'),
mock.call('ntpdate', '-v', check_exit_code=[0, 1])]
return_value = utils.determine_time_method()
self.assertEqual('ntpdate', return_value)
mock_execute.assert_has_calls(calls)
def test_determine_time_method_chronyd(self, mock_execute):
mock_execute.side_effect = [
('', ''), # Returns nothing on ntpdate call
]
calls = [mock.call('chronyd', '-h')]
return_value = utils.determine_time_method()
self.assertEqual('chronyd', return_value)
mock_execute.assert_has_calls(calls)
@mock.patch.object(utils, 'determine_time_method', autospec=True)
def test_sync_clock_ntp(self, mock_time_method, mock_execute):
self.config(ntp_server='192.168.1.1')
mock_time_method.return_value = 'ntpdate'
utils.sync_clock()
mock_execute.assert_has_calls([mock.call('ntpdate', '192.168.1.1')])
@mock.patch.object(utils, 'determine_time_method', autospec=True)
def test_sync_clock_ntp_raises_exception(self, mock_time_method,
mock_execute):
self.config(ntp_server='192.168.1.1')
self.config(fail_if_clock_not_set=True)
mock_time_method.return_value = 'ntpdate'
mock_execute.side_effect = processutils.ProcessExecutionError()
self.assertRaises(errors.CommandExecutionError, utils.sync_clock)
@mock.patch.object(utils, 'determine_time_method', autospec=True)
def test_sync_clock_chrony(self, mock_time_method, mock_execute):
self.config(ntp_server='192.168.1.1')
mock_time_method.return_value = 'chronyd'
utils.sync_clock()
mock_execute.assert_has_calls([
mock.call('chronyc', 'shutdown', check_exit_code=[0, 1]),
mock.call("chronyd -q 'server 192.168.1.1 iburst'", shell=True),
])
@mock.patch.object(utils, 'determine_time_method', autospec=True)
def test_sync_clock_chrony_failure(self, mock_time_method, mock_execute):
self.config(ntp_server='192.168.1.1')
self.config(fail_if_clock_not_set=True)
mock_time_method.return_value = 'chronyd'
mock_execute.side_effect = [
('', ''),
processutils.ProcessExecutionError(stderr='time verboten'),
]
self.assertRaisesRegex(errors.CommandExecutionError,
'Failed to sync time using chrony to ntp '
'server:', utils.sync_clock)
@mock.patch.object(utils, 'determine_time_method', autospec=True)
def test_sync_clock_none(self, mock_time_method, mock_execute):
self.config(ntp_server='192.168.1.1')
mock_time_method.return_value = None
utils.sync_clock(ignore_errors=True)
self.assertEqual(0, mock_execute.call_count)
@mock.patch.object(utils, 'determine_time_method', autospec=True)
def test_sync_clock_ntp_server_is_none(self, mock_time_method,
mock_execute):
self.config(ntp_server=None)
mock_time_method.return_value = None
utils.sync_clock()
self.assertEqual(0, mock_execute.call_count)
@mock.patch.object(utils, '_unmount_any_config_drives', autospec=True)
@mock.patch.object(utils, '_booted_from_vmedia', autospec=True)
@mock.patch.object(utils, '_check_vmedia_device', autospec=True)
@mock.patch.object(utils, '_find_vmedia_device_by_labels', autospec=True)
@mock.patch.object(shutil, 'copy', autospec=True)
@mock.patch.object(utils, 'mounted', autospec=True)
@mock.patch.object(utils, 'execute', autospec=True)
class TestCopyConfigFromVmedia(testtools.TestCase):
def test_vmedia_found_not_booted_from_vmedia(
self, mock_execute, mock_mount, mock_copy,
mock_find_device, mock_check_vmedia, mock_booted_from_vmedia,
mock_unmount_config):
mock_booted_from_vmedia.return_value = False
mock_find_device.return_value = '/dev/fake'
utils.copy_config_from_vmedia()
mock_mount.assert_not_called()
mock_execute.assert_not_called()
mock_copy.assert_not_called()
mock_check_vmedia.assert_not_called()
self.assertTrue(mock_booted_from_vmedia.called)
self.assertTrue(mock_unmount_config.called)
def test_no_vmedia(
self, mock_execute, mock_mount, mock_copy,
mock_find_device, mock_check_vmedia, mock_booted_from_vmedia,
mock_unmount_config):
mock_booted_from_vmedia.return_value = True
mock_find_device.return_value = None
utils.copy_config_from_vmedia()
mock_mount.assert_not_called()
mock_execute.assert_not_called()
mock_copy.assert_not_called()
mock_check_vmedia.assert_not_called()
self.assertFalse(mock_booted_from_vmedia.called)
self.assertTrue(mock_unmount_config.called)
def test_no_files(
self, mock_execute, mock_mount, mock_copy,
mock_find_device, mock_check_vmedia, mock_booted_from_vmedia,
mock_unmount_config):
mock_booted_from_vmedia.return_value = True
temp_path = tempfile.mkdtemp()
self.addCleanup(lambda: shutil.rmtree(temp_path))
mock_execute.side_effect = processutils.ProcessExecutionError
mock_find_device.return_value = '/dev/something'
mock_mount.return_value.__enter__.return_value = temp_path
utils.copy_config_from_vmedia()
mock_mount.assert_called_once_with('/dev/something')
mock_execute.assert_called_once_with('findmnt', '-n', '-oTARGET',
'/dev/something')
mock_copy.assert_not_called()
self.assertTrue(mock_booted_from_vmedia.called)
self.assertTrue(mock_unmount_config.called)
def test_mounted_no_files(
self, mock_execute, mock_mount, mock_copy,
mock_find_device, mock_check_vmedia, mock_booted_from_vmedia,
mock_unmount_config):
mock_booted_from_vmedia.return_value = True
mock_execute.return_value = '/some/path', ''
mock_find_device.return_value = '/dev/something'
utils.copy_config_from_vmedia()
mock_execute.assert_called_once_with(
'findmnt', '-n', '-oTARGET', '/dev/something')
mock_copy.assert_not_called()
mock_mount.assert_not_called()
self.assertTrue(mock_booted_from_vmedia.called)
self.assertTrue(mock_unmount_config.called)
@mock.patch.object(os, 'makedirs', autospec=True)
def test_copy(
self, mock_makedirs, mock_execute, mock_mount, mock_copy,
mock_find_device, mock_check_vmedia, mock_booted_from_vmedia,
mock_unmount_config):
mock_booted_from_vmedia.return_value = True
mock_find_device.return_value = '/dev/something'
mock_execute.side_effect = processutils.ProcessExecutionError("")
path = tempfile.mkdtemp()
self.addCleanup(lambda: shutil.rmtree(path))
def _fake_mount(dev):
self.assertEqual('/dev/something', dev)
# NOTE(dtantsur): makedirs is mocked
os.mkdir(os.path.join(path, 'etc'))
os.mkdir(os.path.join(path, 'etc', 'ironic-python-agent'))
os.mkdir(os.path.join(path, 'etc', 'ironic-python-agent.d'))
with open(os.path.join(path, 'not copied'), 'wt') as fp:
fp.write('not copied')
with open(os.path.join(path, 'etc', 'ironic-python-agent',
'ironic.crt'), 'wt') as fp:
fp.write('I am a cert')
with open(os.path.join(path, 'etc', 'ironic-python-agent.d',
'ironic.conf'), 'wt') as fp:
fp.write('I am a config')
return mock.MagicMock(**{'__enter__.return_value': path})
mock_find_device.return_value = '/dev/something'
mock_mount.side_effect = _fake_mount
utils.copy_config_from_vmedia()
mock_makedirs.assert_has_calls([
mock.call('/etc/ironic-python-agent', exist_ok=True),
mock.call('/etc/ironic-python-agent.d', exist_ok=True),
], any_order=True)
mock_mount.assert_called_once_with('/dev/something')
mock_copy.assert_has_calls([
mock.call(mock.ANY, '/etc/ironic-python-agent/ironic.crt'),
mock.call(mock.ANY, '/etc/ironic-python-agent.d/ironic.conf'),
], any_order=True)
self.assertTrue(mock_booted_from_vmedia.called)
self.assertTrue(mock_unmount_config.called)
@mock.patch.object(os, 'makedirs', autospec=True)
def test_copy_mounted(
self, mock_makedirs, mock_execute, mock_mount,
mock_copy, mock_find_device, mock_check_vmedia,
mock_booted_from_vmedia,
mock_unmount_config):
mock_booted_from_vmedia.return_value = True
mock_find_device.return_value = '/dev/something'
path = tempfile.mkdtemp()
self.addCleanup(lambda: shutil.rmtree(path))
# NOTE(dtantsur): makedirs is mocked
os.mkdir(os.path.join(path, 'etc'))
os.mkdir(os.path.join(path, 'etc', 'ironic-python-agent'))
os.mkdir(os.path.join(path, 'etc', 'ironic-python-agent.d'))
with open(os.path.join(path, 'not copied'), 'wt') as fp:
fp.write('not copied')
with open(os.path.join(path, 'etc', 'ironic-python-agent',
'ironic.crt'), 'wt') as fp:
fp.write('I am a cert')
with open(os.path.join(path, 'etc', 'ironic-python-agent.d',
'ironic.conf'), 'wt') as fp:
fp.write('I am a config')
mock_execute.return_value = path, ''
mock_find_device.return_value = '/dev/something'
utils.copy_config_from_vmedia()
mock_makedirs.assert_has_calls([
mock.call('/etc/ironic-python-agent', exist_ok=True),
mock.call('/etc/ironic-python-agent.d', exist_ok=True),
], any_order=True)
mock_execute.assert_called_once_with(
'findmnt', '-n', '-oTARGET', '/dev/something')
mock_copy.assert_has_calls([
mock.call(mock.ANY, '/etc/ironic-python-agent/ironic.crt'),
mock.call(mock.ANY, '/etc/ironic-python-agent.d/ironic.conf'),
], any_order=True)
mock_mount.assert_not_called()
self.assertTrue(mock_booted_from_vmedia.called)
self.assertTrue(mock_unmount_config.called)
@mock.patch.object(requests, 'get', autospec=True)
class TestStreamingClient(base.IronicAgentTest):
def test_ok(self, mock_get):
client = utils.StreamingClient()
self.assertTrue(client.verify)
self.assertIsNone(client.cert)
with client("http://url") as result:
response = mock_get.return_value.__enter__.return_value
self.assertIs(result, response.iter_content.return_value)
mock_get.assert_called_once_with("http://url", verify=True, cert=None,
stream=True, timeout=60)
response.iter_content.assert_called_once_with(1024 * 1024)
def test_retries(self, mock_get):
self.config(image_download_connection_retries=1,
image_download_connection_retry_interval=1)
mock_get.side_effect = requests.ConnectionError
client = utils.StreamingClient()
self.assertRaises(errors.CommandExecutionError,
client("http://url").__enter__)
mock_get.assert_called_with("http://url", verify=True, cert=None,
stream=True, timeout=60)
self.assertEqual(2, mock_get.call_count)
class TestCheckVirtualMedia(base.IronicAgentTest):
@mock.patch.object(utils, 'execute', autospec=True)
def test_check_vmedia_device(self, mock_execute):
lsblk = 'KNAME="sdh" SIZE="1610612736" TYPE="disk" TRAN="usb"\n'
mock_execute.return_value = (lsblk, '')
self.assertTrue(utils._check_vmedia_device('/dev/sdh'))
mock_execute.assert_called_with('lsblk', '-n', '-s', '-P', '-b',
'-oKNAME,TRAN,TYPE,SIZE',
'/dev/sdh')
@mock.patch.object(utils, 'execute', autospec=True)
def test_check_vmedia_device_rom(self, mock_execute):
lsblk = 'KNAME="sr0" SIZE="1610612736" TYPE="rom" TRAN="usb"\n'
mock_execute.return_value = (lsblk, '')
self.assertTrue(utils._check_vmedia_device('/dev/sr0'))
mock_execute.assert_called_with('lsblk', '-n', '-s', '-P', '-b',
'-oKNAME,TRAN,TYPE,SIZE',
'/dev/sr0')
@mock.patch.object(utils, 'execute', autospec=True)
def test_check_vmedia_device_too_large(self, mock_execute):
lsblk = 'KNAME="sdh" SIZE="1610612736000" TYPE="disk" TRAN="usb"\n'
mock_execute.return_value = (lsblk, '')
self.assertFalse(utils._check_vmedia_device('/dev/sdh'))
mock_execute.assert_called_with('lsblk', '-n', '-s', '-P', '-b',
'-oKNAME,TRAN,TYPE,SIZE',
'/dev/sdh')
@mock.patch.object(utils, 'execute', autospec=True)
def test_check_vmedia_device_part(self, mock_execute):
lsblk = ('KNAME="sdh1" SIZE="1610612736" TYPE="part" TRAN=""\n'
'KNAME="sdh" SIZE="1610612736" TYPE="disk" TRAN="sata"\n')
mock_execute.return_value = (lsblk, '')
self.assertFalse(utils._check_vmedia_device('/dev/sdh1'))
mock_execute.assert_called_with('lsblk', '-n', '-s', '-P', '-b',
'-oKNAME,TRAN,TYPE,SIZE',
'/dev/sdh1')
@mock.patch.object(utils, 'execute', autospec=True)
def test_check_vmedia_device_other(self, mock_execute):
lsblk = 'KNAME="sdh" SIZE="1610612736" TYPE="other" TRAN="usb"\n'
mock_execute.return_value = (lsblk, '')
self.assertFalse(utils._check_vmedia_device('/dev/sdh'))
mock_execute.assert_called_with('lsblk', '-n', '-s', '-P', '-b',
'-oKNAME,TRAN,TYPE,SIZE',
'/dev/sdh')
@mock.patch.object(utils, 'execute', autospec=True)
def test_check_vmedia_device_sata(self, mock_execute):
lsblk = 'KNAME="sdh" SIZE="1610612736" TYPE="disk" TRAN="sata"\n'
mock_execute.return_value = (lsblk, '')
self.assertFalse(utils._check_vmedia_device('/dev/sdh'))
mock_execute.assert_called_with('lsblk', '-n', '-s', '-P', '-b',
'-oKNAME,TRAN,TYPE,SIZE',
'/dev/sdh')
@mock.patch.object(utils, 'execute', autospec=True)
def test_check_vmedia_device_scsi(self, mock_execute):
lsblk = 'KNAME="sdh" SIZE="1610612736" TYPE="other" TRAN="scsi"\n'
mock_execute.return_value = (lsblk, '')
self.assertFalse(utils._check_vmedia_device('/dev/sdh'))
mock_execute.assert_called_with('lsblk', '-n', '-s', '-P', '-b',
'-oKNAME,TRAN,TYPE,SIZE',
'/dev/sdh')
class TestCheckEarlyLogging(base.IronicAgentTest):
@mock.patch.object(utils, 'LOG', autospec=True)
def test_early_logging_goes_to_logger(self, mock_log):
info = mock.Mock()
mock_log.info.side_effect = info
# Reset the buffer to be empty.
utils._EARLY_LOG_BUFFER = []
# Store some data via _early_log
utils._early_log('line 1.')
utils._early_log('line 2 %s', 'message')
expected_messages = ['line 1.',
'line 2 message']
self.assertEqual(expected_messages, utils._EARLY_LOG_BUFFER)
# Test we've got data in the buffer.
info.assert_not_called()
# Test the other half of this.
utils.log_early_log_to_logger()
expected_calls = [mock.call('Early logging: %s', 'line 1.'),
mock.call('Early logging: %s', 'line 2 message')]
info.assert_has_calls(expected_calls)
class TestUnmountOfConfig(base.IronicAgentTest):
@mock.patch.object(utils, '_early_log', autospec=True)
@mock.patch.object(os.path, 'ismount', autospec=True)
@mock.patch.object(utils, 'execute', autospec=True)
@mock.patch.object(time, 'sleep', autospec=True)
def test__unmount_any_config_drives(self, mock_sleep, mock_exec,
mock_ismount, mock_log,):
mock_ismount.side_effect = iter([True, True, False])
utils._unmount_any_config_drives()
self.assertEqual(2, mock_sleep.call_count)
self.assertEqual(2, mock_log.call_count)
mock_exec.assert_has_calls([
mock.call('umount', '/mnt/config'),
mock.call('umount', '/mnt/config')])
class BareMetalUtilsTestCase(base.IronicAgentTest):
def test_unlink(self):
with mock.patch.object(os, "unlink", autospec=True) as unlink_mock:
unlink_mock.return_value = None
utils.unlink_without_raise("/fake/path")
unlink_mock.assert_called_once_with("/fake/path")
def test_unlink_ENOENT(self):
with mock.patch.object(os, "unlink", autospec=True) as unlink_mock:
unlink_mock.side_effect = OSError(errno.ENOENT)
utils.unlink_without_raise("/fake/path")
unlink_mock.assert_called_once_with("/fake/path")
class ExecuteTestCase(base.IronicAgentTest):
# Allow calls to utils.execute() and related functions
block_execute = False
@mock.patch.object(processutils, 'execute', autospec=True)
@mock.patch.object(os.environ, 'copy', return_value={}, autospec=True)
def test_execute_use_standard_locale_no_env_variables(self, env_mock,
execute_mock):
utils.execute('foo', use_standard_locale=True)
execute_mock.assert_called_once_with('foo',
env_variables={'LC_ALL': 'C'})
@mock.patch.object(processutils, 'execute', autospec=True)
def test_execute_use_standard_locale_with_env_variables(self,
execute_mock):
utils.execute('foo', use_standard_locale=True,
env_variables={'foo': 'bar'})
execute_mock.assert_called_once_with('foo',
env_variables={'LC_ALL': 'C',
'foo': 'bar'})
@mock.patch.object(processutils, 'execute', autospec=True)
def test_execute_not_use_standard_locale(self, execute_mock):
utils.execute('foo', use_standard_locale=False,
env_variables={'foo': 'bar'})
execute_mock.assert_called_once_with('foo',
env_variables={'foo': 'bar'})
@mock.patch.object(utils, 'LOG', autospec=True)
def _test_execute_with_log_stdout(self, log_mock, log_stdout=None):
with mock.patch.object(
processutils, 'execute', autospec=True) as execute_mock:
execute_mock.return_value = ('stdout', 'stderr')
if log_stdout is not None:
utils.execute('foo', log_stdout=log_stdout)
else:
utils.execute('foo')
execute_mock.assert_called_once_with('foo')
name, args, kwargs = log_mock.debug.mock_calls[0]
if log_stdout is False:
self.assertEqual(1, log_mock.debug.call_count)
self.assertNotIn('stdout', args[0])
else:
self.assertEqual(2, log_mock.debug.call_count)
self.assertIn('stdout', args[0])
def test_execute_with_log_stdout_default(self):
self._test_execute_with_log_stdout()
def test_execute_with_log_stdout_true(self):
self._test_execute_with_log_stdout(log_stdout=True)
def test_execute_with_log_stdout_false(self):
self._test_execute_with_log_stdout(log_stdout=False)
@mock.patch.object(utils, 'LOG', autospec=True)
@mock.patch.object(processutils, 'execute', autospec=True)
def test_execute_command_not_found(self, execute_mock, log_mock):
execute_mock.side_effect = FileNotFoundError
self.assertRaises(FileNotFoundError, utils.execute, 'foo')
execute_mock.assert_called_once_with('foo')
name, args, kwargs = log_mock.debug.mock_calls[0]
self.assertEqual(1, log_mock.debug.call_count)
self.assertIn('not found', args[0])
class MkfsTestCase(base.IronicAgentTest):
@mock.patch.object(utils, 'execute', autospec=True)
def test_mkfs(self, execute_mock):
utils.mkfs('ext4', '/my/block/dev')
utils.mkfs('msdos', '/my/msdos/block/dev')
utils.mkfs('swap', '/my/swap/block/dev')
expected = [mock.call('mkfs', '-t', 'ext4', '-F', '/my/block/dev',
use_standard_locale=True),
mock.call('mkfs', '-t', 'msdos', '/my/msdos/block/dev',
use_standard_locale=True),
mock.call('mkswap', '/my/swap/block/dev',
use_standard_locale=True)]
self.assertEqual(expected, execute_mock.call_args_list)
@mock.patch.object(utils, 'execute', autospec=True)
def test_mkfs_with_label(self, execute_mock):
utils.mkfs('ext4', '/my/block/dev', 'ext4-vol')
utils.mkfs('msdos', '/my/msdos/block/dev', 'msdos-vol')
utils.mkfs('swap', '/my/swap/block/dev', 'swap-vol')
expected = [mock.call('mkfs', '-t', 'ext4', '-F', '-L', 'ext4-vol',
'/my/block/dev',
use_standard_locale=True),
mock.call('mkfs', '-t', 'msdos', '-n', 'msdos-vol',
'/my/msdos/block/dev',
use_standard_locale=True),
mock.call('mkswap', '-L', 'swap-vol',
'/my/swap/block/dev',
use_standard_locale=True)]
self.assertEqual(expected, execute_mock.call_args_list)
@mock.patch.object(utils, 'execute', autospec=True,
side_effect=processutils.ProcessExecutionError(
stderr=os.strerror(errno.ENOENT)))
def test_mkfs_with_unsupported_fs(self, execute_mock):
self.assertRaises(errors.FileSystemNotSupported,
utils.mkfs, 'foo', '/my/block/dev')
@mock.patch.object(utils, 'execute', autospec=True,
side_effect=processutils.ProcessExecutionError(
stderr='fake'))
def test_mkfs_with_unexpected_error(self, execute_mock):
self.assertRaises(processutils.ProcessExecutionError, utils.mkfs,
'ext4', '/my/block/dev', 'ext4-vol')
@mock.patch.object(utils, 'execute', autospec=True)
class GetRouteSourceTestCase(base.IronicAgentTest):
def test_get_route_source_ipv4(self, mock_execute):
mock_execute.return_value = ('XXX src 1.2.3.4 XXX\n cache', None)
source = utils.get_route_source('XXX')
self.assertEqual('1.2.3.4', source)
def test_get_route_source_ipv6(self, mock_execute):
mock_execute.return_value = ('XXX src 1:2::3:4 metric XXX\n cache',
None)
source = utils.get_route_source('XXX')
self.assertEqual('1:2::3:4', source)
def test_get_route_source_ipv6_linklocal(self, mock_execute):
mock_execute.return_value = (
'XXX src fe80::1234:1234:1234:1234 metric XXX\n cache', None)
source = utils.get_route_source('XXX')
self.assertIsNone(source)
def test_get_route_source_ipv6_linklocal_allowed(self, mock_execute):
mock_execute.return_value = (
'XXX src fe80::1234:1234:1234:1234 metric XXX\n cache', None)
source = utils.get_route_source('XXX', ignore_link_local=False)
self.assertEqual('fe80::1234:1234:1234:1234', source)
def test_get_route_source_indexerror(self, mock_execute):
mock_execute.return_value = ('XXX src \n cache', None)
source = utils.get_route_source('XXX')
self.assertIsNone(source)
class ParseDeviceTagsTestCase(base.IronicAgentTest):
def test_empty(self):
result = utils.parse_device_tags("\n\n")
self.assertEqual([], list(result))
def test_parse(self):
tags = """
PTUUID="00016a50" PTTYPE="dos" LABEL=""
TYPE="vfat" PART_ENTRY_SCHEME="gpt" PART_ENTRY_NAME="EFI System Partition"
"""
result = list(utils.parse_device_tags(tags))
self.assertEqual([
{'PTUUID': '00016a50', 'PTTYPE': 'dos', 'LABEL': ''},
{'TYPE': 'vfat', 'PART_ENTRY_SCHEME': 'gpt',
'PART_ENTRY_NAME': 'EFI System Partition'}
], result)
|