forked from Azure/WALinuxAgent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
waagent
6753 lines (6107 loc) · 267 KB
/
waagent
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
#!/usr/bin/env python
#
# Azure Linux Agent
#
# Copyright 2015 Microsoft Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Requires Python 2.6+ and Openssl 1.0+
#
# Implements parts of RFC 2131, 1541, 1497 and
# http://msdn.microsoft.com/en-us/library/cc227282%28PROT.10%29.aspx
# http://msdn.microsoft.com/en-us/library/cc227259%28PROT.13%29.aspx
#
import crypt
import random
import array
import base64
import httplib
import os
import os.path
import platform
import pwd
import re
import shutil
import socket
import SocketServer
import struct
import string
import subprocess
import sys
import tempfile
import textwrap
import threading
import time
import traceback
import xml.dom.minidom
import fcntl
import inspect
import zipfile
import json
import datetime
import xml.sax.saxutils
from distutils.version import LooseVersion
if not hasattr(subprocess,'check_output'):
def check_output(*popenargs, **kwargs):
r"""Backport from subprocess module from python 2.7"""
if 'stdout' in kwargs:
raise ValueError('stdout argument not allowed, it will be overridden.')
process = subprocess.Popen(stdout=subprocess.PIPE, *popenargs, **kwargs)
output, unused_err = process.communicate()
retcode = process.poll()
if retcode:
cmd = kwargs.get("args")
if cmd is None:
cmd = popenargs[0]
raise subprocess.CalledProcessError(retcode, cmd, output=output)
return output
# Exception classes used by this module.
class CalledProcessError(Exception):
def __init__(self, returncode, cmd, output=None):
self.returncode = returncode
self.cmd = cmd
self.output = output
def __str__(self):
return "Command '%s' returned non-zero exit status %d" % (self.cmd, self.returncode)
subprocess.check_output=check_output
subprocess.CalledProcessError=CalledProcessError
GuestAgentName = "WALinuxAgent"
GuestAgentLongName = "Azure Linux Agent"
GuestAgentVersion = "WALinuxAgent-2.0.17"
ProtocolVersion = "2012-11-30" #WARNING this value is used to confirm the correct fabric protocol.
Config = None
WaAgent = None
DiskActivated = False
Openssl = "openssl"
Children = []
ExtensionChildren = []
VMM_STARTUP_SCRIPT_NAME='install'
VMM_CONFIG_FILE_NAME='linuxosconfiguration.xml'
global RulesFiles
RulesFiles = [ "/lib/udev/rules.d/75-persistent-net-generator.rules",
"/etc/udev/rules.d/70-persistent-net.rules" ]
VarLibDhcpDirectories = ["/var/lib/dhclient", "/var/lib/dhcpcd", "/var/lib/dhcp"]
EtcDhcpClientConfFiles = ["/etc/dhcp/dhclient.conf", "/etc/dhcp3/dhclient.conf"]
global LibDir
LibDir = "/var/lib/waagent"
global provisioned
provisioned=False
global provisionError
provisionError=None
HandlerStatusToAggStatus = {"installed":"Installing", "enabled":"Ready", "unintalled":"NotReady", "disabled":"NotReady"}
WaagentConf = """\
#
# Azure Linux Agent Configuration
#
Role.StateConsumer=None # Specified program is invoked with the argument "Ready" when we report ready status
# to the endpoint server.
Role.ConfigurationConsumer=None # Specified program is invoked with XML file argument specifying role configuration.
Role.TopologyConsumer=None # Specified program is invoked with XML file argument specifying role topology.
Provisioning.Enabled=y #
Provisioning.DeleteRootPassword=y # Password authentication for root account will be unavailable.
Provisioning.RegenerateSshHostKeyPair=y # Generate fresh host key pair.
Provisioning.SshHostKeyPairType=rsa # Supported values are "rsa", "dsa" and "ecdsa".
Provisioning.MonitorHostName=y # Monitor host name changes and publish changes via DHCP requests.
ResourceDisk.Format=y # Format if unformatted. If 'n', resource disk will not be mounted.
ResourceDisk.Filesystem=ext4 # Typically ext3 or ext4. FreeBSD images should use 'ufs2' here.
ResourceDisk.MountPoint=/mnt/resource #
ResourceDisk.EnableSwap=n # Create and use swapfile on resource disk.
ResourceDisk.SwapSizeMB=0 # Size of the swapfile.
LBProbeResponder=y # Respond to load balancer probes if requested by Azure.
Logs.Verbose=n # Enable verbose logs
OS.RootDeviceScsiTimeout=300 # Root device timeout in seconds.
OS.OpensslPath=None # If "None", the system default version is used.
"""
README_FILENAME="DATALOSS_WARNING_README.txt"
README_FILECONTENT="""\
WARNING: THIS IS A TEMPORARY DISK.
Any data stored on this drive is SUBJECT TO LOSS and THERE IS NO WAY TO RECOVER IT.
Please do not use this disk for storing any personal or application data.
For additional details to please refer to the MSDN documentation at : http://msdn.microsoft.com/en-us/library/windowsazure/jj672979.aspx
"""
############################################################
# BEGIN DISTRO CLASS DEFS
############################################################
############################################################
# AbstractDistro
############################################################
class AbstractDistro(object):
"""
AbstractDistro defines a skeleton neccesary for a concrete Distro class.
Generic methods and attributes are kept here, distribution specific attributes
and behavior are to be placed in the concrete child named distroDistro, where
distro is the string returned by calling python platform.linux_distribution()[0].
So for CentOS the derived class is called 'centosDistro'.
"""
def __init__(self):
"""
Generic Attributes go here. These are based on 'majority rules'.
This __init__() may be called or overriden by the child.
"""
self.agent_service_name = os.path.basename(sys.argv[0])
self.selinux=None
self.service_cmd='/usr/sbin/service'
self.ssh_service_restart_option='restart'
self.ssh_service_name='ssh'
self.ssh_config_file='/etc/ssh/sshd_config'
self.hostname_file_path='/etc/hostname'
self.dhcp_client_name='dhclient'
self.requiredDeps = [ 'route', 'shutdown', 'ssh-keygen', 'useradd', 'usermod',
'openssl', 'sfdisk', 'fdisk', 'mkfs',
'sed', 'grep', 'sudo', 'parted' ]
self.init_script_file='/etc/init.d/waagent'
self.agent_package_name='WALinuxAgent'
self.fileBlackList = [ "/root/.bash_history", "/var/log/waagent.log",'/etc/resolv.conf' ]
self.agent_files_to_uninstall = ["/etc/waagent.conf", "/etc/logrotate.d/waagent"]
self.grubKernelBootOptionsFile = '/etc/default/grub'
self.grubKernelBootOptionsLine = 'GRUB_CMDLINE_LINUX_DEFAULT='
self.getpidcmd = 'pidof'
self.mount_dvd_cmd = 'mount'
self.sudoers_dir_base = '/etc'
self.waagent_conf_file = WaagentConf
self.shadow_file_mode=0600
self.shadow_file_path="/etc/shadow"
self.dhcp_enabled = False
def isSelinuxSystem(self):
"""
Checks and sets self.selinux = True if SELinux is available on system.
"""
if self.selinux == None:
if Run("which getenforce",chk_err=False):
self.selinux = False
else:
self.selinux = True
return self.selinux
def isSelinuxRunning(self):
"""
Calls shell command 'getenforce' and returns True if 'Enforcing'.
"""
if self.isSelinuxSystem():
return RunGetOutput("getenforce")[1].startswith("Enforcing")
else:
return False
def setSelinuxEnforce(self,state):
"""
Calls shell command 'setenforce' with 'state' and returns resulting exit code.
"""
if self.isSelinuxSystem():
if state: s = '1'
else: s='0'
return Run("setenforce "+s)
def setSelinuxContext(self,path,cn):
"""
Calls shell 'chcon' with 'path' and 'cn' context.
Returns exit result.
"""
if self.isSelinuxSystem():
return Run('chcon ' + cn + ' ' + path)
def setHostname(self,name):
"""
Shell call to hostname.
Returns resulting exit code.
"""
return Run('hostname ' + name)
def publishHostname(self,name):
"""
Set the contents of the hostname file to 'name'.
Return 1 on failure.
"""
try:
r=SetFileContents(self.hostname_file_path, name)
for f in EtcDhcpClientConfFiles:
if os.path.exists(f) and FindStringInFile(f,r'^[^#]*?send\s*host-name.*?(<hostname>|gethostname[(,)])') == None :
r=ReplaceFileContentsAtomic('/etc/dhcp/dhclient.conf', "send host-name \"" + name + "\";\n"
+ "\n".join(filter(lambda a: not a.startswith("send host-name"), GetFileContents('/etc/dhcp/dhclient.conf').split('\n'))))
except:
return 1
return r
def installAgentServiceScriptFiles(self):
"""
Create the waagent support files for service installation.
Called by registerAgentService()
Abstract Virtual Function. Over-ridden in concrete Distro classes.
"""
pass
def registerAgentService(self):
"""
Calls installAgentService to create service files.
Shell exec service registration commands. (e.g. chkconfig --add waagent)
Abstract Virtual Function. Over-ridden in concrete Distro classes.
"""
pass
def uninstallAgentService(self):
"""
Call service subsystem to remove waagent script.
Abstract Virtual Function. Over-ridden in concrete Distro classes.
"""
pass
def unregisterAgentService(self):
"""
Calls self.stopAgentService and call self.uninstallAgentService()
"""
self.stopAgentService()
self.uninstallAgentService()
def startAgentService(self):
"""
Service call to start the Agent service
"""
return Run(self.service_cmd + ' ' + self.agent_service_name + ' start')
def stopAgentService(self):
"""
Service call to stop the Agent service
"""
return Run(self.service_cmd + ' ' + self.agent_service_name + ' stop',False)
def restartSshService(self):
"""
Service call to re(start) the SSH service
"""
sshRestartCmd = self.service_cmd + " " + self.ssh_service_name + " " + self.ssh_service_restart_option
retcode = Run(sshRestartCmd)
if retcode > 0:
Error("Failed to restart SSH service with return code:" + str(retcode))
return retcode
def sshDeployPublicKey(self,fprint,path):
"""
Generic sshDeployPublicKey - over-ridden in some concrete Distro classes due to minor differences in openssl packages deployed
"""
error=0
SshPubKey = OvfEnv().OpensslToSsh(fprint)
if SshPubKey != None:
AppendFileContents(path, SshPubKey)
else:
Error("Failed: " + fprint + ".crt -> " + path)
error = 1
return error
def checkPackageInstalled(self,p):
"""
Query package database for prescence of an installed package.
Abstract Virtual Function. Over-ridden in concrete Distro classes.
"""
pass
def checkPackageUpdateable(self,p):
"""
Online check if updated package of walinuxagent is available.
Abstract Virtual Function. Over-ridden in concrete Distro classes.
"""
pass
def deleteRootPassword(self):
"""
Generic root password removal.
"""
filepath="/etc/shadow"
ReplaceFileContentsAtomic(filepath,"root:*LOCK*:14600::::::\n"
+ "\n".join(filter(lambda a: not a.startswith("root:"),GetFileContents(filepath).split('\n'))))
os.chmod(filepath,self.shadow_file_mode)
if self.isSelinuxSystem():
self.setSelinuxContext(filepath,'system_u:object_r:shadow_t:s0')
Log("Root password deleted.")
return 0
def changePass(self,user,password):
Log("Change user password")
crypt_id = Config.get("Provisioning.PasswordCryptId")
if crypt_id is None:
crypt_id = "6"
salt_len = Config.get("Provisioning.PasswordCryptSaltLength")
try:
salt_len = int(salt_len)
if salt_len < 0 or salt_len > 10:
salt_len = 10
except (ValueError, TypeError):
salt_len = 10
return self.chpasswd(user, password, crypt_id=crypt_id,
salt_len=salt_len)
def chpasswd(self, username, password, crypt_id=6, salt_len=10):
passwd_hash = self.gen_password_hash(password, crypt_id, salt_len)
cmd = "usermod -p '{0}' {1}".format(passwd_hash, username)
ret, output = RunGetOutput(cmd, log_cmd=False)
if ret != 0:
return "Failed to set password for {0}: {1}".format(username, output)
def gen_password_hash(self, password, crypt_id, salt_len):
collection = string.ascii_letters + string.digits
salt = ''.join(random.choice(collection) for _ in range(salt_len))
salt = "${0}${1}".format(crypt_id, salt)
return crypt.crypt(password, salt)
def load_ata_piix(self):
return WaAgent.TryLoadAtapiix()
def unload_ata_piix(self):
"""
Generic function to remove ata_piix.ko.
"""
return WaAgent.TryUnloadAtapiix()
def deprovisionWarnUser(self):
"""
Generic user warnings used at deprovision.
"""
print("WARNING! Nameserver configuration in /etc/resolv.conf will be deleted.")
def deprovisionDeleteFiles(self):
"""
Files to delete when VM is deprovisioned
"""
for a in VarLibDhcpDirectories:
Run("rm -f " + a + "/*")
# Clear LibDir, remove nameserver and root bash history
for f in os.listdir(LibDir) + self.fileBlackList:
try:
os.remove(f)
except:
pass
return 0
def uninstallDeleteFiles(self):
"""
Files to delete when agent is uninstalled.
"""
for f in self.agent_files_to_uninstall:
try:
os.remove(f)
except:
pass
return 0
def checkDependencies(self):
"""
Generic dependency check.
Return 1 unless all dependencies are satisfied.
"""
if self.checkPackageInstalled('NetworkManager'):
Error(GuestAgentLongName + " is not compatible with network-manager.")
return 1
try:
m= __import__('pyasn1')
except ImportError:
Error(GuestAgentLongName + " requires python-pyasn1 for your Linux distribution.")
return 1
for a in self.requiredDeps:
if Run("which " + a + " > /dev/null 2>&1",chk_err=False):
Error("Missing required dependency: " + a)
return 1
return 0
def packagedInstall(self,buildroot):
"""
Called from setup.py for use by RPM.
Copies generated files waagent.conf, under the buildroot.
"""
if not os.path.exists(buildroot+'/etc'):
os.mkdir(buildroot+'/etc')
SetFileContents(buildroot+'/etc/waagent.conf', MyDistro.waagent_conf_file)
if not os.path.exists(buildroot+'/etc/logrotate.d'):
os.mkdir(buildroot+'/etc/logrotate.d')
SetFileContents(buildroot+'/etc/logrotate.d/waagent', WaagentLogrotate)
self.init_script_file=buildroot+self.init_script_file
# this allows us to call installAgentServiceScriptFiles()
if not os.path.exists(os.path.dirname(self.init_script_file)):
os.mkdir(os.path.dirname(self.init_script_file))
self.installAgentServiceScriptFiles()
def GetIpv4Address(self):
"""
Return the ip of the
first active non-loopback interface.
"""
addr=''
iface,addr=GetFirstActiveNetworkInterfaceNonLoopback()
return addr
def GetMacAddress(self):
return GetMacAddress()
def GetInterfaceName(self):
return GetFirstActiveNetworkInterfaceNonLoopback()[0]
def RestartInterface(self, iface, max_retry=3):
for retry in range(1, max_retry + 1):
ret = Run("ifdown " + iface + " && ifup " + iface)
if ret == 0:
return
Log("Failed to restart interface: {0}, ret={1}".format(iface, ret))
if retry < max_retry:
Log("Retry restart interface in 5 seconds")
time.sleep(5)
def CreateAccount(self,user, password, expiration, thumbprint):
return CreateAccount(user, password, expiration, thumbprint)
def DeleteAccount(self,user):
return DeleteAccount(user)
def ActivateResourceDisk(self):
"""
Format, mount, and if specified in the configuration
set resource disk as swap.
"""
global DiskActivated
format = Config.get("ResourceDisk.Format")
if format == None or format.lower().startswith("n"):
DiskActivated = True
return
device = DeviceForIdePort(1)
if device == None:
Error("ActivateResourceDisk: Unable to detect disk topology.")
return
device = "/dev/" + device
mountlist = RunGetOutput("mount")[1]
mountpoint = GetMountPoint(mountlist, device)
if(mountpoint):
Log("ActivateResourceDisk: " + device + "1 is already mounted.")
else:
mountpoint = Config.get("ResourceDisk.MountPoint")
if mountpoint == None:
mountpoint = "/mnt/resource"
CreateDir(mountpoint, "root", 0755)
fs = Config.get("ResourceDisk.Filesystem")
if fs == None:
fs = "ext3"
partition = device + "1"
#Check partition type
Log("Detect GPT...")
ret = RunGetOutput("parted {0} print".format(device))
if ret[0] == 0 and "gpt" in ret[1]:
Log("GPT detected.")
#GPT(Guid Partition Table) is used.
#Get partitions.
parts = filter(lambda x : re.match("^\s*[0-9]+", x), ret[1].split("\n"))
#If there are more than 1 partitions, remove all partitions
#and create a new one using the entire disk space.
if len(parts) > 1:
for i in range(1, len(parts) + 1):
Run("parted {0} rm {1}".format(device, i))
Run("parted {0} mkpart primary 0% 100%".format(device))
Run("mkfs." + fs + " " + partition + " -F")
else:
existingFS = RunGetOutput("sfdisk -q -c " + device + " 1", chk_err=False)[1].rstrip()
if existingFS == "7" and fs != "ntfs":
Run("sfdisk -c " + device + " 1 83")
Run("mkfs." + fs + " " + partition)
if Run("mount " + partition + " " + mountpoint, chk_err=False):
#If mount failed, try to format the partition and mount again
Warn("Failed to mount resource disk. Retry mounting.")
Run("mkfs." + fs + " " + partition + " -F")
if Run("mount " + partition + " " + mountpoint):
Error("ActivateResourceDisk: Failed to mount resource disk (" + partition + ").")
return
Log("Resource disk (" + partition + ") is mounted at " + mountpoint + " with fstype " + fs)
#Create README file under the root of resource disk
SetFileContents(os.path.join(mountpoint,README_FILENAME), README_FILECONTENT)
DiskActivated = True
#Create swap space
swap = Config.get("ResourceDisk.EnableSwap")
if swap == None or swap.lower().startswith("n"):
return
sizeKB = int(Config.get("ResourceDisk.SwapSizeMB")) * 1024
if os.path.isfile(mountpoint + "/swapfile") and os.path.getsize(mountpoint + "/swapfile") != (sizeKB * 1024):
os.remove(mountpoint + "/swapfile")
if not os.path.isfile(mountpoint + "/swapfile"):
Run("dd if=/dev/zero of=" + mountpoint + "/swapfile bs=1024 count=" + str(sizeKB))
Run("mkswap " + mountpoint + "/swapfile")
Run("chmod 600 " + mountpoint + "/swapfile")
if not Run("swapon " + mountpoint + "/swapfile"):
Log("Enabled " + str(sizeKB) + " KB of swap at " + mountpoint + "/swapfile")
else:
Error("ActivateResourceDisk: Failed to activate swap at " + mountpoint + "/swapfile")
def Install(self):
return Install()
def mediaHasFilesystem(self,dsk):
if len(dsk) == 0 :
return False
if Run("LC_ALL=C fdisk -l " + dsk + " | grep Disk"):
return False
return True
def mountDVD(self,dvd,location):
return RunGetOutput(self.mount_dvd_cmd + ' ' + dvd + ' ' + location)
def GetHome(self):
return GetHome()
def getDhcpClientName(self):
return self.dhcp_client_name
def initScsiDiskTimeout(self):
"""
Set the SCSI disk timeout when the agent starts running
"""
self.setScsiDiskTimeout()
def setScsiDiskTimeout(self):
"""
Iterate all SCSI disks(include hot-add) and set their timeout if their value are different from the OS.RootDeviceScsiTimeout
"""
try:
scsiTimeout = Config.get("OS.RootDeviceScsiTimeout")
for diskName in [disk for disk in os.listdir("/sys/block") if disk.startswith("sd")]:
self.setBlockDeviceTimeout(diskName, scsiTimeout)
except:
pass
def setBlockDeviceTimeout(self, device, timeout):
"""
Set SCSI disk timeout by set /sys/block/sd*/device/timeout
"""
if timeout != None and device:
filePath = "/sys/block/" + device + "/device/timeout"
if(GetFileContents(filePath).splitlines()[0].rstrip() != timeout):
SetFileContents(filePath,timeout)
Log("SetBlockDeviceTimeout: Update the device " + device + " with timeout " + timeout)
def waitForSshHostKey(self, path):
"""
Provide a dummy waiting, since by default, ssh host key is created by waagent and the key
should already been created.
"""
if(os.path.isfile(path)):
return True
else:
Error("Can't find host key: {0}".format(path))
return False
def isDHCPEnabled(self):
return self.dhcp_enabled
def stopDHCP(self):
"""
Stop the system DHCP client so that the agent can bind on its port. If
the distro has set dhcp_enabled to True, it will need to provide an
implementation of this method.
"""
raise NotImplementedError('stopDHCP method missing')
def startDHCP(self):
"""
Start the system DHCP client. If the distro has set dhcp_enabled to
True, it will need to provide an implementation of this method.
"""
raise NotImplementedError('startDHCP method missing')
def translateCustomData(self, data):
"""
Translate the custom data from a Base64 encoding. Default to no-op.
"""
decodeCustomData = Config.get("Provisioning.DecodeCustomData")
if decodeCustomData != None and decodeCustomData.lower().startswith("y"):
return base64.b64decode(data)
return data
def getConfigurationPath(self):
return "/etc/waagent.conf"
def getProcessorCores(self):
return int(RunGetOutput("grep 'processor.*:' /proc/cpuinfo |wc -l")[1])
def getTotalMemory(self):
return int(RunGetOutput("grep MemTotal /proc/meminfo |awk '{print $2}'")[1])/1024
def getInterfaceNameByMac(self, mac):
ret, output = RunGetOutput("ifconfig -a")
if ret != 0:
raise Exception("Failed to get network interface info")
output = output.replace('\n', '')
match = re.search(r"(eth\d).*(HWaddr|ether) {0}".format(mac),
output, re.IGNORECASE)
if match is None:
raise Exception("Failed to get ifname with mac: {0}".format(mac))
output = match.group(0)
eths = re.findall(r"eth\d", output)
if eths is None or len(eths) == 0:
raise Exception("Failed to get ifname with mac: {0}".format(mac))
return eths[-1]
def configIpV4(self, ifName, addr, netmask=24):
ret, output = RunGetOutput("ifconfig {0} up".format(ifName))
if ret != 0:
raise Exception("Failed to bring up {0}: {1}".format(ifName,
output))
ret, output = RunGetOutput("ifconfig {0} {1}/{2}".format(ifName, addr,
netmask))
if ret != 0:
raise Exception("Failed to config ipv4 for {0}: {1}".format(ifName,
output))
def setDefaultGateway(self, gateway):
Run("/sbin/route add default gw" + gateway, chk_err=False)
def routeAdd(self, net, mask, gateway):
Run("/sbin/route add -net " + net + " netmask " + mask + " gw " + gateway,
chk_err=False)
def getNdDriverVersion(self):
"""
if error happens, raise a RdmaError
"""
try:
with open("/var/lib/hyperv/.kvp_pool_0", "r") as f:
lines = f.read()
r = re.search("NdDriverVersion\0+(\d\d\d\.\d)", lines)
if r is not None:
NdDriverVersion = r.groups()[0]
return NdDriverVersion #e.g. NdDriverVersion = 142.0
else :
Log("Error: NdDriverVersion not found.")
return None
except Exception as e:
errMsg = 'Cannot update status: Failed to enable the extension with error: %s, stack trace: %s' % (str(e), traceback.format_exc())
Log(errMsg)
raise RdmaError(RdmaConfig.nd_driver_detect_error)
def checkInstallHyperV(self):
return None
def getRdmaPackageVersion(self):
return None
def rdmaUpdate(self,updateRdmaRepository=None):
Log("rdmaUpdate in base class")
pass
def checkRDMA(self):
Log("checkRDMA in base class")
pass
############################################################
# GentooDistro
############################################################
gentoo_init_file = """\
#!/sbin/runscript
command=/usr/sbin/waagent
pidfile=/var/run/waagent.pid
command_args=-daemon
command_background=true
name="Azure Linux Agent"
depend()
{
need localmount
use logger network
after bootmisc modules
}
"""
class gentooDistro(AbstractDistro):
"""
Gentoo distro concrete class
"""
def __init__(self): #
super(gentooDistro,self).__init__()
self.service_cmd='/sbin/service'
self.ssh_service_name='sshd'
self.hostname_file_path='/etc/conf.d/hostname'
self.dhcp_client_name='dhcpcd'
self.shadow_file_mode=0640
self.init_file=gentoo_init_file
def publishHostname(self,name):
try:
if (os.path.isfile(self.hostname_file_path)):
r=ReplaceFileContentsAtomic(self.hostname_file_path, "hostname=\"" + name + "\"\n"
+ "\n".join(filter(lambda a: not a.startswith("hostname="), GetFileContents(self.hostname_file_path).split("\n"))))
except:
return 1
return r
def installAgentServiceScriptFiles(self):
SetFileContents(self.init_script_file, self.init_file)
os.chmod(self.init_script_file, 0755)
def registerAgentService(self):
self.installAgentServiceScriptFiles()
return Run('rc-update add ' + self.agent_service_name + ' default')
def uninstallAgentService(self):
return Run('rc-update del ' + self.agent_service_name + ' default')
def unregisterAgentService(self):
self.stopAgentService()
return self.uninstallAgentService()
def checkPackageInstalled(self,p):
if Run('eix -I ^' + p + '$',chk_err=False):
return 0
else:
return 1
def checkPackageUpdateable(self,p):
if Run('eix -u ^' + p + '$',chk_err=False):
return 0
else:
return 1
def RestartInterface(self, iface):
Run("/etc/init.d/net." + iface + " restart")
############################################################
# SuSEDistro
############################################################
suse_init_file = """\
#! /bin/sh
#
# Azure Linux Agent sysV init script
#
# Copyright 2013 Microsoft Corporation
# Copyright SUSE LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# /etc/init.d/waagent
#
# and symbolic link
#
# /usr/sbin/rcwaagent
#
# System startup script for the waagent
#
### BEGIN INIT INFO
# Provides: AzureLinuxAgent
# Required-Start: $network sshd
# Required-Stop: $network sshd
# Default-Start: 3 5
# Default-Stop: 0 1 2 6
# Description: Start the AzureLinuxAgent
### END INIT INFO
PYTHON=/usr/bin/python
WAZD_BIN=/usr/sbin/waagent
WAZD_CONF=/etc/waagent.conf
WAZD_PIDFILE=/var/run/waagent.pid
test -x "$WAZD_BIN" || { echo "$WAZD_BIN not installed"; exit 5; }
test -e "$WAZD_CONF" || { echo "$WAZD_CONF not found"; exit 6; }
. /etc/rc.status
# First reset status of this service
rc_reset
# Return values acc. to LSB for all commands but status:
# 0 - success
# 1 - misc error
# 2 - invalid or excess args
# 3 - unimplemented feature (e.g. reload)
# 4 - insufficient privilege
# 5 - program not installed
# 6 - program not configured
#
# Note that starting an already running service, stopping
# or restarting a not-running service as well as the restart
# with force-reload (in case signalling is not supported) are
# considered a success.
case "$1" in
start)
echo -n "Starting AzureLinuxAgent"
## Start daemon with startproc(8). If this fails
## the echo return value is set appropriate.
startproc -f ${PYTHON} ${WAZD_BIN} -daemon
rc_status -v
;;
stop)
echo -n "Shutting down AzureLinuxAgent"
## Stop daemon with killproc(8) and if this fails
## set echo the echo return value.
killproc -p ${WAZD_PIDFILE} ${PYTHON} ${WAZD_BIN}
rc_status -v
;;
try-restart)
## Stop the service and if this succeeds (i.e. the
## service was running before), start it again.
$0 status >/dev/null && $0 restart
rc_status
;;
restart)
## Stop the service and regardless of whether it was
## running or not, start it again.
$0 stop
sleep 1
$0 start
rc_status
;;
force-reload|reload)
rc_status
;;
status)
echo -n "Checking for service AzureLinuxAgent "
## Check status with checkproc(8), if process is running
## checkproc will return with exit status 0.
checkproc -p ${WAZD_PIDFILE} ${PYTHON} ${WAZD_BIN}
rc_status -v
;;
probe)
;;
*)
echo "Usage: $0 {start|stop|status|try-restart|restart|force-reload|reload}"
exit 1
;;
esac
rc_exit
"""
class SuSEDistro(AbstractDistro):
"""
SuSE Distro concrete class
Put SuSE specific behavior here...
"""
def __init__(self):
super(SuSEDistro,self).__init__()
dist_info = DistInfo()
dist_info_fullname = DistInfo(fullname=1)
self.dhcp_client_name = 'dhcpcd'
if ((dist_info_fullname[0] == 'SUSE Linux Enterprise Server' and dist_info[1] >= '12') or \
(dist_info_fullname[0] == 'openSUSE' and dist_info[1] >= '13.2')):
self.dhcp_client_name = 'wickedd-dhcp4'
self.dhcp_enabled = True
self.grubKernelBootOptionsFile = '/boot/grub/menu.lst'
self.grubKernelBootOptionsLine = 'kernel'
self.getpidcmd = 'pidof '
self.hostname_file_path = '/etc/HOSTNAME'
self.init_file = suse_init_file
self.kernel_boot_options_file = '/boot/grub/menu.lst'
self.modprobe_path = '/usr/bin/modprobe'
self.requiredDeps += [ "/sbin/insserv" ]
self.reboot_path = '/sbin/reboot'
self.rpm_path = '/bin/rpm'
self.service_cmd = '/sbin/service'
self.ssh_service_name ='sshd'
if(dist_info[1] == "11"):
self.ps_path = '/bin/ps'
else:
self.ps_path = '/usr/bin/ps'
self.zypper_path = '/usr/bin/zypper'
def checkPackageInstalled(self,p):
if Run("rpm -q " + p,chk_err=False):
return 0
else:
return 1
def checkPackageUpdateable(self,p):
if Run("zypper list-updates | grep " + p,chk_err=False):
return 1
else:
return 0
def installAgentServiceScriptFiles(self):
try:
SetFileContents(self.init_script_file, self.init_file)
os.chmod(self.init_script_file, 0744)
except:
pass
def registerAgentService(self):
self.installAgentServiceScriptFiles()
return Run('insserv ' + self.agent_service_name)
def uninstallAgentService(self):
return Run('insserv -r ' + self.agent_service_name)
def unregisterAgentService(self):
self.stopAgentService()
return self.uninstallAgentService()
def startDHCP(self):
Run("service " + self.dhcp_client_name + " start", chk_err=False)
def stopDHCP(self):
Run("service " + self.dhcp_client_name + " stop", chk_err=False)
def getRdmaPackageVersion(self):
"""
"""
error, output = RunGetOutput(self.zypper_path + " info " + RdmaConfig.rmda_package_name)
if(error == RdmaConfig.process_success):
r = re.search("Version: (\S+)", output)
if r is not None:
package_version = r.groups()[0] # e.g. package_version is "20150707.140.0_k3.12.28_4-3.1."
return package_version
else:
return None
else: