/
rackspace_cloudserver.py
250 lines (187 loc) · 5.81 KB
/
rackspace_cloudserver.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
import getopt
import sys
import httplib
from pprint import pprint
from pprint import pformat
import json
import re
import time
DEBUG=0
PROGRAM_NAME="rackspace_cloudserver.py"
##http://docs.rackspace.com/auth/api/v1.1/auth-client-devguide/content/List_Versions-d1e232.html
#endpoints=[
# "https://lon.identity.api.rackspacecloud.com",
# "https://identity.api.rackspacecloud.com"
#]
#http://docs.rackspace.com/servers/api/v1.0/cs-devguide/content/Authentication-d1e506.html
endpoints=[
("lon.auth.api.rackspacecloud.com", "/v1.0"),
( "auth.api.rackspacecloud.com", "/v1.0")
]
ENDPOINT=()
COUNT=0
DEFAULT_CLOUD_SERVER={
"server" : {
"name" : "cstest",
"imageId" : 112,
"flavorId" : 1
}
}
def get_debug():
return DEBUG
def log(message):
print message
def debug(message):
if DEBUG>0:
log("debug[%2d]: " % DEBUG + message)
def usage(message=None):
if message is not None:
print message
print """
usage: %s [-v] [-h] [-c file] -u user -k key run | help
-h - usage help
-v - verbose/debug output
-c - specify the file name with the json specification what cloud server should be created
-u
-k
args:
help - displays info about this program
run - run this program
defaults:
# json specification used to create a cloud sever if no -c option is specified
{
"server" : {
"name" : "mytest",
"imageId" : 112,
"flavorId" : 1,
"metadata" : {
"key1" : "value1"
}
}
}
example:
todo
""" % PROGRAM_NAME
def debug_http_connection(e,method, index, body, headers ):
if DEBUG!=1:
return
debug("http request");
log(" "+e + " " + method + " " + index)
log(" headers: ")
for hname, hvalue in headers.items():
log(" " + hname + ": " + hvalue)
if body:
log("body:")
log(" "+body)
def debug_http_response(res):
if DEBUG!=1:
return
debug("http response");
log(" "+str(res.status) + " " + res.reason )
log(" headers")
for hname, hvalue in res.getheaders():
log(" " + hname + ": " + hvalue)
#", ".join( map (str, res.getheaders() ) ) )
def debug_paylaod(payload):
if DEBUG!=1:
return
l=len(payload)
debug("read " + str(l) + " from the server:")
if l!=0 :
log(payload)
def autenticate(user, key):
for (e, index ) in endpoints:
conn=httplib.HTTPSConnection(e)
headers={ "X-Auth-User": user,
"X-Auth-Key" : key }
method="GET"
body=""
debug_http_connection(e,method, index, body, headers )
conn.request(method, index,body, headers)
res = conn.getresponse()
debug_http_response(res)
payload= res.read()
debug_paylaod(payload)
conn.close()
if res.status > 200:
ENDPOINT=(e, index)
return res
return None
def get_token(res):
if res is None:
return
return res.getheader("x-auth-token")
def get_server_mgmt_url(res):
if res is None:
return
return res.getheader("x-server-management-url")
#curl --verbose -d @create-cloud.txt
# -H "Content-Type: application/json"
# -H "X-Auth-Token: a2772b...9de"
# https://lon.servers.api.rackspacecloud.com/v1.0/10001641/servers | json_xs -t dump
def create_cloud_server (token, mgmt_url, nr, cs=DEFAULT_CLOUD_SERVER):
(tmp , e, index)=re.search("(https://)([^/]*)(/.*)", mgmt_url).groups()
conn=httplib.HTTPSConnection(e)
headers={ "X-Auth-Token" : token,
"Content-Type" : "application/json" }
method="POST"
body=cs
cs_name=body['server']['name'] + str(nr)
body['server']['name']=cs_name
index=index + "/servers"
log("creating new cloud server with a name: " + cs_name )
debug_http_connection(e, method, index, json.dumps(body), headers )
conn.request(method, index, json.dumps(body), headers)
res = conn.getresponse()
debug_http_response(res)
payload= res.read()
tmp=json.dumps(json.loads(payload), indent=1)
if DEBUG:
debug_paylaod(tmp)
else:
log(tmp)
conn.close()
def main():
debug("main start")
debug(sys.argv[0])
optlist, args = getopt.getopt(sys.argv[1:], 'vu:k:')
debug("options: " + ', '.join( map(str,optlist) ) )
debug("arguments: " + ", ".join(args ))
user, key = None, None
for o, val in optlist:
if o == "-v":
global DEBUG;
DEBUG = 1
elif o == "-h":
usage()
sys.exit()
elif o =="-u":
user=val
elif o =="-k":
key=val
else:
assert False, "unhandled option"
debug("user: <" + str(user) + "> key: <" + str(key) + ">")
if len(args) == 0:
usage("missing arguments")
sys.exit()
if args[0] == "help":
usage("displaying help")
sys.exit()
elif args[0] is None:
usage("missing argument")
sys.exit()
elif args[0] == "run" and user is not None and key is not None:
res=autenticate(user, key)
if not res :
log("can't authenticate, try using -v")
usage("")
sys.exit()
token=get_token(res)
mgmt_url=get_server_mgmt_url(res)
create_cloud_server(token, mgmt_url, int(time.time()))
else:
usage("unrecognized arguments")
sys.exit()
if __name__ == '__main__':
main()