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