d5c8b3b226108c12ae489477f869559b590b9e47
[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
22 import java.time.Duration;
23 import java.time.Instant;
24 import java.util.ArrayList;
25 import java.util.List;
26 import java.util.Map;
27 import java.util.UUID;
28 import java.util.concurrent.ScheduledFuture;
29
30 import javax.annotation.PostConstruct;
31
32 import org.apache.commons.lang3.StringUtils;
33 import org.onap.dcaegen2.collectors.datafile.model.logging.MdcVariables;
34 import org.onap.dcaegen2.collectors.datafile.tasks.ScheduledTasks;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
37 import org.slf4j.MDC;
38 import org.slf4j.Marker;
39 import org.slf4j.MarkerFactory;
40 import org.springframework.beans.factory.annotation.Autowired;
41 import org.springframework.context.annotation.Configuration;
42 import org.springframework.http.HttpStatus;
43 import org.springframework.http.ResponseEntity;
44 import org.springframework.scheduling.TaskScheduler;
45 import org.springframework.scheduling.annotation.EnableScheduling;
46
47 import io.swagger.annotations.ApiOperation;
48 import reactor.core.publisher.Mono;
49
50 /**
51  * Api for starting and stopping DFC.
52  *
53  * @author <a href="mailto:przemyslaw.wasala@nokia.com">Przemysław Wąsala</a> on 6/13/18
54  * @author <a href="mailto:henrik.b.andersson@est.tech">Henrik Andersson</a>
55  */
56 @Configuration
57 @EnableScheduling
58 public class SchedulerConfig {
59
60     private static final Duration SCHEDULING_DELAY_FOR_DATAFILE_COLLECTOR_TASKS = Duration.ofSeconds(15);
61     private static final Duration SCHEDULING_REQUEST_FOR_CONFIGURATION_DELAY = Duration.ofMinutes(5);
62     private static final Duration SCHEDULING_DELAY_FOR_DATAFILE_PURGE_CACHE = Duration.ofHours(1);
63     private static final Logger logger = LoggerFactory.getLogger(SchedulerConfig.class);
64     private static final Marker ENTRY = MarkerFactory.getMarker("ENTRY");
65     private static final Marker EXIT = MarkerFactory.getMarker("EXIT");
66     private static List<ScheduledFuture<?>> scheduledFutureList = new ArrayList<>();
67     private Map<String, String> contextMap;
68
69     private final TaskScheduler taskScheduler;
70     private final ScheduledTasks scheduledTask;
71     private final CloudConfiguration cloudConfiguration;
72
73     /**
74      * Constructor.
75      *
76      * @param taskScheduler The scheduler used to schedule the tasks.
77      * @param scheduledTasks The scheduler that will actually handle the tasks.
78      * @param cloudConfiguration The DFC configuration.
79      */
80     @Autowired
81     public SchedulerConfig(TaskScheduler taskScheduler, ScheduledTasks scheduledTasks,
82             CloudConfiguration cloudConfiguration) {
83         this.taskScheduler = taskScheduler;
84         this.scheduledTask = scheduledTasks;
85         this.cloudConfiguration = cloudConfiguration;
86     }
87
88     /**
89      * Function which have to stop tasks execution.
90      *
91      * @return response entity about status of cancellation operation
92      */
93     @ApiOperation(value = "Get response on stopping task execution")
94     public synchronized Mono<ResponseEntity<String>> getResponseFromCancellationOfTasks() {
95         scheduledFutureList.forEach(x -> x.cancel(false));
96         scheduledFutureList.clear();
97         MdcVariables.setMdcContextMap(contextMap);
98         logger.info(EXIT, "Stopped Datafile workflow");
99         MDC.clear();
100         return Mono.just(new ResponseEntity<>("Datafile Service has already been stopped!", HttpStatus.CREATED));
101     }
102
103     /**
104      * Function for starting scheduling Datafile workflow.
105      *
106      * @return status of operation execution: true - started, false - not started
107      */
108     @PostConstruct
109     @ApiOperation(value = "Start task if possible")
110     public synchronized boolean tryToStartTask() {
111         String requestId = MDC.get(REQUEST_ID);
112         if (StringUtils.isBlank(requestId)) {
113             MDC.put(REQUEST_ID, UUID.randomUUID().toString());
114         }
115         String invocationId = MDC.get(INVOCATION_ID);
116         if (StringUtils.isBlank(invocationId)) {
117             MDC.put(INVOCATION_ID, UUID.randomUUID().toString());
118         }
119         contextMap = MDC.getCopyOfContextMap();
120         logger.info(ENTRY, "Start scheduling Datafile workflow");
121         if (scheduledFutureList.isEmpty()) {
122             scheduledFutureList.add(taskScheduler.scheduleAtFixedRate(() -> cloudConfiguration.runTask(contextMap),
123                     Instant.now(), SCHEDULING_REQUEST_FOR_CONFIGURATION_DELAY));
124             scheduledFutureList.add(
125                     taskScheduler.scheduleWithFixedDelay(() -> scheduledTask.scheduleMainDatafileEventTask(contextMap),
126                             SCHEDULING_DELAY_FOR_DATAFILE_COLLECTOR_TASKS));
127             scheduledFutureList
128                     .add(taskScheduler.scheduleWithFixedDelay(() -> scheduledTask.purgeCachedInformation(Instant.now()),
129                             SCHEDULING_DELAY_FOR_DATAFILE_PURGE_CACHE));
130
131             return true;
132         } else {
133             return false;
134         }
135
136     }
137 }