/
AppDetailTask.java
292 lines (265 loc) · 11.9 KB
/
AppDetailTask.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
package io.pivotal.cfapp.task;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.cloudfoundry.client.v2.ClientV2Exception;
import org.cloudfoundry.client.v2.applications.ApplicationStatisticsRequest;
import org.cloudfoundry.client.v2.applications.ApplicationStatisticsResponse;
import org.cloudfoundry.client.v2.applications.InstanceStatistics;
import org.cloudfoundry.client.v2.applications.Statistics;
import org.cloudfoundry.client.v2.applications.SummaryApplicationRequest;
import org.cloudfoundry.client.v2.applications.Usage;
import org.cloudfoundry.operations.DefaultCloudFoundryOperations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
import io.pivotal.cfapp.config.PasSettings;
import io.pivotal.cfapp.domain.AppDetail;
import io.pivotal.cfapp.domain.Buildpack;
import io.pivotal.cfapp.domain.Space;
import io.pivotal.cfapp.domain.Stack;
import io.pivotal.cfapp.domain.product.PivnetCache;
import io.pivotal.cfapp.event.AppDetailReadyToBeRetrievedEvent;
import io.pivotal.cfapp.event.AppDetailRetrievedEvent;
import io.pivotal.cfapp.service.AppDetailService;
import io.pivotal.cfapp.service.BuildpacksCache;
import io.pivotal.cfapp.service.EventsService;
import io.pivotal.cfapp.service.StacksCache;
import lombok.extern.slf4j.Slf4j;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@Slf4j
@Component
public class AppDetailTask implements ApplicationListener<AppDetailReadyToBeRetrievedEvent> {
private final PasSettings settings;
private final DefaultCloudFoundryOperations opsClient;
private final AppDetailService appDetailsService;
private final EventsService eventsService;
private final BuildpacksCache buildpacksCache;
private final StacksCache stacksCache;
private final ApplicationEventPublisher publisher;
private final PivnetCache pivnetCache;
private final AppDetailReadyToBeCollectedDecider appDetailReadyToBeCollectedDecider;
@Autowired
public AppDetailTask(
PivnetCache pivnetCache,
PasSettings settings,
DefaultCloudFoundryOperations opsClient,
AppDetailService appDetailsService,
EventsService eventsService,
BuildpacksCache buildpacksCache,
StacksCache stacksCache,
ApplicationEventPublisher publisher,
AppDetailReadyToBeCollectedDecider appDetailReadyToBeCollectedDecider) {
this.pivnetCache = pivnetCache;
this.settings = settings;
this.opsClient = opsClient;
this.appDetailsService = appDetailsService;
this.eventsService = eventsService;
this.buildpacksCache = buildpacksCache;
this.stacksCache = stacksCache;
this.publisher = publisher;
this.appDetailReadyToBeCollectedDecider = appDetailReadyToBeCollectedDecider;
}
private DefaultCloudFoundryOperations buildClient(Space target) {
return DefaultCloudFoundryOperations
.builder()
.from(opsClient)
.organization(target.getOrganizationName())
.space(target.getSpaceName())
.build();
}
public void collect(List<Space> spaces) {
log.info("AppDetailTask started");
appDetailsService
.deleteAll()
.thenMany(Flux.fromIterable(spaces))
.concatMap(this::listApplications)
.flatMap(this::getSummaryInfo)
.flatMap(this::getStatistics)
.flatMap(this::getLastEvent)
.flatMap(appDetailsService::save)
.thenMany(appDetailsService.findAll())
.collectList()
.subscribe(
result -> {
publisher.publishEvent(new AppDetailRetrievedEvent(this).detail(result));
log.info("AppDetailTask completed");
},
error -> {
log.error("AppDetailTask terminated with error", error);
}
);
}
private String getBuildpack(String buildpackId) {
Buildpack buildpack = buildpacksCache.getBuildpackById(buildpackId);
if (buildpack != null) {
return settings.getBuildpack(buildpack.getName());
}
return null;
}
private String getBuildpackLatestVersion(String buildpackId) {
return pivnetCache.findLatestProductReleaseBySlug(getBuildpack(buildpackId) + "-buildpack").getVersion();
}
private LocalDateTime getBuildpackReleaseDate(String buildpackId) {
LocalDate releaseDate = pivnetCache.findLatestProductReleaseBySlug(getBuildpack(buildpackId) + "-buildpack").getReleaseDate();
if (releaseDate != null){
return releaseDate.atStartOfDay();
}
return null;
}
private String getBuildpackReleaseNotesUrl(String buildpackId) {
return pivnetCache.findLatestProductReleaseBySlug(getBuildpack(buildpackId) + "-buildpack").getReleaseNotesUrl();
}
private String getBuildpackReleaseType(String buildpackId) {
return pivnetCache.findLatestProductReleaseBySlug(getBuildpack(buildpackId) + "-buildpack").getReleaseType();
}
private String getBuildpackVersion(String buildpackId) {
Buildpack buildpack = buildpacksCache.getBuildpackById(buildpackId);
if (buildpack != null) {
return buildpack.getVersion();
}
return null;
}
protected Mono<AppDetail> getLastEvent(AppDetail fragment) {
log.trace("Fetching last event for application id={}, name={} in org={}, space={}", fragment.getAppId(), fragment.getAppName(), fragment.getOrganization(), fragment.getSpace());
return eventsService.getEvents(fragment.getAppId(), 1)
.flatMapMany(envelope -> eventsService.toFlux(envelope))
.next()
.map(e ->
AppDetail
.from(fragment)
.lastEvent(e.getType())
.lastEventActor(e.getActor())
.lastEventTime(e.getTime())
.build()
)
.defaultIfEmpty(fragment);
}
protected Mono<AppDetail> getStatistics(AppDetail fragment) {
log.trace("Fetching application statistics for org={}, space={}, id={}, name={}", fragment.getOrganization(), fragment.getSpace(), fragment.getAppId(), fragment.getAppName());
return buildClient(buildSpace(fragment.getOrganization(), fragment.getSpace()))
.getCloudFoundryClient()
.applicationsV2()
.statistics(ApplicationStatisticsRequest.builder().applicationId(fragment.getAppId()).build())
.map(stats ->
AppDetail
.from(fragment)
.diskUsed(nullSafeDiskUsed(stats))
.memoryUsed(nullSafeMemoryUsed(stats))
.build()
)
.onErrorResume(ClientV2Exception.class, e -> Mono.just(fragment));
}
protected Mono<AppDetail> getSummaryInfo(AppDetail fragment) {
log.trace("Fetching application summary for org={}, space={}, id={}, name={}", fragment.getOrganization(), fragment.getSpace(), fragment.getAppId(), fragment.getAppName());
return opsClient
.getCloudFoundryClient()
.applicationsV2()
.summary(SummaryApplicationRequest.builder().applicationId(fragment.getAppId()).build())
.map(sar ->
AppDetail
.from(fragment)
.buildpack(getBuildpack(sar.getDetectedBuildpackId()))
.buildpackVersion(getBuildpackVersion(sar.getDetectedBuildpackId()))
.image(sar.getDockerImage())
.stack(nullSafeStack(sar.getStackId()))
.lastPushed(nullSafeLocalDateTime(sar.getPackageUpdatedAt()))
.buildpackReleaseType(getBuildpackReleaseType(sar.getDetectedBuildpackId()))
.buildpackReleaseDate(getBuildpackReleaseDate(sar.getDetectedBuildpackId()))
.buildpackLatestVersion(getBuildpackLatestVersion(sar.getDetectedBuildpackId()))
.buildpackLatestUrl(getBuildpackReleaseNotesUrl(sar.getDetectedBuildpackId()))
.build()
)
.onErrorResume(ClientV2Exception.class, e -> Mono.just(fragment));
}
@Override
public void onApplicationEvent(AppDetailReadyToBeRetrievedEvent event) {
if (appDetailReadyToBeCollectedDecider.isDecided()) {
collect(List.copyOf(appDetailReadyToBeCollectedDecider.getSpaces()));
appDetailReadyToBeCollectedDecider.reset();
}
}
protected Flux<AppDetail> listApplications(Space target) {
return
buildClient(target)
.applications()
.list()
.map(as ->
AppDetail
.builder()
.appId(as.getId())
.appName(as.getName())
.organization(target.getOrganizationName())
.space(target.getSpaceName())
.runningInstances(nullSafeInteger(as.getRunningInstances()))
.totalInstances(nullSafeInteger(as.getInstances()))
.requestedState(as.getRequestedState().toLowerCase())
.urls(as.getUrls())
.build()
);
}
private String nullSafeStack(String stackId) {
Stack stack = stacksCache.getStackById(stackId);
if (stack != null) {
return stack.getName();
}
return "unknown";
}
private static Space buildSpace(String organization, String space) {
return Space
.builder()
.organizationName(organization)
.spaceName(space)
.build();
}
private static Long nullSafeDiskUsed(ApplicationStatisticsResponse stats) {
Long result = 0L;
Map<String, InstanceStatistics> instances = stats.getInstances();
if (instances != null) {
Statistics innerStats;
for (InstanceStatistics is: instances.values()) {
innerStats = is.getStatistics();
Usage usage;
if (innerStats != null) {
usage = innerStats.getUsage();
if (usage != null && usage.getDisk() != null) {
result += usage.getDisk();
}
}
}
}
return result;
}
private static Integer nullSafeInteger(Integer value) {
return value != null ? value: 0;
}
private static LocalDateTime nullSafeLocalDateTime(String value) {
return StringUtils.isNotBlank(value)
? Instant.parse(value).atZone(ZoneId.systemDefault()).toLocalDateTime()
: null;
}
private static Long nullSafeMemoryUsed(ApplicationStatisticsResponse stats) {
Long result = 0L;
Map<String, InstanceStatistics> instances = stats.getInstances();
if (instances != null) {
Statistics innerStats;
for (InstanceStatistics is: instances.values()) {
innerStats = is.getStatistics();
Usage usage;
if (innerStats != null) {
usage = innerStats.getUsage();
if (usage != null && usage.getMemory() != null) {
result += usage.getMemory();
}
}
}
}
return result;
}
}