3
3
4
4
import httplib
5
5
import os
6
+ import time
6
7
7
8
8
9
HTTPTIMEOUT = 3
10
+ MAX_RETRY_TIMES = 3
11
+ WAIT_INTERNAL = 1
9
12
INSTANCE_TAG_DIR = "/var/lib/cloud/nvs/"
10
13
TAG_FILE_NAME = "instance-id"
11
14
INSTANCE_ID_URI = "/2009-04-04/meta-data/instance-id"
12
15
HOST_NAME_URI = "/2009-04-04/meta-data/local-hostname"
13
16
14
17
15
18
def send_request (uri ):
16
- global HTTPTIMEOUT
17
19
url = '169.254.169.254'
18
20
method = 'GET'
19
21
headers = {'Content-type' : 'application/json' ,
20
22
'Accept' : 'application/json' }
21
- conn = httplib .HTTPConnection (url , timeout = HTTPTIMEOUT )
22
- conn .request (method , uri , '' , headers )
23
- response = conn .getresponse ()
24
- data = response .read ()
25
- conn .close ()
26
23
27
- if response .status != 200 :
28
- raise Exception ()
29
-
30
- return data
24
+ for i in range (0 , MAX_RETRY_TIMES ):
25
+ try :
26
+ conn = httplib .HTTPConnection (url , timeout = HTTPTIMEOUT )
27
+ conn .request (method , uri , '' , headers )
28
+ response = conn .getresponse ()
29
+ data = response .read ()
30
+ conn .close ()
31
+ status = response .status
32
+ if status in (200 , 202 ):
33
+ return data
34
+ else :
35
+ if i + 1 == MAX_RETRY_TIMES :
36
+ msg = ('Unexpected status %(status)s while %(method)s '
37
+ '%(uri)s' % locals ())
38
+ raise Exception (msg )
39
+ else :
40
+ time .sleep (WAIT_INTERNAL )
41
+ continue
42
+ except Exception as e :
43
+ print 'Exception occurs while %(method)s %(url)s%(uri)s' % locals ()
44
+ if i + 1 == MAX_RETRY_TIMES :
45
+ raise e
46
+ else :
47
+ time .sleep (WAIT_INTERNAL )
31
48
32
49
33
50
def get_host_name ():
@@ -44,8 +61,6 @@ def get_instance_id():
44
61
45
62
46
63
def make_instance_tag (instance_id ):
47
- global INSTANCE_TAG_DIR
48
- global TAG_FILE_NAME
49
64
if not os .path .exists (INSTANCE_TAG_DIR ):
50
65
os .makedirs (INSTANCE_TAG_DIR )
51
66
@@ -55,8 +70,6 @@ def make_instance_tag(instance_id):
55
70
56
71
57
72
def is_new_instance (instance_id ):
58
- global INSTANCE_TAG_DIR
59
- global TAG_FILE_NAME
60
73
if not os .path .exists (INSTANCE_TAG_DIR ):
61
74
return True
62
75
@@ -78,7 +91,7 @@ def change_host_name(host_name):
78
91
# change /etc/hostname
79
92
with open ('/etc/hostname' , 'w' ) as f :
80
93
f .writelines ([host_name , '\n ' ])
81
- # enable new host name immediately
94
+ # enable new host name immediately
82
95
os .system ("hostname %s" % host_name )
83
96
84
97
# add new host name to /etc/hosts
0 commit comments