61a336b6ce6bb63ecfd19db27435d05e750e0399
[appc.git] / appc-dispatcher / appc-workflow-management / appc-workflow-management-core / src / main / java / org / onap / appc / workflow / activator / TransactionAbortedMarker.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP : APPC
4  * ================================================================================
5  * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Copyright (C) 2017 Amdocs
8  * ================================================================================
9  * Modifications (C) 2019 Ericsson
10  * =============================================================================
11  * Licensed under the Apache License, Version 2.0 (the "License");
12  * you may not use this file except in compliance with the License.
13  * You may obtain a copy of the License at
14  * 
15  *      http://www.apache.org/licenses/LICENSE-2.0
16  * 
17  * Unless required by applicable law or agreed to in writing, software
18  * distributed under the License is distributed on an "AS IS" BASIS,
19  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20  * See the License for the specific language governing permissions and
21  * limitations under the License.
22  * 
23  * ============LICENSE_END=========================================================
24  */
25
26 package org.onap.appc.workflow.activator;
27
28 import com.att.eelf.configuration.EELFLogger;
29 import com.att.eelf.configuration.EELFManager;
30 import org.onap.appc.transactionrecorder.TransactionRecorder;
31 import org.osgi.framework.BundleContext;
32 import org.osgi.framework.FrameworkUtil;
33 import org.osgi.framework.ServiceReference;
34 import java.io.BufferedReader;
35 import java.io.File;
36 import java.io.FileReader;
37 import java.io.FileWriter;
38 import java.io.IOException;
39 import java.util.UUID;
40 import java.util.concurrent.ScheduledExecutorService;
41 import java.util.concurrent.TimeUnit;
42
43 public class TransactionAbortedMarker implements Runnable {
44
45     private ScheduledExecutorService executor = null;
46
47     public static final String PREFIX = "APPC";
48     public static final String SUFFIX = "VM";
49     private final EELFLogger logger = EELFManager.getInstance().getLogger(TransactionAbortedMarker.class);
50
51     public TransactionAbortedMarker(ScheduledExecutorService executor){
52         this.executor = executor;
53     }
54
55     @Override
56     public void run() {
57         try {
58             TransactionRecorder recorder = lookupTransactionRecorder();
59
60             File newAppcInstanceIdFile = File.createTempFile(PREFIX, SUFFIX);
61             File parentDirectory = newAppcInstanceIdFile.getParentFile();
62             if (logger.isDebugEnabled()) {
63                 logger.debug("New instance id file path" + newAppcInstanceIdFile.getAbsolutePath());
64             }
65
66             File[] allInstanceIdFiles = getAllInstanceIdFiles(parentDirectory);
67
68             if (allInstanceIdFiles.length > 0) {
69                 File lastModifiedFile = getLastModifiedFile(allInstanceIdFiles);
70                 if (logger.isDebugEnabled()) {
71                     logger.debug("Last Modified File" + lastModifiedFile.getName());
72                 }
73                 String prevAppcInstanceId = readInstanceId(lastModifiedFile);
74                 recorder.markTransactionsAborted(prevAppcInstanceId);
75                 boolean isFileDeleted = lastModifiedFile.delete();
76                 logger.debug("Previous file deleted  " + isFileDeleted);
77             }
78             String newAppcInstanceId = writeNewInstanceId(newAppcInstanceIdFile);
79             recorder.setAppcInstanceId(newAppcInstanceId);
80         } catch (TransactionRecorderServiceNotFoundException e) {
81             logger.warn("Transaction Recorder Service Not Found, Next attempt after 30 seconds");
82             executor.schedule(this,30, TimeUnit.SECONDS);
83         } catch (Exception e) {
84             logger.error("Error on workflow manager bundle start-up" + e.getMessage(), e);
85             throw new RuntimeException(e);
86         }
87     }
88
89
90
91     protected TransactionRecorder lookupTransactionRecorder() throws TransactionRecorderServiceNotFoundException {
92         String message = null;
93         BundleContext bctx = FrameworkUtil.getBundle(TransactionRecorder.class).getBundleContext();
94         if(bctx!=null){
95             ServiceReference sref= bctx.getServiceReference(TransactionRecorder.class.getName());
96             TransactionRecorder transactionRecorder;
97             if (sref != null) {
98                 transactionRecorder = (TransactionRecorder) bctx.getService(sref);
99                 if (transactionRecorder != null) {
100                     return transactionRecorder;
101                 }
102             }
103         }
104         message = "Cannot find service org.onap.appc.transactionrecorder.TransactionRecorder";
105         logger.warn(message);
106         throw new TransactionRecorderServiceNotFoundException(message);
107     }
108
109     private String writeNewInstanceId(File newInstanceIdFile) throws IOException {
110         String newAppcInstanceId = UUID.randomUUID().toString();
111         try (FileWriter writer = new FileWriter(newInstanceIdFile)) {
112             writer.write(newAppcInstanceId);
113         }
114         catch (IOException e){
115             String message = "Error writing appc-instance-id";
116             logger.error(message,e);
117             throw new RuntimeException(message);
118         }
119         logger.debug("new appc-instance-id = " + newAppcInstanceId);
120         return newAppcInstanceId;
121     }
122
123     private String readInstanceId(File lastModifiedFile) {
124         String prevAppcInstanceId = null;
125         BufferedReader buffReader;
126         try (FileReader reader = new FileReader(lastModifiedFile)) {
127             buffReader = new BufferedReader(reader);
128             prevAppcInstanceId = buffReader.readLine();
129         }
130         catch (IOException e){
131             String message ="Error reading previous appc-instance-id";
132             logger.error(message,e);
133             throw new RuntimeException(message);
134         }
135         logger.debug("previous appc-instance-id " + prevAppcInstanceId);
136         return prevAppcInstanceId;
137     }
138
139     private File[] getAllInstanceIdFiles(File directory) {
140         return directory.listFiles(pathname -> {
141             if (pathname.getName().startsWith(PREFIX)
142                     && pathname.getName().endsWith(SUFFIX)
143                     && pathname.length()>0)
144                 return true;
145             return false;
146         });
147     }
148
149     private File getLastModifiedFile(File[] allInstanceIdFiles) {
150         File lastModifiedFile = allInstanceIdFiles[0];
151         long lastModified = allInstanceIdFiles[0].lastModified();
152         for(File file:allInstanceIdFiles){
153             if(file.lastModified() > lastModified){
154                 lastModified = file.lastModified();
155                 lastModifiedFile = file;
156             }
157         }
158         return lastModifiedFile;
159     }
160 }