This repository has been archived by the owner on Apr 24, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 64
/
api.clj
2590 lines (2330 loc) · 112 KB
/
api.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
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
;;
;; Copyright (c) Two Sigma Open Source, LLC
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
;;
(ns cook.mesos.api
(:require [camel-snake-kebab.core :refer [->snake_case ->kebab-case]]
[cheshire.core :as cheshire]
[clj-time.coerce :as tc]
[clj-time.core :as t]
[clj-time.format :as tf]
[clojure.set :as set]
[clojure.string :as str]
[clojure.tools.logging :as log]
[clojure.walk :as walk :refer [keywordize-keys]]
[compojure.api.middleware :as c-mw]
[compojure.api.sweet :as c-api]
[compojure.core :refer [ANY GET POST routes]]
[cook.cors :as cors]
[cook.mesos.quota :as quota]
[cook.mesos.reason :as reason]
[cook.mesos.schema :refer [constraint-operators host-placement-types straggler-handling-types]]
[cook.mesos.share :as share]
[cook.mesos.task-stats :as task-stats]
[cook.mesos.unscheduled :as unscheduled]
[cook.mesos.util :as util]
[cook.mesos]
[cook.util :refer [ZeroInt PosNum NonNegNum PosInt NonNegInt PosDouble UserName NonEmptyString]]
[datomic.api :as d :refer [q]]
[liberator.core :as liberator]
[liberator.util :refer [combine]]
[me.raynes.conch :as sh]
[mesomatic.scheduler]
[metatransaction.core :refer [db]]
[metrics.histograms :as histograms]
[metrics.meters :as meters]
[metrics.timers :as timers]
[plumbing.core :refer [map-from-vals map-keys map-vals mapply]]
[ring.middleware.format-params :as format-params]
[ring.util.response :as res]
[schema.core :as s]
[swiss.arrows :refer :all])
(:import (clojure.lang Atom Var)
com.codahale.metrics.ScheduledReporter
(java.io OutputStreamWriter)
(java.net ServerSocket URLEncoder)
(java.util Date UUID)
javax.servlet.ServletResponse
org.apache.curator.test.TestingServer
(org.joda.time DateTime Minutes)
schema.core.OptionalKey))
;; We use Liberator to handle requests on our REST endpoints.
;; The control flow among Liberator's handler functions is described here:
;; https://clojure-liberator.github.io/liberator/doc/decisions.html
;; This is necessary to prevent a user from requesting a uid:gid
;; pair other than their own (for example, root)
(sh/let-programs
[_id "/usr/bin/id"]
(defn uid [user-name]
(str/trim (_id "-u" user-name)))
(defn gid [user-name]
(str/trim (_id "-g" user-name))))
(defn render-error
[ctx]
{:error (::error ctx)})
(def cook-liberator-attrs
{:available-media-types ["application/json"]
;; necessary to play well with as-response below
:handle-no-content (fn [ctx] "No content.")
;; Don't serialize the response; leave that to compojure-api
:as-response (fn [data ctx] (combine {:body data} ctx))
:handle-forbidden render-error
:handle-malformed render-error
:handle-not-found render-error
:handle-unprocessable-entity render-error})
(defn base-cook-handler
[resource-attrs]
(mapply liberator/resource (merge cook-liberator-attrs resource-attrs)))
;;
;; /rawscheduler
;;
(defn prepare-schema-response
"Takes a schema and outputs a new schema which conforms to our responses.
Modifications:
1. changes keys to snake_case"
[schema]
(map-keys (fn [k]
(if (instance? OptionalKey k)
(update k :k ->snake_case)
(->snake_case k)))
schema))
(def iso-8601-format (:date-time tf/formatters))
(s/defschema CookInfo
"Schema for the /info endpoint response"
{:authentication-scheme s/Str
:commit s/Str
:start-time s/Inst
:version s/Str})
(def PortMapping
"Schema for Docker Portmapping"
{:host-port (s/both s/Int (s/pred #(<= 0 % 65536) 'between-0-and-65536))
:container-port (s/both s/Int (s/pred #(<= 0 % 65536) 'between-0-and-65536))
(s/optional-key :protocol) s/Str})
(def DockerInfo
"Schema for a DockerInfo"
{:image s/Str
(s/optional-key :network) s/Str
(s/optional-key :force-pull-image) s/Bool
(s/optional-key :parameters) [{:key s/Str :value s/Str}]
(s/optional-key :port-mapping) [PortMapping]})
(def Volume
"Schema for a Volume"
{(s/optional-key :container-path) s/Str
:host-path s/Str
(s/optional-key :mode) s/Str})
(def Container
"Schema for a Mesos Container"
{:type s/Str
(s/optional-key :docker) DockerInfo
(s/optional-key :volumes) [Volume]})
(def Uri
"Schema for a Mesos fetch URI, which has many options"
{:value s/Str
(s/optional-key :executable?) s/Bool
(s/optional-key :extract?) s/Bool
(s/optional-key :cache?) s/Bool})
(def UriRequest
"Schema for a Mesos fetch URI as it would be included in JSON requests
or responses. Avoids question-marks in the key names."
{:value s/Str
(s/optional-key :executable) s/Bool
(s/optional-key :extract) s/Bool
(s/optional-key :cache) s/Bool})
(def Instance
"Schema for a description of a single job instance."
{:status s/Str
:task_id s/Uuid
:executor_id s/Uuid
:slave_id s/Str
:hostname s/Str
:preempted s/Bool
:backfilled s/Bool
:ports [s/Int]
(s/optional-key :start_time) s/Int
(s/optional-key :mesos_start_time) s/Int
(s/optional-key :end_time) s/Int
(s/optional-key :reason_code) s/Int
(s/optional-key :output_url) s/Str
(s/optional-key :cancelled) s/Bool
(s/optional-key :reason_string) s/Str
(s/optional-key :executor) s/Str
(s/optional-key :exit_code) s/Int
(s/optional-key :progress) s/Int
(s/optional-key :progress_message) s/Str
(s/optional-key :sandbox_directory) s/Str})
(defn max-128-characters-and-alphanum?
"Returns true if s contains only '.', '_', '-' or
any word characters and has length at most 128"
[s]
(re-matches #"[\.a-zA-Z0-9_-]{0,128}" s))
(defn non-empty-max-128-characters-and-alphanum?
"Returns true if s contains only '.', '_', '-' or any
word characters and has length at least 1 and most 128"
[s]
(re-matches #"[\.a-zA-Z0-9_-]{1,128}" s))
(def Application
"Schema for the application a job corresponds to"
{:name (s/constrained s/Str non-empty-max-128-characters-and-alphanum?)
:version (s/constrained s/Str non-empty-max-128-characters-and-alphanum?)})
(def Constraint
"Schema for user defined job host constraint"
[(s/one NonEmptyString "attribute")
(s/one (s/pred #(contains? (set (map name constraint-operators))
(str/lower-case %))
'constraint-operator-exists?)
"operator")
(s/one NonEmptyString "pattern")])
(s/defschema JobName
(s/both s/Str (s/both s/Str (s/pred max-128-characters-and-alphanum? 'max-128-characters-and-alphanum?))))
(s/defschema JobNameListFilter
(s/both s/Str (s/pred (fn [s]
(re-matches #"[\.a-zA-Z0-9_\-\*]*" s)))))
(s/defschema JobPriority
(s/both s/Int (s/pred #(<= 0 % 100) 'between-0-and-100)))
(defn valid-runtimes?
"Returns false if the expected-runtime of the given job
is greater than the max-runtime; otherwise, returns true"
[{:keys [expected-runtime max-runtime]}]
(if (and expected-runtime max-runtime)
(<= expected-runtime max-runtime)
true))
(def JobMap
"Schema for the fields of a job"
{:uuid s/Uuid
:command s/Str
:name JobName
:priority JobPriority
:max-retries PosInt
:max-runtime PosInt
(s/optional-key :uris) [Uri]
(s/optional-key :ports) (s/pred #(not (neg? %)) 'nonnegative?)
(s/optional-key :env) {NonEmptyString s/Str}
(s/optional-key :labels) {NonEmptyString s/Str}
(s/optional-key :constraints) [Constraint]
(s/optional-key :container) Container
(s/optional-key :executor) (s/enum "cook" "mesos")
(s/optional-key :progress-output-file) NonEmptyString
(s/optional-key :progress-regex-string) NonEmptyString
(s/optional-key :group) s/Uuid
(s/optional-key :disable-mea-culpa-retries) s/Bool
:cpus PosDouble
:mem PosDouble
(s/optional-key :gpus) (s/both s/Int (s/pred pos? 'pos?))
;; Make sure the user name is valid. It must begin with a lower case character, end with
;; a lower case character or a digit, and has length between 2 to (62 + 2).
:user UserName
(s/optional-key :application) Application
(s/optional-key :expected-runtime) PosInt})
(def Job
"Full schema for a job"
(s/constrained JobMap valid-runtimes?))
(def JobRequestMap
"Schema for the fields of a job request"
(-> JobMap
(dissoc :max-runtime :name :priority :user)
(assoc :cpus PosNum
:mem PosNum
(s/optional-key :env) {s/Keyword s/Str}
(s/optional-key :labels) {s/Keyword s/Str}
(s/optional-key :max-runtime) PosInt
(s/optional-key :name) JobName
(s/optional-key :priority) JobPriority
;; The Java job client used to send the
;; status field on job submission. At some
;; point, that changed, but we will keep
;; allowing it here for backwards compat.
(s/optional-key :status) s/Str
(s/optional-key :uris) [UriRequest])))
(def JobRequest
"Schema for the part of a request that launches a single job."
(s/constrained JobRequestMap valid-runtimes?))
(def JobResponseBase
"Schema for a description of a job (as returned by the API).
The structure is similar to JobRequest, but has some differences.
For example, it can include descriptions of instances for the job."
(-> JobRequestMap
(dissoc (s/optional-key :group))
(dissoc (s/optional-key :status))
(merge {:framework-id (s/maybe s/Str)
:retries-remaining NonNegInt
:status s/Str
:state s/Str
:submit-time (s/maybe PosInt)
:user UserName
(s/optional-key :gpus) s/Int
(s/optional-key :groups) [s/Uuid]
(s/optional-key :instances) [Instance]})
prepare-schema-response))
(def JobResponseDeprecated
"Deprecated. New fields should be added only to the JobResponse schema."
JobResponseBase)
(def JobResponse
"Schema for a description of a job (as returned by the API)."
(let [ParentGroup {:uuid s/Uuid, :name s/Str}]
(-> JobResponseBase
(assoc (s/optional-key :groups) [ParentGroup]))))
(def InstanceResponse
"Schema for a description of a job instance (as returned by the API)."
(let [ParentJob {:uuid s/Uuid
:name s/Str
:status s/Str
:state s/Str
:user UserName}]
(-> Instance
(assoc :job ParentJob))))
(def JobOrInstanceIds
"Schema for any number of job and/or instance uuids"
{(s/optional-key :job) [s/Uuid]
(s/optional-key :instance) [s/Uuid]})
(def QueryJobsParamsDeprecated
"Schema for querying for jobs by job and/or instance uuid, allowing optionally
for 'partial' results, meaning that some uuids can be valid and others not"
(-> JobOrInstanceIds
(assoc (s/optional-key :partial) s/Bool)))
(def allowed-list-states (set/union util/job-states util/instance-states))
(def QueryJobsParams
"Schema for querying for jobs by job uuid, allowing optionally for
'partial' results, meaning that some uuids can be valid and others not"
{(s/optional-key :uuid) [s/Uuid]
(s/optional-key :partial) s/Bool
(s/optional-key :user) UserName
(s/optional-key :state) [(apply s/enum allowed-list-states)]
(s/optional-key :start) s/Str
(s/optional-key :end) s/Str
(s/optional-key :limit) NonNegInt
(s/optional-key :name) JobNameListFilter})
(def QueryInstancesParams
"Schema for querying for instances by instance uuid, allowing optionally for
'partial' results, meaning that some uuids can be valid and others not"
{:uuid [s/Uuid]
(s/optional-key :partial) s/Bool})
(def Attribute-Equals-Parameters
"A schema for the parameters of a host placement with type attribute-equals"
{:attribute s/Str})
(def Balanced-Parameters
"A schema for the parameters of a host placement with type balanced"
{:attribute s/Str
:minimum PosInt})
(def HostPlacement
"A schema for host placement"
(s/conditional
#(= (:type %) :attribute-equals)
{:type (s/eq :attribute-equals)
:parameters Attribute-Equals-Parameters}
#(= (:type %) :balanced)
{:type (s/eq :balanced)
:parameters Balanced-Parameters}
:else
{:type (s/pred #(contains? (set (map util/without-ns host-placement-types)) %)
'host-placement-type-exists?)
(s/optional-key :parameters) {}}))
(def Quantile-Deviation-Parameters
{:multiplier (s/both s/Num (s/pred #(> % 1.0) 'greater-than-one))
:quantile (s/both s/Num (s/pred #(< 0.0 % 1.0) 'between-zero-one))})
(def StragglerHandling
"A schema for host placement"
(s/conditional
#(= (:type %) :quantile-deviation)
{:type (s/eq :quantile-deviation)
:parameters Quantile-Deviation-Parameters}
:else
{:type (s/pred #(contains? (set (map util/without-ns straggler-handling-types)) %)
'straggler-handling-type-exists?)
(s/optional-key :parameters) {}}))
(def Group
"A schema for a job group"
{:uuid s/Uuid
(s/optional-key :host-placement) HostPlacement
(s/optional-key :straggler-handling) StragglerHandling
(s/optional-key :name) s/Str})
(def QueryGroupsParams
"Schema for querying for groups, allowing optionally for 'partial'
results, meaning that some uuids can be valid and others not"
{:uuid [s/Uuid]
(s/optional-key :detailed) s/Bool
(s/optional-key :partial) s/Bool})
(def KillGroupsParams
"Schema for killing groups by uuid"
{:uuid [s/Uuid]})
(def GroupResponse
"A schema for a group http response"
(-> Group
(merge
{:jobs [s/Uuid]
(s/optional-key :waiting) s/Int
(s/optional-key :running) s/Int
(s/optional-key :completed) s/Int})
prepare-schema-response))
(def RawSchedulerRequest
"Schema for a request to the raw scheduler endpoint."
{:jobs [JobRequest]
(s/optional-key :override-group-immutability) s/Bool
(s/optional-key :groups) [Group]})
(defn- mk-container-params
"Helper for build-container. Transforms parameters into the datomic schema."
[cid params]
(when (seq params)
{:docker/parameters (mapv (fn [{:keys [key value]}]
{:docker.param/key key
:docker.param/value value})
params)}))
(defn- mkvolumes
"Helper for build-container. Transforms volumes into the datomic schema."
[cid vols]
(when (seq vols)
(let [vol-maps (mapv (fn [{:keys [container-path host-path mode]}]
(merge (when container-path
{:container.volume/container-path container-path})
(when host-path
{:container.volume/host-path host-path})
(when mode
{:container.volume/mode (str/upper-case mode)})))
vols)]
{:container/volumes vol-maps})))
(defn- mk-docker-ports
"Helper for build-container. Transforms port-mappings into the datomic schema."
[cid ports]
(when (seq ports)
(let [port-maps (mapv (fn [{:keys [container-port host-port protocol]}]
(merge (when container-port
{:docker.portmap/container-port container-port})
(when host-port
{:docker.portmap/host-port host-port})
(when protocol
{:docker.portmap/protocol (str/upper-case protocol)})))
ports)]
{:docker/port-mapping port-maps})))
(defn- build-container
"Helper for submit-jobs, deal with container structure."
[user id container]
(let [container-id (d/tempid :db.part/user)
docker-id (d/tempid :db.part/user)
ctype (:type container)
volumes (or (:volumes container) [])]
(if (= (str/lower-case ctype) "docker")
(let [docker (:docker container)
params (or (:parameters docker) [])
port-mappings (or (:port-mapping docker) [])
user-params (filter #(= (:key %) "user") params)
expected-user-param (str (uid user) ":" (gid user))]
(when (some #(not= expected-user-param (:value %)) user-params)
(throw (ex-info "user parameter must match uid and gid of user submitting."
{:expected-user-param expected-user-param
:user-params-submitted user-params})))
[[:db/add id :job/container container-id]
(merge {:db/id container-id
:container/type "DOCKER"}
(mkvolumes container-id volumes))
[:db/add container-id :container/docker docker-id]
(merge {:db/id docker-id
:docker/image (:image docker)
:docker/force-pull-image (:force-pull-image docker false)}
(when (:network docker) {:docker/network (:network docker)})
(mk-container-params docker-id params)
(mk-docker-ports docker-id port-mappings))])
{})))
(defn- str->executor-enum
"Converts an executor string to the corresponding executor option enum.
Throws an IllegalArgumentException if the string is non-nil and not supported."
[executor]
(when executor
(case executor
"cook" :executor/cook
"mesos" :executor/mesos
(throw (IllegalArgumentException. (str "Unsupported executor type: " executor))))))
(s/defn make-job-txn
"Creates the necessary txn data to insert a job into the database"
[job :- Job]
(let [{:keys [uuid command max-retries max-runtime expected-runtime priority cpus mem gpus
user name ports uris env labels container group application disable-mea-culpa-retries
constraints executor progress-output-file progress-regex-string]
:or {group nil
disable-mea-culpa-retries false}} job
db-id (d/tempid :db.part/user)
ports (when (and ports (not (zero? ports)))
[[:db/add db-id :job/ports ports]])
uris (mapcat (fn [{:keys [value executable? cache? extract?]}]
(let [uri-id (d/tempid :db.part/user)
optional-params {:resource.uri/executable? executable?
:resource.uri/extract? extract?
:resource.uri/cache? cache?}]
[[:db/add db-id :job/resource uri-id]
(reduce-kv
;; This only adds the optional params to the DB if they were explicitly set
(fn [txn-map k v]
(if-not (nil? v)
(assoc txn-map k v)
txn-map))
{:db/id uri-id
:resource/type :resource.type/uri
:resource.uri/value value}
optional-params)]))
uris)
env (mapcat (fn [[k v]]
(let [env-var-id (d/tempid :db.part/user)]
[[:db/add db-id :job/environment env-var-id]
{:db/id env-var-id
:environment/name k
:environment/value v}]))
env)
labels (mapcat (fn [[k v]]
(let [label-var-id (d/tempid :db.part/user)]
[[:db/add db-id :job/label label-var-id]
{:db/id label-var-id
:label/key k
:label/value v}]))
labels)
constraints (mapcat (fn [[attribute operator pattern]]
(let [constraint-var-id (d/tempid :db.part/user)]
[[:db/add db-id :job/constraint constraint-var-id]
{:db/id constraint-var-id
:constraint/attribute attribute
:constraint/operator (keyword "constraint.operator"
(str/lower-case operator))
:constraint/pattern pattern}]))
constraints)
container (if (nil? container) [] (build-container user db-id container))
executor (str->executor-enum executor)
;; These are optionally set datoms w/ default values
maybe-datoms (reduce into
[]
[(when (and priority (not= util/default-job-priority priority))
[[:db/add db-id :job/priority priority]])
(when (and max-runtime (not= Long/MAX_VALUE max-runtime))
[[:db/add db-id :job/max-runtime max-runtime]])
(when (and gpus (not (zero? gpus)))
(let [gpus-id (d/tempid :db.part/user)]
[[:db/add db-id :job/resource gpus-id]
{:db/id gpus-id
:resource/type :resource.type/gpus
:resource/amount (double gpus)}]))])
commit-latch-id (d/tempid :db.part/user)
commit-latch {:db/id commit-latch-id
:commit-latch/committed? true
:commit-latch/uuid (UUID/randomUUID)}
txn (cond-> {:db/id db-id
:job/command command
:job/commit-latch commit-latch-id
:job/custom-executor false
:job/disable-mea-culpa-retries disable-mea-culpa-retries
:job/max-retries max-retries
:job/name (or name "cookjob") ; set the default job name if not provided.
:job/resource [{:resource/type :resource.type/cpus
:resource/amount cpus}
{:resource/type :resource.type/mem
:resource/amount mem}]
:job/state :job.state/waiting
:job/submit-time (Date.)
:job/user user
:job/uuid uuid}
application (assoc :job/application
{:application/name (:name application)
:application/version (:version application)})
expected-runtime (assoc :job/expected-runtime expected-runtime)
executor (assoc :job/executor executor)
progress-output-file (assoc :job/progress-output-file progress-output-file)
progress-regex-string (assoc :job/progress-regex-string progress-regex-string))]
;; TODO batch these transactions to improve performance
(-> ports
(into uris)
(into env)
(into constraints)
(into labels)
(into container)
(into maybe-datoms)
(conj txn)
(conj commit-latch))))
(defn make-type-parameter-txn
"Makes txn map for an entity conforming to the pattern of
{:<namespace>/type <type>
:<namespace>/parameters {<parameters>}}
The entity must be marked with isComponent true
Example:
(make-type-parameter-txn {:type :quantile-deviation
:parameters {:quantile 0.5 :multiplier 2.5}}
:straggler-handling)
{:straggler-handling/type :straggler-handling.type/quantile-deviation
:straggler-handling/parameters {:straggler-handling.quantile-deviation/quantile 0.5
:straggler-handling.quantile-deviation/multiplier 2.5}}"
[{:keys [type parameters]} name-space]
(let [namespace-fn (partial util/namespace-datomic name-space)]
(merge
{(namespace-fn :type) (namespace-fn :type type)}
(when (seq parameters)
{(namespace-fn :parameters) (map-keys (partial namespace-fn type)
parameters)}))))
(s/defn make-group-txn
"Creates the transaction data necessary to insert a group to the database. job-db-ids is the
list of all db-ids (datomic temporary ids) of jobs that belong to this group"
[group :- Group job-db-ids]
{:db/id (d/tempid :db.part/user)
:group/uuid (:uuid group)
:group/name (:name group)
:group/job job-db-ids
:group/host-placement (-> group
:host-placement
(make-type-parameter-txn :host-placement))
:group/straggler-handling (-> group
:straggler-handling
(make-type-parameter-txn :straggler-handling))})
(defn group-exists?
"True if a group with guuid exists in the database, false otherwise"
[db guuid]
(not (nil? (d/entity db [:group/uuid guuid]))))
(defn job-exists?
"True if a job with juuid exists in the database, false otherwise"
[db juuid]
(not (nil? (d/entity db [:job/uuid juuid]))))
(defn valid-group-uuid?
"Returns truth-y if the provided guuid corresponds to a valid group for a new
job to belong to. Returns false otherwise."
[db new-guuids commit-latch-id override-immutability? guuid]
(let [group-exists (group-exists? db guuid)]
(cond
(contains? new-guuids guuid) :created-in-transaction
(not group-exists) :new
(and group-exists override-immutability?) :override-existing
:else false)))
(defn make-default-host-placement
[]
{:type :all})
(def default-straggler-handling
{:type :none})
(defn make-default-group
[guuid]
; Have to validate (check uuid is unused)
{:uuid guuid
:name "defaultgroup"
:host-placement (make-default-host-placement)
:straggler-handling default-straggler-handling})
(defn validate-and-munge-job
"Takes the user, the parsed json from the job and a list of the uuids of
new-groups (submitted in the same request as the job). Returns proper Job
objects, or else throws an exception"
[db user task-constraints gpu-enabled? new-group-uuids
{:keys [cpus mem gpus uuid command priority max-retries max-runtime expected-runtime name
uris ports env labels container group application disable-mea-culpa-retries
constraints executor progress-output-file progress-regex-string]
:or {group nil
disable-mea-culpa-retries false}
:as job}
& {:keys [commit-latch-id override-group-immutability?]
:or {commit-latch-id nil
override-group-immutability? false}}]
(let [group-uuid (when group group)
munged (merge
{:user user
:uuid uuid
:command command
:name (or name "cookjob") ; Add default job name if user does not provide a name.
:priority (or priority util/default-job-priority)
:max-retries max-retries
:max-runtime (or max-runtime Long/MAX_VALUE)
:ports (or ports 0)
:cpus (double cpus)
:mem (double mem)
:disable-mea-culpa-retries disable-mea-culpa-retries}
(when gpus {:gpus (int gpus)})
(when env {:env (walk/stringify-keys env)})
(when uris {:uris (map (fn [{:keys [value executable cache extract]}]
(merge {:value value}
(when executable {:executable? executable})
(when cache {:cache? cache})
(when extract {:extract? extract})))
uris)})
(when labels {:labels (walk/stringify-keys labels)})
;; Rest framework keywordifies all keys, we want these to be strings!
(when constraints {:constraints constraints})
(when group-uuid {:group group-uuid})
(when container {:container container})
(when expected-runtime {:expected-runtime expected-runtime})
(when executor {:executor executor})
(when progress-output-file {:progress-output-file progress-output-file})
(when progress-regex-string {:progress-regex-string progress-regex-string})
(when application {:application application}))]
(s/validate Job munged)
(when (and (:gpus munged) (not gpu-enabled?))
(throw (ex-info (str "GPU support is not enabled") {:gpus gpus})))
(when (> cpus (:cpus task-constraints))
(throw (ex-info (str "Requested " cpus " cpus, but only allowed to use "
(:cpus task-constraints))
{:constraints task-constraints
:job job})))
(when (> mem (* 1024 (:memory-gb task-constraints)))
(throw (ex-info (str "Requested " mem "mb memory, but only allowed to use "
(* 1024 (:memory-gb task-constraints)))
{:constraints task-constraints
:job job})))
(when (and (:retry-limit task-constraints)
(> max-retries (:retry-limit task-constraints)))
(throw (ex-info (str "Requested " max-retries " exceeds the maximum retry limit")
{:constraints task-constraints
:job job})))
(doseq [{:keys [executable? extract?] :as uri} (:uris munged)
:when (and (not (nil? executable?)) (not (nil? extract?)))]
(throw (ex-info "Uri cannot set executable and extract" uri)))
(when (and group-uuid
(not (valid-group-uuid? db
new-group-uuids
commit-latch-id
override-group-immutability?
group-uuid)))
(throw (ex-info (str "Invalid group UUID " group-uuid " provided. A valid"
" group UUID either: 1. belongs to a group created "
"in the same request or 2. does not belong to any "
"existing group, or group created in this request")
{:uuid group-uuid})))
munged))
(defn validate-and-munge-group
"Takes the parsed json from the group and returns proper Group objects, or else throws an
exception"
[db group]
(let [group-name (:name group)
hp (:host-placement group)
group (-> group
(assoc :name (or group-name "cookgroup"))
(assoc :host-placement (or hp (make-default-host-placement)))
(assoc :straggler-handling (or (:straggler-handling group)
default-straggler-handling)))]
(s/validate Group group)
(when (group-exists? db (:uuid group))
(throw (ex-info (str "Group UUID " (:uuid group) " already used") {:uuid group})))
group))
(defn retrieve-url-path
"Constructs a URL to query the sandbox directory of the task.
Uses the provided sandbox-directory to determine the sandbox directory.
Hard codes fun stuff like the port we run the agent on.
Users will need to add the file path & offset to their query.
Refer to the 'Using the output_url' section in docs/scheduler-rest-api.adoc for further details."
[agent-hostname task-id sandbox-directory]
(try
(when sandbox-directory
(str "http://" agent-hostname ":5051" "/files/read.json?path="
(URLEncoder/encode sandbox-directory "UTF-8")))
(catch Exception e
(log/debug e "Unable to retrieve directory path for" task-id "on agent" agent-hostname)
nil)))
(defn fetch-instance-map
"Converts the instance entity to a map representing the instance fields."
[db instance]
(let [hostname (:instance/hostname instance)
task-id (:instance/task-id instance)
executor (:instance/executor instance)
sandbox-directory (:instance/sandbox-directory instance)
url-path (retrieve-url-path hostname task-id sandbox-directory)
start (:instance/start-time instance)
mesos-start (:instance/mesos-start-time instance)
end (:instance/end-time instance)
cancelled (:instance/cancelled instance)
reason (reason/instance-entity->reason-entity db instance)
exit-code (:instance/exit-code instance)
progress (:instance/progress instance)
progress-message (:instance/progress-message instance)]
(cond-> {:backfilled false ;; Backfill has been deprecated
:executor_id (:instance/executor-id instance)
:hostname hostname
:ports (vec (sort (:instance/ports instance)))
:preempted (:instance/preempted? instance false)
:slave_id (:instance/slave-id instance)
:status (name (:instance/status instance))
:task_id task-id}
executor (assoc :executor (name executor))
start (assoc :start_time (.getTime start))
mesos-start (assoc :mesos_start_time (.getTime mesos-start))
end (assoc :end_time (.getTime end))
cancelled (assoc :cancelled cancelled)
exit-code (assoc :exit_code exit-code)
url-path (assoc :output_url url-path)
reason (assoc :reason_code (:reason/code reason)
:reason_string (:reason/string reason))
progress (assoc :progress progress)
progress-message (assoc :progress_message progress-message)
sandbox-directory (assoc :sandbox_directory sandbox-directory))))
(defn fetch-job-map
[db framework-id job-uuid]
(let [job (d/entity db [:job/uuid job-uuid])
resources (util/job-ent->resources job)
groups (:group/_job job)
application (:job/application job)
expected-runtime (:job/expected-runtime job)
executor (:job/executor job)
progress-output-file (:job/progress-output-file job)
progress-regex-string (:job/progress-regex-string job)
state (util/job-ent->state job)
constraints (->> job
:job/constraint
(map util/remove-datomic-namespacing)
(map (fn [{:keys [attribute operator pattern]}]
(->> [attribute (str/upper-case (name operator)) pattern]
(map str)))))
instances (map #(fetch-instance-map db %1) (:job/instance job))
submit-time (when (:job/submit-time job) ; due to a bug, submit time may not exist for some jobs
(.getTime (:job/submit-time job)))
job-map {:command (:job/command job)
:constraints constraints
:cpus (:cpus resources)
:disable_mea_culpa_retries (:job/disable-mea-culpa-retries job false)
:env (util/job-ent->env job)
:framework_id framework-id
:gpus (int (:gpus resources 0))
:instances instances
:labels (util/job-ent->label job)
:max_retries (:job/max-retries job) ; consistent with input
:max_runtime (:job/max-runtime job Long/MAX_VALUE) ; consistent with input
:mem (:mem resources)
:name (:job/name job "cookjob")
:ports (:job/ports job 0)
:priority (:job/priority job util/default-job-priority)
:retries_remaining (- (:job/max-retries job) (util/job-ent->attempts-consumed db job))
:state state
:status (name (:job/state job))
:submit_time submit-time
:uris (:uris resources)
:user (:job/user job)
:uuid (:job/uuid job)}]
(cond-> job-map
groups (assoc :groups (map #(str (:group/uuid %)) groups))
application (assoc :application (util/remove-datomic-namespacing application))
expected-runtime (assoc :expected-runtime expected-runtime)
executor (assoc :executor (name executor))
progress-output-file (assoc :progress-output-file progress-output-file)
progress-regex-string (assoc :progress-regex-string progress-regex-string))))
(defn fetch-group-live-jobs
"Get all jobs from a group that are currently running or waiting (not complete)"
[db guuid]
(let [group (d/entity db [:group/uuid guuid])
jobs (:group/job group)
completed? #(-> % :job/state (= :job.state/completed))]
(remove completed? jobs)))
(defn fetch-group-job-details
[db guuid]
(let [group (d/entity db [:group/uuid guuid])
jobs (:group/job group)
jobs-by-state (group-by :job/state jobs)]
{:completed (count (:job.state/completed jobs-by-state))
:running (count (:job.state/running jobs-by-state))
:waiting (count (:job.state/waiting jobs-by-state))}))
(defn fetch-group-map
[db guuid]
(let [group (d/entity db [:group/uuid guuid])
jobs (:group/job group)]
(-> (into {} group)
;; Remove job because we don't want to walk entire job list
(dissoc :group/job)
util/remove-datomic-namespacing
(assoc :jobs (map :job/uuid jobs))
(update-in [:host-placement :type] util/without-ns)
(update-in [:straggler-handling :type] util/without-ns))))
(defn instance-uuid->job-uuid
"Queries for the job uuid from an instance uuid.
Returns nil if the instance uuid doesn't correspond
a job"
[db instance-uuid]
(->> (d/entity db [:instance/task-id (str instance-uuid)])
:job/_instance
:job/uuid))
(defn- wrap-seq
"Returns:
- [v] if v is not nil and not sequential
- v otherwise"
[v]
(if (or (nil? v) (sequential? v))
v
[v]))
(defn retrieve-jobs
"Returns a tuple that either has the shape:
[true {::jobs ...
::jobs-requested ...
::instances-requested ...}]
or:
[false {::error ...}]
Given a collection of job and/or instance uuids, attempts to return the
corresponding set of existing job uuids. By default (or if the 'partial'
query parameter is false), the function returns an ::error if any of the
provided job or instance uuids cannot be found. If 'partial' is true, the
function will return the subset of job uuids that were found, assuming at
least one was found. This 'partial' flag allows a client to query a
particular cook cluster for a set of uuids, where some of them may not belong
to that cluster, and get back the data for those that do match."
[conn ctx]
(let [jobs (wrap-seq (get-in ctx [:request :query-params :job]))
instances (wrap-seq (get-in ctx [:request :query-params :instance]))
allow-partial-results (get-in ctx [:request :query-params :partial])
instance-uuid->job-uuid #(instance-uuid->job-uuid (d/db conn) %)
instance-jobs (mapv instance-uuid->job-uuid instances)
exists? #(job-exists? (db conn) %)
existing-jobs (filter exists? jobs)]
(cond
(and (= (count existing-jobs) (count jobs))
(every? some? instance-jobs))
[true {::jobs (into jobs instance-jobs)
::jobs-requested jobs
::instances-requested instances}]
(and allow-partial-results
(or (pos? (count existing-jobs))
(some some? instance-jobs)))
[true {::jobs (into existing-jobs (filter some? instance-jobs))
::jobs-requested jobs
::instances-requested instances}]
(some nil? instance-jobs)
[false {::error (str "UUID "
(str/join
\space
(filter (comp nil? instance-uuid->job-uuid)
instances))
" didn't correspond to an instance")}]
:else
[false {::error (str "UUID "
(str/join
\space
(set/difference (set jobs) (set existing-jobs)))
" didn't correspond to a job")}])))
(defn instances-exist?
[conn ctx]
"Returns a tuple that either has the shape:
[true {::jobs ...}]
or:
[false {::non-existing-uuids ...}]
Given a collection of instance uuids, attempts to return the corresponding set of *existing*
parent job uuids. By default (or if the 'partial' query parameter is false), the function
returns an ::error if any of the provided instance uuids cannot be found. If
'partial' is true, the function will return the subset of job uuids that were found,
assuming at least one was found. This 'partial' flag allows a client to query a
particular cook cluster for a set of uuids, where some of them may not belong to that
cluster, and get back the data for those that do match."
(let [uuids (wrap-seq (::instances ctx))
allow-partial-results? (::allow-partial-results? ctx)
instance-uuid->job-uuid #(instance-uuid->job-uuid (d/db conn) %)
job-uuids (mapv instance-uuid->job-uuid uuids)]
(cond
(every? some? job-uuids)
[true {::jobs job-uuids}]