-
Notifications
You must be signed in to change notification settings - Fork 75
/
Copy pathlinode.py
2047 lines (1646 loc) · 67 KB
/
linode.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
import string
import sys
from dataclasses import dataclass, field
from datetime import datetime
from enum import Enum
from os import urandom
from random import randint
from typing import Any, Dict, List, Optional, Union
from urllib import parse
from linode_api4.common import load_and_validate_keys
from linode_api4.errors import UnexpectedResponseError
from linode_api4.objects.base import (
Base,
MappedObject,
Property,
_flatten_request_body_recursive,
)
from linode_api4.objects.dbase import DerivedBase
from linode_api4.objects.filtering import FilterableAttribute
from linode_api4.objects.image import Image
from linode_api4.objects.networking import (
Firewall,
IPAddress,
IPv6Range,
VPCIPAddress,
)
from linode_api4.objects.nodebalancer import NodeBalancer
from linode_api4.objects.region import Region
from linode_api4.objects.serializable import JSONObject, StrEnum
from linode_api4.objects.vpc import VPC, VPCSubnet
from linode_api4.paginated_list import PaginatedList
from linode_api4.util import drop_null_keys
PASSWORD_CHARS = string.ascii_letters + string.digits + string.punctuation
class InstanceDiskEncryptionType(StrEnum):
"""
InstanceDiskEncryptionType defines valid values for the
Instance(...).disk_encryption field.
API Documentation: TODO
"""
enabled = "enabled"
disabled = "disabled"
class Backup(DerivedBase):
"""
A Backup of a Linode Instance.
API Documentation: https://techdocs.akamai.com/linode-api/reference/get-backup
"""
api_endpoint = "/linode/instances/{linode_id}/backups/{id}"
derived_url_path = "backups"
parent_id_name = "linode_id"
properties = {
"id": Property(identifier=True),
"created": Property(is_datetime=True),
"duration": Property(),
"updated": Property(is_datetime=True),
"finished": Property(is_datetime=True),
"message": Property(),
"status": Property(volatile=True),
"type": Property(),
"linode_id": Property(identifier=True),
"label": Property(),
"configs": Property(),
"disks": Property(),
"region": Property(slug_relationship=Region),
"available": Property(),
}
def restore_to(self, linode, **kwargs):
"""
Restores a Linode’s Backup to the specified Linode.
API Documentation: https://techdocs.akamai.com/linode-api/reference/post-restore-backup
:param linode: The id of the Instance or the Instance to share the IPAddresses with.
This Instance will be able to bring up the given addresses.
:type: linode: int or Instance
:param kwargs: A dict containing the The ID of the Linode to restore a Backup to and
a boolean that, if True, deletes all Disks and Configs on
the target Linode before restoring.
:type: kwargs: dict
Example usage:
kwargs = {
"linode_id": 123,
"overwrite": true
}
:returns: Returns true if the operation was successful
:rtype: bool
"""
d = {
"linode_id": linode,
}
d.update(kwargs)
self._client.post(
"{}/restore".format(Backup.api_endpoint),
model=self,
data=_flatten_request_body_recursive(d),
)
return True
class Disk(DerivedBase):
"""
A Disk for the storage space on a Compute Instance.
API Documentation: https://techdocs.akamai.com/linode-api/reference/get-linode-disk
"""
api_endpoint = "/linode/instances/{linode_id}/disks/{id}"
derived_url_path = "disks"
parent_id_name = "linode_id"
properties = {
"id": Property(identifier=True),
"created": Property(is_datetime=True),
"label": Property(mutable=True),
"size": Property(),
"status": Property(volatile=True),
"filesystem": Property(),
"updated": Property(is_datetime=True),
"linode_id": Property(identifier=True),
"disk_encryption": Property(),
}
def duplicate(self):
"""
Copies a disk, byte-for-byte, into a new Disk belonging to the same Linode. The Linode must have enough
storage space available to accept a new Disk of the same size as this one or this operation will fail.
API Documentation: https://techdocs.akamai.com/linode-api/reference/post-clone-linode-disk
:returns: A Disk object representing the cloned Disk
:rtype: Disk
"""
d = self._client.post("{}/clone".format(Disk.api_endpoint), model=self)
if not "id" in d:
raise UnexpectedResponseError(
"Unexpected response duplicating disk!", json=d
)
return Disk(self._client, d["id"], self.linode_id)
def reset_root_password(self, root_password=None):
"""
Resets the password of a Disk you have permission to read_write.
API Documentation: https://techdocs.akamai.com/linode-api/reference/post-reset-disk-password
:param root_password: The new root password for the OS installed on this Disk. The password must meet the complexity
strength validation requirements for a strong password.
:type: root_password: str
"""
rpass = root_password
if not rpass:
rpass = Instance.generate_root_password()
params = {
"password": rpass,
}
self._client.post(
"{}/password".format(Disk.api_endpoint), model=self, data=params
)
def resize(self, new_size):
"""
Resizes this disk. The Linode Instance this disk belongs to must have
sufficient space available to accommodate the new size, and must be
offline.
**NOTE** If resizing a disk down, the filesystem on the disk must still
fit on the new disk size. You may need to resize the filesystem on the
disk first before performing this action.
API Documentation: https://techdocs.akamai.com/linode-api/reference/post-resize-disk
:param new_size: The intended new size of the disk, in MB
:type new_size: int
:returns: True if the resize was initiated successfully.
:rtype: bool
"""
self._client.post(
"{}/resize".format(Disk.api_endpoint),
model=self,
data={"size": new_size},
)
return True
class Kernel(Base):
"""
The primary component of every Linux system. The kernel interfaces
with the system’s hardware and it controls the operating system’s core functionality.
Your Compute Instance is capable of running one of three kinds of kernels:
- Upstream kernel (or distribution-supplied kernel): This kernel is maintained
and provided by your Linux distribution. A major benefit of this kernel is that the
distribution was designed with this kernel in mind and all updates are managed through
the distributions package management system. It also may support features not present
in the Linode kernel (for example, SELinux).
- Linode kernel: Linode also maintains kernels that can be used on a Compute Instance.
If selected, these kernels are provided to your Compute Instance at boot
(not directly installed on your system). The Current Kernels page displays a
list of all the available Linode kernels.
- Custom-compiled kernel: A kernel that you compile from source. Compiling a kernel
can let you use features not available in the upstream or Linode kernels, but it takes longer
to compile the kernel from source than to download it from your package manager. For more
information on custom compiled kernels, review our guides for Debian, Ubuntu, and CentOS.
API Documentation: https://techdocs.akamai.com/linode-api/reference/get-kernel
"""
api_endpoint = "/linode/kernels/{id}"
properties = {
"created": Property(is_datetime=True),
"deprecated": Property(),
"description": Property(),
"id": Property(identifier=True),
"kvm": Property(),
"label": Property(),
"updates": Property(),
"version": Property(),
"architecture": Property(),
"xen": Property(),
"built": Property(),
"pvops": Property(),
}
class Type(Base):
"""
Linode Plan type to specify the resources available to a Linode Instance.
API Documentation: https://techdocs.akamai.com/linode-api/reference/get-linode-type
"""
api_endpoint = "/linode/types/{id}"
properties = {
"disk": Property(),
"id": Property(identifier=True),
"label": Property(),
"network_out": Property(),
"price": Property(),
"region_prices": Property(),
"addons": Property(),
"memory": Property(),
"transfer": Property(),
"vcpus": Property(),
"gpus": Property(),
"successor": Property(),
"accelerated_devices": Property(),
# type_class is populated from the 'class' attribute of the returned JSON
}
def _populate(self, json):
"""
Allows changing the name "class" in JSON to "type_class" in python
"""
super()._populate(json)
if json is not None and "class" in json:
setattr(self, "type_class", json["class"])
else:
setattr(self, "type_class", None)
# allow filtering on this converted type
type_class = FilterableAttribute("class")
@dataclass
class ConfigInterfaceIPv4(JSONObject):
"""
ConfigInterfaceIPv4 represents the IPv4 configuration of a VPC interface.
"""
vpc: str = ""
nat_1_1: str = ""
@dataclass
class ConfigInterfaceIPv6SLAACOptions(JSONObject):
"""
ConfigInterfaceIPv6SLAACOptions is used to set a single IPv6 SLAAC configuration of a VPC interface.
"""
range: str = ""
@dataclass
class ConfigInterfaceIPv6RangeOptions(JSONObject):
"""
ConfigInterfaceIPv6RangeOptions is used to set a single IPv6 range configuration of a VPC interface.
"""
range: str = ""
@dataclass
class ConfigInterfaceIPv6Options(JSONObject):
"""
ConfigInterfaceIPv6Options is used to set the IPv6 configuration of a VPC interface.
"""
slaac: List[ConfigInterfaceIPv6SLAACOptions] = field(
default_factory=lambda: []
)
ranges: List[ConfigInterfaceIPv6RangeOptions] = field(
default_factory=lambda: []
)
is_public: bool = False
@dataclass
class ConfigInterfaceIPv6SLAAC(JSONObject):
"""
ConfigInterfaceIPv6SLAAC represents a single SLAAC address under a VPC interface's IPv6 configuration.
"""
put_class = ConfigInterfaceIPv6SLAACOptions
range: str = ""
address: str = ""
@dataclass
class ConfigInterfaceIPv6Range(JSONObject):
"""
ConfigInterfaceIPv6Range represents a single IPv6 address under a VPC interface's IPv6 configuration.
"""
put_class = ConfigInterfaceIPv6RangeOptions
range: str = ""
@dataclass
class ConfigInterfaceIPv6(JSONObject):
"""
ConfigInterfaceIPv6 represents the IPv6 configuration of a VPC interface.
"""
put_class = ConfigInterfaceIPv6Options
slaac: List[ConfigInterfaceIPv6SLAAC] = field(default_factory=lambda: [])
ranges: List[ConfigInterfaceIPv6Range] = field(default_factory=lambda: [])
is_public: bool = False
class NetworkInterface(DerivedBase):
"""
This class represents a Configuration Profile's network interface object.
NOTE: This class cannot be used for the `interfaces` attribute on Config
POST and PUT requests.
API Documentation: https://techdocs.akamai.com/linode-api/reference/get-linode-config-interface
"""
api_endpoint = (
"/linode/instances/{instance_id}/configs/{config_id}/interfaces/{id}"
)
derived_url_path = "interfaces"
parent_id_name = "config_id"
properties = {
"id": Property(identifier=True),
"purpose": Property(),
"label": Property(),
"ipam_address": Property(),
"primary": Property(mutable=True),
"active": Property(),
"vpc_id": Property(id_relationship=VPC),
"subnet_id": Property(),
"ipv4": Property(mutable=True, json_object=ConfigInterfaceIPv4),
"ipv6": Property(mutable=True, json_object=ConfigInterfaceIPv6),
"ip_ranges": Property(mutable=True),
}
def __init__(self, client, id, parent_id, instance_id=None, json=None):
"""
We need a special constructor here because this object's parent
has a parent itself.
"""
if not instance_id and not isinstance(parent_id, tuple):
raise ValueError(
"ConfigInterface must either be created with a instance_id or a tuple of "
"(config_id, instance_id) for parent_id!"
)
if isinstance(parent_id, tuple):
instance_id = parent_id[1]
parent_id = parent_id[0]
DerivedBase.__init__(self, client, id, parent_id, json=json)
self._set("instance_id", instance_id)
def __repr__(self):
return f"Interface: {self.purpose} {self.id}"
@property
def subnet(self) -> VPCSubnet:
"""
Get the subnet this VPC is referencing.
:returns: The VPCSubnet associated with this interface.
:rtype: VPCSubnet
"""
return VPCSubnet(self._client, self.subnet_id, self.vpc_id)
@dataclass
class InstancePlacementGroupAssignment(JSONObject):
"""
Represents an assignment between an instance and a Placement Group.
This is intended to be used when creating, cloning, and migrating
instances.
"""
id: int
compliant_only: bool = False
@dataclass
class ConfigInterface(JSONObject):
"""
Represents a single interface in a Configuration Profile.
This class only contains data about a config interface.
If you would like to access a config interface directly,
consider using :any:`NetworkInterface`.
API Documentation: https://techdocs.akamai.com/linode-api/reference/get-linode-config-interface
"""
purpose: str = "public"
# Public/VPC-specific
primary: Optional[bool] = None
# VLAN-specific
label: Optional[str] = None
ipam_address: Optional[str] = None
# VPC-specific
vpc_id: Optional[int] = None
subnet_id: Optional[int] = None
ipv4: Optional[Union[ConfigInterfaceIPv4, Dict[str, Any]]] = None
ipv6: Optional[Union[ConfigInterfaceIPv6, Dict[str, Any]]] = None
ip_ranges: Optional[List[str]] = None
# Computed
id: int = 0
def __repr__(self):
return f"Interface: {self.purpose}"
def _serialize(self, is_put: bool = False):
purpose_formats = {
"public": {"purpose": "public", "primary": self.primary},
"vlan": {
"purpose": "vlan",
"label": self.label,
"ipam_address": self.ipam_address,
},
"vpc": {
"purpose": "vpc",
"primary": self.primary,
"subnet_id": self.subnet_id,
"ipv4": self.ipv4,
"ipv6": self.ipv6,
"ip_ranges": self.ip_ranges,
},
}
if self.purpose not in purpose_formats:
raise ValueError(
f"Unknown interface purpose: {self.purpose}",
)
return _flatten_request_body_recursive(
{
k: v
for k, v in purpose_formats[self.purpose].items()
if v is not None
},
is_put=is_put,
)
class Config(DerivedBase):
"""
A Configuration Profile for a Linode Instance.
API Documentation: https://techdocs.akamai.com/linode-api/reference/get-linode-config
"""
api_endpoint = "/linode/instances/{linode_id}/configs/{id}"
derived_url_path = "configs"
parent_id_name = "linode_id"
properties = {
"id": Property(identifier=True),
"linode_id": Property(identifier=True),
"helpers": Property(mutable=True),
"created": Property(is_datetime=True),
"root_device": Property(mutable=True),
"kernel": Property(relationship=Kernel, mutable=True),
"devices": Property(), # TODO: mutable=True),
"initrd": Property(relationship=Disk),
"updated": Property(),
"comments": Property(mutable=True),
"label": Property(mutable=True),
"run_level": Property(mutable=True),
"virt_mode": Property(mutable=True),
"memory_limit": Property(mutable=True),
"interfaces": Property(mutable=True, json_object=ConfigInterface),
}
@property
def network_interfaces(self):
"""
Returns the Network Interfaces for this Configuration Profile.
This differs from the `interfaces` field as each NetworkInterface
object is treated as its own API object.
API Documentation: https://techdocs.akamai.com/linode-api/reference/get-linode-config-interfaces
"""
return [
NetworkInterface(
self._client, v.id, self.id, instance_id=self.linode_id
)
for v in self.interfaces
]
def _populate(self, json):
"""
Map devices more nicely while populating.
"""
if json is None or len(json) < 1:
return
# needed here to avoid circular imports
from .volume import Volume # pylint: disable=import-outside-toplevel
DerivedBase._populate(self, json)
devices = {}
for device_index, device in json["devices"].items():
if not device:
devices[device_index] = None
continue
dev = None
if "disk_id" in device and device["disk_id"]: # this is a disk
dev = Disk.make_instance(
device["disk_id"], self._client, parent_id=self.linode_id
)
else:
dev = Volume.make_instance(
device["volume_id"], self._client, parent_id=self.linode_id
)
devices[device_index] = dev
self._set("devices", MappedObject(**devices))
def _serialize(self, *args, **kwargs):
"""
Overrides _serialize to transform interfaces into json
"""
partial = DerivedBase._serialize(self, *args, **kwargs)
interfaces = []
for c in self.interfaces:
if isinstance(c, ConfigInterface):
interfaces.append(c._serialize(*args, **kwargs))
else:
interfaces.append(c)
partial["interfaces"] = interfaces
return partial
def interface_create_public(self, primary=False) -> NetworkInterface:
"""
Creates a public interface for this Configuration Profile.
API Documentation: https://techdocs.akamai.com/linode-api/reference/post-linode-config-interface
:param primary: Whether this interface is a primary interface.
:type primary: bool
:returns: The newly created NetworkInterface.
:rtype: NetworkInterface
"""
return self._interface_create({"purpose": "public", "primary": primary})
def interface_create_vlan(
self, label: str, ipam_address=None
) -> NetworkInterface:
"""
Creates a VLAN interface for this Configuration Profile.
API Documentation: https://techdocs.akamai.com/linode-api/reference/post-linode-config-interface
:param label: The label of the VLAN to associate this interface with.
:type label: str
:param ipam_address: The IPAM address of this interface for the associated VLAN.
:type ipam_address: str
:returns: The newly created NetworkInterface.
:rtype: NetworkInterface
"""
params = {
"purpose": "vlan",
"label": label,
}
if ipam_address is not None:
params["ipam_address"] = ipam_address
return self._interface_create(params)
def interface_create_vpc(
self,
subnet: Union[int, VPCSubnet],
primary=False,
ipv4: Union[Dict[str, Any], ConfigInterfaceIPv4] = None,
ipv6: Union[Dict[str, Any], ConfigInterfaceIPv6Options] = None,
ip_ranges: Optional[List[str]] = None,
) -> NetworkInterface:
"""
Creates a VPC interface for this Configuration Profile.
API Documentation: https://techdocs.akamai.com/linode-api/reference/post-linode-config-interface
:param subnet: The VPC subnet to associate this interface with.
:type subnet: int or VPCSubnet
:param primary: Whether this is a primary interface.
:type primary: bool
:param ipv4: The IPv4 configuration of the interface for the associated subnet.
:type ipv4: Dict or ConfigInterfaceIPv4
:param ipv6: The IPv6 configuration of the interface for the associated subnet.
:type ipv6: Dict or ConfigInterfaceIPv6Options
:param ip_ranges: A list of IPs or IP ranges in the VPC subnet.
Packets to these CIDRs are routed through the
VPC network interface.
:type ip_ranges: List of str
:returns: The newly created NetworkInterface.
:rtype: NetworkInterface
"""
params = {
"purpose": "vpc",
"subnet_id": subnet,
"primary": primary,
"ipv4": ipv4,
"ipv6": ipv6,
"ip_ranges": ip_ranges,
}
return self._interface_create(
drop_null_keys(_flatten_request_body_recursive(params))
)
def interface_reorder(self, interfaces: List[Union[int, NetworkInterface]]):
"""
Change the order of the interfaces for this Configuration Profile.
API Documentation: https://techdocs.akamai.com/linode-api/reference/post-linode-config-interfaces
:param interfaces: A list of interfaces in the desired order.
:type interfaces: List of str or NetworkInterface
"""
ids = [
v.id if isinstance(v, NetworkInterface) else v for v in interfaces
]
self._client.post(
"{}/interfaces/order".format(Config.api_endpoint),
model=self,
data={"ids": ids},
)
self.invalidate()
def _interface_create(self, body: Dict[str, Any]) -> NetworkInterface:
"""
The underlying ConfigInterface creation API call.
"""
result = self._client.post(
"{}/interfaces".format(Config.api_endpoint), model=self, data=body
)
self.invalidate()
if not "id" in result:
raise UnexpectedResponseError(
"Unexpected response creating Interface", json=result
)
i = NetworkInterface(
self._client, result["id"], self.id, self.linode_id, result
)
return i
class MigrationType:
COLD = "cold"
WARM = "warm"
class Instance(Base):
"""
A Linode Instance.
API Documentation: https://techdocs.akamai.com/linode-api/reference/get-linode-instance
"""
api_endpoint = "/linode/instances/{id}"
properties = {
"id": Property(identifier=True),
"label": Property(mutable=True),
"group": Property(mutable=True),
"status": Property(volatile=True),
"created": Property(is_datetime=True),
"updated": Property(volatile=True, is_datetime=True),
"region": Property(slug_relationship=Region),
"alerts": Property(mutable=True),
"image": Property(slug_relationship=Image),
"disks": Property(derived_class=Disk),
"configs": Property(derived_class=Config),
"type": Property(slug_relationship=Type),
"backups": Property(mutable=True),
"ipv4": Property(unordered=True),
"ipv6": Property(),
"hypervisor": Property(),
"specs": Property(),
"tags": Property(mutable=True, unordered=True),
"host_uuid": Property(),
"watchdog_enabled": Property(mutable=True),
"has_user_data": Property(),
"disk_encryption": Property(),
"lke_cluster_id": Property(),
"capabilities": Property(unordered=True),
}
@property
def ips(self):
"""
The ips related collection is not normalized like the others, so we have to
make an ad-hoc object to return for its response
API Documentation: https://techdocs.akamai.com/linode-api/reference/get-linode-ips
:returns: A List of the ips of the Linode Instance.
:rtype: List[IPAddress]
"""
if not hasattr(self, "_ips"):
result = self._client.get(
"{}/ips".format(Instance.api_endpoint), model=self
)
if not "ipv4" in result:
raise UnexpectedResponseError(
"Unexpected response loading IPs", json=result
)
v4pub = []
for c in result["ipv4"]["public"]:
i = IPAddress(self._client, c["address"], c)
v4pub.append(i)
v4pri = []
for c in result["ipv4"]["private"]:
i = IPAddress(self._client, c["address"], c)
v4pri.append(i)
shared_ips = []
for c in result["ipv4"]["shared"]:
i = IPAddress(self._client, c["address"], c)
shared_ips.append(i)
reserved = []
for c in result["ipv4"]["reserved"]:
i = IPAddress(self._client, c["address"], c)
reserved.append(i)
vpc = [
VPCIPAddress.from_json(v) for v in result["ipv4"].get("vpc", [])
]
slaac = IPAddress(
self._client,
result["ipv6"]["slaac"]["address"],
result["ipv6"]["slaac"],
)
link_local = IPAddress(
self._client,
result["ipv6"]["link_local"]["address"],
result["ipv6"]["link_local"],
)
ranges = [
IPv6Range(self._client, r["range"])
for r in result["ipv6"]["global"]
]
ips = MappedObject(
**{
"ipv4": {
"public": v4pub,
"private": v4pri,
"shared": shared_ips,
"reserved": reserved,
"vpc": vpc,
},
"ipv6": {
"slaac": slaac,
"link_local": link_local,
"ranges": ranges,
},
}
)
self._set("_ips", ips)
return self._ips
@property
def available_backups(self):
"""
The backups response contains what backups are available to be restored.
API Documentation: https://techdocs.akamai.com/linode-api/reference/get-backups
:returns: A List of the available backups for the Linode Instance.
:rtype: List[Backup]
"""
if not hasattr(self, "_avail_backups"):
result = self._client.get(
"{}/backups".format(Instance.api_endpoint), model=self
)
if not "automatic" in result:
raise UnexpectedResponseError(
"Unexpected response loading available backups!",
json=result,
)
automatic = []
for a in result["automatic"]:
cur = Backup(self._client, a["id"], self.id, a)
automatic.append(cur)
snap = None
if result["snapshot"]["current"]:
snap = Backup(
self._client,
result["snapshot"]["current"]["id"],
self.id,
result["snapshot"]["current"],
)
psnap = None
if result["snapshot"]["in_progress"]:
psnap = Backup(
self._client,
result["snapshot"]["in_progress"]["id"],
self.id,
result["snapshot"]["in_progress"],
)
self._set(
"_avail_backups",
MappedObject(
**{
"automatic": automatic,
"snapshot": {
"current": snap,
"in_progress": psnap,
},
}
),
)
return self._avail_backups
def reset_instance_root_password(self, root_password=None):
"""
Resets the root password for this Linode.
API Documentation: https://techdocs.akamai.com/linode-api/reference/post-reset-linode-password
:param root_password: The root user’s password on this Linode. Linode passwords must
meet a password strength score requirement that is calculated internally
by the API. If the strength requirement is not met, you will receive a
Password does not meet strength requirement error.
:type: root_password: str
"""
rpass = root_password
if not rpass:
rpass = Instance.generate_root_password()
params = {
"root_pass": rpass,
}
self._client.post(
"{}/password".format(Instance.api_endpoint), model=self, data=params
)
def transfer_year_month(self, year, month):
"""
Get per-linode transfer for specified month
API Documentation: https://techdocs.akamai.com/linode-api/reference/get-linode-transfer-by-year-month
:param year: Numeric value representing the year to look up.
:type: year: int
:param month: Numeric value representing the month to look up.
:type: month: int
:returns: The network transfer statistics for the specified month.
:rtype: MappedObject
"""
result = self._client.get(
"{}/transfer/{}/{}".format(
Instance.api_endpoint,
parse.quote(str(year)),
parse.quote(str(month)),
),
model=self,
)
return MappedObject(**result)
@property
def transfer(self):
"""
Get per-linode transfer
API Documentation: https://techdocs.akamai.com/linode-api/reference/get-linode-transfer
:returns: The network transfer statistics for the current month.
:rtype: MappedObject
"""
if not hasattr(self, "_transfer"):
result = self._client.get(
"{}/transfer".format(Instance.api_endpoint), model=self
)
if not "used" in result:
raise UnexpectedResponseError(
"Unexpected response when getting Transfer Pool!"
)
mapped = MappedObject(**result)
setattr(self, "_transfer", mapped)
return self._transfer
@property
def placement_group(self) -> Optional["PlacementGroup"]:
"""
Returns the PlacementGroup object for the Instance.
:returns: The Placement Group this instance is under.
:rtype: Optional[PlacementGroup]
"""
# Workaround to avoid circular import
from linode_api4.objects.placement import ( # pylint: disable=import-outside-toplevel
PlacementGroup,
)
if not hasattr(self, "_placement_group"):
# Refresh the instance if necessary