b4dc635329b717c54194adc4a6290795ce11aa8d
[dcaegen2/collectors/datafile.git] /
1 /*
2  * ============LICENSE_START======================================================================
3  * Copyright (C) 2018 NOKIA Intellectual Property, 2018-2019 Nordix Foundation. All rights reserved.
4  * ===============================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
6  * in compliance with the License. You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software distributed under the License
11  * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
12  * or implied. See the License for the specific language governing permissions and limitations under
13  * the License.
14  * ============LICENSE_END========================================================================
15  */
16
17 package org.onap.dcaegen2.collectors.datafile.configuration;
18
19 import static org.onap.dcaegen2.collectors.datafile.model.logging.MdcVariables.INVOCATION_ID;
20 import static org.onap.dcaegen2.collectors.datafile.model.logging.MdcVariables.REQUEST_ID;
21 import java.time.Duration;
22 import java.time.Instant;
23 import java.util.ArrayList;
24 import java.util.List;
25 import java.util.Map;
26 import java.util.UUID;
27 import java.util.concurrent.ScheduledFuture;
28 import javax.annotation.PostConstruct;
29 import org.apache.commons.lang3.StringUtils;
30 import org.onap.dcaegen2.collectors.datafile.model.logging.MdcVariables;
31 import org.onap.dcaegen2.collectors.datafile.tasks.ScheduledTasks;
32 import org.slf4j.Logger;
33 import org.slf4j.LoggerFactory;
34 import org.slf4j.MDC;
35 import org.slf4j.Marker;
36 import org.slf4j.MarkerFactory;
37 import org.springframework.beans.factory.annotation.Autowired;
38 import org.springframework.context.annotation.Configuration;
39 import org.springframework.http.HttpStatus;
40 import org.springframework.http.ResponseEntity;
41 import org.springframework.scheduling.TaskScheduler;
42 import org.springframework.scheduling.annotation.EnableScheduling;
43 import io.swagger.annotations.ApiOperation;
44 import reactor.core.publisher.Mono;
45
46 /**
47  * @author <a href="mailto:przemyslaw.wasala@nokia.com">Przemysław Wąsala</a> on 6/13/18
48  */
49 @Configuration
50 @EnableScheduling
51 public class SchedulerConfig {
52
53     private static final Duration SCHEDULING_DELAY_FOR_DATAFILE_COLLECTOR_TASKS = Duration.ofSeconds(15);
54     private static final Duration SCHEDULING_REQUEST_FOR_CONFIGURATION_DELAY = Duration.ofMinutes(5);
55     private static final Duration SCHEDULING_DELAY_FOR_DATAFILE_PURGE_CACHE = Duration.ofHours(1);
56     private static final Logger logger = LoggerFactory.getLogger(SchedulerConfig.class);
57     private static final Marker ENTRY = MarkerFactory.getMarker("ENTRY");
58     private static final Marker EXIT = MarkerFactory.getMarker("EXIT");
59     private static volatile List<ScheduledFuture<?>> scheduledFutureList = new ArrayList<>();
60     private Map<String, String> contextMap;
61
62     private final TaskScheduler taskScheduler;
63     private final ScheduledTasks scheduledTask;
64     private final CloudConfiguration cloudConfiguration;
65
66     @Autowired
67     public SchedulerConfig(TaskScheduler taskScheduler, ScheduledTasks scheduledTask,
68         CloudConfiguration cloudConfiguration) {
69         this.taskScheduler = taskScheduler;
70         this.scheduledTask = scheduledTask;
71         this.cloudConfiguration = cloudConfiguration;
72     }
73
74     /**
75      * Function which have to stop tasks execution.
76      *
77      * @return response entity about status of cancellation operation
78      */
79     @ApiOperation(value = "Get response on stopping task execution")
80     public synchronized Mono<ResponseEntity<String>> getResponseFromCancellationOfTasks() {
81         scheduledFutureList.forEach(x -> x.cancel(false));
82         scheduledFutureList.clear();
83         MdcVariables.setMdcContextMap(contextMap);
84         logger.info(EXIT, "Stopped Datafile workflow");
85         MDC.clear();
86         return Mono.defer(() -> Mono
87             .just(new ResponseEntity<>("Datafile Service has already been stopped!", HttpStatus.CREATED)));
88     }
89
90     /**
91      * Function for starting scheduling Datafile workflow.
92      *
93      * @return status of operation execution: true - started, false - not started
94      */
95     @PostConstruct
96     @ApiOperation(value = "Start task if possible")
97     public synchronized boolean tryToStartTask() {
98         String requestId = MDC.get(REQUEST_ID);
99         if (StringUtils.isBlank(requestId)) {
100             MDC.put(REQUEST_ID, UUID.randomUUID().toString());
101         }
102         String invocationId = MDC.get(INVOCATION_ID);
103         if (StringUtils.isBlank(invocationId)) {
104             MDC.put(INVOCATION_ID, UUID.randomUUID().toString());
105         }
106         contextMap = MDC.getCopyOfContextMap();
107         logger.info(ENTRY, "Start scheduling Datafile workflow");
108         if (scheduledFutureList.isEmpty()) {
109             scheduledFutureList.add(taskScheduler.scheduleAtFixedRate(() -> cloudConfiguration.runTask(contextMap), Instant.now(),
110                     SCHEDULING_REQUEST_FOR_CONFIGURATION_DELAY));
111             scheduledFutureList.add(taskScheduler.scheduleWithFixedDelay(() -> scheduledTask.scheduleMainDatafileEventTask(contextMap),
112                     SCHEDULING_DELAY_FOR_DATAFILE_COLLECTOR_TASKS));
113             scheduledFutureList.add(taskScheduler.scheduleWithFixedDelay(() -> scheduledTask.purgeCachedInformation(Instant.now()),
114                    SCHEDULING_DELAY_FOR_DATAFILE_PURGE_CACHE));
115
116             return true;
117         } else {
118             return false;
119         }
120
121     }
122 }