/
TaskManager.java
1103 lines (866 loc) · 43.8 KB
/
TaskManager.java
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
package com.hubspot.singularity.data;
import static java.nio.charset.StandardCharsets.UTF_8;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.api.transaction.CuratorTransactionFinal;
import org.apache.curator.utils.ZKPaths;
import org.apache.mesos.Protos.TaskStatus;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.annotation.Timed;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.google.inject.name.Named;
import com.hubspot.mesos.JavaUtils;
import com.hubspot.singularity.ExtendedTaskState;
import com.hubspot.singularity.LoadBalancerRequestType;
import com.hubspot.singularity.SingularityCreateResult;
import com.hubspot.singularity.SingularityDeleteResult;
import com.hubspot.singularity.SingularityKilledTaskIdRecord;
import com.hubspot.singularity.SingularityLoadBalancerUpdate;
import com.hubspot.singularity.SingularityMainModule;
import com.hubspot.singularity.SingularityPendingTask;
import com.hubspot.singularity.SingularityPendingTaskId;
import com.hubspot.singularity.SingularitySlave;
import com.hubspot.singularity.SingularityTask;
import com.hubspot.singularity.SingularityTaskCleanup;
import com.hubspot.singularity.SingularityTaskHealthcheckResult;
import com.hubspot.singularity.SingularityTaskHistory;
import com.hubspot.singularity.SingularityTaskHistoryUpdate;
import com.hubspot.singularity.SingularityTaskId;
import com.hubspot.singularity.SingularityTaskIdHolder;
import com.hubspot.singularity.SingularityTaskMetadata;
import com.hubspot.singularity.SingularityTaskShellCommandHistory;
import com.hubspot.singularity.SingularityTaskShellCommandRequest;
import com.hubspot.singularity.SingularityTaskShellCommandRequestId;
import com.hubspot.singularity.SingularityTaskShellCommandUpdate;
import com.hubspot.singularity.SingularityTaskStatusHolder;
import com.hubspot.singularity.config.SingularityConfiguration;
import com.hubspot.singularity.data.transcoders.IdTranscoder;
import com.hubspot.singularity.data.transcoders.StringTranscoder;
import com.hubspot.singularity.data.transcoders.Transcoder;
import com.hubspot.singularity.event.SingularityEventListener;
import com.hubspot.singularity.scheduler.SingularityLeaderCache;
@Singleton
public class TaskManager extends CuratorAsyncManager {
private static final Logger LOG = LoggerFactory.getLogger(CuratorAsyncManager.class);
private static final String TASKS_ROOT = "/tasks";
private static final String ACTIVE_PATH_ROOT = TASKS_ROOT + "/active";
private static final String LAST_ACTIVE_TASK_STATUSES_PATH_ROOT = TASKS_ROOT + "/statuses";
private static final String PENDING_PATH_ROOT = TASKS_ROOT + "/scheduled";
private static final String CLEANUP_PATH_ROOT = TASKS_ROOT + "/cleanup";
private static final String LB_CLEANUP_PATH_ROOT = TASKS_ROOT + "/lbcleanup";
private static final String DRIVER_KILLED_PATH_ROOT = TASKS_ROOT + "/killed";
private static final String FINISHED_TASK_MAIL_QUEUE = TASKS_ROOT + "/mailqueue";
private static final String SHELL_REQUESTS_QUEUE_PATH_ROOT = TASKS_ROOT + "/shellqueue";
private static final String HISTORY_PATH_ROOT = TASKS_ROOT + "/history";
private static final String LAST_HEALTHCHECK_KEY = "LAST_HEALTHCHECK";
private static final String DIRECTORY_KEY = "DIRECTORY";
private static final String CONTAINER_ID_KEY = "CONTAINER_ID";
private static final String TASK_KEY = "TASK";
private static final String NOTIFIED_OVERDUE_TO_FINISH_KEY = "NOTIFIED_OVERDUE_TO_FINISH";
private static final String LOAD_BALANCER_PRE_KEY = "LOAD_BALANCER_";
private static final String SHELLS_PATH = "/shells";
private static final String SHELL_REQUEST_KEY = "REQUEST";
private static final String SHELL_UPDATES_PATH = "/updates";
private static final String HEALTHCHECKS_PATH = "/healthchecks";
private static final String HEALTHCHECKS_FINISHED_PATH = "/healthchecks-finished";
private static final String STARTUP_HEALTHCHECK_PATH_SUFFIX = "-STARTUP";
private static final String METADATA_PATH = "/metadata";
private static final String UPDATES_PATH = "/updates";
private final Transcoder<SingularityTaskHealthcheckResult> healthcheckResultTranscoder;
private final Transcoder<SingularityTaskCleanup> taskCleanupTranscoder;
private final Transcoder<SingularityTask> taskTranscoder;
private final Transcoder<SingularityTaskStatusHolder> taskStatusTranscoder;
private final Transcoder<SingularityKilledTaskIdRecord> killedTaskIdRecordTranscoder;
private final Transcoder<SingularityTaskHistoryUpdate> taskHistoryUpdateTranscoder;
private final Transcoder<SingularityLoadBalancerUpdate> taskLoadBalancerUpdateTranscoder;
private final Transcoder<SingularityPendingTask> pendingTaskTranscoder;
private final Transcoder<SingularityTaskShellCommandRequest> taskShellCommandRequestTranscoder;
private final Transcoder<SingularityTaskShellCommandUpdate> taskShellCommandUpdateTranscoder;
private final Transcoder<SingularityTaskMetadata> taskMetadataTranscoder;
private final IdTranscoder<SingularityPendingTaskId> pendingTaskIdTranscoder;
private final IdTranscoder<SingularityTaskId> taskIdTranscoder;
private final ZkCache<SingularityTask> taskCache;
private final SingularityWebCache webCache;
private final SingularityLeaderCache leaderCache;
private final SingularityEventListener singularityEventListener;
private final String serverId;
@Inject
public TaskManager(CuratorFramework curator, SingularityConfiguration configuration, MetricRegistry metricRegistry, SingularityEventListener singularityEventListener,
IdTranscoder<SingularityPendingTaskId> pendingTaskIdTranscoder, IdTranscoder<SingularityTaskId> taskIdTranscoder, Transcoder<SingularityLoadBalancerUpdate> taskLoadBalancerHistoryUpdateTranscoder,
Transcoder<SingularityTaskStatusHolder> taskStatusTranscoder, Transcoder<SingularityTaskHealthcheckResult> healthcheckResultTranscoder, Transcoder<SingularityTask> taskTranscoder,
Transcoder<SingularityTaskCleanup> taskCleanupTranscoder, Transcoder<SingularityTaskHistoryUpdate> taskHistoryUpdateTranscoder, Transcoder<SingularityPendingTask> pendingTaskTranscoder,
Transcoder<SingularityKilledTaskIdRecord> killedTaskIdRecordTranscoder, Transcoder<SingularityTaskShellCommandRequest> taskShellCommandRequestTranscoder,
Transcoder<SingularityTaskShellCommandUpdate> taskShellCommandUpdateTranscoder, Transcoder<SingularityTaskMetadata> taskMetadataTranscoder,
ZkCache<SingularityTask> taskCache, SingularityWebCache webCache, SingularityLeaderCache leaderCache,
@Named(SingularityMainModule.SERVER_ID_PROPERTY) String serverId) {
super(curator, configuration, metricRegistry);
this.healthcheckResultTranscoder = healthcheckResultTranscoder;
this.taskTranscoder = taskTranscoder;
this.taskStatusTranscoder = taskStatusTranscoder;
this.killedTaskIdRecordTranscoder = killedTaskIdRecordTranscoder;
this.taskCleanupTranscoder = taskCleanupTranscoder;
this.taskHistoryUpdateTranscoder = taskHistoryUpdateTranscoder;
this.taskIdTranscoder = taskIdTranscoder;
this.pendingTaskTranscoder = pendingTaskTranscoder;
this.taskShellCommandRequestTranscoder = taskShellCommandRequestTranscoder;
this.pendingTaskIdTranscoder = pendingTaskIdTranscoder;
this.taskLoadBalancerUpdateTranscoder = taskLoadBalancerHistoryUpdateTranscoder;
this.singularityEventListener = singularityEventListener;
this.taskCache = taskCache;
this.taskShellCommandUpdateTranscoder = taskShellCommandUpdateTranscoder;
this.taskMetadataTranscoder = taskMetadataTranscoder;
this.webCache = webCache;
this.leaderCache = leaderCache;
this.serverId = serverId;
}
// since we can't use creatingParentsIfNeeded in transactions
public void createRequiredParents() {
create(HISTORY_PATH_ROOT);
create(ACTIVE_PATH_ROOT);
}
private String getLastHealthcheckPath(SingularityTaskId taskId) {
return ZKPaths.makePath(getHistoryPath(taskId), LAST_HEALTHCHECK_KEY);
}
private String getMetadataParentPath(SingularityTaskId taskId) {
return ZKPaths.makePath(getHistoryPath(taskId), METADATA_PATH);
}
private String getTaskMetadataPath(SingularityTaskMetadata taskMetadata) {
return ZKPaths.makePath(getMetadataParentPath(taskMetadata.getTaskId()), String.format("%s-%s", taskMetadata.getTimestamp(), taskMetadata.getType()));
}
private String getHealthcheckParentPath(SingularityTaskId taskId) {
return ZKPaths.makePath(getHistoryPath(taskId), HEALTHCHECKS_PATH);
}
private String getHealthchecksFinishedPath(SingularityTaskId taskId) {
return ZKPaths.makePath(getHistoryPath(taskId), HEALTHCHECKS_FINISHED_PATH);
}
private String getLastActiveTaskStatusPath(SingularityTaskId taskId) {
return ZKPaths.makePath(LAST_ACTIVE_TASK_STATUSES_PATH_ROOT, taskId.getId());
}
private String getHealthcheckPath(SingularityTaskHealthcheckResult healthcheck) {
return ZKPaths.makePath(getHealthcheckParentPath(healthcheck.getTaskId()), String.format("%s%s", Long.toString(healthcheck.getTimestamp()), healthcheck.isStartup() ? STARTUP_HEALTHCHECK_PATH_SUFFIX : ""));
}
private String getShellRequestQueuePath(SingularityTaskShellCommandRequest shellRequest) {
return ZKPaths.makePath(SHELL_REQUESTS_QUEUE_PATH_ROOT, shellRequest.getId().getId());
}
private String getFinishedTaskMailQueuePath(SingularityTaskId taskId) {
return ZKPaths.makePath(FINISHED_TASK_MAIL_QUEUE, taskId.getId());
}
private String getShellsParentPath(SingularityTaskId taskId) {
return ZKPaths.makePath(getHistoryPath(taskId), SHELLS_PATH);
}
private String getShellHistoryParentPath(SingularityTaskShellCommandRequestId shellRequestId) {
return ZKPaths.makePath(getShellsParentPath(shellRequestId.getTaskId()), shellRequestId.getSubIdForTaskHistory());
}
private String getShellHistoryRequestPath(SingularityTaskShellCommandRequestId shellRequestId) {
return ZKPaths.makePath(getShellHistoryParentPath(shellRequestId), SHELL_REQUEST_KEY);
}
private String getShellHistoryUpdateParentPath(SingularityTaskShellCommandRequestId shellRequestId) {
return ZKPaths.makePath(getShellHistoryParentPath(shellRequestId), SHELL_UPDATES_PATH);
}
private String getShellHistoryUpdatePath(SingularityTaskShellCommandUpdate shellUpdate) {
return ZKPaths.makePath(getShellHistoryUpdateParentPath(shellUpdate.getShellRequestId()), shellUpdate.getUpdateType().name());
}
private String getTaskPath(SingularityTaskId taskId) {
return ZKPaths.makePath(getHistoryPath(taskId), TASK_KEY);
}
private String getLoadBalancerStatePath(SingularityTaskId taskId, LoadBalancerRequestType requestType) {
return ZKPaths.makePath(getHistoryPath(taskId), LOAD_BALANCER_PRE_KEY + requestType.name());
}
private String getDirectoryPath(SingularityTaskId taskId) {
return ZKPaths.makePath(getHistoryPath(taskId), DIRECTORY_KEY);
}
private String getContainerIdPath(SingularityTaskId taskId) {
return ZKPaths.makePath(getHistoryPath(taskId), CONTAINER_ID_KEY);
}
private String getNotifiedOverduePath(SingularityTaskId taskId) {
return ZKPaths.makePath(getHistoryPath(taskId), NOTIFIED_OVERDUE_TO_FINISH_KEY);
}
private String getUpdatesPath(SingularityTaskId taskId) {
return ZKPaths.makePath(getHistoryPath(taskId), UPDATES_PATH);
}
private String getUpdatePath(SingularityTaskId taskId, ExtendedTaskState state) {
return ZKPaths.makePath(getUpdatesPath(taskId), state.name());
}
private String getRequestPath(String requestId) {
return ZKPaths.makePath(HISTORY_PATH_ROOT, requestId);
}
private String getHistoryPath(SingularityTaskId taskId) {
return ZKPaths.makePath(getRequestPath(taskId.getRequestId()), taskId.getId());
}
private String getActivePath(String taskId) {
return ZKPaths.makePath(ACTIVE_PATH_ROOT, taskId);
}
private String getPendingPath(SingularityPendingTaskId pendingTaskId) {
return ZKPaths.makePath(PENDING_PATH_ROOT, pendingTaskId.getId());
}
private String getCleanupPath(String taskId) {
return ZKPaths.makePath(CLEANUP_PATH_ROOT, taskId);
}
public int getNumCleanupTasks() {
return getNumChildren(CLEANUP_PATH_ROOT);
}
public int getNumLbCleanupTasks() {
return getNumChildren(LB_CLEANUP_PATH_ROOT);
}
public int getNumActiveTasks() {
if (leaderCache.active()) {
return leaderCache.getNumActiveTasks();
}
return getNumChildren(ACTIVE_PATH_ROOT);
}
public int getNumScheduledTasks() {
if (leaderCache.active()) {
return leaderCache.getNumPendingTasks();
}
return getNumChildren(PENDING_PATH_ROOT);
}
public void saveLoadBalancerState(SingularityTaskId taskId, LoadBalancerRequestType requestType, SingularityLoadBalancerUpdate lbUpdate) {
Preconditions.checkState(requestType != LoadBalancerRequestType.DEPLOY);
save(getLoadBalancerStatePath(taskId, requestType), lbUpdate, taskLoadBalancerUpdateTranscoder);
}
public void saveTaskDirectory(SingularityTaskId taskId, String directory) {
save(getDirectoryPath(taskId), Optional.of(directory.getBytes(UTF_8)));
}
public void saveContainerId(SingularityTaskId taskId, String containerId) {
save(getContainerIdPath(taskId), Optional.of(containerId.getBytes(UTF_8)));
}
@Timed
public void saveLastActiveTaskStatus(SingularityTaskStatusHolder taskStatus) {
save(getLastActiveTaskStatusPath(taskStatus.getTaskId()), taskStatus, taskStatusTranscoder);
}
public Optional<String> getDirectory(SingularityTaskId taskId) {
return getData(getDirectoryPath(taskId), StringTranscoder.INSTANCE);
}
public Optional<String> getContainerId(SingularityTaskId taskId) {
return getData(getContainerIdPath(taskId), StringTranscoder.INSTANCE);
}
public void saveHealthcheckResult(SingularityTaskHealthcheckResult healthcheckResult) {
if (canSaveNewHealthcheck(healthcheckResult)) {
final Optional<byte[]> bytes = Optional.of(healthcheckResultTranscoder.toBytes(healthcheckResult));
save(getHealthcheckPath(healthcheckResult), bytes);
save(getLastHealthcheckPath(healthcheckResult.getTaskId()), bytes);
} else {
LOG.warn("Healthchecks have finished, could not save new result {}", healthcheckResult);
}
}
private boolean canSaveNewHealthcheck(SingularityTaskHealthcheckResult healthcheckResult) {
return !exists(getHealthchecksFinishedPath(healthcheckResult.getTaskId()));
}
public void markHealthchecksFinished(SingularityTaskId taskId) {
create(getHealthchecksFinishedPath(taskId));
}
public SingularityCreateResult savePendingTask(SingularityPendingTask task) {
final String pendingPath = getPendingPath(task.getPendingTaskId());
leaderCache.savePendingTask(task);
return save(pendingPath, task, pendingTaskTranscoder);
}
public List<SingularityTaskId> getAllTaskIds() {
final List<String> requestIds = getChildren(HISTORY_PATH_ROOT);
final List<String> paths = Lists.newArrayListWithCapacity(requestIds.size());
for (String requestId : requestIds) {
paths.add(getRequestPath(requestId));
}
return getChildrenAsIdsForParents("getAllTaskIds", paths, taskIdTranscoder);
}
private List<SingularityTaskId> getTaskIds(String root) {
return getChildrenAsIds(root, taskIdTranscoder);
}
public List<String> getActiveTaskIdsAsStrings() {
if (leaderCache.active()) {
return leaderCache.getActiveTaskIdsAsStrings();
}
return getChildren(ACTIVE_PATH_ROOT);
}
public List<SingularityTaskId> getActiveTaskIds() {
return getActiveTaskIds(false);
}
public List<SingularityTaskId> getActiveTaskIds(boolean useWebCache) {
if (leaderCache.active()) {
return leaderCache.getActiveTaskIds();
}
if (useWebCache && webCache.useCachedActiveTasks()) {
return webCache.getActiveTaskIds();
}
return getTaskIds(ACTIVE_PATH_ROOT);
}
public List<SingularityTaskId> getCleanupTaskIds() {
if (leaderCache.active()) {
return leaderCache.getCleanupTaskIds();
}
return getChildrenAsIds(CLEANUP_PATH_ROOT, taskIdTranscoder);
}
public List<SingularityTaskCleanup> getCleanupTasks(boolean useWebCache) {
if (leaderCache.active()) {
return leaderCache.getCleanupTasks();
}
if (useWebCache && webCache.useCachedCleanupTasks()) {
return webCache.getCleanupTasks();
}
List<SingularityTaskCleanup> cleanupTasks = fetchCleanupTasks();
if (useWebCache) {
webCache.cacheTaskCleanup(cleanupTasks);
}
return cleanupTasks;
}
public List<SingularityTaskCleanup> getCleanupTasks() {
return getCleanupTasks(false);
}
public Optional<SingularityTaskCleanup> getTaskCleanup(String taskId) {
if (leaderCache.active()) {
return leaderCache.getTaskCleanup(SingularityTaskId.valueOf(taskId));
}
return getData(getCleanupPath(taskId), taskCleanupTranscoder);
}
public List<SingularityTaskCleanup> fetchCleanupTasks() {
return getAsyncChildren(CLEANUP_PATH_ROOT, taskCleanupTranscoder);
}
public List<SingularityTask> getActiveTasks() {
return getActiveTasks(false);
}
public List<SingularityTask> getActiveTasks(boolean useWebCache) {
if (useWebCache && webCache.useCachedActiveTasks()) {
return webCache.getActiveTasks();
}
List<String> children = Lists.transform(getActiveTaskIds(), new Function<SingularityTaskId, String>() {
@Override
public String apply(SingularityTaskId taskId) {
return getTaskPath(taskId);
}
});
List<SingularityTask> activeTasks = getAsync("getActiveTasks", children, taskTranscoder, taskCache);
if (useWebCache) {
webCache.cacheActiveTasks(activeTasks);
}
return activeTasks;
}
public List<SingularityTaskStatusHolder> getLastActiveTaskStatuses() {
return getAsyncChildren(LAST_ACTIVE_TASK_STATUSES_PATH_ROOT, taskStatusTranscoder);
}
@Timed
public Optional<SingularityTaskStatusHolder> getLastActiveTaskStatus(SingularityTaskId taskId) {
return getData(getLastActiveTaskStatusPath(taskId), taskStatusTranscoder);
}
public List<SingularityTaskStatusHolder> getLastActiveTaskStatusesFor(Collection<SingularityTaskId> activeTaskIds) {
List<String> paths = Lists.newArrayListWithExpectedSize(activeTaskIds.size());
for (SingularityTaskId taskId : activeTaskIds) {
paths.add(getLastActiveTaskStatusPath(taskId));
}
return getAsync("getLastActiveTaskStatusesFor", paths, taskStatusTranscoder);
}
public List<SingularityTask> getTasksOnSlave(Collection<SingularityTaskId> activeTaskIds, SingularitySlave slave) {
final List<SingularityTask> tasks = Lists.newArrayList();
final String sanitizedHost = JavaUtils.getReplaceHyphensWithUnderscores(slave.getHost());
for (SingularityTaskId activeTaskId : activeTaskIds) {
if (activeTaskId.getSanitizedHost().equals(sanitizedHost)) {
Optional<SingularityTask> maybeTask = getTask(activeTaskId);
if (maybeTask.isPresent() && slave.getId().equals(maybeTask.get().getSlaveId().getValue())) {
tasks.add(maybeTask.get());
}
}
}
return tasks;
}
public List<SingularityTaskHistoryUpdate> getTaskHistoryUpdates(SingularityTaskId taskId) {
if (leaderCache.active()) {
return leaderCache.getTaskHistoryUpdates(taskId);
}
List<SingularityTaskHistoryUpdate> updates = getAsyncChildren(getUpdatesPath(taskId), taskHistoryUpdateTranscoder);
Collections.sort(updates);
return updates;
}
public Optional<SingularityTaskHistoryUpdate> getTaskHistoryUpdate(SingularityTaskId taskId, ExtendedTaskState taskState) {
return getData(getUpdatePath(taskId, taskState), taskHistoryUpdateTranscoder);
}
public Map<SingularityTaskId, List<SingularityTaskHistoryUpdate>> getTaskHistoryUpdates(Collection<SingularityTaskId> taskIds) {
if (leaderCache.active()) {
return leaderCache.getTaskHistoryUpdates(taskIds);
}
Map<String, SingularityTaskId> pathsMap = Maps.newHashMap();
for (SingularityTaskId taskId : taskIds) {
pathsMap.put(getHistoryPath(taskId), taskId);
}
return getAsyncNestedChildDataAsMap("getTaskHistoryUpdates", pathsMap, UPDATES_PATH, taskHistoryUpdateTranscoder);
}
public Map<SingularityTaskId, List<SingularityTaskHistoryUpdate>> getAllTaskHistoryUpdates() {
return getTaskHistoryUpdates(getAllTaskIds());
}
public int getNumHealthchecks(SingularityTaskId taskId) {
return getNumChildren(getHealthcheckParentPath(taskId));
}
public int getNumNonstartupHealthchecks(SingularityTaskId taskId) {
int numChecks = 0;
List<String> checks = getChildren(getHealthcheckParentPath(taskId));
for (String check : checks) {
if (!check.endsWith(STARTUP_HEALTHCHECK_PATH_SUFFIX)) {
numChecks++;
}
}
return numChecks;
}
public List<SingularityTaskHealthcheckResult> getHealthcheckResults(SingularityTaskId taskId) {
List<SingularityTaskHealthcheckResult> healthcheckResults = getAsyncChildren(getHealthcheckParentPath(taskId), healthcheckResultTranscoder);
Collections.sort(healthcheckResults);
return healthcheckResults;
}
public void clearStartupHealthchecks(SingularityTaskId taskId) {
Optional<SingularityTaskHealthcheckResult> maybeLastHealthcheck = getLastHealthcheck(taskId);
String parentPath = getHealthcheckParentPath(taskId);
for (String healthcheckPath : getChildren(parentPath)) {
String fullPath = ZKPaths.makePath(parentPath, healthcheckPath);
if (healthcheckPath.endsWith(STARTUP_HEALTHCHECK_PATH_SUFFIX) && (!maybeLastHealthcheck.isPresent() || !getHealthcheckPath(maybeLastHealthcheck.get()).equals(fullPath))) {
delete(fullPath);
}
}
}
public Optional<SingularityTaskHealthcheckResult> getLastHealthcheck(SingularityTaskId taskId) {
return getData(getLastHealthcheckPath(taskId), healthcheckResultTranscoder);
}
public Map<SingularityTaskId, SingularityTaskHealthcheckResult> getLastHealthcheck(Collection<SingularityTaskId> taskIds) {
List<String> paths = Lists.newArrayListWithCapacity(taskIds.size());
for (SingularityTaskId taskId : taskIds) {
paths.add(getLastHealthcheckPath(taskId));
}
List<SingularityTaskHealthcheckResult> healthcheckResults = getAsync("getLastHealthcheck", paths, healthcheckResultTranscoder);
return Maps.uniqueIndex(healthcheckResults, SingularityTaskIdHolder.getTaskIdFunction());
}
public SingularityCreateResult saveTaskHistoryUpdate(SingularityTaskHistoryUpdate taskHistoryUpdate) {
return saveTaskHistoryUpdate(taskHistoryUpdate, false);
}
@Timed
public SingularityCreateResult saveTaskHistoryUpdate(SingularityTaskHistoryUpdate taskHistoryUpdate, boolean overwriteExisting) {
singularityEventListener.taskHistoryUpdateEvent(taskHistoryUpdate);
if (overwriteExisting) {
Optional<SingularityTaskHistoryUpdate> maybeExisting = getTaskHistoryUpdate(taskHistoryUpdate.getTaskId(), taskHistoryUpdate.getTaskState());
LOG.info("Found existing history {}", maybeExisting);
SingularityTaskHistoryUpdate updateWithPrevious;
if (maybeExisting.isPresent()) {
updateWithPrevious = taskHistoryUpdate.withPrevious(maybeExisting.get());
LOG.info("Will save new update {}", updateWithPrevious);
} else {
updateWithPrevious = taskHistoryUpdate;
}
if (leaderCache.active()) {
leaderCache.saveTaskHistoryUpdate(updateWithPrevious, overwriteExisting);
}
return save(getUpdatePath(taskHistoryUpdate.getTaskId(), taskHistoryUpdate.getTaskState()), updateWithPrevious, taskHistoryUpdateTranscoder);
} else {
if (leaderCache.active()) {
leaderCache.saveTaskHistoryUpdate(taskHistoryUpdate, overwriteExisting);
}
return create(getUpdatePath(taskHistoryUpdate.getTaskId(), taskHistoryUpdate.getTaskState()), taskHistoryUpdate, taskHistoryUpdateTranscoder);
}
}
public SingularityDeleteResult deleteTaskHistoryUpdate(SingularityTaskId taskId, ExtendedTaskState state, Optional<SingularityTaskHistoryUpdate> previousStateUpdate) {
if (previousStateUpdate.isPresent()) {
singularityEventListener.taskHistoryUpdateEvent(previousStateUpdate.get());
}
if (leaderCache.active()) {
leaderCache.deleteTaskHistoryUpdate(taskId, state);
}
return delete(getUpdatePath(taskId, state));
}
public boolean isActiveTask(String taskId) {
if (leaderCache.active()) {
return leaderCache.isActiveTask(taskId);
}
return exists(getActivePath(taskId));
}
public List<SingularityTaskId> getTaskIdsForRequest(String requestId) {
return getChildrenAsIds(getRequestPath(requestId), taskIdTranscoder);
}
public Optional<SingularityTaskId> getTaskByRunId(String requestId, String runId) {
Map<SingularityTaskId, SingularityTask> activeTasks = getTasks(getActiveTaskIdsForRequest(requestId));
for (Map.Entry<SingularityTaskId, SingularityTask> entry : activeTasks.entrySet()) {
if (entry.getValue().getTaskRequest().getPendingTask().getRunId().isPresent() && entry.getValue().getTaskRequest().getPendingTask().getRunId().get().equals(runId)) {
return Optional.of(entry.getKey());
}
}
Map<SingularityTaskId, SingularityTask> inactiveTasks = getTasks(getInactiveTaskIdsForRequest(requestId));
for (Map.Entry<SingularityTaskId, SingularityTask> entry : inactiveTasks.entrySet()) {
if (entry.getValue().getTaskRequest().getPendingTask().getRunId().isPresent() && entry.getValue().getTaskRequest().getPendingTask().getRunId().get().equals(runId)) {
return Optional.of(entry.getKey());
}
}
return Optional.absent();
}
private enum TaskFilter {
ACTIVE, INACTIVE;
}
public List<SingularityTaskId> getInactiveTaskIdsForRequest(String requestId) {
return getTaskIdsForRequest(requestId, TaskFilter.INACTIVE);
}
public List<SingularityTaskId> getActiveTaskIdsForRequest(String requestId) {
return getTaskIdsForRequest(requestId, TaskFilter.ACTIVE);
}
public List<SingularityTaskId> filterActiveTaskIds(List<SingularityTaskId> taskIds) {
if (leaderCache.active()) {
return leaderCache.exists(taskIds);
}
final List<String> paths = Lists.newArrayListWithCapacity(taskIds.size());
for (SingularityTaskId taskId : taskIds) {
paths.add(getActivePath(taskId.getId()));
}
return exists("filterActiveTaskIds", paths, taskIdTranscoder);
}
public int getNumLaunchingTasks() {
List<SingularityTaskId> activeTaskIds = getActiveTaskIds();
final Map<String, SingularityTaskId> paths = Maps.newHashMapWithExpectedSize(activeTaskIds.size());
for (SingularityTaskId taskId : activeTaskIds) {
paths.put(getUpdatePath(taskId, ExtendedTaskState.TASK_RUNNING), taskId);
}
return notExists("getNumLaunchingTasks", paths).size();
}
public List<SingularityTaskId> filterInactiveTaskIds(List<SingularityTaskId> taskIds) {
if (leaderCache.active()) {
return leaderCache.getInactiveTaskIds(taskIds);
}
final Map<String, SingularityTaskId> pathsMap = Maps.newHashMap();
for (SingularityTaskId taskId : taskIds) {
pathsMap.put(getActivePath(taskId.getId()), taskId);
}
return notExists("filterInactiveTaskIds", pathsMap);
}
private List<SingularityTaskId> getTaskIdsForRequest(String requestId, TaskFilter taskFilter) {
final List<SingularityTaskId> requestTaskIds = getTaskIdsForRequest(requestId);
final List<SingularityTaskId> activeTaskIds = filterActiveTaskIds(requestTaskIds);
if (taskFilter == TaskFilter.ACTIVE) {
return activeTaskIds;
}
Iterables.removeAll(requestTaskIds, activeTaskIds);
return requestTaskIds;
}
public List<SingularityTaskId> getTaskIdsForDeploy(String requestId, final String deployId, TaskFilter taskFilter) {
List<SingularityTaskId> requestTaskIds = getTaskIdsForRequest(requestId, taskFilter);
final Iterable<SingularityTaskId> deployTaskIds = Iterables.filter(requestTaskIds, new Predicate<SingularityTaskId>() {
@Override
public boolean apply(SingularityTaskId input) {
return input.getDeployId().equals(deployId);
}
});
return ImmutableList.copyOf(deployTaskIds);
}
public List<SingularityTaskId> getActiveTaskIdsForDeploy(String requestId, final String deployId) {
return getTaskIdsForDeploy(requestId, deployId, TaskFilter.ACTIVE);
}
public List<SingularityTaskId> getInactiveTaskIdsForDeploy(String requestId, final String deployId) {
return getTaskIdsForDeploy(requestId, deployId, TaskFilter.INACTIVE);
}
public List<SingularityTaskId> getInactiveTaskIds(List<String> requestIds) {
List<String> paths = Lists.newArrayListWithCapacity(requestIds.size());
for (String requestId : requestIds) {
paths.add(getRequestPath(requestId));
}
List<SingularityTaskId> taskIds = getChildrenAsIdsForParents("getInactiveTaskIds", paths, taskIdTranscoder);
return filterInactiveTaskIds(taskIds);
}
public Optional<SingularityTaskHistory> getTaskHistory(SingularityTaskId taskId) {
final Optional<SingularityTask> task = getTaskCheckCache(taskId, true);
if (!task.isPresent()) {
return Optional.absent();
}
List<SingularityTaskHistoryUpdate> taskUpdates = getTaskHistoryUpdates(taskId);
Optional<String> directory = getDirectory(taskId);
Optional<String> containerId = getContainerId(taskId);
List<SingularityTaskHealthcheckResult> healthchecks = getHealthcheckResults(taskId);
List<SingularityLoadBalancerUpdate> loadBalancerUpdates = Lists.newArrayListWithCapacity(2);
checkLoadBalancerHistory(loadBalancerUpdates, taskId, LoadBalancerRequestType.ADD);
checkLoadBalancerHistory(loadBalancerUpdates, taskId, LoadBalancerRequestType.REMOVE);
List<SingularityTaskShellCommandHistory> shellCommandHistory = getTaskShellCommandHistory(taskId);
List<SingularityTaskMetadata> taskMetadata = getTaskMetadata(taskId);
return Optional.of(new SingularityTaskHistory(taskUpdates, directory, containerId, healthchecks, task.get(), loadBalancerUpdates, shellCommandHistory, taskMetadata));
}
private List<SingularityTaskShellCommandHistory> getTaskShellCommandHistory(SingularityTaskId taskId) {
List<SingularityTaskShellCommandRequest> shellRequests = getTaskShellCommandRequestsForTask(taskId);
List<SingularityTaskShellCommandHistory> shellCommandHistory = new ArrayList<>(shellRequests.size());
for (SingularityTaskShellCommandRequest shellRequest : shellRequests) {
shellCommandHistory.add(new SingularityTaskShellCommandHistory(shellRequest, getTaskShellCommandUpdates(shellRequest.getId())));
}
return shellCommandHistory;
}
private List<SingularityTaskMetadata> getTaskMetadata(SingularityTaskId taskId) {
List<SingularityTaskMetadata> taskMetadata = getAsyncChildren(getMetadataParentPath(taskId), taskMetadataTranscoder);
Collections.sort(taskMetadata);
return taskMetadata;
}
private void checkLoadBalancerHistory(List<SingularityLoadBalancerUpdate> loadBalancerUpdates, SingularityTaskId taskId, LoadBalancerRequestType lbRequestType) {
Optional<SingularityLoadBalancerUpdate> lbHistory = getLoadBalancerState(taskId, lbRequestType);
if (lbHistory.isPresent()) {
loadBalancerUpdates.add(lbHistory.get());
}
}
public boolean hasNotifiedOverdue(SingularityTaskId taskId) {
return checkExists(getNotifiedOverduePath(taskId)).isPresent();
}
public void saveNotifiedOverdue(SingularityTaskId taskId) {
save(getNotifiedOverduePath(taskId), Optional.<byte[]> absent());
}
public Optional<SingularityLoadBalancerUpdate> getLoadBalancerState(SingularityTaskId taskId, LoadBalancerRequestType requestType) {
return getData(getLoadBalancerStatePath(taskId, requestType), taskLoadBalancerUpdateTranscoder);
}
public Optional<SingularityPendingTask> getPendingTask(SingularityPendingTaskId pendingTaskId) {
if (leaderCache.active()) {
return leaderCache.getPendingTask(pendingTaskId);
}
return getData(getPendingPath(pendingTaskId), pendingTaskTranscoder);
}
private Optional<SingularityTask> getTaskCheckCache(SingularityTaskId taskId, boolean shouldCheckExists) {
final String path = getTaskPath(taskId);
return getData(path, taskTranscoder, taskCache, shouldCheckExists);
}
@Timed
public Optional<SingularityTask> getTask(SingularityTaskId taskId) {
return getTaskCheckCache(taskId, false);
}
public boolean taskExistsInZk(SingularityTaskId taskId) {
return checkExists(getTaskPath(taskId)).isPresent();
}
public void activateLeaderCache() {
leaderCache.cachePendingTasks(fetchPendingTasks());
leaderCache.cacheActiveTaskIds(getTaskIds(ACTIVE_PATH_ROOT));
leaderCache.cacheCleanupTasks(fetchCleanupTasks());
leaderCache.cacheKilledTasks(fetchKilledTaskIdRecords());
leaderCache.cacheTaskHistoryUpdates(getAllTaskHistoryUpdates());
}
private List<SingularityPendingTask> fetchPendingTasks() {
return getAsyncChildren(PENDING_PATH_ROOT, pendingTaskTranscoder);
}
public List<SingularityPendingTaskId> getPendingTaskIds() {
return getPendingTaskIds(false);
}
public List<SingularityPendingTaskId> getPendingTaskIds(boolean useWebCache) {
if (leaderCache.active()) {
return leaderCache.getPendingTaskIds();
}
if (useWebCache && webCache.useCachedPendingTasks()) {
return webCache.getPendingTaskIds();
}
return getChildrenAsIds(PENDING_PATH_ROOT, pendingTaskIdTranscoder);
}
public List<SingularityPendingTaskId> getPendingTaskIdsForRequest(final String requestId) {
List<SingularityPendingTaskId> pendingTaskIds = getPendingTaskIds();
return ImmutableList.copyOf(Iterables.filter(pendingTaskIds, new Predicate<SingularityPendingTaskId>() {
@Override
public boolean apply(SingularityPendingTaskId pendingTaskId) {
return pendingTaskId.getRequestId().equals(requestId);
}
}));
}
public List<SingularityPendingTask> getPendingTasksForRequest(final String requestId) {
return getAsync(
PENDING_PATH_ROOT,
getPendingTaskIdsForRequest(requestId).stream().map(this::getPendingPath).collect(Collectors.toList()),
pendingTaskTranscoder
);
}
public List<SingularityPendingTask> getPendingTasks() {
return getPendingTasks(false);
}
public List<SingularityPendingTask> getPendingTasks(boolean useWebCache) {
if (leaderCache.active()) {
return leaderCache.getPendingTasks();
}
if (useWebCache && webCache.useCachedPendingTasks()) {
return webCache.getPendingTasks();
}
List<SingularityPendingTask> pendingTasks = fetchPendingTasks();
if (useWebCache) {
webCache.cachePendingTasks(pendingTasks);
}
return pendingTasks;
}
public void createTaskAndDeletePendingTask(SingularityTask task) {
try {
createTaskAndDeletePendingTaskPrivate(task);
} catch (Throwable t) {
throw Throwables.propagate(t);
}
}
public Map<SingularityTaskId, SingularityTask> getTasks(Iterable<SingularityTaskId> taskIds) {
final List<String> paths = Lists.newArrayList();
for (SingularityTaskId taskId : taskIds) {
paths.add(getTaskPath(taskId));
}
return Maps.uniqueIndex(getAsync("getTasks", paths, taskTranscoder, taskCache), SingularityTaskIdHolder.getTaskIdFunction());
}
private void createTaskAndDeletePendingTaskPrivate(SingularityTask task) throws Exception {
deletePendingTask(task.getTaskRequest().getPendingTask().getPendingTaskId());
final long now = System.currentTimeMillis();
String msg = String.format("Task launched because of %s", task.getTaskRequest().getPendingTask().getPendingTaskId().getPendingType().name());
if (task.getTaskRequest().getPendingTask().getUser().isPresent()) {
msg = String.format("%s by %s", msg, task.getTaskRequest().getPendingTask().getUser().get());
}
if (task.getTaskRequest().getPendingTask().getMessage().isPresent()) {
msg = String.format("%s (%s)", msg, task.getTaskRequest().getPendingTask().getMessage().get());
}
saveTaskHistoryUpdate(new SingularityTaskHistoryUpdate(task.getTaskId(), now, ExtendedTaskState.TASK_LAUNCHED, Optional.of(msg), Optional.<String>absent()));
saveLastActiveTaskStatus(new SingularityTaskStatusHolder(task.getTaskId(), Optional.<TaskStatus>absent(), now, serverId, Optional.of(task.getSlaveId().getValue())));
try {
final String path = getTaskPath(task.getTaskId());
CuratorTransactionFinal transaction = curator.inTransaction().create().forPath(path, taskTranscoder.toBytes(task)).and();
transaction.create().forPath(getActivePath(task.getTaskId().getId())).and().commit();
leaderCache.putActiveTask(task);
taskCache.set(path, task);
} catch (KeeperException.NodeExistsException nee) {
LOG.error("Task or active path already existed for {}", task.getTaskId());
}
}
public List<SingularityTaskId> getLBCleanupTasks() {
return getChildrenAsIds(LB_CLEANUP_PATH_ROOT, taskIdTranscoder);
}
private String getLBCleanupPath(SingularityTaskId taskId) {
return ZKPaths.makePath(LB_CLEANUP_PATH_ROOT, taskId.getId());
}
private String getKilledPath(SingularityTaskId taskId) {
return ZKPaths.makePath(DRIVER_KILLED_PATH_ROOT, taskId.getId());
}
public SingularityDeleteResult deleteLBCleanupTask(SingularityTaskId taskId) {
return delete(getLBCleanupPath(taskId));
}
public SingularityCreateResult createLBCleanupTask(SingularityTaskId taskId) {
return create(getLBCleanupPath(taskId));
}
public SingularityCreateResult saveKilledRecord(SingularityKilledTaskIdRecord killedTaskIdRecord) {
if (leaderCache.active()) {
leaderCache.addKilledTask(killedTaskIdRecord);
}
return save(getKilledPath(killedTaskIdRecord.getTaskId()), killedTaskIdRecord, killedTaskIdRecordTranscoder);
}
public List<SingularityKilledTaskIdRecord> getKilledTaskIdRecords() {
if (leaderCache.active()) {
return leaderCache.getKilledTasks();
}
return fetchKilledTaskIdRecords();
}
public List<SingularityKilledTaskIdRecord> fetchKilledTaskIdRecords() {
return getAsyncChildren(DRIVER_KILLED_PATH_ROOT, killedTaskIdRecordTranscoder);
}
public SingularityDeleteResult deleteKilledRecord(SingularityTaskId taskId) {
if (leaderCache.active()) {
leaderCache.deleteKilledTask(taskId);
}
return delete(getKilledPath(taskId));
}
@Timed
public SingularityDeleteResult deleteLastActiveTaskStatus(SingularityTaskId taskId) {
return delete(getLastActiveTaskStatusPath(taskId));
}
public SingularityCreateResult saveTaskMetadata(SingularityTaskMetadata taskMetadata) {
return save(getTaskMetadataPath(taskMetadata), taskMetadata, taskMetadataTranscoder);
}
public SingularityCreateResult saveTaskShellCommandRequestToQueue(SingularityTaskShellCommandRequest shellRequest) {
return save(getShellRequestQueuePath(shellRequest), shellRequest, taskShellCommandRequestTranscoder);
}
public SingularityCreateResult saveTaskFinishedInMailQueue(SingularityTaskId taskId) {
return save(getFinishedTaskMailQueuePath(taskId), Optional.<byte[]>absent());
}
public List<SingularityTaskId> getTaskFinishedMailQueue() {
return getChildrenAsIds(FINISHED_TASK_MAIL_QUEUE, taskIdTranscoder);
}
public SingularityDeleteResult deleteFinishedTaskMailQueue(SingularityTaskId taskId) {
return delete(getFinishedTaskMailQueuePath(taskId));
}
public SingularityCreateResult saveTaskShellCommandRequestToTask(SingularityTaskShellCommandRequest shellRequest) {
return save(getShellHistoryRequestPath(shellRequest.getId()), shellRequest, taskShellCommandRequestTranscoder);
}
public SingularityCreateResult saveTaskShellCommandUpdate(SingularityTaskShellCommandUpdate shellUpdate) {
return save(getShellHistoryUpdatePath(shellUpdate), shellUpdate, taskShellCommandUpdateTranscoder);