-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathheroku.clj
executable file
·411 lines (355 loc) · 14 KB
/
heroku.clj
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
#!/usr/bin/env bb
(load-file "src/corona/envdef.clj")
(load-file "src/corona/pom_version_get.clj")
(ns heroku
"See https://github.com/clojure/tools.cli"
(:require
[clojure.string :as cstr]
[corona.envdef :as env]
[clojure.tools.cli :refer [parse-opts]]
[clojure.java.io :as jio]
[corona.pom-version-get :as pom]
)
(:import
java.lang.ProcessBuilder$Redirect
))
(def git "git")
(def push "push")
(def master "master")
(def heroku-envs
"levels 0 and 1 - the top two levels"
((comp
set
(partial map (comp name first))
(partial filter (fn [[k v]] (<= (get-in v [:level]) 1))))
env/environment))
#_(println "heroku-envs" heroku-envs)
(defn heroku-env-name [level]
((comp
name first first
(partial filter (fn [[k v]] (= (get-in v [:level]) level))))
env/environment))
(def heroku-envs
"levels 0 and 1 - the top two levels"
(set (map heroku-env-name [0 1])))
(def heroku-prod
"levels 0 and 1 - the top two levels"
(heroku-env-name 0))
#_(println "heroku-prod" heroku-prod)
(defn heroku-app-name [heroku-env] (str heroku-env "-bot"))
(def pipelined-heroku-apps
"Git branch-names must have the format 'heroku-<map-value>'."
(zipmap [:src-app :dst-app]
((comp
vec
(partial map (comp heroku-app-name heroku-env-name)))
[1 0])))
#_(println "pipelined-heroku-apps" pipelined-heroku-apps)
(def heroku-apps ((comp set vals) pipelined-heroku-apps))
#_(println "heroku-apps" heroku-apps)
#_(System/exit 1)
(defn in?
"true if `sequence` contains `elem`. See (contains? (set sequence) elem)"
[sequence elem]
(boolean (some (fn [e] (= elem e)) sequence)))
(def start "start")
(def stop "stop")
(def restart "restart")
(def deploy "deploy")
(def deleteWebhook "deleteWebhook")
(def setWebhook "setWebhook")
(def showUsers "showUsers")
(def promote "promote")
(def getMockData "getMockData")
(def getLogs "getLogs")
(def updateClojureCliVersion "updateClojureCliVersion")
(def cli-actions
"TODO a new action must be manually inserted into this list. Use macros for
that"
[start stop restart deploy deleteWebhook setWebhook showUsers promote
getMockData getLogs
updateClojureCliVersion])
(def cli-options
;; An option with a required argument
[["-e" "--heroku-env HENV"
(str "Heroku environment to run the action against.\n"
(let [align " "]
(str align "One of the:\n"
(cstr/join \newline
(map (fn [a] (str align " " a)) heroku-envs)))))
:validate [(fn [henv] (in? heroku-envs henv))
(str "Must be an element of " heroku-envs)]]
["-f" "--force" "Force deployment"]
["-h" "--help"]])
(defn usage [options-summary]
(->> ["Usage: program-name action [options]"
""
"Action is one of the:"
(cstr/join \newline (map (fn [a] (str " " a)) cli-actions))
""
"Options:"
options-summary]
(cstr/join \newline)))
(defn error-msg [errors]
(str "The following errors occurred while parsing your command:\n\n"
(cstr/join \newline errors)))
(defn validate-args
"Validate command line arguments. Either return a map indicating the program
should exit (with a error message, and optional ok status), or a map
indicating the action the program should take and the options provided."
[args]
(let [{:keys [options arguments errors summary]}
(parse-opts args cli-options)]
(cond
(:help options) ; help => exit OK with usage summary
{:exit-message (usage summary) :ok? true}
errors ; errors => exit with description of errors
{:exit-message (error-msg errors)}
;; custom validation on arguments
(= 1 (count arguments))
(cond
((set cli-actions)
(first arguments))
{:action (first arguments) :options options}
:else
{:exit-message (format "Unknown action: %s\n\n%s"
(first arguments) (usage summary))})
:else ; failed custom validation => exit with usage summary
{:exit-message (usage summary)})))
(defn exit [status msg]
(println msg)
(System/exit status))
(defn trim-last-newline [s]
(if (and (not-empty s) (.endsWith s "\n"))
(.substring s 0 (dec (count s)))
s))
(defn shell-command
"Executes shell command. Exits script when the shell-command has a non-zero
exit code, propagating it. Accepts the following options:
`:input`: instead of reading from stdin, read from this string.
`:to-string?`: instead of writing to stdoud, write to a string and
return it."
([args] (shell-command args nil))
([args {:keys [:input :to-string?]}]
(let [args (mapv str args)
pb (cond-> (-> (ProcessBuilder. ^java.util.List args)
(.redirectError ProcessBuilder$Redirect/INHERIT))
(not to-string?)
(.redirectOutput ProcessBuilder$Redirect/INHERIT)
#_(.redirectOutput ProcessBuilder$Redirect/PIPE)
#_(.redirectOutput (ProcessBuilder$Redirect/appendTo temp))
(not input) (.redirectInput ProcessBuilder$Redirect/INHERIT))
proc (.start pb)]
(when input
(with-open [w (jio/writer (.getOutputStream proc))]
(binding [*out* w]
(print input)
(flush))))
(let [string-out
(when to-string? ;; i.e when output not redirected
#_(println "Not redirected; reading from proc to-string ...")
(let [sw (java.io.StringWriter.)]
(with-open [w (jio/reader
(.getInputStream proc)
#_(jio/input-stream (File. (.toString temp)))
)]
(jio/copy w sw))
(str sw)))
exit-code (.waitFor proc)]
(when-not (zero? exit-code)
(System/exit exit-code))
(printf "%s\n" string-out)
string-out))))
(defn sh [& raw-args]
(let [args (remove empty? raw-args)]
(println "#" (cstr/join " " args))
(->> (shell-command args
(conj
#_{:to-string? false}
{:to-string? true}))
(trim-last-newline))))
(defn sh-mkdir-p [dir-name]
(sh "mkdir" "-p" dir-name))
(defn sh-heroku
[app & cmds]
{:pre [(in? heroku-apps app)]}
(apply sh (into ["heroku"] (conj (vec cmds) "--app" app))))
(defn get-commit!
([] (get-commit! master))
([branch] (sh git "rev-parse" "--short" branch)))
(defn set-config! [app commit clojure-cli-version]
{:pre [(in? heroku-apps app)]}
(sh-heroku app "config:set" (str "COMMIT=" commit) clojure-cli-version))
(def ps:scale "ps:scale")
(defn stop! [app]
{:pre [(in? heroku-apps app)]}
(sh-heroku app ps:scale "web=0"))
(defn start! [app]
{:pre [(in? heroku-apps app)]}
(sh-heroku app ps:scale "web=1"))
(defn restart!
"There's a special heroku command for it"
[app]
{:pre [(in? heroku-apps app)]}
(sh-heroku app "ps:restart"))
(defn open-papertrail [app]
{:pre [(in? heroku-apps app)]}
(sh-heroku app "addons:open" "papertrail"))
(defn publish-source!
"Publish the source code only when deploying to production"
[commit rest-args]
;; seems like `git push --tags` pushes only tags w/o the code
(sh git "tag" "--annotate" "--message" "''"
(str pom/pom-version "-" commit) commit)
(doseq [remote ["origin" "gitlab"]]
;; See also `git push --tags $pushFlags $remote`
(sh git push rest-args "--follow-tags" "--verbose" remote)))
;; (defmacro dbg-let
;; "Display the let-values; does not evaluate the body"
;; [vs & body]
;; `(let ~vs
;; ((comp
;; doall
;; (partial map (fn [~'v]
;; (printf "%s: %s\n" (first ~'v) (eval (second ~'v)))))
;; (partial partition-all 2))
;; (quote ~vs))))
;; TODO undo "git tag" when something fails
(def custom-env ".custom.env")
(defn deploy! [prm-app {:keys [heroku-env] :as options}]
{:pre [(in? heroku-apps prm-app)]}
(let [commit (get-commit!)
clojure-cli-version (let [props (java.util.Properties.)
key "CLOJURE_CLI_VERSION"]
(.load props (jio/reader custom-env))
(str key "=" (get props key)))
app (heroku-app-name heroku-env)
remote app ;; TODO check this change
rest-args (if (:force options) "--force" "")]
(open-papertrail app)
(stop! app)
(set-config! app commit clojure-cli-version)
(sh git push rest-args remote master)
(start! app)
(when (= heroku-env heroku-prod)
(publish-source! commit rest-args))))
(defn promote! [{:keys [src-app dst-app]} options]
{:pre [(and (not= src-app dst-app)
(in? heroku-apps src-app)
(in? heroku-apps dst-app))]}
(let [commit (get-commit! (format "remotes/%s/%s" src-app master))
clojure-cli-version (let [props (java.util.Properties.)
key "CLOJURE_CLI_VERSION"]
(.load props (jio/reader custom-env))
(str key "=" (get props key)))
rest-args (if (:force options) "--force" "")]
(open-papertrail dst-app)
(stop! dst-app)
(set-config! dst-app commit clojure-cli-version)
(sh-heroku src-app "pipelines:promote")
(start! dst-app)
(publish-source! commit rest-args)))
(defn sh-curl [& cmds] (apply (partial sh "curl") cmds))
(defn sh-wget [& cmds] (apply (partial sh "wget") cmds))
(def --output-document "--output-document") #_(def -O "-O")
(def --form "--form")
(defn webhook-action-prms [webhook-action telegram-token]
[--form "drop_pending_updates=true" "--request" "POST"
(format "https://api.telegram.org/bot%s/%s"
telegram-token webhook-action)])
;; Examples:
;; ./heroku.clj deploy --heroku-env hokuspokus
;; ./heroku.clj deploy -e hokuspokus
(let [{:keys [action options exit-message ok?]}
(validate-args *command-line-args*)]
(if exit-message
(exit (if ok? 0 1) exit-message)
(let [heroku-env (:heroku-env options)
heroku-app (heroku-app-name heroku-env)
telegram-token (get-in env/environment
[(keyword heroku-env) :telegram-token])]
(condp = action
start (start! heroku-app)
stop (stop! heroku-app)
restart (restart! heroku-app)
deploy (deploy! heroku-app options)
promote (promote! pipelined-heroku-apps options)
#_(str "
# Search in logs:
rg --search-zip SEARCH_TERM ./log/
gzip -cd ./log/* | grep SEARCH_TERM
gzip --to-stdout --decompress ./log/* | grep SEARCH_TERM
heroku logs --num 1500 --app $APP # last 1500 lines
heroku logs --tail --app $APP
")
;; TODO plot log entries on a timescale:
;; parse the logfile, compute timestamp diffs
getLogs
(let [log-dir (str "log/" heroku-env)
pt-token (sh-heroku heroku-app
"config:get" "PAPERTRAIL_API_TOKEN")
pt-header (format "X-Papertrail-Token: %s" pt-token)]
(sh-mkdir-p log-dir)
(doseq [hour-ago '(0 1)]
;;; It takes approximately 6-7 hours for logs to be available in the archive.
;;; https://help.papertrailapp.com/kb/how-it-works/permanent-log-archives
(let [hour-ago-delayed (+ hour-ago 7)
date (str hour-ago-delayed " hours ago")
date-ago (sh "date" "-u" (str "--date=" date) "+%Y-%m-%d-%H")
out-file (format "%s/%s-UTC.tsv.gz" log-dir date-ago)]
(sh-curl "--silent" "--no-include" "--output" out-file
"--location" "--header" pt-header
(format
"https://papertrailapp.com/api/v1/archives/%s/download"
date-ago)))))
getMockData
(let [dst-dir "resources/mockup"]
(sh-mkdir-p dst-dir) ;; when running for the 1st time
(sh-wget
#_"https://coronavirus-tracker-api.herokuapp.com/all"
#_"https://covid-tracker-us.herokuapp.com/all"
((comp
(partial format "https://%s/all")
#_first
second)
env/api-servers)
--output-document (format "%s/all.json" dst-dir))
(sh-wget env/owid-prod
--output-document
(format "%s/owid-covid-data.json" dst-dir)))
deleteWebhook
(apply sh-curl
(webhook-action-prms deleteWebhook telegram-token))
setWebhook
#_(printf "%s\n" (into
[--form (format "'url=https://%s.herokuapp.com/%s'"
heroku-app telegram-token)]
(webhook-action-prms telegram-token setWebhook)))
(apply sh-curl
(into
;; WTF? wrapping single quotes around url=... causes webhook
;; deletion
[--form (format "url=https://%s.herokuapp.com/%s"
heroku-app telegram-token)]
(webhook-action-prms setWebhook telegram-token)))
;; obtain the log using the heroku-papertrail plugin
showUsers
;; TODO prohibit sh-heroku from writing to stdout
((comp
(fn [s] (cstr/split s #"\n")))
(sh-heroku heroku-app
;; pt stands for the papertrail plugin; it requires
;; `heroku plugins:install heroku-papertrail`
"pt" (format ":type -ssl-client-cert -%s"
(System/getenv "MY_TELEGRAM_ID"))))
updateClojureCliVersion
((comp
(fn [script]
(sh "sed" "--in-place" "-e" script custom-env ".env"))
(partial format "s|CLOJURE_CLI_VERSION=.*|CLOJURE_CLI_VERSION=%s|")
first
re-find
(partial re-matcher #"((\d+)\.)+(\d+)"))
(sh "clj" "--version"))
;; TODO implement dbase transfer between environments test -> prod
))))