Skip to content

Commit 6cbdf74

Browse files
author
Wangpan
committed
update set hostname script
1 parent 9143a9f commit 6cbdf74

File tree

1 file changed

+28
-15
lines changed

1 file changed

+28
-15
lines changed

set_hostname.py

Lines changed: 28 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -3,31 +3,48 @@
33

44
import httplib
55
import os
6+
import time
67

78

89
HTTPTIMEOUT = 3
10+
MAX_RETRY_TIMES = 3
11+
WAIT_INTERNAL = 1
912
INSTANCE_TAG_DIR = "/var/lib/cloud/nvs/"
1013
TAG_FILE_NAME = "instance-id"
1114
INSTANCE_ID_URI = "/2009-04-04/meta-data/instance-id"
1215
HOST_NAME_URI = "/2009-04-04/meta-data/local-hostname"
1316

1417

1518
def send_request(uri):
16-
global HTTPTIMEOUT
1719
url = '169.254.169.254'
1820
method = 'GET'
1921
headers = {'Content-type': 'application/json',
2022
'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()
2623

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)
3148

3249

3350
def get_host_name():
@@ -44,8 +61,6 @@ def get_instance_id():
4461

4562

4663
def make_instance_tag(instance_id):
47-
global INSTANCE_TAG_DIR
48-
global TAG_FILE_NAME
4964
if not os.path.exists(INSTANCE_TAG_DIR):
5065
os.makedirs(INSTANCE_TAG_DIR)
5166

@@ -55,8 +70,6 @@ def make_instance_tag(instance_id):
5570

5671

5772
def is_new_instance(instance_id):
58-
global INSTANCE_TAG_DIR
59-
global TAG_FILE_NAME
6073
if not os.path.exists(INSTANCE_TAG_DIR):
6174
return True
6275

@@ -78,7 +91,7 @@ def change_host_name(host_name):
7891
# change /etc/hostname
7992
with open('/etc/hostname', 'w') as f:
8093
f.writelines([host_name, '\n'])
81-
# enable new host name immediately
94+
# enable new host name immediately
8295
os.system("hostname %s" % host_name)
8396

8497
# add new host name to /etc/hosts

0 commit comments

Comments
 (0)