-
Notifications
You must be signed in to change notification settings - Fork 2
/
deploy-app.py
303 lines (262 loc) · 10.4 KB
/
deploy-app.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
#!/usr/local/bin/python
import argparse
from datetime import datetime, timedelta
import json
import os
import requests
from requests.exceptions import ConnectionError, Timeout
import time
import sys
import yaml
field_map = (
(lambda x: x["image_path"], "4"),
(lambda x: x["access_ports"], "7"),
(lambda x: x["default_flavor"]["name"], "9"),
)
DEBUG = True if os.getenv("ACTIONS_STEP_DEBUG") == "true" else False
def die(msg, rc=2):
print(f"::error::{msg}")
sys.exit(rc)
def set_output(name, value):
print(f"::set-output name={name}::{value}")
def log(msg):
print(msg, flush=True)
def debug(msg):
if DEBUG:
print(f"::debug::{msg}", flush=True)
def get_image_revision():
ref = os.getenv('GITHUB_REF')
if ref == "refs/heads/master":
return "latest"
elif ref.startswith("refs/tags/"):
return ref.split("/")[-1]
else:
tokens = ref.split("/")
imagerev = "-".join(tokens[2:])
if tokens[1] == "pull":
imagerev = "pr-" + imagerev
return imagerev
def app_diff(oldapp, newapp):
fields = []
for (field, field_id) in field_map:
if field(oldapp) != field(newapp):
fields.append(field_id)
return fields
def load_response(r, stream=False):
items = r.text.splitlines() if stream else [ r.text ]
resp = []
for item in items:
d = json.loads(item)
if len(d) == 1 and "data" in d:
d = d["data"]
resp.append(d)
return resp if stream else resp[0]
def get_mc(console, username, password):
r = requests.post(f"{console}/api/v1/login",
json={"username": username, "password": password})
if r.status_code != requests.codes.ok:
log(f"MC login failed: {console}: {r.status_code} {r.text}")
die(f"Failed to log in to the console: {console}")
token = r.json()["token"]
apibase = f"{console}/api/v1/auth"
def mc(path, method="POST", timeout=300, headers={}, data={},
success_codes=[requests.codes.ok], **kwargs):
req_hdrs = {
"Accept": "application/json",
"Authorization": f"Bearer {token}",
}
req_hdrs.update(headers)
if data:
req_data = data
else:
req_data = kwargs
r = requests.request(method, f"{apibase}/{path}",
headers=req_hdrs,
json=req_data,
timeout=timeout)
if r.status_code not in success_codes:
log(f"MC call failed: {console} {path}: {r.status_code} {r.text}")
die(f"MC call failed: {path}, {r.status_code}")
try:
resp = load_response(r)
except Exception:
# Check if response is a JSON stream
resp = load_response(r, stream=True)
return resp
return mc
def check_status(resp):
success = True
if isinstance(resp, list):
for item in resp:
if "message" in item:
debug(item["message"])
if "result" in item:
code = int(item["result"].get("code"))
if code != requests.codes.ok:
log(item["result"].get("message") or f"Error: {code}")
success = False
else:
debug(item["result"].get("message"))
return success
def create_cluster(mc, region, cloudlet_org, cloudlet_name, cluster_org, cluster_name, flavor,
deployment="kubernetes"):
data = {
"clusterinst": {
"deployment": deployment,
"flavor": {
"name": flavor,
},
"key": {
"cloudlet_key": {
"name": cloudlet_name,
"organization": cloudlet_org,
},
"cluster_key": {
"name": cluster_name,
},
"organization": cluster_org,
},
},
"region": region,
}
search_data = {
"clusterinst": {
"key": data["clusterinst"]["key"],
},
"region": data["region"],
}
cluster = mc("ctrl/ShowClusterInst", data=search_data)
if cluster:
# Validate cluster parameters
mismatches = []
reqd_cluster = data["clusterinst"]
if cluster["flavor"]["name"] != reqd_cluster["flavor"]["name"]:
mismatches.append(("flavor", reqd_cluster["flavor"]["name"]))
if cluster["deployment"] != reqd_cluster["deployment"]:
mismatches.append(("deployment", reqd_cluster["deployment"]))
if mismatches:
mismatch_desc = ", ".join(
["{} != {}".format(x[0], x[1]) for x in mismatches])
raise Exception("Cluster \"{}\" present but has incompatible config: {}".format(
cluster_name, mismatch_desc))
else:
log(f"Creating {flavor} {deployment} cluster: {cluster_name}")
start = datetime.now()
try:
mc("ctrl/CreateClusterInst", data=data, timeout=30)
except (ConnectionError, Timeout):
# Check to see if the cluster is ready
timeout = timedelta(minutes=30)
while datetime.now() - start < timeout:
clusters = mc("ctrl/ShowClusterInst", data=data)
if clusters and clusters["state"] == 5:
# Cluster is ready
return
time.sleep(10)
raise Exception("Timed out waiting for cluster")
def main(args):
actions = []
deployments = []
for envvar in ("INPUT_USERNAME", "INPUT_PASSWORD"):
if not os.getenv(envvar):
die(f"Mandatory variable not set: {envvar}")
if not os.path.exists(args.appconfig):
raise Exception(f"App instance definition not found: {args.appconfig}")
with open(args.appconfig) as f:
app = yaml.load(f, Loader=yaml.Loader)
# Accept aliases for app definition keys
for (key, alias) in (("access_ports", "accessports"),
("default_flavor", "defaultflavor"),
("image_path", "imagepath"),
("image_type", "imagetype")):
if key not in app["app"] and alias in app["app"]:
app["app"][key] = app["app"][alias]
del app["app"][alias]
# Accept string values for image type
image_type_codes = {
"ImageTypeDocker": 1,
"ImageTypeQcow": 2,
"ImageTypeHelm": 3,
}
if app["app"]["image_type"] in image_type_codes:
app["app"]["image_type"] = image_type_codes[app["app"]["image_type"]]
try:
region = app["region"]
app_key = app["app"]["key"]
image_path = app["app"]["image_path"]
if ":" not in image_path:
image_rev = get_image_revision()
app["app"]["image_path"] = f"{image_path}:{image_rev}"
except Exception as e:
raise Exception(f"Failed to load app definition: {e}")
set_output("setup", args.setup)
set_output("image", app["app"]["image_path"])
if args.setup == "main":
console = "https://console.mobiledgex.net"
else:
console = f"https://console-{args.setup}.mobiledgex.net"
# Get app flavor and deployment for cluster creation
try:
flavor = app["app"]["default_flavor"]["name"]
deployment = app["app"]["deployment"]
except KeyError:
flavor = "m4.small"
deployment = "kubernetes"
mc = get_mc(console, username=os.getenv("INPUT_USERNAME"),
password=os.getenv("INPUT_PASSWORD"))
# Check if app exists
existing_app = mc("ctrl/ShowApp", data={
"region": region,
"app": { "key": app_key },
})
if existing_app:
log(f"Updating existing app: {app_key}")
action = "UpdateApp"
app["app"]["fields"] = app_diff(existing_app, app["app"])
else:
log(f"Creating new app: {app_key}")
action = "CreateApp"
# Create/update app
actions.append(action)
mc(f"ctrl/{action}", data=app)
if os.path.exists(args.appinstsconfig):
with open(args.appinstsconfig) as f:
appinsts = yaml.load(f, Loader=yaml.Loader)
for appinst in appinsts:
try:
appinst["region"] = region
appinst["appinst"]["key"]["app_key"] = app_key
clusterinst_key = appinst["appinst"]["key"]["cluster_inst_key"]
cluster_name = clusterinst_key["cluster_key"]["name"]
cluster_org = clusterinst_key.get("organization", app_key["organization"])
cloudlet_name = clusterinst_key["cloudlet_key"]["name"]
cloudlet_org = clusterinst_key["cloudlet_key"]["organization"]
except Exception as e:
raise Exception(f"Failed to load app instances definition: {e}")
create_cluster(mc, region, cloudlet_org, cloudlet_name, cluster_org, cluster_name, flavor,
deployment=deployment)
existing_appinst = mc("ctrl/ShowAppInst", data=appinst)
if existing_appinst:
log(f"Updating app instance {cluster_name},{cluster_org} @ {cloudlet_name},{cloudlet_org}")
resp = mc("ctrl/RefreshAppInst", data=appinst)
if check_status(resp):
debug(f"Updated app inst {cluster_name},{cluster_org} @ {cloudlet_name},{cloudlet_org}")
else:
log(f"Creating new app instance {cluster_name},{cluster_org} @ {cloudlet_name},{cloudlet_org}")
resp = mc("ctrl/CreateAppInst", data=appinst)
if check_status(resp):
debug(f"Created app inst {cluster_name},{cluster_org} @ {cloudlet_name},{cloudlet_org}")
deployments.append(f"{cloudlet_name}:{cloudlet_org}:{cluster_name}:{cluster_org}")
set_output("actions", ",".join(actions))
set_output("deployments", ",".join(deployments))
if __name__ == "__main__":
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--appconfig", help="Path to app config",
default=".mobiledgex/app.yml")
parser.add_argument("--appinstsconfig", help="Path to app instances config",
default=".mobiledgex/appinsts.yml")
parser.add_argument("--setup", "-s", help="Setup to deploy app to",
default="main")
args = parser.parse_args()
main(args)