/
node.py
5339 lines (4681 loc) · 214 KB
/
node.py
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
# Copyright 2012-2017 Canonical Ltd. This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).
"""Node objects."""
__all__ = [
"Controller",
"Device",
"Node",
"Machine",
"RackController",
"RegionController",
]
from collections import (
defaultdict,
namedtuple,
)
from datetime import timedelta
from functools import partial
from itertools import count
from operator import attrgetter
import random
import re
import socket
from socket import gethostname
from urllib.parse import urlparse
import uuid
from crochet import TimeoutError
from django.contrib.auth.models import User
from django.core.exceptions import (
ObjectDoesNotExist,
PermissionDenied,
ValidationError,
)
from django.db import connection
from django.db.models import (
BigIntegerField,
BooleanField,
CASCADE,
CharField,
DateTimeField,
ForeignKey,
IntegerField,
Manager,
ManyToManyField,
Model,
OneToOneField,
PositiveIntegerField,
PROTECT,
Q,
SET_DEFAULT,
SET_NULL,
TextField,
)
from django.db.models.query import QuerySet
from django.shortcuts import get_object_or_404
from maasserver import (
DefaultMeta,
locks,
)
from maasserver.clusterrpc.pods import decompose_machine
from maasserver.clusterrpc.power import (
power_cycle,
power_driver_check,
power_off_node,
power_on_node,
power_query,
power_query_all,
)
from maasserver.enum import (
ALLOCATED_NODE_STATUSES,
BMC_TYPE,
FILESYSTEM_FORMAT_TYPE_CHOICES_DICT,
FILESYSTEM_TYPE,
INTERFACE_LINK_TYPE,
INTERFACE_TYPE,
IPADDRESS_FAMILY,
IPADDRESS_TYPE,
NODE_CREATION_TYPE,
NODE_PERMISSION,
NODE_STATUS,
NODE_STATUS_CHOICES,
NODE_STATUS_CHOICES_DICT,
NODE_TYPE,
NODE_TYPE_CHOICES,
POWER_STATE,
POWER_STATE_CHOICES,
SERVICE_STATUS,
)
from maasserver.exceptions import (
NodeStateViolation,
NoScriptsFound,
PowerProblem,
)
from maasserver.fields import (
JSONObjectField,
MAASIPAddressField,
MAC,
)
from maasserver.models.blockdevice import BlockDevice
from maasserver.models.bootresource import BootResource
from maasserver.models.cleansave import CleanSave
from maasserver.models.config import Config
from maasserver.models.domain import Domain
from maasserver.models.fabric import Fabric
from maasserver.models.filesystem import Filesystem
from maasserver.models.filesystemgroup import FilesystemGroup
from maasserver.models.interface import (
BondInterface,
BridgeInterface,
Interface,
PhysicalInterface,
VLANInterface,
)
from maasserver.models.iscsiblockdevice import ISCSIBlockDevice
from maasserver.models.licensekey import LicenseKey
from maasserver.models.ownerdata import OwnerData
from maasserver.models.partitiontable import PartitionTable
from maasserver.models.physicalblockdevice import PhysicalBlockDevice
from maasserver.models.service import Service
from maasserver.models.staticipaddress import StaticIPAddress
from maasserver.models.subnet import Subnet
from maasserver.models.tag import Tag
from maasserver.models.timestampedmodel import (
now,
TimestampedModel,
)
from maasserver.models.vlan import VLAN
from maasserver.models.zone import Zone
from maasserver.node_status import (
COMMISSIONING_LIKE_STATUSES,
get_failed_status,
is_failed_status,
MONITORED_STATUSES,
NODE_FAILURE_MONITORED_STATUS_TIMEOUTS,
NODE_TRANSITIONS,
)
from maasserver.rpc import (
getAllClients,
getClientFor,
getClientFromIdentifiers,
)
from maasserver.server_address import get_maas_facing_server_addresses
from maasserver.storage_layouts import (
get_storage_layout_for_node,
StorageLayoutError,
StorageLayoutMissingBootDiskError,
)
from maasserver.utils import synchronised
from maasserver.utils.dns import validate_hostname
from maasserver.utils.mac import get_vendor_for_mac
from maasserver.utils.orm import (
get_one,
MAASQueriesMixin,
post_commit,
post_commit_do,
transactional,
with_connection,
)
from maasserver.utils.threads import (
callOutToDatabase,
deferToDatabase,
)
from maasserver.worker_user import get_worker_user
from metadataserver.enum import (
RESULT_TYPE,
SCRIPT_STATUS,
)
from metadataserver.user_data import generate_user_data_for_status
from netaddr import (
IPAddress,
IPNetwork,
)
import petname
from piston3.models import Token
from provisioningserver.drivers.osystem import OperatingSystemRegistry
from provisioningserver.drivers.pod import Capabilities
from provisioningserver.drivers.power.registry import PowerDriverRegistry
from provisioningserver.events import (
EVENT_DETAILS,
EVENT_TYPES,
)
from provisioningserver.logger import get_maas_logger
from provisioningserver.refresh import (
get_sys_info,
refresh,
)
from provisioningserver.refresh.node_info_scripts import IPADDR_OUTPUT_NAME
from provisioningserver.rpc.cluster import (
AddChassis,
DisableAndShutoffRackd,
IsImportBootImagesRunning,
RefreshRackControllerInfo,
)
from provisioningserver.rpc.exceptions import (
NoConnectionsAvailable,
PowerActionFail,
RefreshAlreadyInProgress,
UnknownPowerType,
)
from provisioningserver.utils import (
flatten,
sorttop,
znums,
)
from provisioningserver.utils.enum import map_enum_reverse
from provisioningserver.utils.env import (
get_maas_id,
set_maas_id,
)
from provisioningserver.utils.fs import NamedLock
from provisioningserver.utils.ipaddr import get_mac_addresses
from provisioningserver.utils.network import (
annotate_with_default_monitored_interfaces,
)
from provisioningserver.utils.twisted import (
asynchronous,
callOut,
deferWithTimeout,
synchronous,
)
from twisted.internet.defer import (
Deferred,
inlineCallbacks,
succeed,
)
from twisted.internet.threads import deferToThread
maaslog = get_maas_logger("node")
# Holds the known `bios_boot_methods`. If `bios_boot_method` is not in this
# list then it will fallback to `DEFAULT_BIOS_BOOT_METHOD`.
KNOWN_BIOS_BOOT_METHODS = frozenset(["pxe", "uefi", "powernv", "powerkvm"])
# Default `bios_boot_method`. See `KNOWN_BIOS_BOOT_METHOD` above for usage.
DEFAULT_BIOS_BOOT_METHOD = "pxe"
# Return type from `get_effective_power_info`.
PowerInfo = namedtuple("PowerInfo", (
"can_be_started",
"can_be_stopped",
"can_be_queried",
"power_type",
"power_parameters",
))
DefaultGateways = namedtuple("DefaultGateways", (
"ipv4",
"ipv6",
))
GatewayDefinition = namedtuple("GatewayDefinition", (
"interface_id",
"subnet_id",
"gateway_ip",
))
def generate_node_system_id():
"""Return an unused six-digit system ID.
This chooses an ID at random and returns it if it's not currently in use.
There is a chance of a collision between concurrent processes, which would
result in an `IntegrityError` in one process or the other, but it's small:
there are over 183 million six-digit system IDs to choose from.
"""
for attempt in range(1, 1001):
system_num = random.randrange(24 ** 5, 24 ** 6)
system_id = znums.from_int(system_num)
with connection.cursor() as cursor:
cursor.execute(
"SELECT 1 FROM maasserver_node "
"WHERE system_id = %s", [system_id])
if cursor.fetchone() is None:
return system_id
else:
# Wow, really? This should _never_ happen. You must be managing a
# *lot* of machines. This is here as a fail-safe; it does not feels
# right to leave a loop that might never terminate in the code.
raise AssertionError(
"The unthinkable has come to pass: after %d iterations "
"we could find no unused node identifiers." % attempt)
class NodeQueriesMixin(MAASQueriesMixin):
def filter_by_spaces(self, spaces):
"""Return the set of nodes with at least one interface in the specified
spaces.
"""
return self.filter(
interface__ip_addresses__subnet__vlan__space__in=spaces)
def exclude_spaces(self, spaces):
"""Return the set of nodes without any interfaces in the specified
spaces.
"""
return self.exclude(
interface__ip_addresses__subnet__vlan__space__in=spaces)
def filter_by_fabrics(self, fabrics):
"""Return the set of nodes with at least one interface in the specified
fabrics.
"""
return self.filter(
interface__vlan__fabric__in=fabrics)
def exclude_fabrics(self, fabrics):
"""Return the set of nodes without any interfaces in the specified
fabrics.
"""
return self.exclude(
interface__vlan__fabric__in=fabrics)
def filter_by_fabric_classes(self, fabric_classes):
"""Return the set of nodes with at least one interface in the specified
fabric classes.
"""
return self.filter(
interface__vlan__fabric__class_type__in=fabric_classes)
def exclude_fabric_classes(
self, fabric_classes):
"""Return the set of nodes without any interfaces in the specified
fabric classes.
"""
return self.exclude(
interface__vlan__fabric__class_type__in=fabric_classes)
def filter_by_vids(self, vids):
"""Return the set of nodes with at least one interface whose VLAN has
one of the specified VIDs.
"""
return self.filter(
interface__vlan__vid__in=vids)
def exclude_vids(self, vids):
"""Return the set of nodes without any interfaces whose VLAN has one of
the specified VIDs.
"""
return self.exclude(
interface__vlan__vid__in=vids)
def filter_by_subnets(self, subnets):
"""Return the set of nodes with at least one interface configured on
one of the specified subnets.
"""
return self.filter(
interface__ip_addresses__subnet__in=subnets)
def exclude_subnets(self, subnets):
"""Return the set of nodes without any interfaces configured on one of
the specified subnets.
"""
return self.exclude(
interface__ip_addresses__subnet__in=subnets)
def filter_by_subnet_cidrs(self, subnet_cidrs):
"""Return the set of nodes with at least one interface configured on
one of the specified subnet with the given CIDRs.
"""
return self.filter(
interface__ip_addresses__subnet__cidr__in=subnet_cidrs)
def exclude_subnet_cidrs(self, subnet_cidrs):
"""Return the set of nodes without any interfaces configured on one of
the specified subnet with the given CIDRs.
"""
return self.exclude(
interface__ip_addresses__subnet__cidr__in=subnet_cidrs)
def filter_by_domains(self, domain_names):
"""Return the set of nodes with at least one interface configured in
one of the specified dns zone names.
"""
return self.filter(
interface__ip_addresses__dnsresource_set__domain__name__in=(
domain_names))
def exclude_domains(self, domain_names):
"""Return the set of nodes without any interfaces configured in
one of the specified dns zone names.
"""
return self.exclude(
interface__ip_addresses__dnsresource_set__domain__name__in=(
domain_names))
class NodeQuerySet(QuerySet, NodeQueriesMixin):
"""Custom QuerySet which mixes in some additional queries specific to
nodes. This needs to be a mixin because an identical method is needed on
both the Manager and all QuerySets which result from calling the manager.
"""
class BaseNodeManager(Manager, NodeQueriesMixin):
"""A utility to manage the collection of Nodes."""
extra_filters = {}
def get_queryset(self):
queryset = NodeQuerySet(self.model, using=self._db)
return queryset.filter(**self.extra_filters)
def filter_by_ids(self, query, ids=None):
"""Filter `query` result set by system_id values.
:param query: A QuerySet of Nodes.
:type query: django.db.models.query.QuerySet_
:param ids: Optional set of ids to filter by. If given, nodes whose
system_ids are not in `ids` will be ignored.
:type param_ids: Sequence
:return: A filtered version of `query`.
.. _django.db.models.query.QuerySet: https://docs.djangoproject.com/
en/dev/ref/models/querysets/
"""
if ids is None:
return query
else:
return query.filter(system_id__in=ids)
def _filter_visible_nodes(self, nodes, user, perm):
"""Filter a `Node` query depending on user permissions.
:param nodes: A `Node` query set.
:param user: The user making the request; the filtering is based on
their privileges.
:param perm: Type of access requested. For example, a user may be
allowed to view some nodes that they are not allowed to edit.
:type perm: `NODE_PERMISSION`
:return: A version of `node` that is filtered to include only those
nodes that `user` is allowed to access.
"""
# If the data is corrupt, this can get called with None for
# user where a Node should have an owner but doesn't.
# Nonetheless, the code should not crash with corrupt data.
if user is None:
return nodes.none()
if user.is_superuser:
# Admin is allowed to see all nodes.
return nodes
# Non-admins aren't allowed to see controllers.
nodes = nodes.exclude(
Q(node_type__in=[
NODE_TYPE.RACK_CONTROLLER,
NODE_TYPE.REGION_CONTROLLER,
NODE_TYPE.REGION_AND_RACK_CONTROLLER,
]))
if perm == NODE_PERMISSION.VIEW:
return nodes.filter(Q(owner__isnull=True) | Q(owner=user))
elif perm == NODE_PERMISSION.EDIT:
return nodes.filter(owner=user)
elif perm == NODE_PERMISSION.ADMIN:
return nodes.none()
else:
raise NotImplementedError(
"Invalid permission check (invalid permission name: %s)." %
perm)
def get_nodes(self, user, perm, ids=None, from_nodes=None):
"""Fetch Nodes on which the User_ has the given permission.
Warning: there could be a lot of nodes! Keep scale in mind when
calling this, and watch performance in general. Prefetch related
data where appropriate.
:param user: The user that should be used in the permission check.
:type user: User_
:param perm: The permission to check.
:type perm: a permission string from NODE_PERMISSION
:param ids: If given, limit result to nodes with these system_ids.
:type ids: Sequence.
:param from_nodes: Optionally, restrict the answer to these nodes.
:type from_nodes: Query set of `Node`.
.. _User: https://
docs.djangoproject.com/en/dev/topics/auth/
#django.contrib.auth.models.User
"""
if from_nodes is None:
from_nodes = self.all()
else:
# Make sure even if given a query set of multiple node types
# get_nodes only returns nodes applicable to this manager.
from_nodes = from_nodes.filter(**self.extra_filters)
nodes = self._filter_visible_nodes(from_nodes, user, perm)
return self.filter_by_ids(nodes, ids)
def get_node_or_404(self, system_id, user, perm, **kwargs):
"""Fetch a `Node` by system_id. Raise exceptions if no `Node` with
this system_id exist or if the provided user has not the required
permission on this `Node`.
:param name: The system_id.
:type name: string
:param user: The user that should be used in the permission check.
:type user: django.contrib.auth.models.User
:param perm: The permission to assert that the user has on the node.
:type perm: unicode
:raises: django.http.Http404_,
:class:`maasserver.exceptions.PermissionDenied`.
.. _django.http.Http404: https://
docs.djangoproject.com/en/dev/topics/http/views/
#the-http404-exception
"""
kwargs.update(self.extra_filters)
node = get_object_or_404(
self.model, system_id=system_id, **kwargs)
if user.has_perm(perm, node):
return node.as_self()
else:
raise PermissionDenied()
class GeneralManager(BaseNodeManager):
"""All the node types:"""
class MachineManager(BaseNodeManager):
"""Machines (i.e. deployable objects)."""
extra_filters = {'node_type': NODE_TYPE.MACHINE}
def get_allocated_visible_machines(self, token, ids):
"""Fetch Machines that were allocated to the User_/oauth token.
:param user: The user whose machines to fetch
:type user: User_
:param token: The OAuth token associated with the Machines.
:type token: piston3.models.Token.
:param ids: Optional set of IDs to filter by. If given, machines whose
system_ids are not in `ids` will be ignored.
:type param_ids: Sequence
.. _User: https://
docs.djangoproject.com/en/dev/topics/auth/
#django.contrib.auth.models.User
"""
if ids is None:
machines = self.filter(token=token)
else:
machines = self.filter(token=token, system_id__in=ids)
return machines
def get_available_machines_for_acquisition(self, for_user):
"""Find the machines that can be acquired by the given user.
:param for_user: The user who is to acquire the machine.
:type for_user: :class:`django.contrib.auth.models.User`
:return: Those machines which can be acquired by the user.
:rtype: `django.db.models.query.QuerySet`
"""
available_machines = self.get_nodes(for_user, NODE_PERMISSION.VIEW)
return available_machines.filter(status=NODE_STATUS.READY)
class DeviceManager(BaseNodeManager):
"""Devices are all the non-deployable nodes."""
extra_filters = {'node_type': NODE_TYPE.DEVICE}
class ControllerManager(BaseNodeManager):
"""All controllers `RackController`, `RegionController`, and
`RegionRackController`."""
extra_filters = {
'node_type__in': [
NODE_TYPE.RACK_CONTROLLER,
NODE_TYPE.REGION_CONTROLLER,
NODE_TYPE.REGION_AND_RACK_CONTROLLER,
]}
class RackControllerManager(ControllerManager):
"""Rack controllers are nodes which are used by MAAS to deploy nodes."""
extra_filters = {
'node_type__in': [
NODE_TYPE.RACK_CONTROLLER,
NODE_TYPE.REGION_AND_RACK_CONTROLLER,
]}
def get_running_controller(self):
"""Return the rack controller for the current host.
:raises: `DoesNotExist` if no matching controller is found.
"""
return self.get(system_id=get_maas_id())
def filter_by_url_accessible(self, url, with_connection=True):
"""Return a list of rack controllers which have access to the given URL
If a hostname is given MAAS will do a DNS lookup to discover the IP(s).
MAAS then uses the information it has about the network to return a
a list of rack controllers which should have access to each IP."""
if '://' not in url:
# urlparse only works if given with a protocol
parsed_url = urlparse("FAKE://%s" % url)
else:
parsed_url = urlparse(url)
# getaddrinfo can return duplicates
ips = set(
address[4][0]
for address in socket.getaddrinfo(parsed_url.hostname, None)
)
subnets = set(Subnet.objects.get_best_subnet_for_ip(ip) for ip in ips)
usable_racks = set(RackController.objects.filter(
interface__ip_addresses__subnet__in=subnets,
interface__ip_addresses__ip__isnull=False))
# There is no MAAS defined subnet for loop back so if its in our list
# of IPs add ourself
if '127.0.0.1' in ips or '::1' in ips:
running_rack = self.get_running_controller()
if running_rack is not None:
usable_racks.add(running_rack)
if with_connection:
conn_rack_ids = [client.ident for client in getAllClients()]
return [
rack
for rack in usable_racks
if rack.system_id in conn_rack_ids
]
else:
return list(usable_racks)
def get_accessible_by_url(self, url, with_connection=True):
"""Return a rack controller with access to a URL."""
racks = self.filter_by_url_accessible(url, with_connection)
if not racks:
return None
else:
# Lazy load balancing
return random.choice(racks)
class RegionControllerManager(ControllerManager):
"""Region controllers are the API, UI, and Coordinators of MAAS."""
extra_filters = {
'node_type__in': [
NODE_TYPE.REGION_CONTROLLER,
NODE_TYPE.REGION_AND_RACK_CONTROLLER,
]}
def get_running_controller(self):
"""Return the region controller for the current host.
:raises: `DoesNotExist` if no matching controller is found.
"""
return self.get(system_id=get_maas_id())
def get_or_create_running_controller(self):
"""Return the region controller for the current host.
:attention: This should be called early in the start-up process for a
region controller to ensure that it can refer to itself.
If the MAAS ID has been set, this searches for the controller only by
its system ID. If the controller is not found `DoesNotExist` will be
raised.
If the MAAS ID has not yet been set this tries to discover a matching
node via the current host's name and its MAC addresses. If no matching
node is found, a new region controller will be created. In either case
the MAAS ID will be set on the filesystem once the transaction has
been committed.
"""
maas_id = get_maas_id()
if maas_id is None:
node = self._find_or_create_running_controller()
else:
try:
node = Node.objects.get(system_id=maas_id)
except Node.DoesNotExist:
# The MAAS ID on the filesystem is stale. Perhaps this machine
# has not been cleaned-up sufficiently from a previous life?
# Regardless, a deliberate act has brought this about, like a
# purge of the database, so we continue instead of crashing.
node = self._find_or_create_running_controller()
else:
node = self._upgrade_running_node(node)
# A region needs to have a commissioning_script_set available to
# allow commissioning data to be sent on start.
if node.current_commissioning_script_set is None:
# Avoid circular dependencies
from metadataserver.models import ScriptSet
script_set = ScriptSet.objects.create_commissioning_script_set(
node)
node.current_commissioning_script_set = script_set
node.save()
return node
def _find_or_create_running_controller(self):
"""Find the controller for the current host, or create one.
Tries to discover the controller via the current host's name and MAC
addresses. Don't use this if the MAAS ID has been set.
If the discovered node is not yet a controller it is upgraded. If no
node is found a preconfigured controller is minted. In either case,
the MAAS ID on the filesystem is set post-commit.
"""
node = self._find_running_node()
if node is None:
region = self._create_running_controller()
else:
region = self._upgrade_running_node(node)
post_commit_do(set_maas_id, region.system_id)
return region
def _find_running_node(self):
"""Find the node for the current host.
Tries to discover the node via the current host's name and MAC
addresses. Don't use this if the MAAS ID has been set.
"""
hostname = gethostname()
filter_hostname = Q(hostname=hostname)
filter_macs = Q(interface__mac_address__in=get_mac_addresses())
# Look at all nodes, not just controllers; we might have to upgrade.
nodes = Node.objects.filter(filter_hostname | filter_macs)
# Select distinct because the join to MACs might yield duplicates.
return get_one(nodes.distinct())
def _upgrade_running_node(self, node):
"""Upgrade a node to a region controller for the host machine.
This node is already known to MAAS, but this MAY be the first time
that regiond has run on it, so ensure it's a region, owned by the
worker user.
"""
update_fields = []
if not node.is_region_controller:
if node.is_rack_controller:
node.node_type = NODE_TYPE.REGION_AND_RACK_CONTROLLER
else:
node.node_type = NODE_TYPE.REGION_CONTROLLER
update_fields.append("node_type")
if node.owner is None:
node.owner = get_worker_user()
update_fields.append("owner")
if len(update_fields) > 0:
node.save(update_fields=update_fields)
# Always cast to a region controller.
return node.as_region_controller()
def _create_running_controller(self):
"""Create a region controller for the host machine.
This node is NOT previously known to MAAS, and this is the first time
regiond has run on it. Create a region controller only; it can be
upgraded to a region+rack controller later if necessary.
"""
hostname = gethostname()
# Bug#1614584: it is possible that gethostname() reurns the FQDN.
# Split it up, and get the appropriate domain. If we wind up creating
# one for it, we are not authoritative.
# Just in case the default domain has not been created, let's create it
# here, even if we subsequently overwrite it inside the if statement.
domain = Domain.objects.get_default_domain()
if hostname.find('.') > 0:
hostname, domainname = hostname.split('.', 1)
(domain, _) = Domain.objects.get_or_create(
name=domainname, defaults={'authoritative': False})
return self.create(
owner=get_worker_user(), hostname=hostname, domain=domain)
def get_or_create_uuid(self):
maas_uuid = Config.objects.get_config("uuid")
if maas_uuid is None:
maas_uuid = str(uuid.uuid4())
Config.objects.set_config("uuid", maas_uuid)
return maas_uuid
def get_default_domain():
"""Get the default domain name."""
return Domain.objects.get_default_domain().id
def get_default_zone():
"""Return the ID of the default zone."""
return Zone.objects.get_default_zone().id
# Statuses for which it makes sense to release a node.
RELEASABLE_STATUSES = frozenset([
NODE_STATUS.ALLOCATED,
NODE_STATUS.RESERVED,
NODE_STATUS.BROKEN,
NODE_STATUS.DEPLOYING,
NODE_STATUS.DEPLOYED,
NODE_STATUS.FAILED_DEPLOYMENT,
NODE_STATUS.FAILED_DISK_ERASING,
NODE_STATUS.FAILED_RELEASING,
])
class Node(CleanSave, TimestampedModel):
"""A `Node` represents a physical machine used by the MAAS Server.
:ivar system_id: The unique identifier for this `Node`.
(e.g. 'node-41eba45e-4cfa-11e1-a052-00225f89f211').
:ivar hostname: This `Node`'s hostname. Must conform to RFCs 952 and 1123.
:ivar node_type: The type of node. This is used to specify if the node is
to be used as a node for deployment, as a device, or a rack controller
:ivar parent: An optional parent `Node`. This node will be deleted along
with all its resources when the parent node gets deleted or released.
This is only relevant for node types other than node.
:ivar status: This `Node`'s status. See the vocabulary
:class:`NODE_STATUS`.
:ivar previous_status: This `Node`'s previous status. See the vocabulary
:class:`NODE_STATUS`.
:ivar error_description: A human-readable description of why a node is
marked broken. Only meaningful when the node is in the state 'BROKEN'.
:ivar owner: This `Node`'s owner if it's in use, None otherwise.
:ivar bios_boot_method: The boot method used by the cluster to allow
this node to boot. E.g. "pxe".
:ivar osystem: This `Node`'s booting operating system, if it's blank then
the default_osystem will be used.
:ivar distro_series: This `Node`'s booting distro series, if
it's blank then the default_distro_series will be used.
:ivar bmc: The BMC / power controller for this node.
:ivar tags: The list of :class:`Tag`s associated with this `Node`.
:ivar objects: The :class:`GeneralManager`.
:ivar install_rackd: An optional flag to indicate if this node should be
deployed with the rack controller.
:ivar enable_ssh: An optional flag to indicate if this node can have
ssh enabled during commissioning, allowing the user to ssh into the
machine's commissioning environment using the user's SSH key.
:ivar skip_networking: An optional flag to indicate if this node
networking configuration doesn't need to be touched when it is
commissioned.
:ivar default_user: The username this `Node` will be configured with,
None otherwise.
"""
class Meta(DefaultMeta):
"""Needed for South to recognize this model."""
system_id = CharField(
max_length=41, unique=True, default=generate_node_system_id,
editable=False)
hostname = CharField(
max_length=255, default='', blank=True, unique=True,
validators=[validate_hostname])
# What Domain do we use for this host unless the individual StaticIPAddress
# record overrides it?
domain = ForeignKey(
Domain, default=get_default_domain, null=True, blank=True,
editable=True, on_delete=PROTECT)
# TTL for this Node's IP addresses. Since this must be the same for all
# records of the same time on any given name, we need to coordinate the TTL
# with any addresses that come from DNSResource.
# If None, then we inherit from the parent Domain, or the global default.
address_ttl = PositiveIntegerField(default=None, null=True, blank=True)
status = IntegerField(
choices=NODE_STATUS_CHOICES, editable=False,
default=NODE_STATUS.DEFAULT)
previous_status = IntegerField(
choices=NODE_STATUS_CHOICES, editable=False,
default=NODE_STATUS.DEFAULT)
# Set to time in the future when the node status should transition to
# a failed status. This is used by the StatusMonitorService inside
# the region processes. Each run periodically to update nodes.
status_expires = DateTimeField(
null=True, blank=False, default=None, editable=False)
owner = ForeignKey(
User, default=None, blank=True, null=True, editable=False,
on_delete=PROTECT)
bios_boot_method = CharField(max_length=31, blank=True, null=True)
osystem = CharField(
max_length=255, blank=True, default='')
distro_series = CharField(
max_length=255, blank=True, default='')
architecture = CharField(max_length=31, blank=True, null=True)
min_hwe_kernel = CharField(max_length=31, blank=True, null=True)
hwe_kernel = CharField(max_length=31, blank=True, null=True)
node_type = IntegerField(
choices=NODE_TYPE_CHOICES, editable=False, default=NODE_TYPE.DEFAULT)
parent = ForeignKey(
"Node", default=None, blank=True, null=True, editable=True,
related_name="children", on_delete=CASCADE)
agent_name = CharField(max_length=255, default='', blank=True, null=True)
error_description = TextField(blank=True, default='', editable=False)
zone = ForeignKey(
Zone, verbose_name="Physical zone",
default=get_default_zone, editable=True, db_index=True,
on_delete=SET_DEFAULT)
# Juju expects the following standard constraints, which are stored here
# as a basic optimisation over querying the lshw output.
cpu_count = IntegerField(default=0)
cpu_speed = IntegerField(default=0) # MHz
memory = IntegerField(default=0)
swap_size = BigIntegerField(null=True, blank=True, default=None)
bmc = ForeignKey(
'BMC', db_index=True, null=True, editable=False, unique=False,
on_delete=CASCADE)
# Power parameters specific to this node instance. Global power parameters
# are stored in this node's BMC.
instance_power_parameters = JSONObjectField(
max_length=(2 ** 15), blank=True, default="")
power_state = CharField(
max_length=10, null=False, blank=False,
choices=POWER_STATE_CHOICES, default=POWER_STATE.UNKNOWN,
editable=False)
# Set when a rack controller says its going to update the power state
# for this node. This prevents other rack controllers from also checking
# this node at the same time.
power_state_queried = DateTimeField(
null=True, blank=False, default=None, editable=False)
# Set when a rack controller has actually checked this power state and
# the last time the power was updated.
power_state_updated = DateTimeField(
null=True, blank=False, default=None, editable=False)
# Updated each time a rack controller finishes syncing boot images.
last_image_sync = DateTimeField(
null=True, blank=False, default=None, editable=False)
token = ForeignKey(
Token, db_index=True, null=True, editable=False, unique=False,
on_delete=CASCADE)
error = CharField(max_length=255, blank=True, default='')
netboot = BooleanField(default=True)
license_key = CharField(max_length=30, null=True, blank=True)
# Only used by Machine. Set to the creation type based on how the machine
# ended up in the Pod.
creation_type = IntegerField(
null=False, blank=False, default=NODE_CREATION_TYPE.PRE_EXISTING)
tags = ManyToManyField(Tag)
# Record the Interface the node last booted from.
# This will be used for determining which Interface to create a static
# IP reservation for when starting a node.
boot_interface = ForeignKey(
Interface, default=None, blank=True, null=True, editable=False,
related_name='+', on_delete=SET_NULL)
# Record the last IP address of the cluster this node used to request
# TFTP data. This is used to send the correct IP address for the node to
# download the image to install. Since the node just contacted the cluster
# using this IP address then it will be able to access the images at this
# IP address.
boot_cluster_ip = MAASIPAddressField(
unique=False, null=True, editable=False, blank=True, default=None)
# Record the PhysicalBlockDevice that this node uses as its boot disk.
# This will be used to make sure GRUB is installed to this device.
boot_disk = ForeignKey(
PhysicalBlockDevice, default=None, blank=True, null=True,
editable=False, related_name='+', on_delete=SET_NULL)
# Default IPv4 subnet link on an interface for this node. This is used to
# define the default IPv4 route the node should use.
gateway_link_ipv4 = ForeignKey(
StaticIPAddress, default=None, blank=True, null=True,