-
Notifications
You must be signed in to change notification settings - Fork 0
/
qbert.py
210 lines (168 loc) · 7.6 KB
/
qbert.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
import json
import base64
from http import client as httplib
from urllib import parse as urlparse
def do_request(action, host, relative_url, headers, body):
"""Simple helper function to run REST calls."""
conn = httplib.HTTPSConnection(host)
body_json = json.JSONEncoder().encode(body)
conn.request(action, relative_url, body_json, headers)
response = conn.getresponse()
return conn, response
def get_service_url(service_name, catalog, region):
"""Loop through the catalog and return the url for a service in a region."""
for service in catalog:
if service['name'] == service_name:
for endpoint in service['endpoints']:
if endpoint['region'] == region and endpoint['interface'] == "public":
return endpoint['url']
def put_request(url, token, url_path, body):
"""Small helper function to do PUT requests."""
headers = {"Content-Type": "application/json", "Accept": "application/json", "X-Auth-Token": token}
_, net_location, path, _, _ = urlparse.urlsplit(url)
full_path = "{0}/{1}".format(path, url_path)
_, response = do_request("PUT", net_location, full_path, headers, body)
if response.status != 200:
print("URL: {}\n STATUS: {}\n MESSAGE: {}".format(full_path, response.status, response.reason))
return response.status
try:
response_body = json.loads(response.read().decode('utf-8'))
except ValueError:
print("Cannot load JSON. Maybe this API doesn't return JSON")
response_body = response.read()
return response_body
def delete_request(url, token, url_path):
"""Small helper function to do PUT requests."""
headers = {"Accept": "application/json", "X-Auth-Token": token}
body = ""
_, net_location, path, _, _ = urlparse.urlsplit(url)
full_path = "{0}/{1}".format(path, url_path)
_, response = do_request("DELETE", net_location, full_path, headers, body)
if response.status != 200:
print("URL: {}{}\n STATUS: {}\n MESSAGE: {}".format(net_location, full_path, response.status, response.reason))
return response.status
try:
response_body = json.loads(response.read().decode('utf-8'))
except ValueError:
print("Cannot load JSON. Maybe this API doesn't return JSON")
response_body = response.read()
return response_body
def get_request(url, token, url_path, type="JSON"):
"""Small helper function to do GET requests."""
headers = {"Accept": "application/json", "X-Auth-Token": token}
body = ""
_, net_location, path, _, _ = urlparse.urlsplit(url)
full_path = "{0}/{1}".format(path, url_path)
_, response = do_request("GET", net_location, full_path, headers, body)
if response.status != 200:
print("URL: {}\n STATUS: {}\n MESSAGE: {}".format(full_path, response.status, response.reason))
return response.status
if type == "JSON":
response_body = json.loads(response.read().decode('utf-8'))
else:
response_body = response.read()
return response_body
def get_node_pool(url, token):
"""Grabbing Node Pool ID."""
response_body = get_request(url, token, "cloudproviders")
for node_pool in response_body:
if node_pool['name'] == 'platform9':
return node_pool['nodePoolUuid']
def create_cluster(qbert_url, token, cluster_name, containers_cidr, services_cidr,
externalDnsName, privileged, appCatalogEnabled, allowWorkloadsOnMaster,
runtimeConfig, nodePoolUuid, networkPlugin, debug_flag):
"""Create a Kubernetes Cluster via Qbert."""
print("Creating Cluster.")
headers = {"Content-Type": "application/json", "Accept": "application/json",
"X-Auth-Token": token}
body = {
"name": cluster_name,
"containersCidr": containers_cidr,
"servicesCidr": services_cidr,
"externalDnsName": externalDnsName,
"privileged": privileged,
"appCatalogEnabled": appCatalogEnabled,
"allowWorkloadsOnMaster": allowWorkloadsOnMaster,
"runtimeConfig": runtimeConfig,
"nodePoolUuid": nodePoolUuid,
"networkPlugin": networkPlugin,
"debug": debug_flag
}
_, net_location, path, _, _ = urlparse.urlsplit(qbert_url)
node_pool_path = "{0}/{1}".format(path, "clusters")
_, response = do_request("POST", net_location, node_pool_path, headers, body)
if response.status != 200:
print("{0}: {1}".format(response.status, response.reason))
return response.status
response_body = json.loads(response.read().decode('utf-8'))
return response_body['uuid']
def get_qbert_v3_url(qbert_url, project_id):
"""Keystone only hands out a v1 url I need v3."""
qbert_v3_url = "{0}/v3/{1}".format(qbert_url[0:-3], project_id)
return qbert_v3_url
def get_token_v3(host, username, password, tenant):
"""Connect to Keystone and get a token."""
print("Getting a valid keystone token.")
headers = {"Content-Type": "application/json", "Accept": "application/json"}
body = {
"auth": {
"identity": {
"methods": ["password"],
"password": {
"user": {
"name": username,
"domain": {"id": "default"},
"password": password
}
}
},
"scope": {
"project": {
"name": tenant,
"domain": {"id": "default"}
}
}
}
}
conn, response = do_request("POST", host, "/keystone/v3/auth/tokens",
headers, body)
if response.status not in (200, 201):
print("STATUS: {0}\n MESSAGE: {1}".format(response.status, response.reason))
return response.status
token = response.getheader('X-Subject-Token')
response_body = json.loads(response.read().decode('utf-8'))
catalog = response_body['token']['catalog']
project_id = response_body['token']['project']['id']
conn.close()
return token, catalog, project_id
def get_kube_config(qbert_url, admin_token, endpoint, cluster_id, project_id, user, pw):
"""Download kubeconfig for our cluster."""
token, _, project_id = get_token_v3(endpoint, user, pw, project_id)
response_body = get_request(qbert_url, token, "kubeconfig/{0}".format(cluster_id), "RAW")
# Hash credentials and store with kubeconfig
credentials = {
"username": user,
"password": pw
}
credential_string = json.dumps(credentials)
bearer_token = base64.b64encode(credential_string.encode("utf-8"))
raw_kubeconfig = response_body.replace("__INSERT_BEARER_TOKEN_HERE__".encode("utf-8"), bearer_token)
return raw_kubeconfig.decode("utf-8")
def post_request(url, token, url_path, body, more_headers={}):
"""Small helper function to do POST requests."""
headers = {"Content-Type": "application/json", "Accept": "application/json", "X-Auth-Token": token}
if more_headers:
for k, v in more_headers.items():
headers[k] = v
_, net_location, path, _, _ = urlparse.urlsplit(url)
full_path = "{0}/{1}".format(path, url_path)
_, response = do_request("POST", net_location, full_path, headers, body)
if response.status != 200:
print("URL: {}\n STATUS: {}\n MESSAGE: {}".format(full_path, response.status, response.reason))
return response.status
try:
response_body = json.loads(response.read().decode('utf-8'))
except ValueError:
print("Cannot load JSON. Maybe this API doesn't return JSON")
response_body = response.read()
return response_body