-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandler.star
More file actions
3034 lines (2617 loc) · 114 KB
/
Copy pathhandler.star
File metadata and controls
3034 lines (2617 loc) · 114 KB
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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
load("openrun.in", "openrun")
load("openrun_admin.in", "openrun_admin")
load("build.in", "build")
load("utils.star", "query_param", "query_param_list", "get_perms", "params_to_text",
"parse_lines", "short_sha", "short_age", "human_size", "pct_num", "nonzero_time", "sort_recent",
"flash_result", "parse_kv_rows", "kv_rows", "raw_kv_rows",
"path_domain_str", "sync_flags", "sync_result_summary", "review_from_dryrun",
"needs_approval", "docs_link")
# Route handlers for the console. Each screen has a *_data function which
# builds the full page context; action handlers run the mutation and re-render
# the same context with a Flash/FlashError message. Mutation results must read
# ret.error BEFORE the *_data call: an unread plugin error fails the next
# plugin call. The error_handler in app.star is the fallback when that is
# missed.
# ---------- Apps ----------
def build_app_rows(all_apps):
# Folds staging entries into their main app's row and returns the row
# dicts rendered by the shared app_table template. all_apps must come
# from list_apps with include_internal=True
staging_by_main = {}
for entry in all_apps:
if entry["is_stage"]:
staging_by_main[entry["main_app"]] = entry
rows = []
for entry in all_apps:
if entry["main_app"]:
continue
stage = staging_by_main.get(entry["id"])
# The staging app carries the most recent sync state (prod picks it
# up on promote); fall back to the prod app's value. get() keeps this
# working against servers older than the applied_sync_id field
sync_id = (stage.get("applied_sync_id", "") if stage else "") or entry.get("applied_sync_id", "")
staging = None
if stage:
staging = {
"version": stage["version"],
"git_sha": short_sha(stage["git_sha"]),
"git_message": stage["git_message"],
# staging has a version prod does not have yet
"ahead": stage["version_mismatch"],
}
rows.append({
"name": entry["name"],
"path": entry["path"],
"url": entry["url"],
"auth": entry["auth"],
"is_dev": entry.get("is_dev") or False,
# Only set when list_apps ran with check_approval=True (apps page);
# the backend mirrors the staging app's audit onto the main app
"needs_approval": entry.get("needs_approval") or False,
"is_git": bool(entry["git_branch"]),
# Declarative means a sync source last applied the app. Git
# presence is not the signal: image/proxy spec apps have no git
"sync_id": sync_id,
"is_declarative": bool(sync_id),
# "-" is the placeholder for apps with no source (image/proxy specs)
"source": entry["source"] if entry["source"] != "-" else "",
"source_url": entry["source_url"],
"git_branch": entry["git_branch"],
"spec": entry.get("spec") or "",
"version": entry["version"],
"git_sha": short_sha(entry["git_sha"]),
"git_message": entry["git_message"],
"staging": staging,
"created_by": entry.get("created_by") or "",
"update_age": short_age(entry["update_age"]),
"update_time": entry.get("update_time") or "",
"update_user": entry.get("update_user") or "",
})
return rows
def apps_data(req):
# Apps list page: apps grouped by their managing sync, plus unmanaged.
# The promote/approval tabs show the apps waiting on that action as a
# flat list, with the row action switched to Promote/Approve
query = query_param(req, "query")
filter = query_param(req, "filter") # "", "declarative" or "imperative"
tab = query_param(req, "tab") # "", "promote" or "approval"
# include_internal picks up staging/preview apps; staging entries are
# folded into their main app's row instead of being listed separately.
# check_approval adds the needs_approval flag (cached server-side)
all_apps = openrun.list_apps(query=query, include_internal=True,
check_approval=True).value
# Sync entries the user can read. Apps whose sync entry is not visible
# (no sync:read) are shown in the unmanaged section instead
syncs = {}
sync_ret = openrun.list_sync()
for entry in (sync_ret.value if not sync_ret.error else []):
syncs[entry["id"]] = {
"id": entry["id"],
"repo": entry["path"],
"branch": entry["metadata"]["git_branch"],
"state": entry["status"]["state"], # Enabled / Disabled / Failing
"last_exec": nonzero_time(entry["status"]["last_execution_time"]),
}
grouped = {} # sync id -> app rows, for apps last applied by a live sync
unmanaged = [] # created/last updated imperatively
tab_apps = [] # rows for the active promote/approval tab
total = 0
declarative_count = 0
promote_count = 0
approval_count = 0
for app in build_app_rows(all_apps):
total += 1
if app["is_declarative"]:
declarative_count += 1
if (filter == "declarative" and not app["is_declarative"]) or \
(filter == "imperative" and app["is_declarative"]):
continue
# The tab badge counts follow the active declarative/imperative
# filter, matching what the tab tables list
if app["staging"] and app["staging"]["ahead"]:
promote_count += 1
if app["needs_approval"]:
approval_count += 1
if tab == "promote" and app["staging"] and app["staging"]["ahead"]:
tab_apps.append(app)
elif tab == "approval" and app["needs_approval"]:
tab_apps.append(app)
if app["sync_id"] and app["sync_id"] in syncs:
grouped.setdefault(app["sync_id"], []).append(app)
else:
unmanaged.append(app)
# Most recently updated apps first, groups ordered by their most
# recently updated app
groups = []
for sync_id in grouped:
apps = sort_recent(grouped[sync_id], "update_time", "path")
groups.append({
"sync": syncs[sync_id],
"apps": apps,
"newest": apps[0]["update_time"] if apps else "",
"repo": syncs[sync_id]["repo"],
})
return {
"Title": "Apps",
"Nav": "apps",
"Query": query,
"Filter": filter,
"Tab": tab,
"TabApps": sort_recent(tab_apps, "update_time", "path"),
"Groups": sort_recent(groups, "newest", "repo"),
"Unmanaged": sort_recent(unmanaged, "update_time", "path"),
"Total": total,
"DeclarativeCount": declarative_count,
"ImperativeCount": total - declarative_count,
"PromoteCount": promote_count,
"ApprovalCount": approval_count,
"Perms": get_perms(),
}
def load_versions(path):
# Returns the version list for the app at path, newest first
ret = openrun.list_versions(path)
if ret.error:
return [], ret.error
versions = []
for entry in ret.value["versions"] or []:
vm = (entry.get("Metadata") or {}).get("version_metadata") or {}
versions.append({
"version": entry["Version"],
"previous": entry.get("PreviousVersion") or 0,
"active": entry.get("Active") or False,
"user": entry.get("UserId") or "",
"create_time": nonzero_time(entry.get("CreateTime")),
"git_sha": short_sha(vm.get("git_commit") or ""),
"git_message": vm.get("git_message") or "",
"git_branch": vm.get("git_branch") or "",
})
return sorted(versions, key=lambda v: v["version"], reverse=True), ""
def resolve_env_path(path, env):
# The prod app path is the external identifier; staging actions resolve
# the linked staging app's path through get_app
if env == "stage":
app_ret = openrun.get_app(path)
if not app_ret.error:
return app_ret.value["stage_path"]
return path
ENV_ORDER = {"prod": "0", "stage": "1", "preview": "2", "dev": "3"}
def app_container_sort_key(entry):
# Sort containers: running first, then prod/stage/preview/dev, then name
running = "0" if entry["state"] == "running" else "1"
return running + ENV_ORDER.get(entry["env"], "9") + entry["name"]
def apps_detail_data(req):
# App detail page: overview, params, permissions, containers, versions
path = query_param(req, "path")
data = {
"Title": "App detail",
"Nav": "apps",
"Path": path,
"Error": "",
"App": None,
"Containers": [],
# Set after a staging-only reload/update, prompts for promotion
"AskPromote": query_param(req, "staged"),
# App permissions evaluated against this app, including the owner rule
"Perms": get_perms(path),
"HelpUrl": docs_link("/docs/applications/lifecycle/"),
}
ret = openrun.get_app(path)
if ret.error:
data["Error"] = ret.error
return data
app = ret.value
data["App"] = app
# Resolve the sync entry which manages this app, if any
if app["applied_sync_id"]:
sync_ret = openrun.list_sync()
for entry in (sync_ret.value if not sync_ret.error else []):
if entry["id"] == app["applied_sync_id"]:
data["Sync"] = {
"repo": entry["path"],
"branch": entry["metadata"]["git_branch"],
}
data["ParamsText"] = params_to_text(app["params"])
# Containers running (or recently run) for this app, current env first
cont_ret = openrun.list_containers()
if not cont_ret.error:
containers = [c for c in cont_ret.value if c["app_path"] == path]
data["Containers"] = sorted(containers, key=app_container_sort_key)
# Audit the app's code for the plugin permissions it requests and whether
# they are pending approval (audited against staging for prod apps)
audit_ret = openrun.audit_app(path)
if audit_ret.error:
data["AuditError"] = audit_ret.error
else:
audit = audit_ret.value
data["Audit"] = review_from_dryrun({"approve_results": [audit]})
data["NeedsApproval"] = audit.get("needs_approval") or False
if app["is_dev"]:
# Dev apps serve directly from disk, no versions are tracked
return data
prod_versions, prod_err = load_versions(path)
stage_versions, stage_err = load_versions(app["stage_path"])
data["ProdVersions"] = prod_versions
data["ProdVersionsError"] = prod_err
data["StageVersions"] = stage_versions
data["StageVersionsError"] = stage_err
return data
def apps_switch_handler(req):
# POST: switch the active version for prod or staging
path = query_param(req, "path")
env = query_param(req, "env") or "prod"
version = query_param(req, "version")
ret = openrun_admin.switch_version(resolve_env_path(path, env), version)
error = ret.error
return flash_result(apps_detail_data(req), error,
"Switched %s to v%s" % (env, version), "Version switch failed")
def require_app_path(req, data_fn):
# The app write plugin APIs take path globs; a missing path must not
# silently become an empty glob (which would match every app). Returns
# (path, None) or ("", error page data)
path = query_param(req, "path").strip()
if not path:
data = data_fn(req)
data["FlashError"] = "App path is required"
return "", data
return path, None
def promote_app_result(req, data_fn, path):
# Promote the staging app to prod and re-render the page via data_fn
# with the result flash. Shared by the detail page, the apps list
# pending-promotion tab and the builder session page
ret = openrun_admin.promote_apps(path)
error = ret.error
data = data_fn(req)
if error:
data["FlashError"] = "Promote failed: %s" % error
elif not ret.value.get("promote_results"):
data["Flash"] = "Nothing to promote, prod matches staging"
else:
data["Flash"] = "Promoted %s to prod" % path
return data
def apps_promote_handler(req):
# POST: promote the staging app to prod
path, error_data = require_app_path(req, apps_detail_data)
if error_data:
return error_data
return promote_app_result(req, apps_detail_data, path)
def approve_app_result(req, data_fn, path):
# Approve the pending plugin permissions (applies to the staging app, or
# directly for dev apps) and re-render the page via data_fn
ret = openrun_admin.approve_apps(path, promote=False)
error = ret.error
data = data_fn(req)
if error:
data["FlashError"] = "Approve failed: %s" % error
else:
data["Flash"] = "Approved pending permissions for %s" % path
return data
def apps_approve_handler(req):
# POST: approve the requested plugin permissions; promotion is asked as
# the next step
path, error_data = require_app_path(req, apps_detail_data)
if error_data:
return error_data
data = approve_app_result(req, apps_detail_data, path)
if not data.get("FlashError"):
data["AskPromote"] = "approve"
return data
def reload_app_staging(path):
# Staging-first reload: approval is requested only when the user holds
# it (the approve flag hard-fails otherwise), promotion is a next step
perms = get_perms(path)
return openrun_admin.reload_apps(path, approve=bool(perms.get("app:approve") or perms.get("admin")), promote=False)
def apps_detail_reload_handler(req):
# POST: reload staging from source, staying on the detail page
path, error_data = require_app_path(req, apps_detail_data)
if error_data:
return error_data
ret = reload_app_staging(path)
error = ret.error
data = apps_detail_data(req)
if error:
data["FlashError"] = "Reload failed: %s" % error
elif ret.value.get("skipped_results") and not ret.value.get("reload_results"):
data["Flash"] = "%s is already up to date" % path
else:
data["Flash"] = "Staging reloaded from source"
data["AskPromote"] = "reload"
return data
def apps_detail_delete_handler(req):
# POST: delete the app and return to the apps list
path, error_data = require_app_path(req, apps_detail_data)
if error_data:
return error_data
ret = openrun_admin.delete_apps(path)
if ret.error:
data = apps_detail_data(req)
data["FlashError"] = "Delete failed: %s" % ret.error
return data
# The app is gone, go back to the apps list
return ace.response(apps_detail_data(req), block="detail_content",
redirect=req.AppPath + "/apps")
def apps_files_handler(req):
# Version files page: the file listing of one app version
path = query_param(req, "path")
version = query_param(req, "version")
env = query_param(req, "env") or "prod"
data = {
"Title": "Version files",
"Nav": "apps",
"Path": path,
"Version": version,
"Env": env,
"Error": "",
"Files": [],
"TotalSize": "",
}
ret = openrun.list_version_files(resolve_env_path(path, env), version=version)
if ret.error:
data["Error"] = ret.error
return data
files = []
total = 0
for entry in ret.value["files"] or []:
total += entry["Size"]
files.append({
"name": entry["Name"],
"size": human_size(entry["Size"]),
"etag": entry["Etag"][:12] if entry["Etag"] else "",
})
data["Files"] = sorted(files, key=lambda f: f["name"])
data["TotalSize"] = human_size(total)
return data
def apps_files_download_handler(req):
# GET: bundle the version's files into a zip and stream it back to the
# client as an attachment (chunked, no disk/db staging); errors re-render
# the files page
path = query_param(req, "path")
version = query_param(req, "version")
env = query_param(req, "env") or "prod"
ret = openrun.get_version_zip(resolve_env_path(path, env), version=version)
if ret.error:
data = apps_files_handler(req)
data["FlashError"] = "Download failed: %s" % ret.error
return data
return ace.response(ret.value["content"], download=ret.value["name"],
content_type="application/zip")
def apps_delete_handler(req):
# POST: delete an app from the apps list
path, error_data = require_app_path(req, apps_data)
if error_data:
return error_data
ret = openrun_admin.delete_apps(path)
error = ret.error
return flash_result(apps_data(req), error, "Deleted %s" % path, "Delete failed")
def apps_reload_handler(req):
# POST: reload staging from the apps list, then go to the detail page
path, error_data = require_app_path(req, apps_data)
if error_data:
return error_data
ret = reload_app_staging(path)
if ret.error:
data = apps_data(req)
data["FlashError"] = "Reload failed: %s" % ret.error
return data
if ret.value.get("skipped_results") and not ret.value.get("reload_results"):
data = apps_data(req)
data["Flash"] = "%s is already up to date" % path
return data
# Staging reloaded; continue on the detail page to review and promote
return ace.response(apps_data(req), block="app_groups",
redirect="%s/apps/detail?path=%s&staged=reload" % (req.AppPath, path))
def apps_list_promote_handler(req):
# POST: promote staging to prod from the pending-promotion tab
path, error_data = require_app_path(req, apps_data)
if error_data:
return error_data
return promote_app_result(req, apps_data, path)
def apps_list_approve_handler(req):
# POST: approve the pending plugin permissions from the approval tab; a
# prod app then shows under pending promotion as the next step
path, error_data = require_app_path(req, apps_data)
if error_data:
return error_data
return approve_app_result(req, apps_data, path)
def run_sync_action(req, data_fn):
# Run a sync and show the detailed apply results on the current page
ret = openrun_admin.run_sync(query_param(req, "sync_id"))
error = ret.error
data = data_fn(req)
if error:
data["FlashError"] = "Sync failed: %s" % error
elif ret.value.get("error"):
data["FlashError"] = "Sync failed: %s" % ret.value["error"]
else:
data["SyncResult"] = sync_result_summary(ret.value)
return data
def apps_sync_handler(req):
# POST: run a sync from the apps list
return run_sync_action(req, apps_data)
# ---------- App create / update forms ----------
def auth_options():
# Valid app auth types from the server: built-ins (default/system/none)
# plus the configured oauth, saml and client cert auth entries
ret = openrun.list_auths()
return ret.value if not ret.error else []
def git_auth_options():
# The git_auth entry names configured on the server, for private repos
ret = openrun.list_git_auths()
return ret.value if not ret.error else []
def binding_options():
# The choices for the app form's service bindings dropdowns: service ids
# (binding to a service creates an auto binding) and the base/derived
# binding paths (an app's own auto bindings are not offered). Errors
# (e.g. no binding:read access) degrade to empty lists
services = []
svc_ret = openrun.list_services()
if not svc_ret.error:
for entry in svc_ret.value:
services.append(entry["service_type"] + "/" + entry["name"])
bindings = []
list_ret = openrun.list_bindings()
if not list_ret.error:
for entry in list_ret.value:
if not entry["path"].startswith("/auto/"):
bindings.append(entry["path"])
return {"services": sorted(services), "bindings": sorted(bindings)}
def posted_bindings(req):
# The bindings selected on the app form, in row order. Rows left on the
# placeholder (empty value) are skipped
return [ref for ref in query_param_list(req, "bindings") if ref]
def app_binding_refs(app):
# The app's current bindings as form dropdown values: an auto binding
# path is mapped back to the service source it was created from (the
# dropdown offers services, not auto binding paths); explicit binding
# paths stay as-is
refs = app.get("bindings") or []
if not refs:
return []
sources = {}
list_ret = openrun.list_bindings()
if not list_ret.error:
for entry in list_ret.value:
sources[entry["path"]] = entry["source"]
mapped = []
for ref in refs:
if ref.startswith("/auto/") and sources.get(ref):
mapped.append(sources[ref])
else:
mapped.append(ref)
return mapped
def form_values(req):
# The form fields for the create/update subpages
return {
"path": query_param(req, "path"),
"source_url": query_param(req, "source_url"),
"spec": query_param(req, "spec"),
"auth": query_param(req, "auth"),
"git_branch": query_param(req, "git_branch"),
"git_auth": query_param(req, "git_auth"),
"params_rows": raw_kv_rows(req, "params"),
"bindings": posted_bindings(req),
"approve": query_param(req, "approve"),
}
def create_form_data(req, values, error):
# Page context for the app create form
return {
"Title": "New app",
"Nav": "apps",
"Mode": "create",
"Step": "edit",
"Error": error,
"Specs": openrun.list_specs().value,
"AuthOptions": auth_options(),
"GitAuthOptions": git_auth_options(),
"BindingOptions": binding_options(),
"Values": values,
"Perms": get_perms(),
}
def approve_step_data(req, values, review, error):
# Create form context for the post-create approval step
data = create_form_data(req, values, error)
data["Step"] = "approve"
data["Review"] = review
return data
def apps_create_page_handler(req):
# App create form page
return create_form_data(req, form_values(req), "")
def apps_create_submit_handler(req):
# POST: validate (dry run), create, or approve a new app
values = form_values(req)
action = query_param(req, "action")
if action == "approve":
# The app was created, approve its pending permissions
ret = openrun_admin.approve_apps(values["path"])
if ret.error:
pending = openrun_admin.approve_apps(values["path"], dry_run=True)
review = {"loads": [], "permissions": []}
if not pending.error:
review = review_from_dryrun({"approve_results": pending.value.get("staged_update_results")})
return approve_step_data(req, values, review, ret.error)
return ace.redirect(req.AppPath + "/apps")
if not values["path"]:
return create_form_data(req, values, "App path is required")
if not values["source_url"]:
return create_form_data(req, values, "Source url is required")
params, err = parse_kv_rows(req, "params")
if err:
return create_form_data(req, values, err)
auth = values["auth"] if values["auth"] != "default" else ""
if action == "create":
# Create the app without approval; if it requests permissions, ask
# for the approval as the next step
ret = openrun_admin.create_app(values["path"], values["source_url"],
approve=False, auth=auth,
spec=values["spec"], git_branch=values["git_branch"],
git_auth=values["git_auth"], params=params,
bindings=values["bindings"])
if ret.error:
return create_form_data(req, values, ret.error)
if needs_approval(ret.value):
return approve_step_data(req, values, review_from_dryrun(ret.value), "")
return ace.redirect(req.AppPath + "/apps")
# Validate: dry run to check the create and gather the requested
# permissions, nothing is committed
ret = openrun_admin.create_app(values["path"], values["source_url"],
approve=True, dry_run=True, auth=auth,
spec=values["spec"], git_branch=values["git_branch"],
git_auth=values["git_auth"], params=params,
bindings=values["bindings"])
if ret.error:
return create_form_data(req, values, ret.error)
data = create_form_data(req, values, "")
data["Validated"] = True
data["Review"] = review_from_dryrun(ret.value)
return data
def update_form_data(req, app, values, error):
# Page context for the app update form
return {
"Title": "Update app",
"Nav": "apps",
"Mode": "update",
"Step": "edit",
"Error": error,
"App": app,
"AuthOptions": auth_options(),
"BindingOptions": binding_options(),
"Values": values,
"Perms": get_perms(values.get("path", "")),
}
def apps_update_page_handler(req):
# App update form page, prefilled from the current app
path = query_param(req, "path")
ret = openrun.get_app(path)
if ret.error:
return update_form_data(req, None, {}, ret.error)
app = ret.value
values = {
"path": app["path"],
"auth": app["auth"] or "default",
"params_rows": kv_rows(app["params"]),
"bindings": app_binding_refs(app),
}
return update_form_data(req, app, values, "")
def apps_update_submit_handler(req):
# POST: apply param/binding (staged) and auth (direct) changes
path = query_param(req, "path")
values = {
"path": path,
"auth": query_param(req, "auth"),
"params_rows": raw_kv_rows(req, "params"),
"bindings": posted_bindings(req),
}
ret = openrun.get_app(path)
if ret.error:
return update_form_data(req, None, values, ret.error)
app = ret.value
params, err = parse_kv_rows(req, "params")
if err:
return update_form_data(req, app, values, err)
params_changed = params != app["params"]
if params_changed:
# Params apply to staging; promotion is asked on the detail page
result = openrun_admin.update_params(path, params, promote=False)
if result.error:
return update_form_data(req, app, values, result.error)
# Compare in dropdown-value space (auto binding paths mapped back to
# their service source), same as the form prefill
bindings_changed = values["bindings"] != app_binding_refs(app)
if bindings_changed:
# Bindings apply to staging like params; a single "-" clears them all
result = openrun_admin.update_bindings(path, values["bindings"] or ["-"],
promote=False)
if result.error:
return update_form_data(req, app, values, result.error)
new_auth = values["auth"] or "default"
if new_auth != (app["auth"] or "default"):
# Auth is an app setting, not version controlled; applies directly
result = openrun_admin.update_auth(path, new_auth)
if result.error:
return update_form_data(req, app, values, result.error)
if (params_changed or bindings_changed) and not app.get("is_dev"):
# Ask about promoting the staged change; dev apps apply directly
# (they have no staging), so there is nothing to promote
return ace.redirect("%s/apps/detail?path=%s&staged=update" % (req.AppPath, path))
return ace.redirect("%s/apps/detail?path=%s" % (req.AppPath, path))
# ---------- Bindings and services ----------
def bindings_data(req):
# Bindings page: services table plus base/derived/auto binding tables
query = query_param(req, "query").lower()
# Map app id -> app path, to show which app an auto binding belongs to
app_paths = {}
for entry in openrun.list_apps(include_internal=True).value:
app_paths[entry["id"]] = entry["path"]
base = []
derived = []
auto = []
total = 0
list_error = ""
list_ret = openrun.list_bindings()
if list_ret.error:
# No binding:read access, show the page with the error instead
list_error = list_ret.error
for entry in (list_ret.value if not list_error else []):
total += 1
path = entry["path"]
derived_from = entry["derived_from"]
created_by = entry.get("created_by") or ""
# Search matches the binding path, the base binding's path and creator
if query and query not in path.lower() and query not in derived_from.lower() and \
query not in created_by.lower():
continue
metadata = entry["metadata"]
staged = entry["staged_metadata"]
grants = metadata["grants"] or []
staged_grants = staged["grants"] or []
config = metadata["config"] or {}
staged_config = staged["config"] or {}
binding = {
"path": path,
"created_by": created_by,
"source": entry["source"],
"service_type": entry["service_type"],
"service_name": entry["service_name"],
"derived_from": derived_from,
"grants": grants,
"staged_grants": staged_grants,
# staging has grant/config changes which are not applied to prod yet
"has_staged": staged_grants != grants or staged_config != config,
"config_keys": sorted(config.keys()),
"update_time": nonzero_time(entry["update_time"]),
}
if path.startswith("/auto/"):
# Auto bindings are created for app service references, path is
# /auto/<app_id>/<service_type>
app_id = path.split("/")[2] if len(path.split("/")) > 3 else ""
binding["app_path"] = app_paths.get(app_id, app_id)
auto.append(binding)
elif derived_from:
derived.append(binding)
else:
base.append(binding)
# Service entries, shown above the binding tables. Search matches the
# service type/name
services = []
services_error = ""
svc_ret = openrun.list_services()
if svc_ret.error:
services_error = svc_ret.error
for entry in (svc_ret.value if not services_error else []):
service_id = entry["service_type"] + "/" + entry["name"]
if query and query not in service_id.lower():
continue
services.append({
"id": service_id,
"service_type": entry["service_type"],
"name": entry["name"],
"is_default": entry["is_default"],
"staging": entry["staging"],
"config_keys": entry["config_keys"] or [],
"update_time": nonzero_time(entry["update_time"]),
})
return {
"Title": "Bindings",
"Nav": "bindings",
"Query": query,
"Total": total,
"Perms": get_perms(),
"FlashError": list_error,
"Services": sorted(services, key=lambda svc: svc["id"]),
"ServicesError": services_error,
# Most recently updated bindings first
"Base": sort_recent(base, "update_time", "path"),
"Derived": sort_recent(derived, "update_time", "path"),
"Auto": sort_recent(auto, "update_time", "path"),
}
def binding_form_values(req):
# The form fields for the binding create/update subpages
return {
"path": query_param(req, "path"),
"source": query_param(req, "source"),
"grants_text": query_param(req, "grants_text"),
"config_rows": raw_kv_rows(req, "config"),
}
def binding_form_data(req, mode, values, error):
# Page context for the binding create/update form
return {
"Title": "New binding" if mode == "create" else "Update binding",
"Nav": "bindings",
"Mode": mode,
"Error": error,
"Values": values,
"Perms": get_perms(),
}
def bindings_create_page_handler(req):
# Binding create form page
return binding_form_data(req, "create", binding_form_values(req), "")
def bindings_create_submit_handler(req):
# POST: validate (dry run) or create a binding
values = binding_form_values(req)
action = query_param(req, "action")
if not values["path"]:
return binding_form_data(req, "create", values, "Binding path is required")
if not values["source"]:
return binding_form_data(req, "create", values, "Source is required")
config, err = parse_kv_rows(req, "config")
if err:
return binding_form_data(req, "create", values, err)
grants = parse_lines(values["grants_text"])
if action == "validate":
ret = openrun_admin.create_binding(values["path"], values["source"],
grants=grants, config=config, dry_run=True)
if ret.error:
return binding_form_data(req, "create", values, ret.error)
data = binding_form_data(req, "create", values, "")
data["Validated"] = True
return data
ret = openrun_admin.create_binding(values["path"], values["source"],
grants=grants, config=config)
if ret.error:
return binding_form_data(req, "create", values, ret.error)
return ace.redirect(req.AppPath + "/bindings")
def find_binding(path):
# Look up one binding by path from the bindings list
ret = openrun.list_bindings()
if ret.error:
return None
for entry in ret.value:
if entry["path"] == path:
return entry
return None
def bindings_update_page_handler(req):
# Binding update form page, prefilled with the staged grants
path = query_param(req, "path")
binding = find_binding(path)
if not binding:
return binding_form_data(req, "update", {"path": path}, "binding %s not found" % path)
# Updates apply to staging first, edit the staged grants
staged_grants = binding["staged_metadata"]["grants"] or []
values = {
"path": path,
"source": binding["source"],
"grants_text": "\n".join(staged_grants),
}
data = binding_form_data(req, "update", values, "")
data["Binding"] = binding
return data
def bindings_update_submit_handler(req):
# POST: apply the grant additions/removals from the textarea diff
path = query_param(req, "path")
values = binding_form_values(req)
values["path"] = path
binding = find_binding(path)
if not binding:
return binding_form_data(req, "update", values, "binding %s not found" % path)
current = binding["staged_metadata"]["grants"] or []
wanted = parse_lines(values["grants_text"])
add_grants = [g for g in wanted if g not in current]
delete_grants = [g for g in current if g not in wanted]
if not add_grants and not delete_grants:
return ace.redirect(req.AppPath + "/bindings")
ret = openrun_admin.update_binding(path, add_grants=add_grants,
delete_grants=delete_grants, promote=True)
if ret.error:
data = binding_form_data(req, "update", values, ret.error)
data["Binding"] = binding
return data
return ace.redirect(req.AppPath + "/bindings")
def bindings_delete_handler(req):
# POST: delete a binding from the bindings list
path = query_param(req, "path")
ret = openrun_admin.delete_binding(path)
error = ret.error
return flash_result(bindings_data(req), error, "Deleted binding %s" % path, "Delete failed")
def service_form_data(req, values, error):
# Page context for the service create form
return {
"Title": "New service",
"Nav": "bindings",
"Error": error,
"Values": values,
"Validated": False,
"Perms": get_perms(),
}
def services_create_page_handler(req):
# Service create form page