/usr/lib/python3/dist-packages/provisioningserver/rpc/clusterservice.py is in python3-maas-provisioningserver 2.4.0~beta2-6865-gec43e47e6-0ubuntu1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 | # Copyright 2014-2016 Canonical Ltd. This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).
"""RPC implementation for clusters."""
__all__ = [
"ClusterClientService",
]
from functools import partial
import json
from operator import itemgetter
import os
from os import urandom
import random
from socket import (
AF_INET,
AF_INET6,
gethostname,
)
import sys
from urllib.parse import urlparse
from apiclient.creds import convert_string_to_tuple
from apiclient.utils import ascii_url
from netaddr import IPAddress
from provisioningserver import concurrency
from provisioningserver.config import (
ClusterConfiguration,
is_dev_environment,
)
from provisioningserver.drivers import ArchitectureRegistry
from provisioningserver.drivers.hardware.seamicro import (
probe_seamicro15k_and_enlist,
)
from provisioningserver.drivers.hardware.ucsm import probe_and_enlist_ucsm
from provisioningserver.drivers.hardware.virsh import probe_virsh_and_enlist
from provisioningserver.drivers.hardware.vmware import probe_vmware_and_enlist
from provisioningserver.drivers.nos.registry import NOSDriverRegistry
from provisioningserver.drivers.power.mscm import probe_and_enlist_mscm
from provisioningserver.drivers.power.msftocs import probe_and_enlist_msftocs
from provisioningserver.drivers.power.recs import probe_and_enlist_recs
from provisioningserver.drivers.power.registry import PowerDriverRegistry
from provisioningserver.logger import (
get_maas_logger,
LegacyLogger,
)
from provisioningserver.refresh import (
get_sys_info,
refresh,
)
from provisioningserver.rpc import (
cluster,
common,
dhcp,
exceptions,
pods,
region,
)
from provisioningserver.rpc.boot_images import (
import_boot_images,
is_import_boot_images_running,
list_boot_images,
)
from provisioningserver.rpc.common import RPCProtocol
from provisioningserver.rpc.interfaces import IConnectionToRegion
from provisioningserver.rpc.osystems import (
gen_operating_systems,
get_os_release_title,
get_preseed_data,
validate_license_key,
)
from provisioningserver.rpc.power import (
get_power_state,
maybe_change_power_state,
)
from provisioningserver.rpc.tags import evaluate_tag
from provisioningserver.security import (
calculate_digest,
get_shared_secret_from_filesystem,
)
from provisioningserver.service_monitor import service_monitor
from provisioningserver.utils import sudo
from provisioningserver.utils.env import (
get_maas_id,
set_maas_id,
)
from provisioningserver.utils.fs import (
get_maas_common_command,
NamedLock,
)
from provisioningserver.utils.network import (
get_all_interfaces_definition,
resolve_host_to_addrinfo,
)
from provisioningserver.utils.shell import (
call_and_check,
ExternalProcessError,
get_env_with_bytes_locale,
)
from provisioningserver.utils.snappy import (
get_snap_path,
running_in_snap,
)
from provisioningserver.utils.twisted import (
call,
callOut,
deferred,
DeferredValue,
makeDeferredWithProcessProtocol,
suppress,
)
from provisioningserver.utils.version import get_maas_version
from twisted import web
from twisted.application.internet import TimerService
from twisted.internet import reactor
from twisted.internet.defer import (
Deferred,
DeferredList,
inlineCallbacks,
maybeDeferred,
returnValue,
)
from twisted.internet.endpoints import (
connectProtocol,
TCP6ClientEndpoint,
)
from twisted.internet.error import (
ConnectError,
ConnectionClosed,
ProcessDone,
)
from twisted.internet.threads import deferToThread
from twisted.protocols import amp
from twisted.python.reflect import fullyQualifiedName
from twisted.web.client import (
_ReadBodyProtocol,
Agent,
)
from twisted.web.http_headers import Headers
from zope.interface import implementer
maaslog = get_maas_logger("rpc.cluster")
log = LegacyLogger()
def catch_probe_and_enlist_error(name, failure):
"""Logs any errors when trying to probe and enlist a chassis."""
maaslog.error(
"Failed to probe and enlist %s nodes: %s",
name, failure.getErrorMessage())
return None
def get_scan_all_networks_args(
scan_all=False, force_ping=False, threads=None, cidrs=None, slow=False,
interface=None):
"""Return the arguments needed to perform a scan of all networks.
The output of this function is suitable for passing into a call
to `subprocess.Popen()`.
:param cidrs: an iterable of CIDR strings
"""
args = [get_maas_common_command(), 'scan-network']
if not is_dev_environment():
args = sudo(args)
if threads is not None:
args.extend(["--threads", str(threads)])
if force_ping:
args.append("--ping")
if slow:
args.append("--slow")
# None of these parameters are relevant if we are scanning everything...
if not scan_all:
# ... but force the caller to be explicit about scanning all networks.
# Keep track of the original length of `args` to make sure we add at
# least one argument.
original_args_length = len(args)
if interface is not None:
args.append(interface)
if cidrs is not None:
args.extend(str(cidr) for cidr in cidrs)
assert original_args_length != len(args), (
"Invalid scan parameters. Must specify cidrs or interface if not "
"using scan_all."
)
binary_args = [
arg.encode(sys.getfilesystemencoding()) for arg in args]
return binary_args
def spawnProcessAndNullifyStdout(protocol, args):
""""Utility function to spawn a process and redirect stdout to /dev/null.
Spawns the process with the specified `protocol` in the reactor, with the
specified list of binary `args`.
"""
# Using childFDs we arrange for the child's stdout to go to /dev/null
# and for stderr to be read asynchronously by the reactor.
with open(os.devnull, "r+b") as devnull:
# This file descriptor to /dev/null will be closed before the
# spawned process finishes, but will remain open in the spawned
# process; that's the Magic Of UNIX™.
reactor.spawnProcess(
protocol, args[0], args, childFDs={
0: devnull.fileno(),
1: devnull.fileno(),
2: 'r'
},
env=get_env_with_bytes_locale())
def executeScanNetworksSubprocess(
scan_all=False, force_ping=False, slow=False, threads=None, cidrs=None,
interface=None):
"""Runs the network scanning subprocess.
Redirects stdout and stderr in the subprocess to /dev/null. Leaves
stderr intact, so that we might pass useful logging through.
Returns the `reason` (see `ProcessProtocol.processEnded`) from the
scan process after waiting for it to complete.
:param cidrs: A list of CIDR strings to run neighbour scans on.
"""
done, protocol = makeDeferredWithProcessProtocol()
# Technically this is not guaranteed to be a string containing just
# one line of text. But reality in this case is both atomic and
# concise. (And if it isn't, we can fix it, since we're calling our
# own command.)
protocol.errReceived = lambda data: (
log.msg("Scan all networks: " + data.decode("utf-8")))
args = get_scan_all_networks_args(
scan_all=scan_all, force_ping=force_ping, slow=slow, threads=threads,
cidrs=cidrs, interface=interface)
spawnProcessAndNullifyStdout(protocol, args)
return done
class Cluster(RPCProtocol):
"""The RPC protocol supported by a cluster controller.
This can be used on the client or server end of a connection; once a
connection is established, AMP is symmetric.
"""
@cluster.Identify.responder
def identify(self):
"""identify()
Implementation of
:py:class:`~provisioningserver.rpc.cluster.Identify`.
"""
ident = get_maas_id()
if ident is None:
ident = ""
return {"ident": ident}
@cluster.Authenticate.responder
def authenticate(self, message):
secret = get_shared_secret_from_filesystem()
salt = urandom(16) # 16 bytes of high grade noise.
digest = calculate_digest(secret, message, salt)
return {"digest": digest, "salt": salt}
@cluster.ListBootImages.responder
def list_boot_images(self):
"""list_boot_images()
Implementation of
:py:class:`~provisioningserver.rpc.cluster.ListBootImages`.
"""
return {"images": list_boot_images()}
@cluster.ListBootImagesV2.responder
def list_boot_images_v2(self):
"""list_boot_images_v2()
Implementation of
:py:class:`~provisioningserver.rpc.cluster.ListBootImagesV2`.
"""
return {"images": list_boot_images()}
@cluster.ImportBootImages.responder
def import_boot_images(self, sources, http_proxy=None, https_proxy=None):
"""import_boot_images()
Implementation of
:py:class:`~provisioningserver.rpc.cluster.ImportBootImages`.
"""
get_proxy_url = lambda url: None if url is None else url.geturl()
import_boot_images(
sources, http_proxy=get_proxy_url(http_proxy),
https_proxy=get_proxy_url(https_proxy))
return {}
@cluster.IsImportBootImagesRunning.responder
def is_import_boot_images_running(self):
"""is_import_boot_images_running()
Implementation of
:py:class:`~provisioningserver.rpc.cluster.IsImportBootImagesRunning`.
"""
return {"running": is_import_boot_images_running()}
@cluster.DescribePowerTypes.responder
def describe_power_types(self):
"""describe_power_types()
Implementation of
:py:class:`~provisioningserver.rpc.cluster.DescribePowerTypes`.
"""
# Detection of missing packages is now done reactively instead of
# proactively. When a power check is performed it will raise an error
# if their are any missing packages.
return {
'power_types': list(
PowerDriverRegistry.get_schema(detect_missing_packages=False)),
}
@cluster.DescribeNOSTypes.responder
def describe_nos_types(self):
"""describe_nos_types()
Implementation of
:py:class:`~provisioningserver.rpc.cluster.DescribeNOSTypes`.
"""
return {
'nos_types': list(NOSDriverRegistry.get_schema()),
}
@cluster.ListSupportedArchitectures.responder
def list_supported_architectures(self):
return {
'architectures': [
{'name': arch.name, 'description': arch.description}
for _, arch in ArchitectureRegistry
],
}
@cluster.ListOperatingSystems.responder
def list_operating_systems(self):
"""list_operating_systems()
Implementation of
:py:class:`~provisioningserver.rpc.cluster.ListOperatingSystems`.
"""
return {"osystems": gen_operating_systems()}
@cluster.GetOSReleaseTitle.responder
def get_os_release_title(self, osystem, release):
"""get_os_release_title()
Implementation of
:py:class:`~provisioningserver.rpc.cluster.GetOSReleaseTitle`.
"""
return {"title": get_os_release_title(osystem, release)}
@cluster.ValidateLicenseKey.responder
def validate_license_key(self, osystem, release, key):
"""validate_license_key()
Implementation of
:py:class:`~provisioningserver.rpc.cluster.ValidateLicenseKey`.
"""
return {"is_valid": validate_license_key(osystem, release, key)}
@cluster.GetPreseedData.responder
def get_preseed_data(
self, osystem, preseed_type, node_system_id, node_hostname,
consumer_key, token_key, token_secret, metadata_url):
"""get_preseed_data()
Implementation of
:py:class:`~provisioningserver.rpc.cluster.GetPreseedData`.
"""
return {
"data": get_preseed_data(
osystem, preseed_type, node_system_id, node_hostname,
consumer_key, token_key, token_secret, metadata_url),
}
@cluster.PowerOn.responder
def power_on(self, system_id, hostname, power_type, context):
"""Turn a node on."""
d = maybe_change_power_state(
system_id, hostname, power_type, power_change='on',
context=context)
d.addCallback(lambda _: {})
return d
@cluster.PowerOff.responder
def power_off(self, system_id, hostname, power_type, context):
"""Turn a node off."""
d = maybe_change_power_state(
system_id, hostname, power_type, power_change='off',
context=context)
d.addCallback(lambda _: {})
return d
@cluster.PowerCycle.responder
def power_cycle(self, system_id, hostname, power_type, context):
"""Power cycle a node."""
d = maybe_change_power_state(
system_id, hostname, power_type, power_change='cycle',
context=context)
d.addCallback(lambda _: {})
return d
@cluster.PowerQuery.responder
def power_query(self, system_id, hostname, power_type, context):
d = get_power_state(
system_id, hostname, power_type, context=context)
d.addCallback(lambda x: {'state': x})
d.addErrback(lambda f: {
'state': 'error',
'error_msg': f.getErrorMessage()})
return d
@cluster.PowerDriverCheck.responder
def power_driver_check(self, power_type):
"""Return a list of missing power driver packages, if any."""
driver = PowerDriverRegistry.get_item(power_type)
if driver is None:
raise exceptions.UnknownPowerType(
"No driver found for power type '%s'" % power_type)
return {"missing_packages": driver.detect_missing_packages()}
@cluster.ConfigureDHCPv4.responder
def configure_dhcpv4(
self, omapi_key, failover_peers, shared_networks,
hosts, interfaces, global_dhcp_snippets=[]):
dhcp.upgrade_shared_networks(shared_networks)
return self.configure_dhcpv4_v2(
omapi_key, failover_peers, shared_networks, hosts, interfaces,
global_dhcp_snippets)
@cluster.ConfigureDHCPv4_V2.responder
def configure_dhcpv4_v2(
self, omapi_key, failover_peers, shared_networks,
hosts, interfaces, global_dhcp_snippets=[]):
server = dhcp.DHCPv4Server(omapi_key)
d = concurrency.dhcp.run(
dhcp.configure, server,
failover_peers, shared_networks, hosts, interfaces,
global_dhcp_snippets)
d.addCallback(lambda _: {})
return d
@cluster.ValidateDHCPv4Config.responder
def validate_dhcpv4_config(
self, omapi_key, failover_peers, shared_networks,
hosts, interfaces, global_dhcp_snippets=[]):
dhcp.upgrade_shared_networks(shared_networks)
return self.validate_dhcpv4_config_v2(
omapi_key, failover_peers, shared_networks, hosts, interfaces,
global_dhcp_snippets)
@cluster.ValidateDHCPv4Config_V2.responder
def validate_dhcpv4_config_v2(
self, omapi_key, failover_peers, shared_networks,
hosts, interfaces, global_dhcp_snippets=[]):
server = dhcp.DHCPv4Server(omapi_key)
d = deferToThread(
dhcp.validate, server,
failover_peers, shared_networks, hosts, interfaces,
global_dhcp_snippets)
d.addCallback(lambda ret: {'errors': ret} if ret is not None else {})
return d
@cluster.ConfigureDHCPv6.responder
def configure_dhcpv6(
self, omapi_key, failover_peers, shared_networks,
hosts, interfaces, global_dhcp_snippets=[]):
dhcp.upgrade_shared_networks(shared_networks)
return self.configure_dhcpv6_v2(
omapi_key, failover_peers, shared_networks, hosts, interfaces,
global_dhcp_snippets)
@cluster.ConfigureDHCPv6_V2.responder
def configure_dhcpv6_v2(
self, omapi_key, failover_peers, shared_networks,
hosts, interfaces, global_dhcp_snippets=[]):
server = dhcp.DHCPv6Server(omapi_key)
d = concurrency.dhcp.run(
dhcp.configure, server,
failover_peers, shared_networks, hosts, interfaces,
global_dhcp_snippets)
d.addCallback(lambda _: {})
return d
@cluster.ValidateDHCPv6Config.responder
def validate_dhcpv6_config(
self, omapi_key, failover_peers, shared_networks,
hosts, interfaces, global_dhcp_snippets=[]):
dhcp.upgrade_shared_networks(shared_networks)
return self.validate_dhcpv6_config_v2(
omapi_key, failover_peers, shared_networks, hosts, interfaces,
global_dhcp_snippets)
@cluster.ValidateDHCPv6Config_V2.responder
def validate_dhcpv6_config_v2(
self, omapi_key, failover_peers, shared_networks,
hosts, interfaces, global_dhcp_snippets=[]):
server = dhcp.DHCPv6Server(omapi_key)
d = deferToThread(
dhcp.validate, server,
failover_peers, shared_networks, hosts, interfaces,
global_dhcp_snippets)
d.addCallback(lambda ret: {'errors': ret} if ret is not None else {})
return d
@amp.StartTLS.responder
def get_tls_parameters(self):
"""get_tls_parameters()
Implementation of
:py:class:`~twisted.protocols.amp.StartTLS`.
"""
try:
from provisioningserver.rpc.testing import tls
except ImportError:
# This is not a development/test environment.
# XXX: Return production TLS parameters.
return {}
else:
return tls.get_tls_parameters_for_cluster()
@cluster.EvaluateTag.responder
def evaluate_tag(
self, system_id, tag_name, tag_definition, tag_nsmap,
credentials, nodes):
"""evaluate_tag()
Implementation of
:py:class:`~provisioningserver.rpc.cluster.EvaluateTag`.
"""
# It's got to run in a thread because it does blocking IO.
d = deferToThread(
evaluate_tag, system_id, nodes, tag_name, tag_definition,
# Transform tag_nsmap into a format that LXML likes.
{entry["prefix"]: entry["uri"] for entry in tag_nsmap},
# Parse the credential string into a 3-tuple.
convert_string_to_tuple(credentials))
return d.addCallback(lambda _: {})
@cluster.RefreshRackControllerInfo.responder
def refresh(self, system_id, consumer_key, token_key, token_secret):
"""RefreshRackControllerInfo()
Implementation of
:py:class:`~provisioningserver.rpc.cluster.RefreshRackControllerInfo`.
"""
def _refresh():
with ClusterConfiguration.open() as config:
return deferToThread(
refresh, system_id, consumer_key, token_key,
token_secret, config.maas_url)
lock = NamedLock('refresh')
try:
lock.acquire()
except lock.NotAvailable:
# Refresh is already running, don't do anything
raise exceptions.RefreshAlreadyInProgress()
else:
# Start gathering node results (lshw, lsblk, etc) but don't wait.
maybeDeferred(_refresh).addBoth(callOut, lock.release).addErrback(
log.err, 'Failed to refresh the rack controller.')
return deferToThread(get_sys_info)
@cluster.AddChassis.responder
def add_chassis(
self, user, chassis_type, hostname, username=None, password=None,
accept_all=False, domain=None, prefix_filter=None,
power_control=None, port=None, protocol=None):
"""AddChassis()
Implementation of
:py:class:`~provisioningserver.rpc.cluster.AddChassis`.
"""
if chassis_type in ('virsh', 'powerkvm'):
d = deferToThread(
probe_virsh_and_enlist,
user, hostname, password, prefix_filter, accept_all,
domain)
d.addErrback(partial(catch_probe_and_enlist_error, "virsh"))
elif chassis_type == 'vmware':
d = deferToThread(
probe_vmware_and_enlist,
user, hostname, username, password, port, protocol,
prefix_filter, accept_all, domain)
d.addErrback(partial(catch_probe_and_enlist_error, "VMware"))
elif chassis_type == 'recs_box':
d = deferToThread(
probe_and_enlist_recs,
user, hostname, port, username, password, accept_all, domain)
d.addErrback(
partial(catch_probe_and_enlist_error, "RECS|Box"))
elif chassis_type == 'seamicro15k':
d = deferToThread(
probe_seamicro15k_and_enlist,
user, hostname, username, password, power_control, accept_all,
domain)
d.addErrback(
partial(catch_probe_and_enlist_error, "SeaMicro 15000"))
elif chassis_type == 'mscm':
d = deferToThread(
probe_and_enlist_mscm, user, hostname, username, password,
accept_all, domain)
d.addErrback(partial(catch_probe_and_enlist_error, "Moonshot"))
elif chassis_type == 'msftocs':
d = deferToThread(
probe_and_enlist_msftocs, user, hostname, port, username,
password, accept_all, domain)
d.addErrback(partial(catch_probe_and_enlist_error, "MicrosoftOCS"))
elif chassis_type == 'ucsm':
d = deferToThread(
probe_and_enlist_ucsm, user, hostname, username, password,
accept_all, domain)
d.addErrback(partial(catch_probe_and_enlist_error, "UCS"))
else:
message = "Unknown chassis type %s" % chassis_type
maaslog.error(message)
return {}
@cluster.DiscoverPod.responder
def discover_pod(
self, type, context, pod_id=None, name=None):
"""DiscoverPod()
Implementation of
:py:class:`~provisioningserver.rpc.cluster.DiscoverPod`.
"""
return pods.discover_pod(
type, context, pod_id=pod_id, name=name)
@cluster.ComposeMachine.responder
def compose_machine(
self, type, context, request, pod_id, name):
"""ComposeMachine()
Implementation of
:py:class:`~provisioningserver.rpc.cluster.ComposeMachine`.
"""
return pods.compose_machine(
type, context, request, pod_id=pod_id, name=name)
@cluster.DecomposeMachine.responder
def decompose_machine(
self, type, context, pod_id, name):
"""DecomposeMachine()
Implementation of
:py:class:`~provisioningserver.rpc.cluster.DecomposeMachine`.
"""
return pods.decompose_machine(
type, context, pod_id=pod_id, name=name)
@cluster.ScanNetworks.responder
def scan_all_networks(
self, scan_all=False, force_ping=False, slow=False, threads=None,
cidrs=None, interface=None):
"""ScanNetworks()
Implementation of
:py:class:`~provisioningserver.rpc.cluster.ScanNetworks`.
"""
lock = NamedLock('scan-networks')
try:
lock.acquire()
except lock.NotAvailable:
# Scan is already running; don't do anything.
raise exceptions.ScanNetworksAlreadyInProgress(
"Only one concurrent network scan is allowed.")
else:
# The lock *must* be released, so put on the paranoid hat here and
# use maybeDeferred to make sure that errors all trigger the call
# to lock.release.
d = maybeDeferred(
executeScanNetworksSubprocess, scan_all=scan_all,
force_ping=force_ping, slow=slow, cidrs=cidrs, threads=threads,
interface=interface)
d.addErrback(suppress, ProcessDone) # Exited normally.
d.addErrback(log.err, 'Failed to scan all networks.')
d.addBoth(callOut, lock.release)
return {}
@cluster.DisableAndShutoffRackd.responder
def disable_and_shutoff_rackd(self):
"""DisableAndShutoffRackd()
Implementation of
:py:class:`~provisioningserver.rpc.cluster.DisableAndShutoffRackd`.
"""
maaslog.info("Attempting to disable the rackd service.")
try:
if running_in_snap():
cmd = os.path.join(get_snap_path(), 'command-maas.wrapper')
call_and_check(
[cmd, 'config', '--mode', 'none'])
else:
# We can't use the --now flag as if the maas-rackd service is
# on but not enabled the service won't be stopped
call_and_check(
['sudo', 'systemctl', 'disable', 'maas-rackd'])
call_and_check(
['sudo', 'systemctl', 'stop', 'maas-rackd'])
except ExternalProcessError as e:
# Since the snap sends a SIGTERM to terminate the process, python
# returns -15 as a return code. This indicates the termination
# signal has been performed and the process terminated. However,
# This is not a failure. As such, work around the non-zero return
# (-15) and do not raise an error.
if not (running_in_snap() and e.returncode == -15):
maaslog.error("Unable to disable and stop the rackd service")
raise exceptions.CannotDisableAndShutoffRackd(
e.output_as_unicode)
maaslog.info("Successfully stopped the rackd service.")
return {}
@implementer(IConnectionToRegion)
class ClusterClient(Cluster):
"""The RPC protocol supported by a cluster controller, client version.
This works hand-in-hand with ``ClusterClientService``, maintaining
the latter's `connections` map.
:ivar address: The `(host, port)` of the remote endpoint.
:ivar eventloop: The event-loop this client is related to.
:ivar service: A reference to the :class:`ClusterClientService` that
made self.
:ivar authenticated: A py:class:`DeferredValue` that will be set when the
region has been authenticated. If the region has been authenticated,
this will be ``True``, otherwise it will be ``False``. If there was an
error, it will return a :py:class:`twisted.python.failure.Failure` via
errback.
:ivar ready: A py:class:`DeferredValue` that will be set when this
connection is up and has performed authentication on the region. If
everything has gone smoothly it will be set to the name of the
event-loop connected to, otherwise it will be set to: `RuntimeError`
if the client service is not running; `KeyError` if there's already a
live connection for this event-loop; or `AuthenticationFailed` if,
guess, the authentication failed.
"""
address = None
eventloop = None
service = None
def __init__(self, address, eventloop, service):
super(ClusterClient, self).__init__()
self.address = address
self.eventloop = eventloop
self.service = service
# Events for this protocol's life-cycle.
self.authenticated = DeferredValue()
self.ready = DeferredValue()
self.localIdent = None
self.remoteVersion = None
@property
def ident(self):
"""The ident of the remote event-loop."""
return self.eventloop
@inlineCallbacks
def authenticateRegion(self):
"""Authenticate the region."""
secret = get_shared_secret_from_filesystem()
message = urandom(16) # 16 bytes of the finest.
response = yield self.callRemote(
region.Authenticate, message=message)
salt, digest = response["salt"], response["digest"]
digest_local = calculate_digest(secret, message, salt)
returnValue(digest == digest_local)
@inlineCallbacks
def registerRackWithRegion(self):
# Grab the URL the rack uses to communicate to the region API along
# with the cluster UUID. It is possible that the cluster UUID is blank.
with ClusterConfiguration.open() as config:
url = config.maas_url
cluster_uuid = config.cluster_uuid
# Grab the set system_id if already set for this controller.
system_id = get_maas_id()
if system_id is None:
# Cannot send None over RPC when the system_id is not set.
system_id = ''
# Gather the required information for registration.
interfaces = get_all_interfaces_definition()
hostname = gethostname()
parsed_url = urlparse(url)
version = get_maas_version()
try:
# Note: we indicate support for beacons here, and act differently
# later depending on if the region we're registering with supports
# them or not.
data = yield self.callRemote(
region.RegisterRackController, system_id=system_id,
hostname=hostname, interfaces=interfaces, url=parsed_url,
nodegroup_uuid=cluster_uuid, beacon_support=True,
version=version)
self.localIdent = data["system_id"]
set_maas_id(self.localIdent)
version = data.get("version", None)
if version is None:
version_log = "MAAS version 2.2 or below"
elif version == "":
version_log = "unknown MAAS version"
else:
version_log = "MAAS version " + version
log.msg(
"Rack controller '%s' registered (via %s) with %s." % (
self.localIdent, self.eventloop, version_log))
# If the region supports beacons, full registration of rack
# interfaces will not have occurred yet. The networks monitoring
# service is responsible for updating the interfaces
# post-registration.
return True
except exceptions.CannotRegisterRackController:
log.msg(
"Rack controller REJECTED by the region (via %s)."
% self.eventloop)
return False
@inlineCallbacks
def performHandshake(self):
d_authenticate = self.authenticateRegion()
self.authenticated.observe(d_authenticate)
authenticated = yield d_authenticate
if authenticated:
log.msg("Event-loop '%s' authenticated." % self.ident)
registered = yield self.registerRackWithRegion()
if registered:
if self.eventloop in self.service.try_connections:
del self.service.try_connections[self.eventloop]
self.service.connections[self.eventloop] = self
self.ready.set(self.eventloop)
else:
self.transport.loseConnection()
self.ready.fail(
exceptions.RegistrationFailed(
"Event-loop '%s' rejected registration."
% self.ident))
else:
log.msg(
"Event-loop '%s' FAILED authentication; "
"dropping connection." % self.ident)
self.transport.loseConnection()
self.ready.fail(
exceptions.AuthenticationFailed(
"Event-loop '%s' failed authentication."
% self.eventloop))
def handshakeSucceeded(self, result):
"""The handshake (identify and authenticate) succeeded.
This does *NOT* mean that the region was successfully authenticated,
merely that the process of authentication did not encounter an error.
"""
def handshakeFailed(self, failure):
"""The handshake (identify and authenticate) failed."""
if failure.check(ConnectionClosed):
# There has been a disconnection, clean or otherwise. There's
# nothing we can do now, so do nothing. The reason will have been
# logged elsewhere.
self.ready.fail(failure)
else:
log.err(
failure, "Event-loop '%s' handshake failed; "
"dropping connection." % self.ident)
self.transport.loseConnection()
self.ready.fail(failure)
def connectionMade(self):
super(ClusterClient, self).connectionMade()
if not self.service.running:
log.msg(
"Event-loop '%s' will be disconnected; the cluster's "
"client service is not running." % self.ident)
self.transport.loseConnection()
self.authenticated.set(None)
self.ready.fail(RuntimeError("Service not running."))
elif self.eventloop in self.service.connections:
log.msg(
"Event-loop '%s' is already connected; "
"dropping connection." % self.ident)
self.transport.loseConnection()
self.authenticated.set(None)
self.ready.fail(KeyError(
"Event-loop '%s' already connected." % self.eventloop))
else:
return self.performHandshake().addCallbacks(
self.handshakeSucceeded, self.handshakeFailed)
def connectionLost(self, reason):
self.service.remove_connection(self.eventloop, self)
super(ClusterClient, self).connectionLost(reason)
@inlineCallbacks
def secureConnection(self):
yield self.callRemote(amp.StartTLS, **self.get_tls_parameters())
# For some weird reason (it's mentioned in Twisted's source),
# TLS negotiation does not complete until we do something with
# the connection. Here we check that the remote event-loop is
# who we expected it to be.
response = yield self.callRemote(region.Identify)
remote_name = response.get("ident")
if remote_name != self.eventloop:
log.msg(
"The remote event-loop identifies itself as %s, but "
"%s was expected." % (remote_name, self.eventloop))
self.transport.loseConnection()
return
# We should now have a full set of parameters for the transport.
log.msg("Host certificate: %r" % self.hostCertificate)
log.msg("Peer certificate: %r" % self.peerCertificate)
class ClusterClientService(TimerService, object):
"""A cluster controller RPC client service.
This is a service - in the Twisted sense - that connects to a set of
remote AMP endpoints. The endpoints are obtained from a view in the
region controller and periodically refreshed; this list is used to
update the connections maintained in this service.
:ivar connections: A mapping of eventloop names to protocol
instances connected to it.
:ivar time_started: Records the time that `startService` was last called,
or `None` if it hasn't yet.
"""
INTERVAL_LOW = 1 # seconds.
INTERVAL_MID = 5 # seconds.
INTERVAL_HIGH = 30 # seconds.
time_started = None
def __init__(self, reactor):
super(ClusterClientService, self).__init__(
self._calculate_interval(None, None), self._tryUpdate)
self.connections = {}
self.try_connections = {}
self._previous_work = (None, None)
self.clock = reactor
# When _doUpdate is called we capture it into _updateInProgress so
# that concurrent calls can piggyback rather than initiating extra
# calls. We start with an already-fired DeferredValue: _tryUpdate
# checks if it is set to decide whether or not to call _doUpdate.
self._updateInProgress = DeferredValue()
self._updateInProgress.set(None)
def startService(self):
self.time_started = self.clock.seconds()
super(ClusterClientService, self).startService()
def getClient(self):
"""Returns a :class:`common.Client` connected to a region.
The client is chosen at random.
:raises: :py:class:`~.exceptions.NoConnectionsAvailable` when
there are no open connections to a region controller.
"""
conns = list(self.connections.values())
if len(conns) == 0:
raise exceptions.NoConnectionsAvailable()
else:
return common.Client(random.choice(conns))
@deferred
def getClientNow(self):
"""Returns a `Defer` that resolves to a :class:`common.Client`
connected to a region.
If a connection already exists to the region then this method
will just return that current connection. If no connections exists
this method will try its best to make a connection before returning
the client.
:raises: :py:class:`~.exceptions.NoConnectionsAvailable` when
there no connections can be made to a region controller.
"""
try:
return self.getClient()
except exceptions.NoConnectionsAvailable:
return self._tryUpdate().addCallback(call, self.getClient)
def getAllClients(self):
"""Return a list of all connected :class:`common.Client`s."""
return [common.Client(conn) for conn in self.connections.values()]
def _tryUpdate(self):
"""Attempt to refresh outgoing connections.
This ensures that calls to `_doUpdate` are deferred, with errors
logged but not propagated. It also ensures that `_doUpdate` is never
called concurrently.
"""
if self._updateInProgress.isSet:
d = maybeDeferred(self._doUpdate).addErrback(
log.err, "Cluster client update failed.")
self._updateInProgress = DeferredValue()
self._updateInProgress.capture(d)
return self._updateInProgress.get()
@inlineCallbacks
def _doUpdate(self):
"""Refresh outgoing connections.
This obtains a list of endpoints from the region then connects
to new ones and drops connections to those no longer used.
"""
info_url_base = urlparse(self._get_rpc_info_url()).decode()
info_url_addresses = yield resolve_host_to_addrinfo(
info_url_base.hostname, ip_version=0, port=info_url_base.port)
# Prefer AF_INET6 addresses
info_url_addresses.sort(key=itemgetter(0), reverse=True)
eventloops = None
for family, _, _, _, sockaddr in info_url_addresses:
addr, port, *_ = sockaddr
# We could use compose_URL (from provisioningserver.utils.url), but
# that just calls url._replace itself, and returns a url literal,
# rather than a url structure. So we use _replace() here as well.
# What we are actually doing here is replacing the given host:port
# in the URL with the answer we got from socket.getaddrinfo().
if family in {AF_INET, AF_INET6}:
if port == 0:
netloc = "[%s]" % IPAddress(addr).ipv6()
else:
netloc = "[%s]:%d" % (IPAddress(addr).ipv6(), port)
else:
continue
info_url = info_url_base._replace(netloc=netloc)
info_url = ascii_url(info_url.geturl())
try:
info = yield self._fetch_rpc_info(info_url)
eventloops = info["eventloops"]
if eventloops is None:
# This means that the region process we've just asked about
# RPC event-loop endpoints is not running the RPC
# advertising service. It could be just starting up for
# example.
log.msg(
"Region is not advertising RPC endpoints."
" (While requesting RPC info at %s)" %
info_url)
else:
yield self._update_connections(eventloops)
except ConnectError as error:
log.msg(
"Region not available: %s "
"(While requesting RPC info at %s)."
% (error, info_url))
except:
log.err(
None, "Failed to contact region. "
"(While requesting RPC info at %s)."
% (info_url))
else:
# The advertising service on the region was not running yet.
break
self._update_interval(
None if eventloops is None else len(eventloops),
len(self.connections))
@staticmethod
def _get_rpc_info_url():
"""Return the URL to the RPC infomation page on the region."""
with ClusterConfiguration.open() as config:
url = urlparse(config.maas_url)
url = url._replace(path="%s/rpc/" % url.path.rstrip("/"))
url = url.geturl()
return ascii_url(url)
@classmethod
def _fetch_rpc_info(cls, url):
def catch_503_error(failure):
# Catch `twisted.web.error.Error` if has a 503 status code. That
# means the region is not all the way up. Ignore the error as this
# service will try again after the calculated interval.
failure.trap(web.error.Error)
if failure.value.status != "503":
failure.raiseException()
else:
return {"eventloops": None}
def read_body(response):
# Read the body of the response and convert it to JSON.
d = Deferred()
protocol = _ReadBodyProtocol(response.code, response.phrase, d)
response.deliverBody(protocol)
d.addCallback(lambda data: json.loads(data.decode('utf-8')))
return d
agent = Agent(reactor)
d = agent.request(
b'GET', url,
Headers({b'User-Agent': [fullyQualifiedName(cls)]}))
d.addCallback(read_body)
d.addErrback(catch_503_error)
return d
def _calculate_interval(self, num_eventloops, num_connections):
"""Calculate the update interval.
The interval is `INTERVAL_LOW` seconds when there are no
connections, so that this can quickly obtain its first
connection.
The interval is also `INTERVAL_LOW` for a time after the service
starts. This helps to get everything connected quickly when the
cluster is started at a similar time to the region.
The interval changes to `INTERVAL_MID` seconds when there are
some connections, but fewer than there are event-loops.
After that it drops back to `INTERVAL_HIGH` seconds.
"""
if self.time_started is not None:
time_running = self.clock.seconds() - self.time_started
if time_running < self.INTERVAL_HIGH:
# This service has recently started; keep trying regularly.
return self.INTERVAL_LOW
if num_eventloops is None:
# The region is not available; keep trying regularly.
return self.INTERVAL_LOW
elif num_eventloops == 0:
# The region is coming up; keep trying regularly.
return self.INTERVAL_LOW
elif num_connections == 0:
# No connections to the region; keep trying regularly.
return self.INTERVAL_LOW
elif num_connections < num_eventloops:
# Some connections to the region, but not to all event
# loops; keep updating reasonably frequently.
return self.INTERVAL_MID
else:
# Fully connected to the region; update every so often.
return self.INTERVAL_HIGH
def _update_interval(self, num_eventloops, num_connections):
"""Change the update interval."""
self._loop.interval = self.step = self._calculate_interval(
num_eventloops, num_connections)
@inlineCallbacks
def _update_connections(self, eventloops):
"""Update the persistent connections to the region.
For each event-loop, ensure that there is (a) a connection
established and that (b) that connection corresponds to one of
the endpoints declared. If not (a), attempt to connect to each
endpoint in turn. If not (b), immediately drop the connection
and proceed as if not (a).
For each established connection to an event-loop, check that
it's still in the list of event-loops to which this cluster
should connect. If not, immediately drop the connection.
"""
def map_to_ipv6(address_port_tuple):
ipaddr, port = address_port_tuple
ipaddr = IPAddress(ipaddr).ipv6()
return str(ipaddr), port
# Ensure that the event-loop addresses are tuples so that
# they'll work as dictionary keys.
eventloops = {
name: [
map_to_ipv6(address)
for address in addresses
if map_to_ipv6(address)
]
for name, addresses in eventloops.items()
}
drop, connect = self._calculate_work(eventloops)
# Log fully connected only once. If that state changes then log
# it again. This prevents flooding the log with the same message when
# the state of the connections has not changed.
prev_work, self._previous_work = self._previous_work, (drop, connect)
if len(drop) == 0 and len(connect) == 0:
if prev_work != (drop, connect) and len(eventloops) > 0:
controllers = {
eventloop.split(':')[0]
for eventloop, _ in eventloops.items()
}
log.msg(
"Fully connected to all %d event-loops on all %d "
"region controllers (%s)." % (
len(eventloops), len(controllers),
', '.join(sorted(controllers))))
# Drop all connections at once, as the are no longer required.
if len(drop) > 0:
log.msg("Dropping connections to event-loops: %s" % (
', '.join(drop.keys())))
yield DeferredList([
maybeDeferred(self._drop_connection, connection)
for eventloop, connections in drop.items()
for connection in connections
], consumeErrors=True)
# Make all the new connections to each endpoint at the same time.
if len(connect) > 0:
log.msg("Making connections to event-loops: %s" % (
', '.join(connect.keys())))
yield DeferredList([
self._make_connections(eventloop, addresses)
for eventloop, addresses in connect.items()
], consumeErrors=True)
def _calculate_work(self, eventloops):
"""Calculate the work that needs to be performed for reconnection."""
drop, connect = {}, {}
# Drop connections to event-loops that no longer include one of
# this cluster's established connections among its advertised
# endpoints. This is most likely to have happened because of
# network reconfiguration on the machine hosting the event-loop,
# and so the connection may have dropped already, but there's
# nothing wrong with a bit of belt-and-braces engineering
# between consenting adults.
for eventloop, addresses in eventloops.items():
if eventloop in self.connections:
connection = self.connections[eventloop]
if connection.address not in addresses:
drop[eventloop] = [connection]
if eventloop in self.try_connections:
connection = self.try_connections[eventloop]
if connection.address not in addresses:
drop[eventloop] = [connection]
# Create new connections to event-loops that the cluster does
# not yet have a connection to.
for eventloop, addresses in eventloops.items():
if ((eventloop not in self.connections and
eventloop not in self.try_connections) or
eventloop in drop):
connect[eventloop] = addresses
# Remove connections to event-loops that are no longer
# advertised by the RPC info view. Most likely this means that
# the process in which the event-loop is no longer running, but
# it could be an indicator of a heavily loaded machine, or a
# fault. In any case, it seems to make sense to disconnect.
for eventloop in self.connections:
if eventloop not in eventloops:
connection = self.connections[eventloop]
drop[eventloop] = [connection]
for eventloop in self.try_connections:
if eventloop not in eventloops:
connection = self.try_connections[eventloop]
drop[eventloop] = [connection]
return drop, connect
@inlineCallbacks
def _make_connections(self, eventloop, addresses):
"""Connect to `eventloop` using all `addresses`."""
for address in addresses:
try:
connection = yield self._make_connection(eventloop, address)
except ConnectError as error:
host, port = address
log.msg("Event-loop %s (%s:%d): %s" % (
eventloop, host, port, error))
except:
host, port = address
log.err(None, (
"Failure with event-loop %s (%s:%d)" % (
eventloop, host, port)))
else:
self.try_connections[eventloop] = connection
break
def _make_connection(self, eventloop, address):
"""Connect to `eventloop` at `address`."""
# Force everything to use AF_INET6 sockets.
endpoint = TCP6ClientEndpoint(self.clock, *address)
protocol = ClusterClient(address, eventloop, self)
return connectProtocol(endpoint, protocol)
def _drop_connection(self, connection):
"""Drop the given `connection`."""
return connection.transport.loseConnection()
def remove_connection(self, eventloop, connection):
"""Remove the connection from the tracked connections.
If this is the last connection that was keeping rackd connected to
a regiond then dhcpd and dhcpd6 services will be turned off.
"""
if eventloop in self.try_connections:
if self.try_connections[eventloop] is connection:
del self.try_connections[eventloop]
if eventloop in self.connections:
if self.connections[eventloop] is connection:
del self.connections[eventloop]
# Disable DHCP when no connections to a region controller.
if len(self.connections) == 0:
stopping_services = []
dhcp_v4 = service_monitor.getServiceByName("dhcpd")
if dhcp_v4.is_on():
dhcp_v4.off()
stopping_services.append("dhcpd")
dhcp_v6 = service_monitor.getServiceByName("dhcpd6")
if dhcp_v6.is_on():
dhcp_v6.off()
stopping_services.append("dhcpd6")
if len(stopping_services) > 0:
log.msg(
"Lost all connections to region controllers. "
"Stopping service(s) %s." % ",".join(stopping_services))
service_monitor.ensureServices()
# Lower the interval so a re-check happens sooner instead of its
# currently set interval.
self._update_interval(0, 0)
|