edbf5880090b92fdf14981509165d8394cf262c7
[dcaegen2/collectors/datafile.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2019 Nordix Foundation.
4  * ================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  * SPDX-License-Identifier: Apache-2.0
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.dcaegen2.collectors.datafile.tasks;
22
23 import static org.awaitility.Awaitility.await;
24 import static org.junit.Assert.assertEquals;
25 import static org.junit.Assert.assertFalse;
26 import static org.junit.Assert.assertTrue;
27 import static org.mockito.ArgumentMatchers.any;
28 import static org.mockito.ArgumentMatchers.anyLong;
29 import static org.mockito.ArgumentMatchers.anyString;
30 import static org.mockito.ArgumentMatchers.notNull;
31 import static org.mockito.Mockito.doReturn;
32 import static org.mockito.Mockito.mock;
33 import static org.mockito.Mockito.spy;
34 import static org.mockito.Mockito.times;
35 import static org.mockito.Mockito.verify;
36 import static org.mockito.Mockito.verifyNoMoreInteractions;
37
38 import ch.qos.logback.classic.spi.ILoggingEvent;
39 import ch.qos.logback.core.read.ListAppender;
40
41 import java.nio.file.Paths;
42 import java.time.Duration;
43 import java.time.Instant;
44 import java.util.HashMap;
45 import java.util.LinkedList;
46 import java.util.List;
47 import java.util.Map;
48
49 import org.apache.commons.lang3.StringUtils;
50 import org.junit.jupiter.api.BeforeEach;
51 import org.junit.jupiter.api.Test;
52 import org.onap.dcaegen2.collectors.datafile.configuration.AppConfig;
53 import org.onap.dcaegen2.collectors.datafile.configuration.ConsumerConfiguration;
54 import org.onap.dcaegen2.collectors.datafile.configuration.ImmutableConsumerConfiguration;
55 import org.onap.dcaegen2.collectors.datafile.configuration.ImmutablePublisherConfiguration;
56 import org.onap.dcaegen2.collectors.datafile.configuration.PublisherConfiguration;
57 import org.onap.dcaegen2.collectors.datafile.exceptions.DatafileTaskException;
58 import org.onap.dcaegen2.collectors.datafile.ftp.Scheme;
59 import org.onap.dcaegen2.collectors.datafile.model.FileData;
60 import org.onap.dcaegen2.collectors.datafile.model.FilePublishInformation;
61 import org.onap.dcaegen2.collectors.datafile.model.FileReadyMessage;
62 import org.onap.dcaegen2.collectors.datafile.model.ImmutableFileData;
63 import org.onap.dcaegen2.collectors.datafile.model.ImmutableFilePublishInformation;
64 import org.onap.dcaegen2.collectors.datafile.model.ImmutableFileReadyMessage;
65 import org.onap.dcaegen2.collectors.datafile.model.ImmutableMessageMetaData;
66 import org.onap.dcaegen2.collectors.datafile.model.MessageMetaData;
67 import org.onap.dcaegen2.collectors.datafile.utils.LoggingUtils;
68 import org.onap.dcaegen2.services.sdk.rest.services.model.logging.MdcVariables;
69 import org.slf4j.MDC;
70
71 import reactor.core.publisher.Flux;
72 import reactor.core.publisher.Mono;
73 import reactor.test.StepVerifier;
74
75 public class ScheduledTasksTest {
76
77     private static final String PM_FILE_NAME = "A20161224.1030-1045.bin.gz";
78     private static final String CHANGE_IDENTIFIER = "PM_MEAS_FILES";
79
80     private AppConfig appConfig = mock(AppConfig.class);
81     private ScheduledTasks testedObject;
82
83     private int uniqueValue = 0;
84     private DMaaPMessageConsumer consumerMock;
85     private PublishedChecker publishedCheckerMock;
86     private FileCollector fileCollectorMock;
87     private DataRouterPublisher dataRouterMock;
88     private Map<String, String> contextMap = new HashMap<String, String>();
89
90     private final String publishUrl = "https://54.45.33.2:1234/unauthenticated.VES_NOTIFICATION_OUTPUT";
91
92     @BeforeEach
93     private void setUp() throws DatafileTaskException {
94         testedObject = spy(new ScheduledTasks(appConfig));
95
96         consumerMock = mock(DMaaPMessageConsumer.class);
97         publishedCheckerMock = mock(PublishedChecker.class);
98         fileCollectorMock = mock(FileCollector.class);
99         dataRouterMock = mock(DataRouterPublisher.class);
100
101         doReturn(consumerMock).when(testedObject).createConsumerTask();
102         doReturn(publishedCheckerMock).when(testedObject).createPublishedChecker();
103         doReturn(fileCollectorMock).when(testedObject).createFileCollector();
104         doReturn(dataRouterMock).when(testedObject).createDataRouterPublisher();
105     }
106
107     private void setUpConfiguration() throws DatafileTaskException {
108         final PublisherConfiguration dmaapPublisherConfiguration = ImmutablePublisherConfiguration.builder() //
109             .publishUrl(publishUrl) //
110             .logUrl("") //
111             .userName("userName") //
112             .passWord("passWord") //
113             .trustStorePath("trustStorePath") //
114             .trustStorePasswordPath("trustStorePasswordPath") //
115             .keyStorePath("keyStorePath") //
116             .keyStorePasswordPath("keyStorePasswordPath") //
117             .enableDmaapCertAuth(true) //
118             .changeIdentifier(CHANGE_IDENTIFIER) //
119             .build(); //
120         final ConsumerConfiguration dmaapConsumerConfiguration = ImmutableConsumerConfiguration.builder() //
121             .topicUrl("topicUrl").trustStorePath("trustStorePath") //
122             .trustStorePasswordPath("trustStorePasswordPath") //
123             .keyStorePath("keyStorePath") //
124             .keyStorePasswordPath("keyStorePasswordPath") //
125             .enableDmaapCertAuth(true) //
126             .build();
127
128         doReturn(dmaapPublisherConfiguration).when(appConfig).getPublisherConfiguration(CHANGE_IDENTIFIER);
129         doReturn(dmaapConsumerConfiguration).when(appConfig).getDmaapConsumerConfiguration();
130         doReturn(true).when(appConfig).isFeedConfigured(CHANGE_IDENTIFIER);
131     }
132
133     private MessageMetaData messageMetaData() {
134         return ImmutableMessageMetaData.builder() //
135             .productName("productName") //
136             .vendorName("") //
137             .lastEpochMicrosec("") //
138             .sourceName("") //
139             .startEpochMicrosec("") //
140             .timeZoneOffset("") //
141             .changeIdentifier(CHANGE_IDENTIFIER) //
142             .changeType("") //
143             .build();
144     }
145
146     private FileData fileData(int instanceNumber) {
147         return ImmutableFileData.builder() //
148             .name(PM_FILE_NAME + instanceNumber) //
149             .fileFormatType("") //
150             .fileFormatVersion("") //
151             .location("ftpes://192.168.0.101/ftp/rop/" + PM_FILE_NAME + instanceNumber) //
152             .scheme(Scheme.FTPS) //
153             .compression("") //
154             .messageMetaData(messageMetaData()) //
155             .build();
156     }
157
158     private List<FileData> files(int size, boolean uniqueNames) {
159         List<FileData> list = new LinkedList<FileData>();
160         for (int i = 0; i < size; ++i) {
161             if (uniqueNames) {
162                 ++uniqueValue;
163             }
164             list.add(fileData(uniqueValue));
165         }
166         return list;
167     }
168
169     private FileReadyMessage createFileReadyMessage(int numberOfFiles, boolean uniqueNames) {
170         return ImmutableFileReadyMessage.builder().files(files(numberOfFiles, uniqueNames)).build();
171     }
172
173     private Flux<FileReadyMessage> fileReadyMessageFlux(int numberOfEvents, int filesPerEvent, boolean uniqueNames) {
174         List<FileReadyMessage> list = new LinkedList<FileReadyMessage>();
175         for (int i = 0; i < numberOfEvents; ++i) {
176             list.add(createFileReadyMessage(filesPerEvent, uniqueNames));
177         }
178         return Flux.fromIterable(list);
179     }
180
181     private FilePublishInformation filePublishInformation() {
182         return ImmutableFilePublishInformation //
183             .builder() //
184             .productName("") //
185             .vendorName("") //
186             .lastEpochMicrosec("") //
187             .sourceName("") //
188             .startEpochMicrosec("") //
189             .timeZoneOffset("") //
190             .name("") //
191             .location("") //
192             .internalLocation(Paths.get("internalLocation")) //
193             .compression("") //
194             .fileFormatType("") //
195             .fileFormatVersion("") //
196             .changeIdentifier(CHANGE_IDENTIFIER) //
197             .context(new HashMap<String, String>()).build();
198     }
199
200     @Test
201     public void purgeFileCache() {
202         testedObject.publishedFilesCache.put(Paths.get("file.xml"));
203
204         testedObject.purgeCachedInformation(Instant.MAX);
205
206         assertEquals(0, testedObject.publishedFilesCacheSize());
207     }
208
209     @Test
210     public void nothingToConsume() throws DatafileTaskException {
211         setUpConfiguration();
212
213         doReturn(consumerMock).when(testedObject).createConsumerTask();
214         doReturn(Flux.empty()).when(consumerMock).getMessageRouterResponse();
215
216         testedObject.executeDatafileMainTask();
217
218         assertEquals(0, testedObject.getCurrentNumberOfTasks());
219         verify(consumerMock, times(1)).getMessageRouterResponse();
220         verifyNoMoreInteractions(consumerMock);
221     }
222
223     @Test
224     public void skippingConsumeDueToCurrentNumberOfTasksGreaterThan50() {
225         doReturn(51).when(testedObject).getCurrentNumberOfTasks();
226
227         testedObject.executeDatafileMainTask();
228
229         verifyNoMoreInteractions(consumerMock);
230     }
231
232     @Test
233     public void executeDatafileMainTask_successfulCase() throws DatafileTaskException {
234         setUpConfiguration();
235
236         final int noOfEvents = 1;
237         final int noOfFilesPerEvent = 1;
238
239         Flux<FileReadyMessage> fileReadyMessages = fileReadyMessageFlux(noOfEvents, noOfFilesPerEvent, true);
240         doReturn(fileReadyMessages).when(consumerMock).getMessageRouterResponse();
241
242         doReturn(false).when(publishedCheckerMock).isFilePublished(anyString(), any(), any());
243
244         Mono<FilePublishInformation> collectedFile = Mono.just(filePublishInformation());
245         doReturn(collectedFile).when(fileCollectorMock).collectFile(notNull(), anyLong(), notNull(), notNull());
246         doReturn(collectedFile).when(dataRouterMock).publishFile(notNull(), anyLong(), notNull());
247
248         testedObject.executeDatafileMainTask();
249
250         await().untilAsserted(() -> assertEquals(0, testedObject.getCurrentNumberOfSubscriptions()));
251
252         assertFalse(StringUtils.isBlank(MDC.get(MdcVariables.REQUEST_ID)));
253
254         verify(appConfig).getDmaapConsumerConfiguration();
255         verify(appConfig).isFeedConfigured(CHANGE_IDENTIFIER);
256         verifyNoMoreInteractions(appConfig);
257     }
258
259     @Test
260     public void executeDatafileMainTask_unconfiguredChangeIdentifier() throws DatafileTaskException {
261         final PublisherConfiguration dmaapPublisherConfiguration = ImmutablePublisherConfiguration.builder() //
262             .publishUrl(publishUrl) //
263             .logUrl("") //
264             .userName("userName") //
265             .passWord("passWord") //
266             .trustStorePath("trustStorePath") //
267             .trustStorePasswordPath("trustStorePasswordPath") //
268             .keyStorePath("keyStorePath") //
269             .keyStorePasswordPath("keyStorePasswordPath") //
270             .enableDmaapCertAuth(true) //
271             .changeIdentifier("Different changeIdentifier") //
272             .build(); //
273         final ConsumerConfiguration dmaapConsumerConfiguration = ImmutableConsumerConfiguration.builder() //
274             .topicUrl("topicUrl").trustStorePath("trustStorePath") //
275             .trustStorePasswordPath("trustStorePasswordPath") //
276             .keyStorePath("keyStorePath") //
277             .keyStorePasswordPath("keyStorePasswordPath") //
278             .enableDmaapCertAuth(true) //
279             .build();
280
281         doReturn(dmaapPublisherConfiguration).when(appConfig).getPublisherConfiguration(CHANGE_IDENTIFIER);
282         doReturn(dmaapConsumerConfiguration).when(appConfig).getDmaapConsumerConfiguration();
283         doReturn(false).when(appConfig).isFeedConfigured(CHANGE_IDENTIFIER);
284         final int noOfEvents = 1;
285         final int noOfFilesPerEvent = 1;
286
287         Flux<FileReadyMessage> fileReadyMessages = fileReadyMessageFlux(noOfEvents, noOfFilesPerEvent, true);
288         doReturn(fileReadyMessages).when(consumerMock).getMessageRouterResponse();
289
290         ListAppender<ILoggingEvent> logAppender = LoggingUtils.getLogListAppender(ScheduledTasks.class);
291         testedObject.executeDatafileMainTask();
292
293         await().untilAsserted(() -> assertEquals(0, testedObject.getCurrentNumberOfSubscriptions()));
294
295         assertTrue("Error missing in log", logAppender.list.toString().contains(
296             "[INFO] No feed is configured for: " + CHANGE_IDENTIFIER + ", file ignored: " + PM_FILE_NAME + "1"));
297     }
298
299     @Test
300     public void createMainTask_consumeFail() {
301         MDC.setContextMap(contextMap);
302         doReturn(Flux.error(new Exception("Failed"))).when(consumerMock).getMessageRouterResponse();
303
304         ListAppender<ILoggingEvent> logAppender = LoggingUtils.getLogListAppender(ScheduledTasks.class);
305         StepVerifier //
306             .create(testedObject.createMainTask(contextMap)) //
307             .expectSubscription() //
308             .expectNextCount(0) //
309             .expectComplete() //
310             .verify(); //
311
312         assertTrue("Error missing in log", logAppender.list.toString()
313             .contains("[ERROR] Polling for file ready message failed, " + "exception: java.lang.Exception: Failed"));
314     }
315
316     @Test
317     public void consume_successfulCase() throws DatafileTaskException {
318         setUpConfiguration();
319
320         final int noOfEvents = 200;
321         final int noOfFilesPerEvent = 200;
322         final int noOfFiles = noOfEvents * noOfFilesPerEvent;
323
324         Flux<FileReadyMessage> fileReadyMessages = fileReadyMessageFlux(noOfEvents, noOfFilesPerEvent, true);
325         doReturn(fileReadyMessages).when(consumerMock).getMessageRouterResponse();
326
327         doReturn(false).when(publishedCheckerMock).isFilePublished(anyString(), anyString(), any());
328
329         Mono<FilePublishInformation> collectedFile = Mono.just(filePublishInformation());
330         doReturn(collectedFile).when(fileCollectorMock).collectFile(notNull(), anyLong(), notNull(), notNull());
331         doReturn(collectedFile).when(dataRouterMock).publishFile(notNull(), anyLong(), notNull());
332
333         StepVerifier //
334             .create(testedObject.createMainTask(contextMap)) //
335             .expectSubscription() //
336             .expectNextCount(noOfFiles) //
337             .expectComplete() //
338             .verify(); //
339
340         assertEquals(0, testedObject.getCurrentNumberOfTasks());
341         assertEquals(0, testedObject.getThreadPoolQueueSize());
342         verify(consumerMock, times(1)).getMessageRouterResponse();
343         verify(fileCollectorMock, times(noOfFiles)).collectFile(notNull(), anyLong(), notNull(), notNull());
344         verify(dataRouterMock, times(noOfFiles)).publishFile(notNull(), anyLong(), notNull());
345         verifyNoMoreInteractions(dataRouterMock);
346         verifyNoMoreInteractions(fileCollectorMock);
347         verifyNoMoreInteractions(consumerMock);
348     }
349
350     @Test
351     public void consume_fetchFailedOnce() throws DatafileTaskException {
352         setUpConfiguration();
353
354         Flux<FileReadyMessage> fileReadyMessages = fileReadyMessageFlux(2, 2, true); // 4 files
355         doReturn(fileReadyMessages).when(consumerMock).getMessageRouterResponse();
356
357         doReturn(false).when(publishedCheckerMock).isFilePublished(anyString(), anyString(), any());
358
359         Mono<FilePublishInformation> collectedFile = Mono.just(filePublishInformation());
360         Mono<Object> error = Mono.error(new Exception("problem"));
361
362         // First file collect will fail, 3 will succeed
363         doReturn(error, collectedFile, collectedFile, collectedFile) //
364             .when(fileCollectorMock) //
365             .collectFile(any(FileData.class), anyLong(), any(Duration.class), notNull());
366
367         doReturn(collectedFile).when(dataRouterMock).publishFile(notNull(), anyLong(), notNull());
368         doReturn(collectedFile).when(dataRouterMock).publishFile(notNull(), anyLong(), notNull());
369
370         StepVerifier //
371             .create(testedObject.createMainTask(contextMap)) //
372             .expectSubscription() //
373             .expectNextCount(3) //
374             .expectComplete() //
375             .verify(); //
376
377         assertEquals(0, testedObject.getCurrentNumberOfTasks());
378         verify(consumerMock, times(1)).getMessageRouterResponse();
379         verify(fileCollectorMock, times(4)).collectFile(notNull(), anyLong(), notNull(), notNull());
380         verify(dataRouterMock, times(3)).publishFile(notNull(), anyLong(), notNull());
381         verifyNoMoreInteractions(dataRouterMock);
382         verifyNoMoreInteractions(fileCollectorMock);
383         verifyNoMoreInteractions(consumerMock);
384     }
385
386     @Test
387     public void consume_publishFailedOnce() throws DatafileTaskException {
388         setUpConfiguration();
389
390         Flux<FileReadyMessage> fileReadyMessages = fileReadyMessageFlux(2, 2, true); // 4 files
391         doReturn(fileReadyMessages).when(consumerMock).getMessageRouterResponse();
392
393         doReturn(false).when(publishedCheckerMock).isFilePublished(anyString(), anyString(), any());
394
395         Mono<FilePublishInformation> collectedFile = Mono.just(filePublishInformation());
396         doReturn(collectedFile).when(fileCollectorMock).collectFile(notNull(), anyLong(), notNull(), notNull());
397
398         Mono<Object> error = Mono.error(new Exception("problem"));
399         // One publish will fail, the rest will succeed
400         doReturn(collectedFile, error, collectedFile, collectedFile) //
401             .when(dataRouterMock) //
402             .publishFile(notNull(), anyLong(), notNull());
403
404         ListAppender<ILoggingEvent> logAppender = LoggingUtils.getLogListAppender(ScheduledTasks.class);
405         StepVerifier //
406             .create(testedObject.createMainTask(contextMap)) //
407             .expectSubscription() //
408             .expectNextCount(3) // 3 completed files
409             .expectComplete() //
410             .verify(); //
411
412         assertTrue("Error missing in log", logAppender.list.toString().contains("[ERROR] File publishing failed: "));
413
414         assertEquals(0, testedObject.getCurrentNumberOfTasks());
415         verify(consumerMock, times(1)).getMessageRouterResponse();
416         verify(fileCollectorMock, times(4)).collectFile(notNull(), anyLong(), notNull(), notNull());
417         verify(dataRouterMock, times(4)).publishFile(notNull(), anyLong(), notNull());
418         verifyNoMoreInteractions(dataRouterMock);
419         verifyNoMoreInteractions(fileCollectorMock);
420         verifyNoMoreInteractions(consumerMock);
421     }
422
423     @Test
424     public void consume_successfulCase_sameFileNames() throws DatafileTaskException {
425         setUpConfiguration();
426
427         final int noOfEvents = 1;
428         final int noOfFilesPerEvent = 100;
429
430         // 100 files with the same name
431         Flux<FileReadyMessage> fileReadyMessages = fileReadyMessageFlux(noOfEvents, noOfFilesPerEvent, false);
432         doReturn(fileReadyMessages).when(consumerMock).getMessageRouterResponse();
433
434         doReturn(false).when(publishedCheckerMock).isFilePublished(anyString(), anyString(), any());
435
436         Mono<FilePublishInformation> collectedFile = Mono.just(filePublishInformation());
437         doReturn(collectedFile).when(fileCollectorMock).collectFile(notNull(), anyLong(), notNull(), notNull());
438         doReturn(collectedFile).when(dataRouterMock).publishFile(notNull(), anyLong(), notNull());
439
440         StepVerifier //
441             .create(testedObject.createMainTask(contextMap)).expectSubscription() //
442             .expectNextCount(1) // 99 is skipped
443             .expectComplete() //
444             .verify(); //
445
446         assertEquals(0, testedObject.getCurrentNumberOfTasks());
447         verify(consumerMock, times(1)).getMessageRouterResponse();
448         verify(fileCollectorMock, times(1)).collectFile(notNull(), anyLong(), notNull(), notNull());
449         verify(dataRouterMock, times(1)).publishFile(notNull(), anyLong(), notNull());
450         verify(publishedCheckerMock, times(1)).isFilePublished(notNull(), anyString(), notNull());
451         verifyNoMoreInteractions(dataRouterMock);
452         verifyNoMoreInteractions(fileCollectorMock);
453         verifyNoMoreInteractions(consumerMock);
454         verifyNoMoreInteractions(dataRouterMock);
455     }
456 }