aboutsummaryrefslogtreecommitdiffstats
path: root/framework/src/main/java/org/onap/cli/fw/store/OnapCommandExecutionStore.java
blob: 71cd245fa73afbfaa0b7004be37075addf6e747f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
/*
 * Copyright 2019 Huawei Technologies Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.onap.cli.fw.store;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.onap.cli.fw.conf.OnapCommandConfig;
import org.onap.cli.fw.conf.OnapCommandConstants;
import org.onap.cli.fw.error.OnapCommandExecutionFailed;
import org.onap.cli.fw.error.OnapCommandExecutionNotFound;
import org.onap.cli.fw.utils.ProcessRunner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class OnapCommandExecutionStore {
    private static Logger log = LoggerFactory.getLogger(OnapCommandExecutionStore.class);

    private static boolean storeReady = false;

    private static SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.US);

    static {
        dateFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
    }

    private static String SEPARATOR = "__";

    private enum SearchMode {
        find,
        file //for developer mode
    }
    private static SearchMode SEARCH_MODE = SearchMode.file;

    public static class ExecutionStoreContext {

        private String executionId;
        private String storePath;
        public String getExecutionId() {
            return executionId;
        }
        public ExecutionStoreContext setExecutionId(String executionId) {
            this.executionId = executionId;
            return this;
        }
        public String getStorePath() {
            return storePath;
        }
        public ExecutionStoreContext setStorePath(String storePath) {
            this.storePath = storePath;
            return this;
        }
    }

    public static class Execution {
        private String id;
        private String requestId;
        private String status;
        private String startTime;
        private String endTime;
        private String input;
        private String output;
        private String profile;
        private String command;
        private String product;
        private String service;

        public String getInput() {
            return input;
        }
        public void setInput(String input) {
            this.input = input;
        }
        public String getOutput() {
            return output;
        }
        public void setOutput(String output) {
            this.output = output;
        }
        public String getProfile() {
            return profile;
        }
        public void setProfile(String profile) {
            this.profile = profile;
        }
        public String getCommand() {
            return command;
        }
        public void setCommand(String command) {
            this.command = command;
        }
        public String getProduct() {
            return product;
        }
        public void setProduct(String product) {
            this.product = product;
        }
        public String getService() {
            return service;
        }
        public void setService(String service) {
            this.service = service;
        }
        public String getId() {
            return id;
        }
        public void setId(String id) {
            this.id = id;
        }
        public String getEndTime() {
            return endTime;
        }
        public void setEndTime(String endTime) {
            this.endTime = endTime;
        }
        public void setStartTime(String timeOfExecution) {
            this.startTime = timeOfExecution;
        }
        public String getStartTime() {
            return startTime;
        }
        public String getStatus() {
            return status;
        }
        public void setStatus(String status) {
            this.status = status;
        }
        public String getRequestId() {
            return requestId;
        }
        public void setRequestId(String requestId) {
            this.requestId = requestId;
        }
    }

    static {
        try {
            FileUtils.forceMkdir(new File(getBasePath()));
            storeReady = true;
        } catch (IOException e) {
            log.error("Failed to create the data store results");
        }
    }

    private static OnapCommandExecutionStore store = null;

    private OnapCommandExecutionStore() {

    }

    public static OnapCommandExecutionStore getStore() {
        if (store == null) {
            store = new OnapCommandExecutionStore();
        }

        return store;
    }

    private static String getBasePath() {
        return OnapCommandConfig.getPropertyValue(OnapCommandConstants.OPEN_CLI_DATA_DIR) +
                File.separator + "executions";
    }

    public ExecutionStoreContext storeExectutionStart(
            String requestId, String product, String service, String cmd, String profile, String input) {

        String executionId = requestId + "-" + System.currentTimeMillis();

        String storePath = getBasePath() + File.separator + executionId + SEPARATOR + product +
                SEPARATOR + service +
                SEPARATOR + cmd +
                (profile != null ? (SEPARATOR + profile) : "" );
        try {
            File dir = new File(storePath);
            FileUtils.forceMkdir(dir);

            if (product != null)
                FileUtils.writeStringToFile(new File(dir.getAbsolutePath() + File.separator + "product"), product);
            if (service != null)
                FileUtils.writeStringToFile(new File(dir.getAbsolutePath() + File.separator + "service"), service);
            if (cmd != null)
                FileUtils.writeStringToFile(new File(dir.getAbsolutePath() + File.separator + "command"), cmd);

            FileUtils.writeStringToFile(new File(dir.getAbsolutePath() + File.separator + "requestId"), requestId);

            FileUtils.writeStringToFile(new File(dir.getAbsolutePath() + File.separator + "executionId"), executionId);

            if (input != null)
                FileUtils.writeStringToFile(new File(dir.getAbsolutePath() + File.separator + "input"), input);
            if (profile != null)
                FileUtils.writeStringToFile(new File(dir.getAbsolutePath() + File.separator + "profile"), profile);
            FileUtils.touch(new File(dir.getAbsolutePath() + File.separator + "in-progress"));
        } catch (IOException e) {
            log.error("Failed to store the execution start details " + storePath);
        }

        return new ExecutionStoreContext().setExecutionId(executionId).setStorePath(storePath);
    }

    public void storeExectutionEnd(
            ExecutionStoreContext execContext,
            String output, String error, boolean passed) {

        try {
            File dir = new File(execContext.getStorePath());
            FileUtils.forceMkdir(dir);

            if (output != null)
                FileUtils.writeStringToFile(new File(dir.getAbsolutePath() + File.separator + "output"), output);
            if (error != null)
                FileUtils.writeStringToFile(new File(dir.getAbsolutePath() + File.separator + "error"), error);

            if (passed)
                FileUtils.touch(new File(dir.getAbsolutePath() + File.separator + "completed"));
            else
                FileUtils.touch(new File(dir.getAbsolutePath() + File.separator + "failed"));

            new File(dir.getAbsolutePath() + File.separator + "in-progress").delete();
        } catch (IOException e) {
            log.error("Failed to store the execution end details " + execContext.storePath);
        }
    }

    public List<OnapCommandExecutionStore.Execution> listExecutions(Map<String, String> search) throws OnapCommandExecutionFailed {
        List <OnapCommandExecutionStore.Execution> list = new ArrayList<>();

        try {
            List <String> dirs = new ArrayList<>();
            if (SEARCH_MODE.equals(SearchMode.file)) {
                for (File f: new File(getBasePath()).listFiles())
                    dirs.add(f.getAbsolutePath());
            } else {
                //find results -type d -newermt '2019-02-11 10:00:00' ! -newermt '2019-02-11 15:10:00' -name "*__*__profile-list*"
                //find 'results' -type d -newermt '2019-02-11T10:00:00.000' ! -newermt '2019-02-11T15:10:00.000' -name "*__*__profile*"

                String searchString = "find '" + new File(getBasePath()).getAbsolutePath() + "' -type d ";

                String startTime = search.get("startTime");
                if (startTime != null) {
                    searchString += " -newermt " + startTime ;
                }

                String endTime = search.get("endTime");
                if (endTime != null) {
                    searchString += " ! -newermt " + endTime ;
                }

                searchString += " -name '";

                if(search.containsKey("execution-id")) {
                    searchString += search.get("execution-id");
                } else if(search.containsKey("request-id")) {
                    searchString += search.get("request-id") + "*";
                } else {
                    searchString += "*";
                }

                for (String term: Arrays.asList(new String []{"product", "service", "command", "profile"})) {
                    searchString += "__";
                    if (search.get(term) != null) {
                        searchString += search.get(term);
                    } else {
                        searchString += "*";
                    }
                }
                if (!searchString.endsWith("*"))
                    searchString += "*";

                searchString += "'";

                ProcessRunner pr = new ProcessRunner(new String [] {searchString}, null, ".");
                pr.overrideToUnix();
                pr.run();
                if (pr.getExitCode() != 0) {
                    throw new OnapCommandExecutionFailed("System failed to search the executions with error " + pr.getError());
                }

                dirs = Arrays.asList(pr.getOutput().split("\\r?\\n"));
            }

            for (String dir: dirs) {
                list.add(this.makeExecution(dir));
            }
        } catch (IOException e) {
            throw new OnapCommandExecutionFailed(e, "Failed to search the executions");
        } catch (InterruptedException e) {
            throw new OnapCommandExecutionFailed(e, "Failed to search the executions");
        }

        return list;
    }

    private Execution makeExecution(String executionStorePath) throws IOException {
        OnapCommandExecutionStore.Execution exectuion = new OnapCommandExecutionStore.Execution();
        if (new File(executionStorePath + File.separator + "requestId").exists())
            exectuion.setRequestId(FileUtils.readFileToString(new File(executionStorePath + File.separator + "requestId")));
        if (new File(executionStorePath + File.separator + "executionId").exists())
            exectuion.setId(FileUtils.readFileToString(new File(executionStorePath + File.separator + "executionId")));
        exectuion.setProduct(FileUtils.readFileToString(new File(executionStorePath + File.separator + "product")));
        exectuion.setService(FileUtils.readFileToString(new File(executionStorePath + File.separator + "service")));
        exectuion.setCommand(FileUtils.readFileToString(new File(executionStorePath + File.separator + "command")));
        if (new File(executionStorePath + File.separator + "profile").exists())
            exectuion.setProfile(FileUtils.readFileToString(new File(executionStorePath + File.separator + "profile")));

        exectuion.setInput(FileUtils.readFileToString(new File(executionStorePath + File.separator + "input")));
        exectuion.setStartTime(dateFormatter.format(new File(executionStorePath + File.separator + "input").lastModified()));

        if (new File(executionStorePath + File.separator + "in-progress").exists()) {
            exectuion.setStatus("in-progress");
        } else if (new File(executionStorePath + File.separator + "completed").exists()) {
            exectuion.setStatus("completed");
            if (new File(executionStorePath + File.separator + "output").exists()) {
                exectuion.setOutput(FileUtils.readFileToString(new File(executionStorePath + File.separator + "output")));
                exectuion.setEndTime(dateFormatter.format(new File(executionStorePath + File.separator + "output").lastModified()));
            }
        } else if (new File(executionStorePath + File.separator + "failed").exists()) {
            exectuion.setStatus("failed");
            if (new File(executionStorePath + File.separator + "error").exists()) {
                exectuion.setOutput(FileUtils.readFileToString(new File(executionStorePath + File.separator + "error")));
                exectuion.setEndTime(dateFormatter.format(new File(executionStorePath + File.separator + "error").lastModified()));
            }
        }

        return exectuion;
    }
    public Execution getExecution(String executionId) throws OnapCommandExecutionNotFound, OnapCommandExecutionFailed {
        File []f =  new File(getBasePath()).listFiles(new FilenameFilter() {

            @Override
            public boolean accept(File dir, String name) {
                if (name.startsWith(executionId)) return true;
                return false;
            }
        });

        if (f.length == 0) {
            throw new OnapCommandExecutionNotFound(executionId);
        }

        try {
            return this.makeExecution(f[0].getAbsolutePath());
        } catch (IOException e) {
            throw new OnapCommandExecutionFailed(e, "Failed to retrieve the execution");
        }
    }
}