-
Notifications
You must be signed in to change notification settings - Fork 118
/
Copy pathmachines.py
3021 lines (2594 loc) · 118 KB
/
machines.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 2015-2021 Canonical Ltd. This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).
__all__ = [
"AnonMachinesHandler",
"MachineHandler",
"MachinesHandler",
"get_storage_layout_params",
]
from collections import namedtuple
import json
import re
from django.conf import settings
from django.core.exceptions import PermissionDenied
from django.db.models import Q
from django.http import (
HttpResponse,
HttpResponseBadRequest,
HttpResponseNotFound,
)
from django.urls import reverse
from formencode import validators
from formencode.validators import Int, StringBool
from piston3.models import Token
from piston3.utils import rc
import yaml
from maascommon.fields import MAC_FIELD_RE
from maasserver import locks
from maasserver.api.logger import maaslog
from maasserver.api.nodes import (
AnonNodeHandler,
AnonNodesHandler,
NodeHandler,
NodesHandler,
PowerMixin,
PowersMixin,
WorkloadAnnotationsMixin,
)
from maasserver.api.support import admin_method, operation
from maasserver.api.utils import (
get_mandatory_param,
get_optional_list,
get_optional_param,
)
from maasserver.clusterrpc.driver_parameters import get_all_power_types
from maasserver.enum import (
BMC_TYPE,
BRIDGE_TYPE,
BRIDGE_TYPE_CHOICES,
BRIDGE_TYPE_CHOICES_DICT,
NODE_STATUS,
NODE_STATUS_CHOICES_DICT,
NODE_TYPE,
)
from maasserver.exceptions import (
MAASAPIBadRequest,
MAASAPIForbidden,
MAASAPIValidationError,
NodesNotAvailable,
NodeStateViolation,
Unauthorized,
)
from maasserver.forms import (
AdminMachineForm,
get_machine_create_form,
get_machine_edit_form,
MachineForm,
)
from maasserver.forms.clone import CloneForm
from maasserver.forms.ephemeral import CommissionForm, ReleaseForm
from maasserver.forms.filesystem import (
MountNonStorageFilesystemForm,
UnmountNonStorageFilesystemForm,
)
from maasserver.forms.pods import ComposeMachineForPodsForm
from maasserver.models import (
Config,
Domain,
Interface,
Machine,
NodeMetadata,
PhysicalBlockDevice,
Pod,
RackController,
VirtualBlockDevice,
)
from maasserver.models.node import RELEASABLE_STATUSES
from maasserver.node_constraint_filter_forms import (
AcquireNodeForm,
nodes_by_interface,
nodes_by_storage,
)
from maasserver.node_status import NODE_TRANSITIONS
from maasserver.permissions import NodePermission, PodPermission
from maasserver.preseed import get_curtin_merged_config
from maasserver.storage_layouts import (
StorageLayoutError,
StorageLayoutForm,
StorageLayoutMissingBootDiskError,
)
from maasserver.utils.forms import compose_invalid_choice_text
from maasserver.utils.orm import get_first, reload_object
# NUMANodeHugepages fields exposed in the API.
DISPLAYED_NUMANODEHUGEPAGES_FIELDS = ("total", "page_size")
# NUMANode fields exposed in the API.
DISPLAYED_NUMANODE_FIELDS = (
"index",
"cores",
"memory",
("hugepages_set", DISPLAYED_NUMANODEHUGEPAGES_FIELDS),
)
# Machine's fields exposed on the API.
DISPLAYED_MACHINE_FIELDS = (
"system_id",
"hostname",
"description",
"hardware_uuid",
"domain",
"fqdn",
"owner",
"owner_data",
"locked",
"cache_sets",
"bcaches",
"bios_boot_method",
"boot_interface",
"architecture",
"min_hwe_kernel",
"hwe_kernel",
"cpu_count",
"cpu_speed",
"memory",
"swap_size",
"storage",
"status",
"osystem",
"distro_series",
"ephemeral_deploy",
"error_description",
"netboot",
"power_type",
"power_state",
"tag_names",
"address_ttl",
"ip_addresses",
"interface_set",
"zone",
"pool",
"disable_ipv4",
"constraints_by_type",
"boot_disk",
"blockdevice_set",
"physicalblockdevice_set",
"virtualblockdevice_set",
"volume_groups",
"raids",
"status_action",
"status_message",
"status_name",
"node_type",
"node_type_name",
"special_filesystems",
"parent",
"pod",
"default_gateways",
"current_commissioning_result_id",
"current_testing_result_id",
"current_installation_result_id",
"commissioning_status",
"commissioning_status_name",
"testing_status",
"testing_status_name",
"cpu_test_status",
"cpu_test_status_name",
"memory_test_status",
"memory_test_status_name",
"network_test_status",
"network_test_status_name",
"storage_test_status",
"storage_test_status_name",
"other_test_status",
"other_test_status_name",
"hardware_info",
"interface_test_status",
"interface_test_status_name",
("numanode_set", DISPLAYED_NUMANODE_FIELDS),
"virtualmachine_id",
"workload_annotations",
"last_sync",
"sync_interval",
"next_sync",
"enable_hw_sync",
"enable_kernel_crash_dump",
)
# Limited set of machine fields exposed on the anonymous API.
DISPLAYED_ANON_MACHINE_FIELDS = (
"system_id",
"hostname",
"domain",
"fqdn",
"architecture",
"status",
"power_type",
"power_state",
"zone",
"status_action",
"status_message",
"status_name",
"node_type",
)
AllocationOptions = namedtuple(
"AllocationOptions",
(
"agent_name",
"bridge_all",
"bridge_type",
"bridge_fd",
"bridge_stp",
"comment",
"install_rackd",
"install_kvm",
"register_vmhost",
"ephemeral_deploy",
"enable_hw_sync",
),
)
def get_storage_layout_params(request, required=False, extract_params=False):
"""Return and validate the storage_layout parameter."""
form = StorageLayoutForm(required=required, data=request.data)
if not form.is_valid():
raise MAASAPIValidationError(form.errors)
# The request data needs to be mutable so replace the immutable QueryDict
# with a mutable one.
request.data = request.data.copy()
storage_layout = request.data.pop("storage_layout", None)
if not storage_layout:
storage_layout = None
else:
storage_layout = storage_layout[0]
params = {}
# Grab all the storage layout parameters.
if extract_params:
for key, value in request.data.items():
if key.startswith("storage_layout_"):
params[key.replace("storage_layout_", "")] = value
# Remove the storage_layout_ parameters from the request.
for key in params:
request.data.pop("storage_layout_%s" % key)
return storage_layout, params
def get_allocation_options(request) -> AllocationOptions:
"""Parses optional parameters for allocation and deployment."""
comment = get_optional_param(request.POST, "comment")
default_bridge_all = False
install_rackd = get_optional_param(
request.POST, "install_rackd", default=False, validator=StringBool
)
install_kvm = get_optional_param(
request.POST, "install_kvm", default=False, validator=StringBool
)
register_vmhost = get_optional_param(
request.POST, "register_vmhost", default=False, validator=StringBool
)
ephemeral_deploy = get_optional_param(
request.POST, "ephemeral_deploy", default=False, validator=StringBool
)
if (install_kvm or register_vmhost) and not ephemeral_deploy:
default_bridge_all = True
bridge_all = get_optional_param(
request.POST,
"bridge_all",
default=default_bridge_all,
validator=StringBool,
)
bridge_type = get_optional_param(
request.POST, "bridge_type", default=BRIDGE_TYPE.STANDARD
)
if bridge_type not in BRIDGE_TYPE_CHOICES_DICT:
raise MAASAPIValidationError(
{
"bridge_type": compose_invalid_choice_text(
"bridge_type", BRIDGE_TYPE_CHOICES
)
}
)
bridge_stp = get_optional_param(
request.POST, "bridge_stp", default=False, validator=StringBool
)
bridge_fd = get_optional_param(
request.POST, "bridge_fd", default=0, validator=Int
)
enable_hw_sync = get_optional_param(
request.POST, "enable_hw_sync", default=False, validator=StringBool
)
agent_name = request.data.get("agent_name", "")
return AllocationOptions(
agent_name,
bridge_all,
bridge_type,
bridge_fd,
bridge_stp,
comment,
install_rackd,
install_kvm,
register_vmhost,
ephemeral_deploy,
enable_hw_sync,
)
def get_allocated_composed_machine(
request, data, storage, interfaces, pods, form, input_constraints
):
"""Return composed machine if input constraints are matched."""
machine = None
# Gather tags and not_tags.
tags = None
not_tags = None
for name, value in input_constraints:
if name == "tags":
tags = value
elif name == "not_tags":
not_tags = value
if tags:
pods = pods.filter(tags__contains=tags)
if not_tags:
pods = pods.exclude(tags__contains=not_tags)
if form.cleaned_data.get("pod"):
pods = pods.filter(name__in=form.cleaned_data.get("pod"))
if form.cleaned_data.get("pod_type"):
pods = pods.filter(power_type__in=form.cleaned_data.get("pod_type"))
if form.cleaned_data.get("not_pod"):
pods = pods.exclude(name__in=form.cleaned_data.get("not_pod"))
if form.cleaned_data.get("not_pod_type"):
pods = pods.exclude(
power_type__in=form.cleaned_data.get("not_pod_type")
)
compose_form = ComposeMachineForPodsForm(
request=request, data=data, pods=pods
)
if compose_form.is_valid():
machine = compose_form.compose()
if machine is not None:
# Set the storage variable so the constraint_map is
# set correct for the composed machine.
storage = nodes_by_storage(storage, node_ids=[machine.id])
if storage is None:
storage = {}
if interfaces:
result = nodes_by_interface(
interfaces,
include_filter=dict(node_config__node_id=machine.id),
)
interfaces = result.label_map
else:
interfaces = {}
return machine, storage, interfaces
class MachineHandler(NodeHandler, WorkloadAnnotationsMixin, PowerMixin):
"""
Manage an individual machine.
A machine is identified by its system_id.
"""
api_doc_section_name = "Machine"
model = Machine
fields = DISPLAYED_MACHINE_FIELDS
def delete(self, request, system_id):
"""@description-title Delete a machine
@description Deletes a machine with the given system_id.
Note: A machine cannot be deleted if it hosts pod virtual machines.
Use ``force`` to override this behavior. Forcing deletion will also
remove hosted pods. E.g. ``/machines/abc123/?force=1``.
@param (string) "{system_id}" [required=true] The machines's system_id.
@success (http-status-code) "204" 204
@error (http-status-code) "400" 400
@error (content) "no-delete" The machine cannot be deleted.
@error (http-status-code) "403" 403
@error (content) "no-perms" The user does not have permission to delete
this machine.
@error (http-status-code) "404" 404
@error (content) "not-found" The requested static-route is not found.
@error-example "not-found"
No Machine matches the given query.
"""
node = self.model.objects.get_node_or_404(
system_id=system_id, user=request.user, perm=NodePermission.admin
)
node.as_self().delete(
force=get_optional_param(request.GET, "force", False, StringBool)
)
return rc.DELETED
@classmethod
def boot_disk(handler, machine):
"""Return the boot_disk for the machine."""
return machine.get_boot_disk()
@classmethod
def boot_interface(handler, machine):
"""The network interface which is used to boot over the network."""
return machine.get_boot_interface()
@classmethod
def parent(handler, machine):
"""The parent machine this machine is child to."""
parent = machine.parent
if parent is not None:
return {
"system_id": parent.system_id,
"resource_uri": reverse(
"machine_handler", args=[parent.system_id]
),
"__incomplete__": True,
}
@classmethod
def pod(handler, machine):
"""The pod this machine is part of."""
bmc = machine.bmc
if bmc is None:
return None
elif bmc.bmc_type == BMC_TYPE.POD:
return {
"id": bmc.id,
"name": bmc.name,
"resource_uri": reverse("pod_handler", kwargs={"id": bmc.id}),
}
else:
return None
@classmethod
def blockdevice_set(handler, machine):
return [
block_device.actual_instance
for block_device in machine.current_config.blockdevice_set.all()
]
@classmethod
def physicalblockdevice_set(handler, machine):
"""Use precached queries instead of attribute on the object."""
return [
block_device.actual_instance
for block_device in machine.current_config.blockdevice_set.all()
if isinstance(block_device.actual_instance, PhysicalBlockDevice)
]
@classmethod
def virtualblockdevice_set(handler, machine):
"""Use precached queries instead of attribute on the object."""
return [
block_device.actual_instance
for block_device in machine.current_config.blockdevice_set.all()
if isinstance(block_device.actual_instance, VirtualBlockDevice)
]
@classmethod
def _filesystem_groups(handler, machine):
"""Return the `FilesystemGroup` for `machine`."""
fsgroup = {}
for block_device in machine.current_config.blockdevice_set.all():
for filesystem in block_device.filesystem_set.all():
if filesystem.filesystem_group is not None:
fsgroup[filesystem.filesystem_group.id] = (
filesystem.filesystem_group
)
for ptable in block_device.partitiontable_set.all():
for partition in ptable.partitions.all():
for filesystem in partition.filesystem_set.all():
if filesystem.filesystem_group is not None:
fsgroup[filesystem.filesystem_group.id] = (
filesystem.filesystem_group
)
return fsgroup.values()
@classmethod
def volume_groups(handler, machine):
"""Return the volume groups on this machine."""
return [
{
"system_id": machine.system_id,
"id": fsgroup.id,
"__incomplete__": True,
}
for fsgroup in handler._filesystem_groups(machine)
if fsgroup.is_lvm()
]
@classmethod
def raids(handler, machine):
"""Return the raids on this machine."""
return [
{
"system_id": machine.system_id,
"id": fsgroup.id,
"__incomplete__": True,
}
for fsgroup in handler._filesystem_groups(machine)
if fsgroup.is_raid()
]
@classmethod
def cache_sets(handler, machine):
"""Return the cache sets on this machine."""
sets = {}
for block_device in machine.current_config.blockdevice_set.all():
for filesystem in block_device.filesystem_set.all():
if filesystem.cache_set is not None:
sets[filesystem.cache_set.id] = filesystem.cache_set
for ptable in block_device.partitiontable_set.all():
for partition in ptable.partitions.all():
for filesystem in partition.filesystem_set.all():
if filesystem.cache_set is not None:
sets[filesystem.cache_set.id] = (
filesystem.cache_set
)
return [
{
"system_id": machine.system_id,
"id": cacheset_id,
"__incomplete__": True,
}
for cacheset_id in sets
]
@classmethod
def bcaches(handler, machine):
"""Return the bcaches on this machine."""
return [
{
"system_id": machine.system_id,
"id": fsgroup.id,
"__incomplete__": True,
}
for fsgroup in handler._filesystem_groups(machine)
if fsgroup.is_bcache()
]
@classmethod
def default_gateways(handler, machine):
"""The default gateways that will be used for this machine."""
gateways = machine.get_default_gateways()
ipv4 = gateways.ipv4.gateway_ip if gateways.ipv4 is not None else None
ipv6 = gateways.ipv6.gateway_ip if gateways.ipv6 is not None else None
return {
"ipv4": {
"gateway_ip": ipv4,
"link_id": machine.gateway_link_ipv4_id,
},
"ipv6": {
"gateway_ip": ipv6,
"link_id": machine.gateway_link_ipv6_id,
},
}
@classmethod
def virtualmachine_id(handler, machine):
"""The ID of the VirtualMachine associated to this machine, or None."""
vm = getattr(machine, "virtualmachine", None)
if vm is None:
return None
return vm.id
def update(self, request, system_id):
"""@description-title Update a machine
@description Updates a machine with the given system_id.
@param (string) "{system_id}" [required=true] The machines's system_id.
@param (string) "hostname" [required=false] The new hostname for this
machine.
@param (string) "description" [required=false] The new description for
this machine.
@param (string) "domain" [required=false] The domain for this machine.
If not given the default domain is used.
@param (string) "architecture" [required=false] The new architecture
for this machine.
@param (string) "min_hwe_kernel" [required=false] A string containing
the minimum kernel version allowed to be ran on this machine.
@param (string) "power_type" [required=false] The new power type for
this machine. If you use the default value, power_parameters will be
set to the empty string. Available to admin users. See the `Power
types`_ section for a list of the available power types.
@param (string) "power_parameters_{param1}" [required=false] The new
value for the 'param1' power parameter. Note that this is dynamic as
the available parameters depend on the selected value of the Machine's
power_type. Available to admin users. See the `Power types`_ section
for a list of the available power parameters for each power type.
@param (boolean) "power_parameters_skip_check" [required=false]
Whether or not the new power parameters for this machine should be
checked against the expected power parameters for the machine's power
type ('true' or 'false'). The default is 'false'.
@param (string) "pool" [required=false] The resource pool to which the
machine should belong. All machines belong to the 'default' resource
pool if they do not belong to any other resource pool.
@param (string) "zone" [required=false] Name of a valid physical zone
in which to place this machine.
@param (string) "swap_size" [required=false] Specifies the size of the
swap file, in bytes. Field accept K, M, G and T suffixes for values
expressed respectively in kilobytes, megabytes, gigabytes and
terabytes.
@param (boolean) "disable_ipv4" [required=false] Deprecated. If
specified, must be false.
@param (int) "cpu_count" [required=false] The amount of CPU cores the
machine has.
@param (string) "memory" [required=false] How much memory the machine
has. Field accept K, M, G and T suffixes for values expressed
respectively in kilobytes, megabytes, gigabytes and terabytes.
@success (http-status-code) "200" 200
@success (json) "success-json" A JSON object containing information
about the updated machine.
@success-example "success-json" [exkey=machines-update]
placeholder text
@error (http-status-code) "404" 404
@error (content) "not-found" The requested machine is not found.
@error-example "not-found"
No Machine matches the given query.
@error (http-status-code) "403" 403
@error (content) "no-perms" The user does not have permission to update
this machine.
"""
machine = self.model.objects.get_node_or_404(
system_id=system_id, user=request.user, perm=NodePermission.admin
)
Form = get_machine_edit_form(request.user)
form = Form(data=request.data, instance=machine)
if form.is_valid():
return form.save()
else:
raise MAASAPIValidationError(form.errors)
@classmethod
def resource_uri(cls, machine=None):
# This method is called by piston in two different contexts:
# - when generating an uri template to be used in the documentation
# (in this case, it is called with node=None).
# - when populating the 'resource_uri' field of an object
# returned by the API (in this case, machine is a Machine object).
machine_system_id = "system_id"
if machine is not None:
machine_system_id = machine.system_id
return ("machine_handler", (machine_system_id,))
@operation(idempotent=True)
def get_token(self, request, system_id):
"""@description-title Get a machine token
@param (string) "{system_id}" [required=true] The machines' system_id.
@success (http-status-code) "200" 200
@success (json) "success-json" A JSON object containing information
about the machine token.
@success-example "success-json" [exkey=machines-placeholder]
placeholder text
@error (http-status-code) "404" 404
@error (content) "not-found" The requested machine is not found.
@error-example "not-found"
No Machine matches the given query.
"""
node = self.model.objects.get_node_or_404(
system_id=system_id,
user=request.user,
perm=NodePermission.admin_read,
)
try:
token = Token.objects.select_related("consumer").get(
nodekey__node=node
)
except Token.DoesNotExist:
return None
return {
"token_key": token.key,
"token_secret": token.secret,
"consumer_key": token.consumer.key,
}
@operation(idempotent=False)
def deploy(self, request, system_id):
"""@description-title Deploy a machine
@description Deploys an operating system to a machine with the given
system_id.
@param (string) "{system_id}" [required=true] The machines's system_id.
@param (string) "user_data" [required=false] If present, this blob of
base64-encoded user-data to be made available to the machines through
the metadata service.
@param (string) "distro_series" [required=false] If present, this
parameter specifies the OS release the machine will use. For example
valid values to deploy Jammy Jellyfish are ``ubuntu/jammy``, ``jammy`` and
``ubuntu/22.04``, ``22.04``.
@param-example "distro_series"
ubuntu/jammy
@param (string) "hwe_kernel" [required=false] If present, this
parameter specified the kernel to be used on the machine
@param (string) "agent_name" [required=false] An optional agent name to
attach to the acquired machine.
@param (boolean) "bridge_all" [required=false] Optionally create a
bridge interface for every configured interface on the machine. The
created bridges will be removed once the machine is released.
(Default: false)
@param (string) "bridge_type" [required=false] Optionally create the
bridges with this type. Possible values are: ``standard``, ``ovs``.
@param (boolean) "bridge_stp" [required=false] Optionally turn spanning
tree protocol on or off for the bridges created on every configured
interface. (Default: false)
@param (int) "bridge_fd" [required=false] Optionally adjust the forward
delay to time seconds. (Default: 15)
@param (string) "comment" [required=false] Optional comment for the
event log.
@param (boolean) "install_rackd" [required=false] If true, the rack
controller will be installed on this machine.
@param (boolean) "install_kvm" [required=false] If true, KVM will be
installed on this machine and added to MAAS.
@param (boolean) "register_vmhost" [required=false] If true, the
machine will be registered as a LXD VM host in MAAS.
@param (boolean) "ephemeral_deploy" [required=false] If true, machine
will be deployed ephemerally even if it has disks.
@param (boolean) "enable_kernel_crash_dump" [required=false] If true, machine
will be deployed with the kernel crash dump feature enabled and configured automatically.
@param (boolean) "vcenter_registration" [required=false] If false, do
not send globally defined VMware vCenter credentials to the machine.
@param (boolean) "enable_hw_sync" [required=false] If true, machine
will be deployed with a small agent periodically pushing hardware data to detect
any change in devices.
@success (http-status-code) "200" 200
@success (json) "success-json" A JSON object containing information
about the deployed machine.
@success-example "success-json" [exkey=machines-deploy] placeholder
text
@error (http-status-code) "404" 404
@error (content) "not-found" The requested machine is not found.
@error-example "not-found"
No Machine matches the given query.
@error (http-status-code) "403" 403
@error (content) "no-perms" The user does not have permission to deploy
this machine.
@error (http-status-code) "503" 503
@error (content) "no-ips" MAAS attempted to allocate an IP address, and
there were no IP addresses available on the relevant cluster interface.
"""
series = request.POST.get("distro_series", None)
license_key = request.POST.get("license_key", None)
hwe_kernel = request.POST.get("hwe_kernel", None)
enable_kernel_crash_dump = request.POST.get(
"enable_kernel_crash_dump", None
)
# Acquiring a node requires EDIT permissions.
machine = self.model.objects.get_node_or_404(
system_id=system_id, user=request.user, perm=NodePermission.edit
)
options = get_allocation_options(request)
# Deploying a node requires re-checking for EDIT permissions.
if not request.user.has_perm(NodePermission.edit, machine):
raise PermissionDenied()
if options.install_rackd and not request.user.has_perm(
NodePermission.admin, machine
):
raise PermissionDenied("Only administrators can deploy MAAS racks")
if (
options.install_kvm or options.register_vmhost
) and not request.user.has_perm(NodePermission.admin, machine):
raise PermissionDenied("Only administratros can deploy VM hosts")
ephemeral_deploy = options.ephemeral_deploy or machine.is_diskless
if (
options.install_kvm or options.register_vmhost
) and ephemeral_deploy:
raise MAASAPIBadRequest(
"A machine can not be a VM host if it is deployed to memory."
)
if machine.status == NODE_STATUS.READY:
with locks.node_acquire:
if machine.owner is not None and machine.owner != request.user:
raise NodeStateViolation(
"Can't allocate a machine belonging to another user."
)
maaslog.info(
"Request from user %s to acquire machine: %s (%s)",
request.user.username,
machine.fqdn,
machine.system_id,
)
machine.acquire(
request.user,
agent_name=options.agent_name,
comment=options.comment,
bridge_all=options.bridge_all,
bridge_type=options.bridge_type,
bridge_stp=options.bridge_stp,
bridge_fd=options.bridge_fd,
)
if NODE_STATUS.DEPLOYING not in NODE_TRANSITIONS[machine.status]:
raise NodeStateViolation(
"Can't deploy a machine that is in the '{}' state".format(
NODE_STATUS_CHOICES_DICT[machine.status]
)
)
if not series:
series = Config.objects.get_config("default_distro_series")
Form = get_machine_edit_form(request.user)
form = Form(instance=machine, data={})
form.set_distro_series(series=series)
if license_key is not None:
form.set_license_key(license_key=license_key)
if hwe_kernel is not None:
form.set_hwe_kernel(hwe_kernel=hwe_kernel)
form.set_enable_kernel_crash_dump(
enable_kernel_crash_dump=(
Config.objects.get_config("enable_kernel_crash_dump")
if enable_kernel_crash_dump is None
else enable_kernel_crash_dump
)
)
form.set_install_rackd(install_rackd=options.install_rackd)
form.set_ephemeral_deploy(ephemeral_deploy=ephemeral_deploy)
form.set_enable_hw_sync(enable_hw_sync=options.enable_hw_sync)
if form.is_valid():
form.save()
else:
raise MAASAPIValidationError(form.errors)
# Check that the curtin preseeds renders correctly
# if not an ephemeral deployment.
if not ephemeral_deploy:
try:
get_curtin_merged_config(request, machine)
except Exception as e:
raise MAASAPIBadRequest("Failed to render preseed: %s" % e) # noqa: B904
if machine.osystem == "esxi" and request.user.has_perm(
NodePermission.admin, machine
):
if get_optional_param(
request.POST,
"vcenter_registration",
default=True,
validator=StringBool,
):
NodeMetadata.objects.update_or_create(
node=machine,
key="vcenter_registration",
defaults={"value": "True"},
)
else:
NodeMetadata.objects.filter(
node=machine, key="vcenter_registration"
).delete()
return self.power_on(request, system_id)
@operation(idempotent=False)
def release(self, request, system_id):
"""@description-title Release a machine
@description Releases a machine with the given system_id. Note that
this operation is the opposite of allocating a machine.
**Erasing drives**:
If neither ``secure_erase`` nor ``quick_erase`` are specified, MAAS
will overwrite the whole disk with null bytes. This can be very slow.
If both ``secure_erase`` and ``quick_erase`` are specified and the
drive does NOT have a secure erase feature, MAAS will behave as if only
``quick_erase`` was specified.
If ``secure_erase`` is specified and ``quick_erase`` is NOT specified
and the drive does NOT have a secure erase feature, MAAS will behave as
if ``secure_erase`` was NOT specified, i.e. MAAS will overwrite the
whole disk with null bytes. This can be very slow.
@param (string) "{system_id}" [required=true] The machines's system_id.
@param (string) "comment" [required=false] Optional comment for the
event log.
@param (boolean) "erase" [required=false] Erase the disk when
releasing.
@param (boolean) "secure_erase" [required=false] Use the drive's secure
erase feature if available. In some cases, this can be much faster
than overwriting the drive. Some drives implement secure erasure by
overwriting themselves so this could still be slow.
@param (boolean) "quick_erase" [required=false] Wipe 2MiB at the start
and at the end of the drive to make data recovery inconvenient and
unlikely to happen by accident. This is not secure.
@param (boolean) "force" [required=false] Will force the release of a
machine. If the machine was deployed as a KVM host, this will be
deleted as well as all machines inside the KVM host. USE WITH CAUTION.
@success (http-status-code) "200" 200
@success (json) "success-json" A JSON object containing information
about the released machine.
@success-example "success-json" [exkey=machines-release] placeholder
text
@error (http-status-code) "404" 404
@error (content) "not-found" The requested machine is not found.
@error-example "not-found"
No Machine matches the given query.
@error (http-status-code) "403" 403
@error (content) "no-perms" The user does not have permission to
release this machine.
@error (http-status-code) "409" 409
@error (content) "no-release" The machine is in a state that prevents
it from being released.
"""
machine = self.model.objects.get_node_or_404(
system_id=system_id, user=request.user, perm=NodePermission.edit
)
form = ReleaseForm(
instance=machine, user=request.user, data=request.data
)
if not form.is_valid():
raise MAASAPIValidationError(form.errors)
if machine.status in (NODE_STATUS.RELEASING, NODE_STATUS.READY):
# Nothing to do if this machine is already releasing, otherwise
# this may be a redundant retry, and the
# postcondition is achieved, so call this success.
pass
elif machine.status in RELEASABLE_STATUSES:
scripts = form.cleaned_data["scripts"]
params = {}
if form.cleaned_data["erase"]:
params["wipe-disks"] = {}
params["wipe-disks"]["secure_erase"] = form.cleaned_data[
"secure_erase"
]
params["wipe-disks"]["quick_erase"] = form.cleaned_data[