forked from Azure/WALinuxAgent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
waagent
2577 lines (2336 loc) · 103 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/python
#
# Windows Azure Linux Agent
#
# Copyright 2012 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.4+ 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 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 subprocess
import sys
import tempfile
import textwrap
import threading
import time
import traceback
import xml.dom.minidom
GuestAgentName = "WALinuxAgent"
GuestAgentLongName = "Windows Azure Linux Agent"
GuestAgentVersion = "WALinuxAgent-1.3.3-PRE"
ProtocolVersion = "2011-12-31"
Config = None
LinuxDistro = "UNKNOWN"
PackagedForDistro = "UNKNOWN"
Verbose = False
WaAgent = None
DiskActivated = False
Openssl = "openssl"
Children = []
PossibleEthernetInterfaces = ["seth0", "seth1", "eth0", "eth1"]
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"]
LibDir = "/var/lib/waagent"
# backport subprocess.check_output if not defined ( for python version < 2.7)
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
# This lets us index into a string or an array of integers transparently.
def Ord(a):
if type(a) == type("a"):
a = ord(a)
return a
def IsWindows():
return (platform.uname()[0] == "Windows")
def IsLinux():
return (platform.uname()[0] == "Linux")
def DetectLinuxDistro():
global LinuxDistro
global PackagedForDistro
if os.path.isfile("/etc/redhat-release"):
LinuxDistro = "RedHat"
return True
if os.path.isfile("/etc/lsb-release") and "Ubuntu" in GetFileContents("/etc/lsb-release"):
LinuxDistro = "Ubuntu"
# Should this run as if it is packaged Ubuntu?
try:
cmd="dpkg -S %s" % os.path.basename(__file__)
retcode, krn = RunGetOutput(cmd,chk_err=False)
if not retcode:
PackagedForDistro = "Ubuntu"
except IOError as e:
pass
return True
if os.path.isfile("/etc/debian_version"):
LinuxDistro = "Debian"
return True
if os.path.isfile("/etc/SuSE-release"):
LinuxDistro = "Suse"
return True
return False
def IsRedHat():
return "RedHat" in LinuxDistro
def IsUbuntu():
return "Ubuntu" in LinuxDistro
def IsPackagedUbuntu():
return "Ubuntu" in PackagedForDistro
def IsDebian():
return IsUbuntu() or "Debian" in LinuxDistro
def IsSuse():
return "Suse" in LinuxDistro
def IsPackaged():
if PackagedForDistro == "UNKNOWN":
return False
return True
def UsesRpm():
return IsRedHat() or IsSuse()
def UsesDpkg():
return IsDebian()
def GetLastPathElement(path):
return path.rsplit('/', 1)[1]
def GetFileContents(filepath):
file = None
try:
file = open(filepath)
except:
return None
if file == None:
return None
try:
return file.read()
finally:
file.close()
def SetFileContents(filepath, contents):
file = open(filepath, "w")
try:
file.write(contents)
finally:
file.close()
def AppendFileContents(filepath, contents):
file = open(filepath, "a")
try:
file.write(contents)
finally:
file.close()
def ReplaceFileContentsAtomic(filepath, contents):
handle, temp = tempfile.mkstemp(dir = os.path.dirname(filepath))
try:
os.write(handle, contents)
finally:
os.close(handle)
try:
os.rename(temp, filepath)
return
except:
pass
os.remove(filepath)
os.rename(temp, filepath)
def GetLineStartingWith(prefix, filepath):
for line in GetFileContents(filepath).split('\n'):
if line.startswith(prefix):
return line
return None
def Run(cmd,chk_err=True):
retcode,out=RunGetOutput(cmd,chk_err)
return retcode
def RunGetOutput(cmd,chk_err=True):
LogIfVerbose(cmd)
try:
output=subprocess.check_output(cmd,stderr=subprocess.STDOUT,shell=True)
except subprocess.CalledProcessError,e :
if chk_err :
Error('CalledProcessError. Error Code: ' + str(e.returncode) )
Error('CalledProcessError. Command string: "' + e.cmd + '"')
Error('CalledProcessError. Command result: "' + e.output[:-1] + '"')
return e.returncode,e.output
return 0,output
def RunSendStdin(cmd,input,chk_err=True):
LogIfVerbose(cmd+input)
try:
me=subprocess.Popen([cmd], shell=True, stdin=subprocess.PIPE,stderr=subprocess.STDOUT,stdout=subprocess.PIPE)
output=me.communicate(input)
except OSError,e :
if chk_err :
Error('CalledProcessError. Error Code:' + str(me.returncode))
Error('CalledProcessError. Command string:"' + cmd + '"' )
Error('CalledProcessError. Command result:"' + output[:-1] + '"')
return 1,output[0]
if me.returncode is not 0 and chk_err is True:
Error('CalledProcessError. Error Code:' + str(me.returncode))
Error('CalledProcessError. Command string:"' + cmd + '"' )
Error('CalledProcessError. Command result:"' + (output[0])[:-1] + '"')
return me.returncode,output[0]
def GetNodeTextData(a):
for b in a.childNodes:
if b.nodeType == b.TEXT_NODE:
return b.data
def GetHome():
home = None
try:
home = GetLineStartingWith("HOME", "/etc/default/useradd").split('=')[1].strip()
except:
pass
if (home == None) or (home.startswith("/") == False):
home = "/home"
return home
def ChangeOwner(filepath, user):
p = None
try:
p = pwd.getpwnam(user)
except:
pass
if p != None:
os.chown(filepath, p[2], p[3])
def CreateDir(dirpath, user, mode):
try:
os.makedirs(dirpath, mode)
except:
pass
ChangeOwner(dirpath, user)
def CreateAccount(user, password, expiration, thumbprint):
if IsWindows():
Log("Skipping CreateAccount on Windows")
return None
userentry = None
try:
userentry = pwd.getpwnam(user)
except:
pass
uidmin = None
try:
uidmin = int(GetLineStartingWith("UID_MIN", "/etc/login.defs").split()[1])
except:
pass
if uidmin == None:
uidmin = 100
if userentry != None and userentry[2] < uidmin:
Error("CreateAccount: " + user + " is a system user. Will not set password.")
return "Failed to set password for system user: " + user + " (0x06)."
if userentry == None:
command = "useradd -m " + user
if expiration != None:
command += " -e " + expiration.split('.')[0]
if Run(command):
Error("Failed to create user account: " + user)
return "Failed to create user account: " + user + " (0x07)."
else:
Log("CreateAccount: " + user + " already exists. Will update password.")
if password != None:
RunSendStdin("chpasswd",(user + ":" + password + "\n"))
try:
if password == None:
SetFileContents("/etc/sudoers.d/waagent", user + " ALL = (ALL) NOPASSWD: ALL\n")
else:
SetFileContents("/etc/sudoers.d/waagent", user + " ALL = (ALL) ALL\n")
os.chmod("/etc/sudoers.d/waagent", 0440)
except:
Error("CreateAccount: Failed to configure sudo access for user.")
return "Failed to configure sudo privileges (0x08)."
home = GetHome()
if thumbprint != None:
dir = home + "/" + user + "/.ssh"
CreateDir(dir, user, 0700)
pub = dir + "/id_rsa.pub"
prv = dir + "/id_rsa"
Run("ssh-keygen -y -f " + thumbprint + ".prv > " + pub)
SetFileContents(prv, GetFileContents(thumbprint + ".prv"))
for f in [pub, prv]:
os.chmod(f, 0600)
ChangeOwner(f, user)
SetFileContents(dir + "/authorized_keys", GetFileContents(pub))
ChangeOwner(dir + "/authorized_keys", user)
Log("Created user account: " + user)
return None
def DeleteAccount(user):
if IsWindows():
Log("Skipping DeleteAccount on Windows")
return
userentry = None
try:
userentry = pwd.getpwnam(user)
except:
pass
if userentry == None:
Error("DeleteAccount: " + user + " not found.")
return
uidmin = None
try:
uidmin = int(GetLineStartingWith("UID_MIN", "/etc/login.defs").split()[1])
except:
pass
if uidmin == None:
uidmin = 100
if userentry[2] < uidmin:
Error("DeleteAccount: " + user + " is a system user. Will not delete account.")
return
Run("> /var/run/utmp") #Delete utmp to prevent error if we are the 'user' deleted
Run("userdel -f -r " + user)
try:
os.remove("/etc/sudoers.d/waagent")
except:
pass
return
def ReloadSshd():
name = None
if IsRedHat() or IsSuse():
name = "sshd"
if IsDebian():
name = "ssh"
if name == None:
return
if not Run("service " + name + " status | grep running"):
Run("service " + name + " reload")
def IsInRangeInclusive(a, low, high):
return (a >= low and a <= high)
def IsPrintable(ch):
return IsInRangeInclusive(ch, Ord('A'), Ord('Z')) or IsInRangeInclusive(ch, Ord('a'), Ord('z')) or IsInRangeInclusive(ch, Ord('0'), Ord('9'))
def HexDump(buffer, size):
if size < 0:
size = len(buffer)
result = ""
for i in range(0, size):
if (i % 16) == 0:
result += "%06X: " % i
byte = struct.unpack("B", buffer[i])[0]
result += "%02X " % byte
if (i & 15) == 7:
result += " "
if ((i + 1) % 16) == 0 or (i + 1) == size:
j = i
while ((j + 1) % 16) != 0:
result += " "
if (j & 7) == 7:
result += " "
j += 1
result += " "
for j in range(i - (i % 16), i + 1):
byte = struct.unpack("B", buffer[j])[0]
k = '.'
if IsPrintable(byte):
k = chr(byte)
result += k
if (i + 1) != size:
result += "\n"
return result
def ThrottleLog(counter):
# Log everything up to 10, every 10 up to 100, then every 100.
return (counter < 10) or ((counter < 100) and ((counter % 10) == 0)) or ((counter % 100) == 0)
def Logger():
class T(object):
def __init__(self):
self.File = None
self.Con = None
self = T()
def LogToFile(message):
FilePath = ["/var/log/waagent.log", "waagent.log"][IsWindows()]
if not os.path.isfile(FilePath) and self.File != None:
self.File.close()
self.File = None
if self.File == None:
self.File = open(FilePath, "a")
self.File.write(message + "\n")
self.File.flush()
def LogToCon(message):
ConPath = '/dev/console'
if self.Con == None:
self.Con = open(ConPath, "a")
self.Con.write(message + "\n")
self.Con.flush()
def Log(message):
LogWithPrefix("", message)
def LogWithPrefix(prefix, message, to_console=True):
t = time.localtime()
t = "%04u/%02u/%02u %02u:%02u:%02u " % (t.tm_year, t.tm_mon, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec)
t += prefix
for line in message.split('\n'):
line = t + line
LogToFile(line)
if to_console:
LogToCon(line)
return Log, LogWithPrefix
Log, LogWithPrefix = Logger()
def NoLog(message):
pass
def LogIfVerbose(message):
if Verbose == True:
LogWithPrefix('',message,to_console=False)
def LogWithPrefixIfVerbose(prefix, message):
if Verbose == True:
LogWithPrefix(prefix, message,to_console=False)
def Warn(message):
LogWithPrefix("WARNING:", message)
def Error(message):
ErrorWithPrefix("", message)
def ErrorWithPrefix(prefix, message):
LogWithPrefix("ERROR:", message)
def Linux_ioctl_GetIpv4Address(ifname):
import fcntl
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s', ifname[:15]))[20:24])
def Linux_ioctl_GetInterfaceMac(ifname):
import fcntl
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
info = fcntl.ioctl(s.fileno(), 0x8927, struct.pack('256s', ifname[:15]))
return ''.join(['%02X' % Ord(char) for char in info[18:24]])
def GetIpv4Address():
if IsLinux():
for ifname in PossibleEthernetInterfaces:
try:
return Linux_ioctl_GetIpv4Address(ifname)
except IOError, e:
pass
else:
try:
return socket.gethostbyname(socket.gethostname())
except Exception, e:
ErrorWithPrefix("GetIpv4Address:", str(e))
ErrorWithPrefix("GetIpv4Address:", traceback.format_exc())
def HexStringToByteArray(a):
b = ""
for c in range(0, len(a) / 2):
b += struct.pack("B", int(a[c * 2:c * 2 + 2], 16))
return b
def GetMacAddress():
if IsWindows():
# Windows: Physical Address. . . . . . . . . : 00-15-17-79-00-7F\n
a = "ipconfig /all | findstr /c:\"Physical Address\" | findstr /v \"00-00-00-00-00-00-00\""
a = os.popen(a).read() # not re-implementing wirh RunGetOutput - not called unless we're in windows
a = re.sub("\s+$", "", a)
a = re.sub(".+ ", "", a)
a = re.sub(":", "", a)
a = re.sub("-", "", a)
else:
for ifname in PossibleEthernetInterfaces:
try:
a = Linux_ioctl_GetInterfaceMac(ifname)
break
except IOError, e:
pass
return HexStringToByteArray(a)
def DeviceForIdePort(n):
if n > 3:
return None
g0 = "00000000"
if n > 1:
g0 = "00000001"
n = n - 2
device = None
path = "/sys/bus/vmbus/devices/"
for vmbus in os.listdir(path):
guid = GetFileContents(path + vmbus + "/device_id").lstrip('{').split('-')
if guid[0] == g0 and guid[1] == "000" + str(n):
for root, dirs, files in os.walk(path + vmbus):
if root.endswith("/block"):
device = dirs[0]
break
break
return device
class Util(object):
def _HttpGet(self, url, headers):
LogIfVerbose("HttpGet(" + url + ")")
maxRetry = 2
if url.startswith("http://"):
url = url[7:]
url = url[url.index("/"):]
for retry in range(0, maxRetry + 1):
strRetry = str(retry)
log = [NoLog, Error][retry > 0]
log("retry HttpGet(" + url + "),retry=" + strRetry)
response = None
strStatus = "None"
try:
httpConnection = httplib.HTTPConnection(self.Endpoint)
if headers == None:
request = httpConnection.request("GET", url)
else:
request = httpConnection.request("GET", url, None, headers)
response = httpConnection.getresponse()
strStatus = str(response.status)
except httplib.HTTPException, e:
Error('HTTPException ' + e.message + ' args: ' + repr(e.args))
log("response HttpGet(" + url + "),retry=" + strRetry + ",status=" + strStatus)
if response == None or response.status != httplib.OK:
Error("HttpGet(" + url + "),retry=" + strRetry + ",status=" + strStatus)
if retry == maxRetry:
Error("return HttpGet(" + url + "),retry=" + strRetry + ",status=" + strStatus)
return None
else:
Error("sleep 10 seconds HttpGet(" + url + "),retry=" + strRetry + ",status=" + strStatus)
time.sleep(10)
else:
log("return HttpGet(" + url + "),retry=" + strRetry + ",status=" + strStatus)
return response.read()
def HttpGetWithoutHeaders(self, url):
return self._HttpGet(url, None)
def HttpGetWithHeaders(self, url):
return self._HttpGet(url, {"x-ms-agent-name": GuestAgentName, "x-ms-version": ProtocolVersion})
def HttpSecureGetWithHeaders(self, url, transportCert):
return self._HttpGet(url, {"x-ms-agent-name": GuestAgentName,
"x-ms-version": ProtocolVersion,
"x-ms-cipher-name": "DES_EDE3_CBC",
"x-ms-guest-agent-public-x509-cert": transportCert})
def HttpPost(self, url, data):
LogIfVerbose("HttpPost(" + url + ")")
maxRetry = 2
for retry in range(0, maxRetry + 1):
strRetry = str(retry)
log = [NoLog, Error][retry > 0]
log("retry HttpPost(" + url + "),retry=" + strRetry)
response = None
strStatus = "None"
try:
httpConnection = httplib.HTTPConnection(self.Endpoint)
request = httpConnection.request("POST", url, data, {"x-ms-agent-name": GuestAgentName,
"Content-Type": "text/xml; charset=utf-8",
"x-ms-version": ProtocolVersion})
response = httpConnection.getresponse()
strStatus = str(response.status)
except httplib.HTTPException, e:
Error('HTTPException ' + e.message + ' args: ' + repr(e.args))
log("response HttpPost(" + url + "),retry=" + strRetry + ",status=" + strStatus)
if response == None or (response.status != httplib.OK and response.status != httplib.ACCEPTED):
Error("HttpPost(" + url + "),retry=" + strRetry + ",status=" + strStatus)
if retry == maxRetry:
Error("return HttpPost(" + url + "),retry=" + strRetry + ",status=" + strStatus)
return None
else:
Error("sleep 10 seconds HttpPost(" + url + "),retry=" + strRetry + ",status=" + strStatus)
time.sleep(10)
else:
log("return HttpPost(" + url + "),retry=" + strRetry + ",status=" + strStatus)
return response
def LoadBalancerProbeServer(port):
class T(object):
def __init__(self, ip, port):
self.ProbeCounter = 0
self.server = SocketServer.TCPServer((ip, port), TCPHandler)
self.server_thread = threading.Thread(target = self.server.serve_forever)
self.server_thread.setDaemon(True)
self.server_thread.start()
def shutdown(self):
self.server.shutdown()
class TCPHandler(SocketServer.BaseRequestHandler):
def GetHttpDateTimeNow(self):
# Date: Fri, 25 Mar 2011 04:53:10 GMT
return time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime())
def handle(self):
context.ProbeCounter = (context.ProbeCounter + 1) % 1000000
log = [NoLog, LogIfVerbose][ThrottleLog(context.ProbeCounter)]
strCounter = str(context.ProbeCounter)
if context.ProbeCounter == 1:
Log("Receiving LB probes.")
log("Received LB probe # " + strCounter)
self.request.recv(1024)
self.request.send("HTTP/1.1 200 OK\r\nContent-Length: 2\r\nContent-Type: text/html\r\nDate: " + self.GetHttpDateTimeNow() + "\r\n\r\nOK")
for retry in range(1,6):
context=None
ip = GetIpv4Address()
if ip == None :
Log("LoadBalancerProbeServer: GetIpv4Address() returned None, sleeping 10 before retry " + str(retry+1) )
time.sleep(10)
else:
try:
context = T(ip,port)
break
except Exception, e:
Log("LoadBalancerProbeServer: Exception contructing socket server: " + str(e))
Log("LoadBalancerProbeServer: Retry socket server construction #" + str(retry+1) )
return context
class ConfigurationProvider(object):
def __init__(self):
self.values = dict()
if os.path.isfile("/etc/waagent.conf") == False:
raise Exception("Missing configuration in /etc/waagent.conf")
try:
for line in GetFileContents("/etc/waagent.conf").split('\n'):
if not line.startswith("#") and "=" in line:
parts = line.split()[0].split('=')
value = parts[1].strip("\" ")
if value != "None":
self.values[parts[0]] = value
else:
self.values[parts[0]] = None
except:
Error("Unable to parse /etc/waagent.conf")
raise
return
def get(self, key):
return self.values.get(key)
class EnvMonitor(object):
def __init__(self):
self.shutdown = False
self.HostName = socket.gethostname()
self.server_thread = threading.Thread(target = self.monitor)
self.server_thread.setDaemon(True)
self.server_thread.start()
self.published = False
def monitor(self):
publish = Config.get("Provisioning.MonitorHostName")
dhcpcmd = "pidof dhclient"
if IsSuse():
dhcpcmd = "pidof dhcpcd"
if IsDebian():
dhcpcmd = "pidof dhclient3"
dhcppid = RunGetOutput(dhcpcmd,chk_err=False)[1]
while not self.shutdown:
for a in RulesFiles:
if os.path.isfile(a):
if os.path.isfile(GetLastPathElement(a)):
os.remove(GetLastPathElement(a))
shutil.move(a, ".")
Log("EnvMonitor: Moved " + a + " -> " + LibDir)
if publish != None and publish.lower().startswith("y"):
try:
if socket.gethostname() != self.HostName:
Log("EnvMonitor: Detected host name change: " + self.HostName + " -> " + socket.gethostname())
self.HostName = socket.gethostname()
WaAgent.UpdateAndPublishHostName(self.HostName)
dhcppid = RunGetOutput(dhcpcmd,chk_err=False)[1]
self.published = True
except:
pass
else:
self.published = True
pid = ""
if not os.path.isdir("/proc/" + dhcppid.strip()):
pid = RunGetOutput(dhcpcmd,chk_err=False)[1]
if pid != "" and pid != dhcppid:
Log("EnvMonitor: Detected dhcp client restart. Restoring routing table.")
WaAgent.RestoreRoutes()
dhcppid = pid
for child in Children:
if child.poll() != None:
Children.remove(child)
time.sleep(5)
def SetHostName(self, name):
if socket.gethostname() == name:
self.published = True
elif Run("hostname " + name):
Error("Error: SetHostName: Cannot set hostname to " + name)
return ("Error: SetHostName: Cannot set hostname to " + name)
def IsNamePublished(self):
return self.published
def ShutdownService(self):
self.shutdown = True
self.server_thread.join()
class Certificates(object):
#
# <CertificateFile xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="certificates10.xsd">
# <Version>2010-12-15</Version>
# <Incarnation>2</Incarnation>
# <Format>Pkcs7BlobWithPfxContents</Format>
# <Data>MIILTAY...
# </Data>
# </CertificateFile>
#
def __init__(self):
self.reinitialize()
def reinitialize(self):
self.Incarnation = None
self.Role = None
def Parse(self, xmlText):
self.reinitialize()
SetFileContents("Certificates.xml", xmlText)
dom = xml.dom.minidom.parseString(xmlText)
for a in [ "CertificateFile", "Version", "Incarnation",
"Format", "Data", ]:
if not dom.getElementsByTagName(a):
Error("Certificates.Parse: Missing " + a)
return None
node = dom.childNodes[0]
if node.localName != "CertificateFile":
Error("Certificates.Parse: root not CertificateFile")
return None
SetFileContents("Certificates.p7m",
"MIME-Version: 1.0\n"
+ "Content-Disposition: attachment; filename=\"Certificates.p7m\"\n"
+ "Content-Type: application/x-pkcs7-mime; name=\"Certificates.p7m\"\n"
+ "Content-Transfer-Encoding: base64\n\n"
+ GetNodeTextData(dom.getElementsByTagName("Data")[0]))
if Run(Openssl + " cms -decrypt -in Certificates.p7m -inkey TransportPrivate.pem -recip TransportCert.pem | " + Openssl + " pkcs12 -nodes -password pass: -out Certificates.pem"):
Error("Certificates.Parse: Failed to extract certificates from CMS message.")
return self
# There may be multiple certificates in this package. Split them.
file = open("Certificates.pem")
pindex = 1
cindex = 1
output = open("temp.pem", "w")
for line in file.readlines():
output.write(line)
if re.match(r'[-]+END .*?(KEY|CERTIFICATE)[-]+$',line):
output.close()
if re.match(r'[-]+END .*?KEY[-]+$',line):
os.rename("temp.pem", str(pindex) + ".prv")
pindex += 1
else:
os.rename("temp.pem", str(cindex) + ".crt")
cindex += 1
output = open("temp.pem", "w")
output.close()
os.remove("temp.pem")
keys = dict()
index = 1
filename = str(index) + ".crt"
while os.path.isfile(filename):
thumbprint = (RunGetOutput(Openssl + " x509 -in " + filename + " -fingerprint -noout")[1]).rstrip().split('=')[1].replace(':', '').upper()
pubkey=RunGetOutput(Openssl + " x509 -in " + filename + " -pubkey -noout")[1]
keys[pubkey] = thumbprint
os.rename(filename, thumbprint + ".crt")
os.chmod(thumbprint + ".crt", 0600)
if IsRedHat():
Run("chcon unconfined_u:object_r:ssh_home_t:s0 " + thumbprint + ".crt")
index += 1
filename = str(index) + ".crt"
index = 1
filename = str(index) + ".prv"
while os.path.isfile(filename):
pubkey = RunGetOutput(Openssl + " rsa -in " + filename + " -pubout 2> /dev/null")[1]
os.rename(filename, keys[pubkey] + ".prv")
os.chmod(keys[pubkey] + ".prv", 0600)
if IsRedHat():
Run("chcon unconfined_u:object_r:ssh_home_t:s0 " + keys[pubkey] + ".prv")
index += 1
filename = str(index) + ".prv"
return self
class SharedConfig(object):
#
# <SharedConfig version="1.0.0.0" goalStateIncarnation="1">
# <Deployment name="db00a7755a5e4e8a8fe4b19bc3b330c3" guid="{ce5a036f-5c93-40e7-8adf-2613631008ab}" incarnation="2">
# <Service name="MyVMRoleService" guid="{00000000-0000-0000-0000-000000000000}" />
# <ServiceInstance name="db00a7755a5e4e8a8fe4b19bc3b330c3.1" guid="{d113f4d7-9ead-4e73-b715-b724b5b7842c}" />
# </Deployment>
# <Incarnation number="1" instance="MachineRole_IN_0" guid="{a0faca35-52e5-4ec7-8fd1-63d2bc107d9b}" />
# <Role guid="{73d95f1c-6472-e58e-7a1a-523554e11d46}" name="MachineRole" settleTimeSeconds="10" />
# <LoadBalancerSettings timeoutSeconds="0" waitLoadBalancerProbeCount="8">
# <Probes>
# <Probe name="MachineRole" />
# <Probe name="55B17C5E41A1E1E8FA991CF80FAC8E55" />
# <Probe name="3EA4DBC19418F0A766A4C19D431FA45F" />
# </Probes>
# </LoadBalancerSettings>
# <OutputEndpoints>
# <Endpoint name="MachineRole:Microsoft.WindowsAzure.Plugins.RemoteAccess.Rdp" type="SFS">
# <Target instance="MachineRole_IN_0" endpoint="Microsoft.WindowsAzure.Plugins.RemoteAccess.Rdp" />
# </Endpoint>
# </OutputEndpoints>
# <Instances>
# <Instance id="MachineRole_IN_0" address="10.115.153.75">
# <FaultDomains randomId="0" updateId="0" updateCount="0" />
# <InputEndpoints>
# <Endpoint name="a" address="10.115.153.75:80" protocol="http" isPublic="true" loadBalancedPublicAddress="70.37.106.197:80" enableDirectServerReturn="false" isDirectAddress="false" disableStealthMode="false">
# <LocalPorts>
# <LocalPortRange from="80" to="80" />
# </LocalPorts>
# </Endpoint>
# <Endpoint name="Microsoft.WindowsAzure.Plugins.RemoteAccess.Rdp" address="10.115.153.75:3389" protocol="tcp" isPublic="false" enableDirectServerReturn="false" isDirectAddress="false" disableStealthMode="false">
# <LocalPorts>
# <LocalPortRange from="3389" to="3389" />
# </LocalPorts>
# </Endpoint>
# <Endpoint name="Microsoft.WindowsAzure.Plugins.RemoteForwarder.RdpInput" address="10.115.153.75:20000" protocol="tcp" isPublic="true" loadBalancedPublicAddress="70.37.106.197:3389" enableDirectServerReturn="false" isDirectAddress="false" disableStealthMode="false">
# <LocalPorts>
# <LocalPortRange from="20000" to="20000" />
# </LocalPorts>
# </Endpoint>
# </InputEndpoints>
# </Instance>
# </Instances>
# </SharedConfig>
#
def __init__(self):
self.reinitialize()
def reinitialize(self):
self.Deployment = None
self.Incarnation = None
self.Role = None
self.LoadBalancerSettings = None
self.OutputEndpoints = None
self.Instances = None
def Parse(self, xmlText):
self.reinitialize()
SetFileContents("SharedConfig.xml", xmlText)
dom = xml.dom.minidom.parseString(xmlText)
for a in [ "SharedConfig", "Deployment", "Service",
"ServiceInstance", "Incarnation", "Role", ]:
if not dom.getElementsByTagName(a):
Error("SharedConfig.Parse: Missing " + a)
return None
node = dom.childNodes[0]
if node.localName != "SharedConfig":
Error("SharedConfig.Parse: root not SharedConfig")
return None
program = Config.get("Role.TopologyConsumer")
if program != None:
Children.append(subprocess.Popen([program, LibDir + "/SharedConfig.xml"]))
return self
class HostingEnvironmentConfig(object):
#
# <HostingEnvironmentConfig version="1.0.0.0" goalStateIncarnation="1">
# <StoredCertificates>
# <StoredCertificate name="Stored0Microsoft.WindowsAzure.Plugins.RemoteAccess.PasswordEncryption" certificateId="sha1:C093FA5CD3AAE057CB7C4E04532B2E16E07C26CA" storeName="My" configurationLevel="System" />
# </StoredCertificates>
# <Deployment name="db00a7755a5e4e8a8fe4b19bc3b330c3" guid="{ce5a036f-5c93-40e7-8adf-2613631008ab}" incarnation="2">
# <Service name="MyVMRoleService" guid="{00000000-0000-0000-0000-000000000000}" />
# <ServiceInstance name="db00a7755a5e4e8a8fe4b19bc3b330c3.1" guid="{d113f4d7-9ead-4e73-b715-b724b5b7842c}" />
# </Deployment>
# <Incarnation number="1" instance="MachineRole_IN_0" guid="{a0faca35-52e5-4ec7-8fd1-63d2bc107d9b}" />
# <Role guid="{73d95f1c-6472-e58e-7a1a-523554e11d46}" name="MachineRole" hostingEnvironmentVersion="1" software="" softwareType="ApplicationPackage" entryPoint="" parameters="" settleTimeSeconds="10" />
# <HostingEnvironmentSettings name="full" Runtime="rd_fabric_stable.110217-1402.RuntimePackage_1.0.0.8.zip">
# <CAS mode="full" />
# <PrivilegeLevel mode="max" />
# <AdditionalProperties><CgiHandlers></CgiHandlers></AdditionalProperties>
# </HostingEnvironmentSettings>
# <ApplicationSettings>
# <Setting name="__ModelData" value="<m role="MachineRole" xmlns="urn:azure:m:v1"><r name="MachineRole"><e name="a" /><e name="b" /><e name="Microsoft.WindowsAzure.Plugins.RemoteAccess.Rdp" /><e name="Microsoft.WindowsAzure.Plugins.RemoteForwarder.RdpInput" /></r></m>" />
# <Setting name="Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString" value="DefaultEndpointsProtocol=http;AccountName=osimages;AccountKey=DNZQ..." />
# <Setting name="Microsoft.WindowsAzure.Plugins.RemoteAccess.AccountEncryptedPassword" value="MIIBnQYJKoZIhvcN..." />
# <Setting name="Microsoft.WindowsAzure.Plugins.RemoteAccess.AccountExpiration" value="2022-07-23T23:59:59.0000000-07:00" />
# <Setting name="Microsoft.WindowsAzure.Plugins.RemoteAccess.AccountUsername" value="test" />
# <Setting name="Microsoft.WindowsAzure.Plugins.RemoteAccess.Enabled" value="true" />
# <Setting name="Microsoft.WindowsAzure.Plugins.RemoteForwarder.Enabled" value="true" />
# <Setting name="Certificate|Microsoft.WindowsAzure.Plugins.RemoteAccess.PasswordEncryption" value="sha1:C093FA5CD3AAE057CB7C4E04532B2E16E07C26CA" />
# </ApplicationSettings>
# <ResourceReferences>
# <Resource name="DiagnosticStore" type="directory" request="Microsoft.Cis.Fabric.Controller.Descriptions.ServiceDescription.Data.Policy" sticky="true" size="1" path="db00a7755a5e4e8a8fe4b19bc3b330c3.MachineRole.DiagnosticStore\" disableQuota="false" />
# </ResourceReferences>
# </HostingEnvironmentConfig>
#
def __init__(self):
self.reinitialize()
def reinitialize(self):
self.StoredCertificates = None
self.Deployment = None
self.Incarnation = None
self.Role = None
self.HostingEnvironmentSettings = None
self.ApplicationSettings = None
self.Certificates = None
self.ResourceReferences = None
def Parse(self, xmlText):
self.reinitialize()
SetFileContents("HostingEnvironmentConfig.xml", xmlText)
dom = xml.dom.minidom.parseString(xmlText)
for a in [ "HostingEnvironmentConfig", "Deployment", "Service",
"ServiceInstance", "Incarnation", "Role", ]:
if not dom.getElementsByTagName(a):
Error("HostingEnvironmentConfig.Parse: Missing " + a)
return None
node = dom.childNodes[0]
if node.localName != "HostingEnvironmentConfig":
Error("HostingEnvironmentConfig.Parse: root not HostingEnvironmentConfig")
return None
self.ApplicationSettings = dom.getElementsByTagName("Setting")
self.Certificates = dom.getElementsByTagName("StoredCertificate")
return self
def DecryptPassword(self, e):
SetFileContents("password.p7m",
"MIME-Version: 1.0\n"
+ "Content-Disposition: attachment; filename=\"password.p7m\"\n"
+ "Content-Type: application/x-pkcs7-mime; name=\"password.p7m\"\n"
+ "Content-Transfer-Encoding: base64\n\n"
+ textwrap.fill(e, 64))
return RunGetOutput(Openssl + " cms -decrypt -in password.p7m -inkey Certificates.pem -recip Certificates.pem")[1]
def ActivateResourceDisk(self):
global DiskActivated
if IsWindows():
DiskActivated = True
Log("Skipping ActivateResourceDisk on Windows")
return
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
for entry in RunGetOutput("mount")[1].split():
if entry.startswith(device + "1"):
Log("ActivateResourceDisk: " + device + "1 is already mounted.")
DiskActivated = True
return
mountpoint = Config.get("ResourceDisk.MountPoint")
if mountpoint == None:
mountpoint = "/mnt/resource"
CreateDir(mountpoint, "root", 0755)
fs = Config.get("ResourceDisk.Filesystem")