This repository was archived by the owner on Oct 20, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathSubscriptionManager.java
More file actions
360 lines (306 loc) · 15 KB
/
Copy pathSubscriptionManager.java
File metadata and controls
360 lines (306 loc) · 15 KB
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
/*
* Copyright (C) 2015 Orange
*
* This software is distributed under the terms and conditions of the 'GNU GENERAL PUBLIC LICENSE
* Version 2' license which can be found in the file 'LICENSE.txt' in this package distribution or
* at 'http://www.gnu.org/licenses/gpl-2.0-standalone.html'.
*/
package com.orange.cepheus.cep;
import com.orange.cepheus.cep.model.Attribute;
import com.orange.cepheus.cep.model.Configuration;
import com.orange.cepheus.cep.model.EventTypeIn;
import com.orange.cepheus.cep.model.Provider;
import com.orange.cepheus.cep.tenant.TenantFilter;
import com.orange.ngsi.client.NgsiClient;
import com.orange.ngsi.model.EntityId;
import com.orange.ngsi.model.SubscribeContext;
import com.orange.ngsi.model.SubscribeError;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.http.HttpHeaders;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.stereotype.Component;
import javax.annotation.PreDestroy;
import java.io.IOException;
import java.net.URI;
import java.time.Duration;
import java.time.Instant;
import java.util.*;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.stream.Collectors;
/**
* SubscriptionManager manage subscriptions of EventTypeIn to provider
* When a configuration is loaded, SubscriptionManager send subscription to every provider
* Every five minutes SubscriptionManager verify if subscription is valid
*/
@Component()
public class SubscriptionManager {
private static Logger logger = LoggerFactory.getLogger(SubscriptionManager.class);
/**
* Inner class for concurrent subscriptions tracking using a RW lock.
*/
private static class Subscriptions {
private HashSet<String> subscriptionIds = new HashSet<>();
private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
public boolean isSubscriptionValid(String subscriptionId) {
try {
readWriteLock.readLock().lock();
return subscriptionIds.contains(subscriptionId);
} finally {
readWriteLock.readLock().unlock();
}
}
private void addSubscription(String subscriptionId) {
try {
readWriteLock.writeLock().lock();
subscriptionIds.add(subscriptionId);
} finally {
readWriteLock.writeLock().unlock();
}
}
private void removeSubscription(String subscriptionId) {
try {
readWriteLock.writeLock().lock();
subscriptionIds.remove(subscriptionId);
} finally {
readWriteLock.writeLock().unlock();
}
}
}
/**
* Periodicity of the subscription task. Default: every 5 min.
* Must be smaller than the subscription duration !
*/
@Value("${subscriptionManager.periodicity:300000}")
private long subscriptionPeriodicity;
/**
* Duration of a NGSI subscription as text.
*/
@Value("${subscriptionManager.duration:PT1H}")
private String subscriptionDuration;
@Value("${subscriptionManager.validateSubscriptionsId:true}")
private boolean validateSubscriptionsId;
@Autowired
private NgsiClient ngsiClient;
@Autowired
private TaskScheduler taskScheduler;
private List<EventTypeIn> eventTypeIns = Collections.emptyList();
private Subscriptions subscriptions = new Subscriptions();
private ScheduledFuture scheduledFuture;
private URI hostURI;
@Autowired(required=false)
TenantFilter tenantFilter;
/**
* Update subscription to new provider of the incoming events defined in the Configuration
*
* @param configuration the new configuration
*/
public void setConfiguration(Configuration configuration) {
hostURI = configuration.getHost();
// Use a new subscription set on each new configuration
// this prevents active subscription tasks to add subscription ids from the previous configuration
// this will also copy the subscription information of the previous configuration to this new configuration
subscriptions = migrateSubscriptions(configuration);
// Keep a reference to configuration for next migration
eventTypeIns = configuration.getEventTypeIns();
if(tenantFilter!=null){
for (EventTypeIn eventType : configuration.getEventTypeIns()) {
for (Provider provider : eventType.getProviders()) {
tenantFilter.getClientProviderMap().put(provider.getServiceName()+provider.getServicePath(), configuration.getService()+configuration.getServicePath());
}
}
}
// TODO : send unsubscribeContext with removedEventTypesIn
// force launch of subscription process for new or invalid subscriptions
scheduleSubscriptionTask();
}
/**
* Check that a given subscription is valid
* unsubscribe if is invalid
*
* @param subscriptionId the id of subscription
* @return true if subscription is valid
*/
public boolean validateSubscriptionId(String subscriptionId, String originatorUrl) {
if (validateSubscriptionsId) {
boolean isValid = subscriptions.isSubscriptionValid(subscriptionId);
if (!isValid) {
logger.warn("unsubscribeContext request: clean invalid subscription id {} / {}", subscriptionId, originatorUrl);
//TODO: add support multi-tenant subscription
ngsiClient.unsubscribeContext(originatorUrl, null, subscriptionId).addCallback(
unsubscribeContextResponse ->
logger.debug("unsubscribeContext completed for {}", originatorUrl),
throwable ->
logger.warn("unsubscribeContext failed for {}", originatorUrl, throwable)
);
}
return isValid;
}
return true;
}
@PreDestroy
public void shutdownGracefully() {
logger.info("Shutting down SubscriptionManager (cleanup subscriptions)");
// Cancel the scheduled subscription task
if (scheduledFuture != null) {
scheduledFuture.cancel(true);
}
// Unsubscribe from all providers
eventTypeIns.forEach(eventTypeIn -> eventTypeIn.getProviders().forEach(this::unsubscribeProvider));
// Try to stop gracefully (letting all unsubscribe complete)
try {
ngsiClient.shutdownGracefully();
} catch (IOException e) {
logger.warn("Failed to shutdown gracefully NGSI pending requests", e);
}
}
/**
* Cancel any previous schedule, run subscription task immediately and schedule it again.
*/
private void scheduleSubscriptionTask() {
if (scheduledFuture != null) {
scheduledFuture.cancel(false);
}
scheduledFuture = taskScheduler.scheduleWithFixedDelay(this::periodicSubscriptionTask, subscriptionPeriodicity);
}
private void periodicSubscriptionTask() {
Instant now = Instant.now();
Instant nextSubscriptionTaskDate = now.plusMillis(subscriptionPeriodicity);
logger.info("Launch of the periodic subscription task at {}", now.toString());
// Futures will use the current subscription list.
// So that they will not add old subscriptions to a new configuration.
Subscriptions subscriptions = this.subscriptions;
for (EventTypeIn eventType : eventTypeIns) {
SubscribeContext subscribeContext = null;
for (Provider provider : eventType.getProviders()) {
boolean deadlineIsPassed = false;
Instant subscriptionDate = provider.getSubscriptionDate();
if (subscriptionDate != null) {
Instant subscriptionEndDate = subscriptionDate.plus(Duration.parse(subscriptionDuration));
// check if deadline is passed
if (nextSubscriptionTaskDate.compareTo(subscriptionEndDate) >= 0) {
deadlineIsPassed = true;
String subscriptionId = provider.getSubscriptionId();
// if delay is passed then clear the subscription info in provider et suppress subscription
if (subscriptionId != null) {
subscriptions.removeSubscription(subscriptionId);
provider.setSubscriptionId(null);
provider.setSubscriptionDate(null);
}
}
}
//Send subscription if subscription is a new subscription or we do not receive a response (subscriptionDate is null)
//Send subscription if deadline is passed
if ((subscriptionDate == null) || deadlineIsPassed) {
// lazy build body request only when the first request requires it
if (subscribeContext == null) {
subscribeContext = buildSubscribeContext(eventType);
}
subscribeProvider(provider, subscribeContext, subscriptions);
}
}
}
}
/**
* Subscribe to a provider
* @param provider
* @param subscribeContext
* @param subscriptions
*/
private void subscribeProvider(Provider provider, SubscribeContext subscribeContext, Subscriptions subscriptions) {
logger.debug("Subscribe to {} for {}", provider.getUrl(), subscribeContext.toString());
ngsiClient.subscribeContext(provider.getUrl(), getHeadersForProvider(provider), subscribeContext).addCallback(subscribeContextResponse -> {
SubscribeError error = subscribeContextResponse.getSubscribeError();
if (error == null) {
String subscriptionId = subscribeContextResponse.getSubscribeResponse().getSubscriptionId();
provider.setSubscriptionDate(Instant.now());
provider.setSubscriptionId(subscriptionId);
subscriptions.addSubscription(subscriptionId);
logger.debug("Subscription done for {}", provider.getUrl());
} else {
logger.warn("Error during subscription for {}: {}", provider.getUrl(), error.getErrorCode());
}
}, throwable -> {
logger.warn("Error during subscription for {}", provider.getUrl(), throwable);
});
}
/**
* Unsubscribe from a provider
* @param provider the provider to unusubscribe from
*/
private void unsubscribeProvider(Provider provider) {
final String subscriptionID = provider.getSubscriptionId();
if (subscriptionID != null) {
logger.debug("Unsubscribe from {} for {}", provider.getUrl(), provider.getSubscriptionId());
// Don't wait for result, remove immediately from subscriptions list
subscriptions.removeSubscription(subscriptionID);
ngsiClient.unsubscribeContext(provider.getUrl(), getHeadersForProvider(provider), provider.getSubscriptionId()).addCallback(
response -> logger.debug("Unsubscribe response for {}: {}", subscriptionID, response.getStatusCode().getCode()),
throwable -> logger.debug("Error during unsubscribe for {}", subscriptionID, throwable));
// Reset provider subscription data
provider.setSubscriptionDate(null);
provider.setSubscriptionId(null);
}
}
private SubscribeContext buildSubscribeContext(EventTypeIn eventType) {
SubscribeContext subscribeContext = new SubscribeContext();
EntityId entityId = new EntityId(eventType.getId(), eventType.getType(), eventType.isPattern());
subscribeContext.setEntityIdList(Collections.singletonList(entityId));
subscribeContext.setAttributeList(eventType.getAttributes().stream().map(Attribute::getName).collect(Collectors.toList()));
subscribeContext.setReference(hostURI.resolve("/ngsi10/notifyContext"));
subscribeContext.setDuration(subscriptionDuration);
return subscribeContext;
}
/**
* Migrate subscriptions from previous configuration to the new configuration
* @param configuration the new configuration where the subscriptions must be inserted
* @return the list of id of the migrated subscriptions
*/
private Subscriptions migrateSubscriptions(Configuration configuration) {
Subscriptions newSubscriptions = new Subscriptions();
// For every previous eventType, find the corresponding one in new configuration
eventTypeIns.forEach(oldEventTypeIn -> {
Optional<EventTypeIn> maybeEventTypeIn =
configuration.getEventTypeIns().stream().filter(e -> e.equals(oldEventTypeIn)).findFirst();
if (maybeEventTypeIn.isPresent()) {
EventTypeIn newEventTypeIn = maybeEventTypeIn.get();
// For every previous provider, find the corresponding one in new configuration
oldEventTypeIn.getProviders().forEach(oldProvider -> {
Optional<Provider> optionalProvider =
newEventTypeIn.getProviders().stream().filter(p -> p.hasSameOrigin(oldProvider)).findFirst();
if (optionalProvider.isPresent()) {
Provider provider = optionalProvider.get();
// Migrate the subscription
provider.setSubscriptionId(oldProvider.getSubscriptionId());
provider.setSubscriptionDate(oldProvider.getSubscriptionDate());
newSubscriptions.addSubscription(oldProvider.getSubscriptionId());
} else {
// Provider not found in new configuration, unsubscribe from it
unsubscribeProvider(oldProvider);
}
});
} else {
// EventType not found in new configuration, unsubscribe from all providers
oldEventTypeIn.getProviders().forEach(this::unsubscribeProvider);
}
});
return newSubscriptions;
}
public HttpHeaders getHeadersForProvider(Provider provider) {
String serviceName = provider.getServiceName();
String servicePath = provider.getServicePath();
if (serviceName == null || serviceName.isEmpty() || servicePath == null || servicePath.isEmpty()) {
return null;
}
HttpHeaders httpHeaders = ngsiClient.getRequestHeaders(provider.getUrl());
httpHeaders.add("Fiware-Service", provider.getServiceName());
httpHeaders.add("Fiware-ServicePath", provider.getServicePath());
return httpHeaders;
}
}