forked from fidlej/sd-agent
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsd-deploy.py
312 lines (217 loc) · 7.45 KB
/
sd-deploy.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
'''
Server Density
www.serverdensity.com
----
A web based server resource monitoring application
Licensed under Simplified BSD License (see LICENSE)
(C) Boxed Ice 2009 all rights reserved
Documentation: http://www.serverdensity.com/docs/agent/autodeploy/
'''
#
# Argument checks
#
import sys
if len(sys.argv) < 5:
print 'Usage: python sd-deploy.py [API URL] [SD URL] [username] [password] [[init]]'
sys.exit(2)
#
# Get server details
#
import socket
# IP
try:
serverIp = socket.gethostbyname(socket.gethostname())
except socket.error, e:
print 'Unable to get server IP: ' + str(e)
sys.exit(2)
# Hostname
try:
serverHostname = hostname = socket.getfqdn()
except socket.error, e:
print 'Unable to get server hostname: ' + str(e)
sys.exit(2)
#
# Get latest agent version
#
print '1/4: Downloading latest agent version';
import httplib
import urllib2
# Request details
try:
requestAgent = urllib2.urlopen('http://www.serverdensity.com/agentupdate/')
responseAgent = requestAgent.read()
except urllib2.HTTPError, e:
print 'Unable to get latest version info - HTTPError = ' + str(e)
sys.exit(2)
except urllib2.URLError, e:
print 'Unable to get latest version info - URLError = ' + str(e)
sys.exit(2)
except httplib.HTTPException, e:
print 'Unable to get latest version info - HTTPException'
sys.exit(2)
except Exception, e:
import traceback
print 'Unable to get latest version info - Exception = ' + traceback.format_exc()
sys.exit(2)
#
# Define downloader function
#
import md5 # I know this is depreciated, but we still support Python 2.4 and hashlib is only in 2.5. Case 26918
import urllib
def downloadFile(agentFile, recursed = False):
print 'Downloading ' + agentFile['name']
downloadedFile = urllib.urlretrieve('http://www.serverdensity.com/downloads/sd-agent/' + agentFile['name'])
# Do md5 check to make sure the file downloaded properly
checksum = md5.new()
f = file(downloadedFile[0], 'rb')
# Although the files are small, we can't guarantee the available memory nor that there
# won't be large files in the future, so read the file in small parts (1kb at time)
while True:
part = f.read(1024)
if not part:
break # end of file
checksum.update(part)
f.close()
# Do we have a match?
if checksum.hexdigest() == agentFile['md5']:
return downloadedFile[0]
else:
# Try once more
if recursed == False:
downloadFile(agentFile, True)
else:
print agentFile['name'] + ' did not match its checksum - it is corrupted. This may be caused by network issues so please try again in a moment.'
sys.exit(2)
#
# Install the agent files
#
# We need to return the data using JSON. As of Python 2.6+, there is a core JSON
# module. We have a 2.4/2.5 compatible lib included with the agent but if we're
# on 2.6 or above, we should use the core module which will be faster
import platform
pythonVersion = platform.python_version_tuple()
# Decode the JSON
if int(pythonVersion[1]) >= 6: # Don't bother checking major version since we only support v2 anyway
import json
try:
updateInfo = json.loads(responseAgent)
except Exception, e:
print 'Unable to get latest version info. Try again later.'
sys.exit(2)
else:
import minjson
try:
updateInfo = minjson.safeRead(responseAgent)
except Exception, e:
print 'Unable to get latest version info. Try again later.'
sys.exit(2)
# Loop through the new files and call the download function
for agentFile in updateInfo['files']:
agentFile['tempFile'] = downloadFile(agentFile)
# If we got to here then everything worked out fine. However, all the files are still in temporary locations so we need to move them
import os
import shutil # Prevents [Errno 18] Invalid cross-device link (case 26878) - http://mail.python.org/pipermail/python-list/2005-February/308026.html
# Make sure doesn't exist already
if os.path.exists('sd-agent/'):
shutil.rmtree('sd-agent/')
os.mkdir('sd-agent')
for agentFile in updateInfo['files']:
print 'Installing ' + agentFile['name']
if agentFile['name'] != 'config.cfg':
shutil.move(agentFile['tempFile'], 'sd-agent/' + agentFile['name'])
print 'Agent files downloaded'
#
# Call API to add new server
#
print '2/4: Adding new server'
# Build API payload
import time
timestamp = time.strftime('%a, %d %b %Y %H:%M:%S GMT', time.gmtime())
postData = urllib.urlencode({'name' : serverHostname, 'ip' : serverIp, 'notes' : 'Added by sd-deploy: ' + timestamp })
# Send request
try:
# Password manager
mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
mgr.add_password(None, sys.argv[1] + '/1.0/', sys.argv[3], sys.argv[4])
opener = urllib2.build_opener(urllib2.HTTPBasicAuthHandler(mgr), urllib2.HTTPDigestAuthHandler(mgr))
urllib2.install_opener(opener)
# Build the request handler
requestAdd = urllib2.Request(sys.argv[1] + '/1.0/?account=' + sys.argv[2] + '&c=servers/add', postData, { 'User-Agent' : 'Server Density Deploy' })
# Do the request, log any errors
responseAdd = urllib2.urlopen(requestAdd)
readAdd = responseAdd.read()
except urllib2.HTTPError, e:
print 'HTTPError = ' + str(e)
if os.path.exists('sd-agent/'):
shutil.rmtree('sd-agent/')
except urllib2.URLError, e:
print 'URLError = ' + str(e)
if os.path.exists('sd-agent/'):
shutil.rmtree('sd-agent/')
except httplib.HTTPException, e: # Added for case #26701
print 'HTTPException' + str(e)
if os.path.exists('sd-agent/'):
shutil.rmtree('sd-agent/')
except Exception, e:
import traceback
print 'Exception = ' + traceback.format_exc()
if os.path.exists('sd-agent/'):
shutil.rmtree('sd-agent/')
# Decode the JSON
if int(pythonVersion[1]) >= 6: # Don't bother checking major version since we only support v2 anyway
import json
try:
serverInfo = json.loads(readAdd)
except Exception, e:
print 'Unable to add server.'
if os.path.exists('sd-agent/'):
shutil.rmtree('sd-agent/')
sys.exit(2)
else:
import minjson
try:
serverInfo = minjson.safeRead(readAdd)
except Exception, e:
print 'Unable to add server.'
if os.path.exists('sd-agent/'):
shutil.rmtree('sd-agent/')
sys.exit(2)
print 'Server added - ID: ' + str(serverInfo['data']['serverId'])
#
# Write config file
#
print '3/4: Writing config file'
configCfg = '[Main]\nsd_url: http://' + sys.argv[2] + '\nagent_key: ' + serverInfo['data']['agentKey'] + '\napache_status_url: http://www.example.com/server-status/?auto'
try:
f = open('sd-agent/config.cfg', 'w')
f.write(configCfg)
f.close()
except Exception, e:
import traceback
print 'Exception = ' + traceback.format_exc()
if os.path.exists('sd-agent/'):
shutil.rmtree('sd-agent/')
print 'Config file written'
#
# Install init.d
#
if len(sys.argv) == 6:
print '4/4: Installing init.d script'
shutil.copy('sd-agent.init', '/etc/init.d/sd-agent')
import subprocess
print 'Setting permissions'
df = subprocess.Popen(['chmod', '0755', '/etc/init.d/sd-agent'], stdout=subprocess.PIPE).communicate()[0]
print 'chkconfig'
df = subprocess.Popen(['chkconfig', '--add', 'sd-agent'], stdout=subprocess.PIPE).communicate()[0]
print 'Setting paths'
path = os.path.realpath(__file__)
path = os.path.dirname(path)
df = subprocess.Popen(['ln', '-s', path + '/sd-agent/', '/usr/bin/sd-agent'], stdout=subprocess.PIPE).communicate()[0]
print 'Install completed'
print 'Launch: /etc/init.d/sd-agent start'
else:
print '4/4: Not installing init.d script'
print 'Install completed'
path = os.path.realpath(__file__)
path = os.path.dirname(path)
print 'Launch: python ' + path + '/sd-agent/agent.py start'