-
Notifications
You must be signed in to change notification settings - Fork 120
/
AgentHostServiceImpl.java
688 lines (567 loc) · 22.9 KB
/
AgentHostServiceImpl.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
/*
* Copyright 2020 flow.ci
*
* 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.flowci.core.agent.service;
import com.flowci.core.agent.dao.AgentDao;
import com.flowci.core.agent.dao.AgentHostDao;
import com.flowci.core.agent.domain.*;
import com.flowci.core.agent.event.AgentHostStatusEvent;
import com.flowci.core.common.config.AppProperties;
import com.flowci.core.common.domain.Variables;
import com.flowci.core.common.helper.CacheHelper;
import com.flowci.core.common.manager.SpringEventManager;
import com.flowci.core.common.manager.SpringTaskManager;
import com.flowci.core.common.service.SettingService;
import com.flowci.core.job.event.NoIdleAgentEvent;
import com.flowci.core.secret.domain.KubeConfigSecret;
import com.flowci.core.secret.domain.RSASecret;
import com.flowci.core.secret.domain.Secret;
import com.flowci.core.secret.event.GetSecretEvent;
import com.flowci.core.user.domain.User;
import com.flowci.docker.ContainerManager;
import com.flowci.docker.DockerManager;
import com.flowci.docker.DockerSSHManager;
import com.flowci.docker.K8sManager;
import com.flowci.docker.domain.*;
import com.flowci.exception.NotAvailableException;
import com.flowci.exception.NotFoundException;
import com.flowci.util.StringHelper;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.RemovalCause;
import com.github.benmanes.caffeine.cache.RemovalListener;
import com.google.common.base.Preconditions;
import lombok.AllArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.core.env.Environment;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.annotation.PostConstruct;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import static com.flowci.core.secret.domain.Secret.Category.KUBE_CONFIG;
import static com.flowci.core.secret.domain.Secret.Category.SSH_RSA;
@Log4j2
@Service
public class AgentHostServiceImpl implements AgentHostService {
private static final String DefaultWorkspace = "/ws";
private static final String DockerSock = "/var/run/docker.sock";
private static final String ContainerNamePrefix = "flowci-agent";
private final Map<Class<?>, HostAdaptor> mapping = new HashMap<>(3);
private final Cache<AgentHost, DockerManager> poolManagerCache =
CacheHelper.createLocalCache(10, 600, new PoolManagerRemover());
@Autowired
private Environment environment;
@Autowired
private AppProperties appProperties;
@Autowired
private AgentDao agentDao;
@Autowired
private AgentHostDao agentHostDao;
@Autowired
private SpringEventManager eventManager;
@Autowired
private TaskExecutor appTaskExecutor;
@Autowired
private DockerManager dockerManager;
@Autowired
private SpringTaskManager taskManager;
@Autowired
private AgentService agentService;
@Autowired
private SettingService settingService;
{
mapping.put(LocalUnixAgentHost.class, new LocalSocketHostAdaptor());
mapping.put(SshAgentHost.class, new SshHostAdaptor());
mapping.put(K8sAgentHost.class, new K8sHostAdaptor());
}
@PostConstruct
public void init() {
autoCreateLocalAgentHost();
syncAgents();
}
//====================================================================
// %% Public functions
//====================================================================
@Override
public AgentHost createOrUpdate(AgentHost host) {
if (StringHelper.hasValue(host.getId())) {
agentHostDao.save(host);
poolManagerCache.invalidate(host);
return host;
}
mapping.get(host.getClass()).create(host);
return host;
}
@Override
public AgentHost disableOrEnable(String name, boolean value) {
AgentHost host = get(name);
host.setDisabled(value);
return agentHostDao.save(host);
}
@Override
public AgentHost delete(String name) {
AgentHost host = get(name);
agentHostDao.deleteById(host.getId());
appTaskExecutor.execute(() -> {
removeAll(host);
});
return host;
}
@Override
public List<AgentHost> list() {
return agentHostDao.findAll();
}
@Override
public AgentHost get(String name) {
Optional<AgentHost> optional = agentHostDao.findByName(name);
if (optional.isPresent()) {
return optional.get();
}
throw new NotFoundException("Agent host {0} not found", name);
}
@Override
public void sync(AgentHost host) {
Optional<DockerManager> optional = getDockerManager(host);
if (!optional.isPresent()) {
log.warn("Fail to get pool manager of host: {}", host.getName());
return;
}
ContainerManager cm = optional.get().getContainerManager();
List<Unit> containerList;
try {
containerList = cm.list(null, ContainerNamePrefix + "*");
} catch (Exception e) {
log.warn("Cannot list containers of host {}", host.getName());
return;
}
Set<AgentItemWrapper> containerSet = AgentItemWrapper.toSet(containerList);
List<Agent> agentList = agentDao.findAllByHostId(host.getId());
Set<AgentItemWrapper> agentSet = AgentItemWrapper.toSet(agentList);
// find and remove containers are not belong to host
containerSet.removeAll(agentSet);
for (AgentItemWrapper item : containerSet) {
try {
List<Unit> list = cm.list(null, item.getName());
if (list.size() > 0) {
cm.delete(list.get(0).getId());
}
log.info("Agent {} has been cleaned up", item.getName());
} catch (Exception ignore) {
}
}
}
@Override
public boolean start(AgentHost host) {
Optional<DockerManager> manager = getDockerManager(host);
if (!manager.isPresent()) {
log.warn("Fail to get pool manager of host: {}", host.getName());
return false;
}
if (host.isDisabled()) {
log.info("Agent host {} is disabled", host.getName());
return false;
}
log.info("try to start agent from host {}", host.getName());
List<Agent> agents = agentDao.findAllByHostId(host.getId());
List<Agent> startList = new LinkedList<>();
DockerManager dockerManager = manager.get();
ContainerManager cm = dockerManager.getContainerManager();
// try to resume if offline, add to start list if resume failed
for (Agent agent : agents) {
if (!agent.isOffline()) {
continue;
}
try {
List<Unit> list = cm.list(null, getContainerName(agent));
// container not exist
if (list.isEmpty()) {
startList.add(agent);
continue;
}
Unit container = list.get(0);
cm.resume(container.getId());
log.info("Agent {} been resumed", agent.getName());
return true;
} catch (Exception e) {
log.warn("Unable to resume agent {}", agent.getName());
startList.add(agent);
}
}
// start from offline, and delete if cannot be started
for (Agent agent : startList) {
try {
StartOption startOption = mapping.get(host.getClass()).buildStartOption(host, agent);
cm.start(startOption);
log.info("Agent {} been started", agent.getName());
return true;
} catch (Exception e) {
log.warn("Unable to restart agent {}", agent.getName());
//TODO: send notification
agentService.delete(agent);
agents.remove(agent);
}
}
// create new agent
if (agents.size() < host.getMaxSize()) {
String random = StringHelper.randomString(5);
String name = String.format("%s-%s", host.getName(), random);
Agent agent = null;
try {
agent = agentService.create(new AgentOption()
.setName(name)
.setTags(host.getTags())
.setExitOnIdle(host.getExitOnIdle())
.setHostId(host.getId())
);
StartOption startOption = mapping.get(host.getClass()).buildStartOption(host, agent);
String cid = cm.start(startOption);
agent.setContainerId(cid);
agentService.update(agent, Agent.Status.STARTING);
log.info("Agent {} been created and started", name);
return true;
} catch (Exception e) {
if (agent != null) {
agentService.delete(agent);
log.warn("Unable to start created agent {}, since {}", agent.getName(), e.getMessage());
}
return false;
}
}
log.warn("Unable to start agent since over the limit size {}", host.getMaxSize());
return false;
}
@Override
public int size(AgentHost host) {
Optional<DockerManager> optional = getDockerManager(host);
if (!optional.isPresent()) {
log.warn("Fail to get pool manager of host: {}", host.getName());
return -1;
}
try {
return optional.get().getContainerManager().list(null, ContainerNamePrefix + "*").size();
} catch (Exception e) {
log.warn("Cannot get container size of host {}", host.getName());
return -1;
}
}
@Override
public void testConn(AgentHost host) {
appTaskExecutor.execute(() -> getDockerManager(host));
}
@Override
public void collect(AgentHost host) {
Optional<DockerManager> optional = getDockerManager(host);
if (!optional.isPresent()) {
log.warn("unable to collect agents in host {} since fail to get pool manager", host.getName());
return;
}
DockerManager manager = optional.get();
List<Agent> agents = agentDao.findAllByHostId(host.getId());
for (Agent agent : agents) {
// delete agent if not started after 60 seconds
if (agent.isStartingOver(60)) {
try {
manager.getContainerManager().delete(agent.getContainerId());
agentService.delete(agent);
log.info("Agent {} is collected since not started over 60 seconds", agent.getName());
} catch (Exception e) {
log.warn("failed to collect agent {} : {}", agent.getName(), e.getMessage());
}
}
}
}
@Override
public void removeAll(AgentHost host) {
List<Agent> list = agentDao.findAllByHostId(host.getId());
for (Agent agent : list) {
agentDao.delete(agent);
}
Optional<DockerManager> optional = getDockerManager(host);
if (!optional.isPresent()) {
log.warn("Fail to get pool manager of host: {}", host.getName());
return;
}
ContainerManager cm = optional.get().getContainerManager();
try {
List<Unit> containers = cm.list(null, ContainerNamePrefix + "*");
for (Unit c : containers) {
cm.delete(c.getId());
}
} catch (Exception e) {
log.warn(e.getMessage());
}
}
@Scheduled(cron = "0 0/5 * * * ?")
public void scheduleCollect() {
taskManager.run("agent-host-collect", false, () -> {
for (AgentHost host : list()) {
collect(host);
}
});
}
//====================================================================
// %% Internal events
//====================================================================
@EventListener
public void onNoIdleAgent(NoIdleAgentEvent event) {
Set<String> agentTags = event.getSelector().getLabel();
List<AgentHost> hosts = agentTags.isEmpty() ? list() : agentHostDao.findAllByTagsIn(agentTags);
if (hosts.isEmpty()) {
log.warn("Unable to find matched agent host for job {}", event.getJobId());
return;
}
for (AgentHost host : hosts) {
if (start(host)) {
return;
}
}
}
//====================================================================
// %% Private functions
//====================================================================
private String getContainerName(Agent agent) {
return String.format("%s-%s", ContainerNamePrefix, StringHelper.escapeNumber(agent.getName()));
}
private void autoCreateLocalAgentHost() {
if (!appProperties.isAutoLocalAgentHost()) {
return;
}
try {
LocalUnixAgentHost host = new LocalUnixAgentHost();
host.setName("localhost");
createOrUpdate(host);
log.info("Local unix agent host been created");
} catch (NotAvailableException e) {
log.warn(e.getMessage());
}
}
private void syncAgents() {
for (AgentHost host : list()) {
try {
sync(host);
} catch (Exception e) {
log.warn(e.getMessage());
}
}
}
/**
* Load or init pool manager from local cache for each agent host
*/
private Optional<DockerManager> getDockerManager(AgentHost host) {
DockerManager manager = poolManagerCache.get(host, (h) -> {
try {
return mapping.get(host.getClass()).init(host);
} catch (Exception e) {
log.warn(e.getMessage());
host.setError(e.getMessage());
}
return null;
});
if (Objects.isNull(manager)) {
updateAgentHostStatus(host, AgentHost.Status.Disconnected);
return Optional.empty();
}
host.setError(null);
updateAgentHostStatus(host, AgentHost.Status.Connected);
return Optional.of(manager);
}
private void updateAgentHostStatus(AgentHost host, AgentHost.Status newStatus) {
if (!agentHostDao.existsById(host.getId())) {
return;
}
host.setStatus(newStatus);
agentHostDao.save(host);
eventManager.publish(new AgentHostStatusEvent(this, host));
}
//====================================================================
// %% Private classes
//====================================================================
private Secret getSecret(String secret, Secret.Category expected) {
GetSecretEvent event = new GetSecretEvent(this, secret);
eventManager.publish(event);
Secret c = event.getFetched();
Preconditions.checkArgument(c != null, "Secret not found");
Preconditions.checkArgument(c.getCategory() == expected, "Invalid secret category");
return c;
}
private interface HostAdaptor {
void create(AgentHost host);
DockerManager init(AgentHost host) throws Exception;
StartOption buildStartOption(AgentHost host, Agent agent);
}
private abstract class AbstractHostAdaptor implements HostAdaptor {
protected void initStartOption(StartOption option, Agent agent) {
option.setImage(environment.getProperty(Variables.Agent.DockerImage, "flowci/agent"));
option.setName(getContainerName(agent));
option.addEnv(Variables.Agent.ServerUrl, settingService.get().getServerUrl());
option.addEnv(Variables.Agent.Token, agent.getToken());
option.addEnv(Variables.Agent.LogLevel, System.getenv(Variables.App.LogLevel));
option.addEnv(Variables.Agent.Volumes, System.getenv(Variables.Agent.Volumes));
option.addEnv(Variables.Agent.Workspace, DefaultWorkspace);
}
}
private class K8sHostAdaptor extends AbstractHostAdaptor {
@Override
public void create(AgentHost host) {
K8sAgentHost k8sHost = (K8sAgentHost) host;
Preconditions.checkArgument(k8sHost.getSecret() != null, "Secret name must be defined");
agentHostDao.insert(k8sHost);
}
@Override
public DockerManager init(AgentHost host) throws Exception {
K8sAgentHost k8sHost = (K8sAgentHost) host;
KubeConfigSecret secret = (KubeConfigSecret) getSecret(k8sHost.getSecret(), KUBE_CONFIG);
String namespace = k8sHost.getNamespace();
K8sOption option = new KubeConfigOption(namespace, secret.getContent().getData());
K8sManager manager = new K8sManager(option);
// check namespace
if (!manager.hasNamespace()) {
throw new Exception(String.format("namespace '%s' not exist", namespace));
}
log.debug("k8s manager initialized");
return manager;
}
@Override
public StartOption buildStartOption(AgentHost host, Agent agent) {
PodStartOption option = new PodStartOption();
initStartOption(option, agent);
option.setLabel(ContainerNamePrefix);
option.addEnv(Variables.Agent.K8sEnabled, Boolean.TRUE.toString());
option.addEnv(Variables.Agent.K8sInCluster, Boolean.TRUE.toString());
// TODO: check is deployed in the k8s cluster
return option;
}
}
private class LocalSocketHostAdaptor extends AbstractHostAdaptor {
@Override
public void create(AgentHost host) {
if (hasCreated()) {
throw new NotAvailableException("Local unix socket agent host been created");
}
if (!Files.exists(Paths.get("/var/run/docker.sock"))) {
deleteIfExist();
throw new NotAvailableException("Docker socket not available");
}
try {
host.setCreatedBy(User.DefaultSystemUser);
agentHostDao.insert(host);
} catch (Exception e) {
log.warn("Unable to create local unix socket agent host: {}", e.getMessage());
throw new NotAvailableException(e.getMessage());
}
}
@Override
public DockerManager init(AgentHost host) {
return dockerManager;
}
@Override
public StartOption buildStartOption(AgentHost host, Agent agent) {
ContainerStartOption option = new ContainerStartOption();
initStartOption(option, agent);
option.addBind(DockerSock, DockerSock);
return option;
}
private boolean hasCreated() {
return agentHostDao.findAllByType(AgentHost.Type.LocalUnixSocket).size() > 0;
}
private void deleteIfExist() {
List<AgentHost> hosts = agentHostDao.findAllByType(AgentHost.Type.LocalUnixSocket);
if (hosts.isEmpty()) {
return;
}
agentHostDao.deleteAll(hosts);
}
}
private class SshHostAdaptor extends AbstractHostAdaptor {
@Override
public void create(AgentHost host) {
SshAgentHost sshHost = (SshAgentHost) host;
Preconditions.checkArgument(sshHost.getSecret() != null, "Secret name must be defined");
agentHostDao.insert(sshHost);
}
@Override
public DockerManager init(AgentHost host) throws Exception {
SshAgentHost sshHost = (SshAgentHost) host;
RSASecret rsa = (RSASecret) getSecret(sshHost.getSecret(), SSH_RSA);
SSHOption option = SSHOption.of(rsa.getPrivateKey(), sshHost.getIp(), sshHost.getUser(), sshHost.getPort());
return new DockerSSHManager(option);
}
@Override
public StartOption buildStartOption(AgentHost host, Agent agent) {
ContainerStartOption option = new ContainerStartOption();
initStartOption(option, agent);
option.addBind(DockerSock, DockerSock);
return option;
}
}
@AllArgsConstructor(staticName = "of")
public static class AgentItemWrapper {
public static <T> Set<AgentItemWrapper> toSet(List<T> list) {
Set<AgentItemWrapper> set = new HashSet<>(list.size());
Iterator<T> iterator = list.iterator();
for (; iterator.hasNext(); ) {
set.add(AgentItemWrapper.of(iterator.next()));
iterator.remove();
}
return set;
}
private final Object object;
public String getName() {
if (object instanceof Agent) {
return ((Agent) object).getName();
}
if (object instanceof Unit) {
return ((Unit) object).getName();
}
throw new IllegalArgumentException();
}
@Override
public boolean equals(Object o) {
if (o instanceof AgentItemWrapper) {
AgentItemWrapper obj = (AgentItemWrapper) o;
return this.getName().equals(obj.getName());
}
return false;
}
@Override
public int hashCode() {
return this.getName().hashCode();
}
}
@Log4j2
private static class PoolManagerRemover implements RemovalListener<AgentHost, DockerManager> {
@Override
public void onRemoval(@Nullable AgentHost agentHost,
@Nullable DockerManager dockerManager,
@Nonnull RemovalCause removalCause) {
if (dockerManager != null) {
try {
dockerManager.close();
} catch (Exception e) {
log.warn("Unable to close agent host", e);
}
}
if (agentHost != null) {
log.info("Agent pool manager for host {} been closed", agentHost.getName());
}
}
}
}