forked from spotify/helios
/
ZooKeeperMasterModel.java
1774 lines (1581 loc) · 71.2 KB
/
ZooKeeperMasterModel.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
/*
* Copyright (c) 2014 Spotify AB.
*
* 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.
*/
package com.spotify.helios.master;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.MoreObjects;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Ordering;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.spotify.helios.common.HeliosRuntimeException;
import com.spotify.helios.common.Json;
import com.spotify.helios.common.descriptors.AgentInfo;
import com.spotify.helios.common.descriptors.Deployment;
import com.spotify.helios.common.descriptors.DeploymentGroup;
import com.spotify.helios.common.descriptors.DeploymentGroupStatus;
import com.spotify.helios.common.descriptors.DeploymentGroupTasks;
import com.spotify.helios.common.descriptors.Goal;
import com.spotify.helios.common.descriptors.HostInfo;
import com.spotify.helios.common.descriptors.HostStatus;
import com.spotify.helios.common.descriptors.Job;
import com.spotify.helios.common.descriptors.JobId;
import com.spotify.helios.common.descriptors.JobStatus;
import com.spotify.helios.common.descriptors.PortMapping;
import com.spotify.helios.common.descriptors.RolloutOptions;
import com.spotify.helios.common.descriptors.RolloutTask;
import com.spotify.helios.common.descriptors.Task;
import com.spotify.helios.common.descriptors.TaskStatus;
import com.spotify.helios.common.descriptors.TaskStatusEvent;
import com.spotify.helios.common.descriptors.ThrottleState;
import com.spotify.helios.rollingupdate.DefaultRolloutPlanner;
import com.spotify.helios.rollingupdate.DeploymentGroupEventFactory;
import com.spotify.helios.rollingupdate.DeploymentGroupEventFactory.RollingUpdateReason;
import com.spotify.helios.rollingupdate.RollingUpdateError;
import com.spotify.helios.rollingupdate.RollingUpdateOp;
import com.spotify.helios.rollingupdate.RollingUpdateOpFactory;
import com.spotify.helios.rollingupdate.RolloutPlanner;
import com.spotify.helios.servicescommon.KafkaRecord;
import com.spotify.helios.servicescommon.KafkaSender;
import com.spotify.helios.servicescommon.VersionedValue;
import com.spotify.helios.servicescommon.ZooKeeperRegistrarUtil;
import com.spotify.helios.servicescommon.coordination.Node;
import com.spotify.helios.servicescommon.coordination.Paths;
import com.spotify.helios.servicescommon.coordination.ZooKeeperClient;
import com.spotify.helios.servicescommon.coordination.ZooKeeperClientProvider;
import com.spotify.helios.servicescommon.coordination.ZooKeeperOperation;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.KeeperException.NoNodeException;
import org.apache.zookeeper.KeeperException.NodeExistsException;
import org.apache.zookeeper.KeeperException.NotEmptyException;
import org.apache.zookeeper.OpResult;
import org.apache.zookeeper.data.Stat;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import static com.google.common.base.Optional.fromNullable;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Strings.isNullOrEmpty;
import static com.google.common.collect.Lists.newArrayList;
import static com.google.common.collect.Lists.reverse;
import static com.spotify.helios.common.descriptors.DeploymentGroupStatus.State.FAILED;
import static com.spotify.helios.common.descriptors.Descriptor.parse;
import static com.spotify.helios.common.descriptors.HostStatus.Status.DOWN;
import static com.spotify.helios.common.descriptors.HostStatus.Status.UP;
import static com.spotify.helios.rollingupdate.DeploymentGroupEventFactory.RollingUpdateReason.HOSTS_CHANGED;
import static com.spotify.helios.rollingupdate.DeploymentGroupEventFactory.RollingUpdateReason.MANUAL;
import static com.spotify.helios.servicescommon.coordination.ZooKeeperOperations.check;
import static com.spotify.helios.servicescommon.coordination.ZooKeeperOperations.create;
import static com.spotify.helios.servicescommon.coordination.ZooKeeperOperations.delete;
import static com.spotify.helios.servicescommon.coordination.ZooKeeperOperations.set;
import static java.util.Collections.emptyList;
import static java.util.Collections.emptyMap;
import static java.util.Collections.singletonList;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
/**
* The Helios Master's view into ZooKeeper.
*/
public class ZooKeeperMasterModel implements MasterModel {
private static final Comparator<TaskStatusEvent> EVENT_COMPARATOR =
new Comparator<TaskStatusEvent>() {
@Override
public int compare(TaskStatusEvent arg0, TaskStatusEvent arg1) {
if (arg1.getTimestamp() > arg0.getTimestamp()) {
return -1;
} else if (arg1.getTimestamp() == arg0.getTimestamp()) {
return 0;
} else {
return 1;
}
}
};
private static final Logger log = LoggerFactory.getLogger(ZooKeeperMasterModel.class);
public static final Map<JobId, TaskStatus> EMPTY_STATUSES = emptyMap();
public static final TypeReference<HostInfo>
HOST_INFO_TYPE =
new TypeReference<HostInfo>() {};
public static final TypeReference<AgentInfo>
AGENT_INFO_TYPE =
new TypeReference<AgentInfo>() {};
public static final TypeReference<Map<String, String>>
STRING_MAP_TYPE =
new TypeReference<Map<String, String>>() {};
public static final TypeReference<List<String>>
STRING_LIST_TYPE =
new TypeReference<List<String>>() {};
private static final String DEPLOYMENT_GROUP_EVENTS_KAFKA_TOPIC = "HeliosDeploymentGroupEvents";
private static final DeploymentGroupEventFactory DEPLOYMENT_GROUP_EVENT_FACTORY =
new DeploymentGroupEventFactory();
private final ZooKeeperClientProvider provider;
private final String name;
private final KafkaSender kafkaSender;
/**
* Constructor
* @param provider {@link ZooKeeperClientProvider}
* @param name The hostname of the machine running the {@link MasterModel}
* @param kafkaSender {@link KafkaSender}
*/
public ZooKeeperMasterModel(final ZooKeeperClientProvider provider,
final String name,
final KafkaSender kafkaSender) {
this.provider = Preconditions.checkNotNull(provider);
this.name = Preconditions.checkNotNull(name);
this.kafkaSender = Preconditions.checkNotNull(kafkaSender);
}
/**
* Registers a host into ZooKeeper. The {@code id} is initially generated randomly by the Agent
* and persisted on disk. This way, in the event that you have two agents attempting to register
* with the same value of @{code host}, the first one will win.
*/
@Override
public void registerHost(final String host, final String id) {
final ZooKeeperClient client = provider.get("registerHost");
try {
ZooKeeperRegistrarUtil.registerHost(client, Paths.configHostId(host), host, id);
} catch (Exception e) {
throw new HeliosRuntimeException("registering host " + host + " failed", e);
}
}
/**
* Returns a list of the hosts/agents that have been registered.
*/
@Override
public List<String> listHosts() {
try {
// TODO (dano): only return hosts whose agents completed registration (i.e. has id nodes)
return provider.get("listHosts").getChildren(Paths.configHosts());
} catch (KeeperException.NoNodeException e) {
return emptyList();
} catch (KeeperException e) {
throw new HeliosRuntimeException("listing hosts failed", e);
}
}
/**
* Returns a list of the host names of the currently running masters.
*/
@Override
public List<String> getRunningMasters() {
final ZooKeeperClient client = provider.get("getRunningMasters");
try {
final List<String> masters = client.getChildren(Paths.statusMaster());
final ImmutableList.Builder<String> upMasters = ImmutableList.builder();
for (final String master : masters) {
if (client.exists(Paths.statusMasterUp(master)) != null) {
upMasters.add(master);
}
}
return upMasters.build();
} catch (KeeperException e) {
throw new HeliosRuntimeException("listing masters failed", e);
}
}
/**
* Undoes the effect of {@link ZooKeeperMasterModel#registerHost(String, String)}. Cleans up
* any leftover host-related things.
*/
@Override
public void deregisterHost(final String host)
throws HostNotFoundException, HostStillInUseException {
final ZooKeeperClient client = provider.get("deregisterHost");
ZooKeeperRegistrarUtil.deregisterHost(client, host);
}
/**
* Adds a job into the configuration.
*/
@Override
public void addJob(final Job job) throws JobExistsException {
log.info("adding job: {}", job);
final JobId id = job.getId();
final UUID operationId = UUID.randomUUID();
final String creationPath = Paths.configJobCreation(id, operationId);
final ZooKeeperClient client = provider.get("addJob");
try {
try {
client.ensurePath(Paths.historyJob(id));
client.transaction(create(Paths.configJob(id), job),
create(Paths.configJobRefShort(id), id),
create(Paths.configJobHosts(id)),
create(creationPath),
// Touch the jobs root node so that its version is bumped on every job
// change down the tree. Effectively, make it that version == cVersion.
set(Paths.configJobs(), UUID.randomUUID().toString().getBytes()));
} catch (final NodeExistsException e) {
if (client.exists(creationPath) != null) {
// The job was created, we're done here
return;
}
throw new JobExistsException(id.toString());
}
} catch (NoNodeException e) {
throw new HeliosRuntimeException("adding job " + job + " failed due to missing ZK path: " +
e.getPath(), e);
} catch (final KeeperException e) {
throw new HeliosRuntimeException("adding job " + job + " failed", e);
}
}
/**
* Given a jobId, returns the N most recent events in its history in the cluster.
*/
@Override
public List<TaskStatusEvent> getJobHistory(final JobId jobId) throws JobDoesNotExistException {
return getJobHistory(jobId, null);
}
/**
* Given a jobId and host, returns the N most recent events in its history on that host in the
* cluster.
*/
@Override
public List<TaskStatusEvent> getJobHistory(final JobId jobId, final String host)
throws JobDoesNotExistException {
final Job descriptor = getJob(jobId);
if (descriptor == null) {
throw new JobDoesNotExistException(jobId);
}
final ZooKeeperClient client = provider.get("getJobHistory");
final List<String> hosts;
try {
hosts = (!isNullOrEmpty(host)) ? singletonList(host) :
client.getChildren(Paths.historyJobHosts(jobId));
} catch (NoNodeException e) {
return emptyList();
} catch (KeeperException e) {
throw Throwables.propagate(e);
}
final List<TaskStatusEvent> jsEvents = Lists.newArrayList();
for (final String h : hosts) {
final List<String> events;
try {
events = client.getChildren(Paths.historyJobHostEvents(jobId, h));
} catch (NoNodeException e) {
continue;
} catch (KeeperException e) {
throw Throwables.propagate(e);
}
for (final String event : events) {
try {
final byte[] data = client.getData(Paths.historyJobHostEventsTimestamp(
jobId, h, Long.valueOf(event)));
final TaskStatus status = Json.read(data, TaskStatus.class);
jsEvents.add(new TaskStatusEvent(status, Long.valueOf(event), h));
} catch (NoNodeException e) { // ignore, it went away before we read it
} catch (KeeperException | IOException e) {
throw Throwables.propagate(e);
}
}
}
return Ordering.from(EVENT_COMPARATOR).sortedCopy(jsEvents);
}
/**
* Create a deployment group.
* <p>
* If successful, the following ZK nodes will be created:
* <ul>
* <li>/config/deployment-groups/[group-name]</li>
* <li>/status/deployment-groups/[group-name]</li>
* <li>/status/deployment-groups/[group-name]/hosts</li>
* </ul>
* These nodes are guaranteed to exist until the DG is removed.
* <p>
* If the operation fails no ZK nodes will be created. If any of the nodes above already exist the
* operation will fail.
*
* @throws DeploymentGroupExistsException If a DG with the same name already exists.
*/
@Override
public void addDeploymentGroup(final DeploymentGroup deploymentGroup)
throws DeploymentGroupExistsException {
log.info("adding deployment-group: {}", deploymentGroup);
final ZooKeeperClient client = provider.get("addDeploymentGroup");
try {
try {
client.ensurePath(Paths.configDeploymentGroups());
client.ensurePath(Paths.statusDeploymentGroups());
client.transaction(
create(Paths.configDeploymentGroup(deploymentGroup.getName()), deploymentGroup),
create(Paths.statusDeploymentGroup(deploymentGroup.getName())),
create(Paths.statusDeploymentGroupHosts(deploymentGroup.getName()),
Json.asBytesUnchecked(emptyList()))
);
} catch (final NodeExistsException e) {
throw new DeploymentGroupExistsException(deploymentGroup.getName());
}
} catch (final KeeperException e) {
throw new HeliosRuntimeException("adding deployment-group " + deploymentGroup + " failed", e);
}
}
@Override
public DeploymentGroup getDeploymentGroup(final String name)
throws DeploymentGroupDoesNotExistException {
log.debug("getting deployment-group: {}", name);
final ZooKeeperClient client = provider.get("getDeploymentGroup");
return getDeploymentGroup(client, name);
}
private DeploymentGroup getDeploymentGroup(final ZooKeeperClient client, final String name)
throws DeploymentGroupDoesNotExistException {
try {
final byte[] data = client.getData(Paths.configDeploymentGroup(name));
return Json.read(data, DeploymentGroup.class);
} catch (NoNodeException e) {
throw new DeploymentGroupDoesNotExistException(name);
} catch (KeeperException | IOException e) {
throw new HeliosRuntimeException("getting deployment-group " + name + " failed", e);
}
}
/**
* Remove a deployment group.
* <p>
* If successful, all ZK nodes associated with the DG will be deleted. Specifically these nodes
* are guaranteed to be non-existent after a successful remove (not all of them might exist
* before, though):
* <ul>
* <li>/config/deployment-groups/[group-name]</li>
* <li>/status/deployment-groups/[group-name]</li>
* <li>/status/deployment-groups/[group-name]/hosts</li>
* <li>/status/deployment-group-tasks/[group-name]</li>
* </ul>
* If the operation fails no ZK nodes will be removed.
*
* @throws DeploymentGroupDoesNotExistException If the DG does not exist.
*/
@Override
public void removeDeploymentGroup(final String name) throws DeploymentGroupDoesNotExistException {
log.info("removing deployment-group: name={}", name);
final ZooKeeperClient client = provider.get("removeDeploymentGroup");
try {
client.ensurePath(Paths.configDeploymentGroups());
client.ensurePath(Paths.statusDeploymentGroups());
client.ensurePath(Paths.statusDeploymentGroupTasks());
final List<ZooKeeperOperation> operations = Lists.newArrayList();
// /status/deployment-group-tasks/[group-name] might exist (if a rolling-update is in
// progress). To avoid inconsistent state make sure it's deleted if it does exist:
//
// * If it exists: delete it.
// * If it doesn't exist, add and delete it in the same transaction. This is a round-about
// way of ensuring that it wasn't created when we commit the transaction.
//
// Having /status/deployment-group-tasks/[group-name] for removed groups around will cause
// DGs to become slower and spam logs with errors so we want to avoid it.
if (client.exists(Paths.statusDeploymentGroupTasks(name)) != null) {
operations.add(delete(Paths.statusDeploymentGroupTasks(name)));
} else {
operations.add(create(Paths.statusDeploymentGroupTasks(name)));
operations.add(delete(Paths.statusDeploymentGroupTasks(name)));
}
operations.add(delete(Paths.configDeploymentGroup(name)));
operations.add(delete(Paths.statusDeploymentGroupHosts(name)));
operations.add(delete(Paths.statusDeploymentGroup(name)));
client.transaction(operations);
} catch (final NoNodeException e) {
throw new DeploymentGroupDoesNotExistException(name);
} catch (final KeeperException e) {
throw new HeliosRuntimeException("removing deployment-group " + name + " failed", e);
}
}
@Override
public void updateDeploymentGroupHosts(final String groupName, final List<String> hosts)
throws DeploymentGroupDoesNotExistException {
log.debug("updating deployment-group hosts: name={}", groupName);
final ZooKeeperClient client = provider.get("updateDeploymentGroupHosts");
try {
Optional<Integer> version = Optional.absent();
List<String> curHosts;
try {
// addDeploymentGroup creates Paths.statusDeploymentGroupHosts(name) so it should always
// exist. If it doesn't, then the DG was (likely) deleted.
final Node node = client.getNode(Paths.statusDeploymentGroupHosts(groupName));
version = Optional.of(node.getStat().getVersion());
curHosts = Json.read(node.getBytes(), new TypeReference<List<String>>() {});
} catch (JsonMappingException e) {
curHosts = Collections.emptyList();
} catch (NoNodeException e) {
// DG was deleted -- abort.
return;
}
if (!version.isPresent() || !hosts.equals(curHosts)) {
// Node not present or hosts have changed
final List<ZooKeeperOperation> ops = Lists.newArrayList();
ops.add(set(Paths.statusDeploymentGroupHosts(groupName), Json.asBytes(hosts)));
final DeploymentGroup deploymentGroup = getDeploymentGroup(groupName);
ImmutableList<Map<String, Object>> events = ImmutableList.of();
if (deploymentGroup.getJobId() != null) {
final DeploymentGroupStatus deploymentGroupStatus = getDeploymentGroupStatus(groupName);
if (deploymentGroupStatus == null || deploymentGroupStatus.getState() != FAILED) {
final RollingUpdateOp op =
getInitRollingUpdateOps(deploymentGroup, hosts, HOSTS_CHANGED, client);
ops.addAll(op.operations());
events = op.events();
}
}
log.info("starting zookeeper transaction for updateDeploymentGroupHosts on "
+ "deployment-group name {} jobId={}. List of operations: {}",
groupName, deploymentGroup.getJobId(), ops);
client.transaction(ops);
emitEvents(DEPLOYMENT_GROUP_EVENTS_KAFKA_TOPIC, events);
}
} catch (NoNodeException e) {
throw new DeploymentGroupDoesNotExistException(groupName, e);
} catch (KeeperException | IOException e) {
throw new HeliosRuntimeException("updating deployment group hosts failed", e);
}
}
@Override
public void rollingUpdate(final DeploymentGroup deploymentGroup,
final JobId jobId,
final RolloutOptions options)
throws DeploymentGroupDoesNotExistException, JobDoesNotExistException {
checkNotNull(deploymentGroup, "deploymentGroup");
log.info("preparing to initiate rolling-update on deployment-group: name={}, jobId={}",
deploymentGroup.getName(), jobId);
final DeploymentGroup updated = deploymentGroup.toBuilder()
.setJobId(jobId)
.setRolloutOptions(options)
.build();
if (getJob(jobId) == null) {
throw new JobDoesNotExistException(jobId);
}
final List<ZooKeeperOperation> operations = Lists.newArrayList();
final ZooKeeperClient client = provider.get("rollingUpdate");
operations.add(set(Paths.configDeploymentGroup(updated.getName()), updated));
try {
final RollingUpdateOp op = getInitRollingUpdateOps(updated, MANUAL, client);
operations.addAll(op.operations());
log.info("starting zookeeper transaction for rolling-update on "
+ "deployment-group name={} jobId={}. List of operations: {}",
deploymentGroup.getName(), jobId, operations);
client.transaction(operations);
emitEvents(DEPLOYMENT_GROUP_EVENTS_KAFKA_TOPIC, op.events());
log.info("initiated rolling-update on deployment-group: name={}, jobId={}",
deploymentGroup.getName(), jobId);
} catch (final NoNodeException e) {
throw new DeploymentGroupDoesNotExistException(deploymentGroup.getName());
} catch (final KeeperException e) {
throw new HeliosRuntimeException(
"rolling-update on deployment-group " + deploymentGroup.getName() + " failed", e);
}
}
private RollingUpdateOp getInitRollingUpdateOps(final DeploymentGroup deploymentGroup,
final RollingUpdateReason reason,
final ZooKeeperClient zooKeeperClient)
throws DeploymentGroupDoesNotExistException, KeeperException {
final List<String> hosts = getDeploymentGroupHosts(deploymentGroup.getName());
return getInitRollingUpdateOps(deploymentGroup, hosts, reason, zooKeeperClient);
}
private RollingUpdateOp getInitRollingUpdateOps(final DeploymentGroup deploymentGroup,
final List<String> hosts,
final RollingUpdateReason reason,
final ZooKeeperClient zooKeeperClient)
throws KeeperException {
final Map<String, HostStatus> hostsAndStatuses = Maps.newLinkedHashMap();
for (final String host : hosts) {
hostsAndStatuses.put(host, getHostStatus(host));
}
final RolloutPlanner rolloutPlanner = DefaultRolloutPlanner.of(deploymentGroup);
final List<RolloutTask> rolloutTasks = rolloutPlanner.plan(hostsAndStatuses);
final DeploymentGroupTasks tasks = DeploymentGroupTasks.newBuilder()
.setRolloutTasks(rolloutTasks)
.setTaskIndex(0)
.setDeploymentGroup(deploymentGroup)
.build();
final RollingUpdateOpFactory opFactory = new RollingUpdateOpFactory(
tasks, DEPLOYMENT_GROUP_EVENT_FACTORY);
return opFactory.start(deploymentGroup, reason, zooKeeperClient);
}
private Map<String, VersionedValue<DeploymentGroupTasks>> getDeploymentGroupTasks(
final ZooKeeperClient client) {
final String folder = Paths.statusDeploymentGroupTasks();
try {
final List<String> names;
try {
names = client.getChildren(folder);
} catch (NoNodeException e) {
return Collections.emptyMap();
}
final Map<String, VersionedValue<DeploymentGroupTasks>> ret = Maps.newHashMap();
for (final String name : names) {
final String path = Paths.statusDeploymentGroupTasks(name);
try {
final Node node = client.getNode(path);
final byte[] data = node.getBytes();
final int version = node.getStat().getVersion();
if (data.length == 0) {
// This can happen because of ensurePath creates an empty node
log.debug("Ignoring empty deployment group tasks {}", name);
} else {
final DeploymentGroupTasks val = parse(data, DeploymentGroupTasks.class);
ret.put(name, VersionedValue.of(val, version));
}
} catch (NoNodeException e) {
// Ignore, the deployment group was deleted before we had a chance to read it.
log.debug("Ignoring deleted deployment group tasks {}", name);
}
}
return ret;
} catch (KeeperException | IOException e) {
throw new HeliosRuntimeException("getting deployment group tasks failed", e);
}
}
private RollingUpdateOp processRollingUpdateTask(final ZooKeeperClient client,
final RollingUpdateOpFactory opFactory,
final RolloutTask task,
final DeploymentGroup deploymentGroup) {
final RolloutTask.Action action = task.getAction();
final String host = task.getTarget();
switch (action) {
case UNDEPLOY_OLD_JOBS:
// add undeploy ops for jobs previously deployed by this deployment group
return rollingUpdateUndeploy(client, opFactory, deploymentGroup, host);
case DEPLOY_NEW_JOB:
// add deploy ops for the new job
return rollingUpdateDeploy(client, opFactory, deploymentGroup, host);
case AWAIT_RUNNING:
return rollingUpdateAwaitRunning(client, opFactory, deploymentGroup, host);
default:
throw new HeliosRuntimeException(String.format(
"unknown rollout task type %s for deployment group %s.",
action, deploymentGroup.getName()));
}
}
@Override
public void rollingUpdateStep() {
final ZooKeeperClient client = provider.get("rollingUpdateStep");
final Map<String, VersionedValue<DeploymentGroupTasks>> tasksMap =
getDeploymentGroupTasks(client);
for (final Map.Entry<String, VersionedValue<DeploymentGroupTasks>> entry :
tasksMap.entrySet()) {
final String deploymentGroupName = entry.getKey();
final VersionedValue<DeploymentGroupTasks> versionedTasks = entry.getValue();
final DeploymentGroupTasks tasks = versionedTasks.value();
log.info("rolling-update step on deployment-group: name={}, tasks={}",
deploymentGroupName, tasks);
try {
final RollingUpdateOpFactory opFactory = new RollingUpdateOpFactory(
tasks, DEPLOYMENT_GROUP_EVENT_FACTORY);
final RolloutTask task = tasks.getRolloutTasks().get(tasks.getTaskIndex());
final RollingUpdateOp op = processRollingUpdateTask(
client, opFactory, task, tasks.getDeploymentGroup());
if (!op.operations().isEmpty()) {
final List<ZooKeeperOperation> ops = Lists.newArrayList();
ops.add(check(Paths.statusDeploymentGroupTasks(deploymentGroupName),
versionedTasks.version()));
ops.addAll(op.operations());
log.info("rolling-update step on deployment-group: name={}, zookeeper operations={}",
deploymentGroupName, ops);
try {
client.transaction(ops);
emitEvents(DEPLOYMENT_GROUP_EVENTS_KAFKA_TOPIC, op.events());
} catch (KeeperException.BadVersionException e) {
// some other master beat us in processing this rolling update step. not exceptional.
// ideally we would check the path in the exception, but curator doesn't provide a path
// for exceptions thrown as part of a transaction.
log.debug("error saving rolling-update operations: {}", e);
} catch (KeeperException e) {
log.error("rolling-update on deployment-group {} failed", deploymentGroupName, e);
}
}
} catch (final Exception e) {
log.error("error processing rolling update step for {}", deploymentGroupName, e);
}
}
}
private void emitEvents(final String topic, final List<Map<String, Object>> events) {
// Emit events
for (final Map<String, Object> event : events) {
kafkaSender.send(KafkaRecord.of(topic, Json.asBytesUnchecked(event)));
}
}
private RollingUpdateOp rollingUpdateTimedoutError(final RollingUpdateOpFactory opFactory,
final String host,
final JobId jobId,
final TaskStatus taskStatus) {
final List<TaskStatus.State> previousJobStates = getPreviousJobStates(jobId, host, 10);
final String baseError = "timed out waiting for job to reach state RUNNING ";
final String stateInfo = String.format(
"(terminal job state %s, previous states: %s)",
taskStatus.getState(),
Joiner.on("->").join(previousJobStates));
final Map<String, Object> metadata = Maps.newHashMap();
metadata.put("jobState", taskStatus.getState());
metadata.put("previousJobStates", previousJobStates);
metadata.put("throttleState", taskStatus.getThrottled());
if (taskStatus.getThrottled().equals(ThrottleState.IMAGE_MISSING)) {
return opFactory.error(
baseError + "due to missing Docker image " + stateInfo,
host,
RollingUpdateError.IMAGE_MISSING,
metadata);
}
if (taskStatus.getThrottled().equals(ThrottleState.IMAGE_PULL_FAILED)) {
return opFactory.error(
baseError + "due to failure pulling Docker image " + stateInfo,
host,
RollingUpdateError.IMAGE_PULL_FAILED,
metadata);
}
if (!Strings.isNullOrEmpty(taskStatus.getContainerError())) {
return opFactory.error(
baseError + stateInfo + " container error: " + taskStatus.getContainerError(),
host,
RollingUpdateError.TIMED_OUT_WAITING_FOR_JOB_TO_REACH_RUNNING,
metadata);
}
return opFactory.error(
baseError + stateInfo,
host,
RollingUpdateError.TIMED_OUT_WAITING_FOR_JOB_TO_REACH_RUNNING,
metadata);
}
private RollingUpdateOp rollingUpdateAwaitRunning(final ZooKeeperClient client,
final RollingUpdateOpFactory opFactory,
final DeploymentGroup deploymentGroup,
final String host) {
final TaskStatus taskStatus = getTaskStatus(client, host, deploymentGroup.getJobId());
final JobId jobId = deploymentGroup.getJobId();
if (taskStatus == null) {
// Handle cases where agent has not written job status to zookeeper.
// If job is not listed under /config/hosts node, it may have been deployed successfully and
// then manually undeployed. The job will not get redeployed, so treat this as a failure.
final Deployment deployment = getDeployment(host, jobId);
if (deployment == null) {
return opFactory.error(
"Job unexpectedly undeployed. Perhaps it was manually undeployed?", host,
RollingUpdateError.JOB_UNEXPECTEDLY_UNDEPLOYED);
}
// Check if we've exceeded the timeout for the rollout operation.
if (isRolloutTimedOut(client, deploymentGroup)) {
return opFactory.error("timed out while retrieving job status", host,
RollingUpdateError.TIMED_OUT_RETRIEVING_JOB_STATUS);
}
// We haven't detected any errors, so assume the agent will write the status soon.
return opFactory.yield();
} else if (!taskStatus.getState().equals(TaskStatus.State.RUNNING)) {
// job isn't running yet
if (isRolloutTimedOut(client, deploymentGroup)) {
// We exceeded the configured deploy timeout, and this job is still not running
return rollingUpdateTimedoutError(opFactory, host, jobId, taskStatus);
}
return opFactory.yield();
} else {
// the job is running on the host. last thing we have to ensure is that it was
// deployed by this deployment group. otherwise some weird conflict has occurred and we
// won't be able to undeploy the job on the next update.
final Deployment deployment = getDeployment(host, deploymentGroup.getJobId());
if (deployment == null) {
return opFactory.error(
"deployment for this job not found in zookeeper. " +
"Perhaps it was manually undeployed?", host,
RollingUpdateError.JOB_UNEXPECTEDLY_UNDEPLOYED);
} else if (!Objects.equals(deployment.getDeploymentGroupName(), deploymentGroup.getName())) {
return opFactory.error(
"job was already deployed, either manually or by a different deployment group", host,
RollingUpdateError.JOB_ALREADY_DEPLOYED);
}
return opFactory.nextTask();
}
}
private boolean isRolloutTimedOut(final ZooKeeperClient client,
final DeploymentGroup deploymentGroup) {
try {
final String statusPath = Paths.statusDeploymentGroupTasks(deploymentGroup.getName());
final long secondsSinceDeploy = MILLISECONDS.toSeconds(
System.currentTimeMillis() - client.getNode(statusPath).getStat().getMtime());
return secondsSinceDeploy > deploymentGroup.getRolloutOptions().getTimeout();
} catch (KeeperException e) {
// statusPath doesn't exist or some other ZK issue. probably this deployment group
// was removed.
log.warn("error determining deployment group modification time: {} - {}",
deploymentGroup.getName(), e);
return false;
}
}
private RollingUpdateOp rollingUpdateDeploy(final ZooKeeperClient client,
final RollingUpdateOpFactory opFactory,
final DeploymentGroup deploymentGroup,
final String host) {
final Deployment deployment = Deployment.of(deploymentGroup.getJobId(), Goal.START,
Deployment.EMTPY_DEPLOYER_USER, this.name,
deploymentGroup.getName());
try {
final String token = MoreObjects.firstNonNull(
deploymentGroup.getRolloutOptions().getToken(), Job.EMPTY_TOKEN);
return opFactory.nextTask(getDeployOperations(client, host, deployment, token));
} catch (JobDoesNotExistException e) {
return opFactory.error(e, host, RollingUpdateError.JOB_NOT_FOUND);
} catch (TokenVerificationException e) {
return opFactory.error(e, host, RollingUpdateError.TOKEN_VERIFICATION_ERROR);
} catch (HostNotFoundException e) {
return opFactory.error(e, host, RollingUpdateError.HOST_NOT_FOUND);
} catch (JobPortAllocationConflictException e) {
return opFactory.error(e, host, RollingUpdateError.PORT_CONFLICT);
} catch (JobAlreadyDeployedException e) {
// Nothing to do
return opFactory.nextTask();
}
}
private RollingUpdateOp rollingUpdateUndeploy(final ZooKeeperClient client,
final RollingUpdateOpFactory opFactory,
final DeploymentGroup deploymentGroup,
final String host) {
final List<ZooKeeperOperation> operations = Lists.newArrayList();
for (final Deployment deployment : getTasks(client, host).values()) {
final boolean isOwnedByDeploymentGroup = Objects.equals(
deployment.getDeploymentGroupName(), deploymentGroup.getName());
final boolean isSameJob = deployment.getJobId().equals(deploymentGroup.getJobId());
final RolloutOptions rolloutOptions = deploymentGroup.getRolloutOptions();
if (isOwnedByDeploymentGroup || (
isSameJob && rolloutOptions.getMigrate())) {
if (isSameJob && isOwnedByDeploymentGroup && deployment.getGoal().equals(Goal.START)) {
// The job we want deployed is already deployed and set to run, so just leave it.
continue;
}
try {
final String token = MoreObjects.firstNonNull(
deploymentGroup.getRolloutOptions().getToken(), Job.EMPTY_TOKEN);
operations.addAll(getUndeployOperations(client, host, deployment.getJobId(), token));
} catch (TokenVerificationException e) {
return opFactory.error(e, host, RollingUpdateError.TOKEN_VERIFICATION_ERROR);
} catch (HostNotFoundException e) {
return opFactory.error(e, host, RollingUpdateError.HOST_NOT_FOUND);
} catch (JobNotDeployedException e) {
// probably somebody beat us to the punch of undeploying. that's fine.
}
}
}
return opFactory.nextTask(operations);
}
@Override
public void stopDeploymentGroup(final String deploymentGroupName)
throws DeploymentGroupDoesNotExistException {
checkNotNull(deploymentGroupName, "name");
log.info("stop deployment-group: name={}", deploymentGroupName);
final ZooKeeperClient client = provider.get("stopDeploymentGroup");
// Delete deployment group tasks (if any) and set DG state to FAILED
final DeploymentGroupStatus status = DeploymentGroupStatus.newBuilder()
.setState(FAILED)
.setError("Stopped by user")
.build();
final String statusPath = Paths.statusDeploymentGroup(deploymentGroupName);
final String tasksPath = Paths.statusDeploymentGroupTasks(deploymentGroupName);
try {
client.ensurePath(Paths.statusDeploymentGroupTasks());
final List<ZooKeeperOperation> operations = Lists.newArrayList();
// NOTE: This remove operation is racey. If tasks exist and the rollout finishes before the
// delete() is executed then this will fail. Conversely, if it doesn't exist but is created
// before the transaction is executed it will also fail. This is annoying for users, but at
// least means we won't have inconsistent state.
//
// That the set() is first in the list of operations is important because of the
// kludgy error checking we do below to disambiguate "doesn't exist" failures from the race
// condition mentioned below.
operations.add(set(statusPath, status));
final Stat tasksStat = client.exists(tasksPath);
if (tasksStat != null) {
operations.add(delete(tasksPath));
} else {
// There doesn't seem to be a "check that node doesn't exist" operation so we
// do a create and a delete on the same path to emulate it.
operations.add(create(tasksPath));
operations.add(delete(tasksPath));
}
client.transaction(operations);
} catch (final NoNodeException e) {
// Either the statusPath didn't exist, in which case the DG does not exist. Or the tasks path
// does not exist which can happen due to the race condition described above. In the latter
// case make sure we don't return a "doesn't exist" error as that would be a lie.
// Yes, the way you figure out which operation in a transaction failed is retarded.
if (((OpResult.ErrorResult) e.getResults().get(0)).getErr() ==
KeeperException.Code.NONODE.intValue()) {
throw new DeploymentGroupDoesNotExistException(deploymentGroupName);
} else {
throw new HeliosRuntimeException(
"stop deployment-group " + deploymentGroupName +
" failed due to a race condition, please retry", e);
}
} catch (final KeeperException e) {
throw new HeliosRuntimeException(
"stop deployment-group " + deploymentGroupName + " failed", e);
}
}
/**
* Returns a {@link Map} of deployment group name to {@link DeploymentGroup} objects for all of
* the deployment groups known.
*/
@Override
public Map<String, DeploymentGroup> getDeploymentGroups() {
log.debug("getting deployment groups");
final String folder = Paths.configDeploymentGroups();
final ZooKeeperClient client = provider.get("getDeploymentGroups");
try {
final List<String> names;
try {
names = client.getChildren(folder);
} catch (NoNodeException e) {
return Maps.newHashMap();
}
final Map<String, DeploymentGroup> descriptors = Maps.newHashMap();
for (final String name : names) {
final String path = Paths.configDeploymentGroup(name);
try {
final byte[] data = client.getData(path);
final DeploymentGroup descriptor = parse(data, DeploymentGroup.class);
descriptors.put(descriptor.getName(), descriptor);
} catch (NoNodeException e) {
// Ignore, the deployment group was deleted before we had a chance to read it.
log.debug("Ignoring deleted deployment group {}", name);
}
}
return descriptors;
} catch (KeeperException | IOException e) {
throw new HeliosRuntimeException("getting deployment groups failed", e);
}
}
@Override
public DeploymentGroupStatus getDeploymentGroupStatus(final String name)
throws DeploymentGroupDoesNotExistException {
log.debug("getting deployment group status: {}", name);
final ZooKeeperClient client = provider.get("getDeploymentGroupStatus");
final DeploymentGroup deploymentGroup = getDeploymentGroup(client, name);
if (deploymentGroup == null) {
return null;
}
try {
final Node node = client.getNode(Paths.statusDeploymentGroup(name));
final byte[] bytes = node.getBytes();
if (bytes.length == 0) {
return null;
}
return Json.read(bytes, DeploymentGroupStatus.class);
} catch (NoNodeException e) {
return null;
} catch (KeeperException | IOException e) {
throw new HeliosRuntimeException("getting deployment group status " + name + " failed", e);
}
}
@Override
public List<String> getDeploymentGroupHosts(final String name)
throws DeploymentGroupDoesNotExistException {
log.debug("getting deployment group hosts: {}", name);
final ZooKeeperClient client = provider.get("getDeploymentGroupHosts");
final DeploymentGroup deploymentGroup = getDeploymentGroup(client, name);
if (deploymentGroup == null) {
throw new DeploymentGroupDoesNotExistException(name);
}
try {
final byte[] data = client.getData(Paths.statusDeploymentGroupHosts(name));
if (data.length > 0) {
return Json.read(data, STRING_LIST_TYPE);
}
} catch (NoNodeException e) {
// not fatal