aboutsummaryrefslogtreecommitdiffstats
path: root/policy-management/src/main/java/org/onap/policy/drools/persistence/FileSystemPersistence.java
blob: d35f5469ed5a8d02f75e52488dfe6a476023f9fe (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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
/*
 * ============LICENSE_START=======================================================
 * ONAP
 * ================================================================================
 * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 * 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.
 * ============LICENSE_END=========================================================
 */

package org.onap.policy.drools.persistence;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Properties;
import java.util.function.BiPredicate;
import lombok.Getter;
import lombok.ToString;
import org.onap.policy.drools.properties.DroolsPropertyConstants;
import org.onap.policy.drools.utils.PropertyUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Properties based Persistence.
 */
@Getter
@ToString
public class FileSystemPersistence implements SystemPersistence {

    /**
     * Properties file extension.
     */
    public static final String PROPERTIES_FILE_EXTENSION = ".properties";

    /**
     * Policy controllers suffix.
     */
    public static final String CONTROLLER_SUFFIX_IDENTIFIER = "-controller";

    /**
     * File Backup Suffix.
     */
    public static final String FILE_BACKUP_SUFFIX = ".bak";

    /**
     * Policy controller properties file suffix.
     */
    public static final String PROPERTIES_FILE_CONTROLLER_SUFFIX =
            CONTROLLER_SUFFIX_IDENTIFIER + PROPERTIES_FILE_EXTENSION;

    /**
     * Topic configuration suffix.
     */
    public static final String TOPIC_SUFFIX_IDENTIFIER = "-topic";

    /**
     * Topic properties file suffix.
     */
    public static final String PROPERTIES_FILE_TOPIC_SUFFIX = TOPIC_SUFFIX_IDENTIFIER + PROPERTIES_FILE_EXTENSION;

    /**
     * Policy engine properties file name.
     */
    public static final String PROPERTIES_FILE_ENGINE = "engine" + PROPERTIES_FILE_EXTENSION;

    public static final String HTTP_SERVER_SUFFIX_IDENTIFIER = "-http-server";
    public static final String PROPERTIES_FILE_HTTP_SERVER_SUFFIX =
            HTTP_SERVER_SUFFIX_IDENTIFIER + PROPERTIES_FILE_EXTENSION;

    public static final String HTTP_CLIENT_SUFFIX_IDENTIFIER = "-http-client";
    public static final String PROPERTIES_FILE_HTTP_CLIENT_SUFFIX =
            HTTP_CLIENT_SUFFIX_IDENTIFIER + PROPERTIES_FILE_EXTENSION;

    /**
     * Installation environment suffix for files.
     */
    public static final String ENV_FILE_SUFFIX = ".environment";

    /**
     * Environment properties extension.
     */
    public static final String ENV_FILE_EXTENSION = ENV_FILE_SUFFIX;

    /**
     * Installation environment suffix for files.
     */
    public static final String SYSTEM_PROPERTIES_SUFFIX = "-system";
    public static final String SYSTEM_PROPERTIES_FILE_SUFFIX = SYSTEM_PROPERTIES_SUFFIX + PROPERTIES_FILE_EXTENSION;

    /**
     * Logger.
     */
    private static final Logger logger = LoggerFactory.getLogger(FileSystemPersistence.class);

    /**
     * Configuration directory.
     */
    protected Path configurationPath = Paths.get(SystemPersistenceConstants.DEFAULT_CONFIGURATION_DIR);


    @Override
    public void setConfigurationDir(String configDir) {
        String tempConfigDir = configDir;

        if (tempConfigDir == null) {
            tempConfigDir = SystemPersistenceConstants.DEFAULT_CONFIGURATION_DIR;
            this.configurationPath = Paths.get(SystemPersistenceConstants.DEFAULT_CONFIGURATION_DIR);
        }

        if (!tempConfigDir.equals(SystemPersistenceConstants.DEFAULT_CONFIGURATION_DIR)) {
            this.configurationPath = Paths.get(tempConfigDir);
        }

        setConfigurationDir();
    }

    @Override
    public void setConfigurationDir() {
        if (Files.notExists(this.configurationPath)) {
            try {
                Files.createDirectories(this.configurationPath);
            } catch (final IOException e) {
                throw new IllegalStateException("cannot create " + this.configurationPath, e);
            }
        }

        if (!Files.isDirectory(this.configurationPath)) {
            throw new IllegalStateException(
                "config directory: " + this.configurationPath + " is not a directory");
        }
    }

    protected Properties getProperties(Path propertiesPath) {
        if (!Files.exists(propertiesPath)) {
            throw new IllegalArgumentException("properties for " + propertiesPath.toString() + " are not persisted.");
        }

        try {
            return PropertyUtil.getProperties(propertiesPath.toFile());
        } catch (final Exception e) {
            throw new IllegalArgumentException("can't read properties for " + propertiesPath.toString(), e);
        }
    }

    @Override
    public Properties getProperties(String name) {
        if (name == null || name.isEmpty()) {
            throw new IllegalArgumentException("properties name must be provided");
        }

        var propertiesPath = Paths.get(this.configurationPath.toString());
        if (name.endsWith(PROPERTIES_FILE_EXTENSION) || name.endsWith(ENV_FILE_EXTENSION)) {
            propertiesPath = propertiesPath.resolve(name);
        } else {
            propertiesPath = propertiesPath.resolve(name + PROPERTIES_FILE_EXTENSION);
        }

        return getProperties(propertiesPath);
    }

    protected List<Properties> getPropertiesList(String suffix) {
        return getPropertiesList(suffix, (name, props) ->  true);
    }

    protected List<Properties> getPropertiesList(String suffix, BiPredicate<String, Properties> preCondition) {
        List<Properties> properties = new ArrayList<>();
        File[] files = this.sortedListFiles();
        for (File file : files) {
            if (file.getName().endsWith(suffix)) {
                addToPropertiesList(file, properties, preCondition);
            }
        }
        return properties;
    }

    private void addToPropertiesList(File file, List<Properties> properties,
                                     BiPredicate<String, Properties> preCondition) {
        try {
            var proposedProps = getProperties(file.getName());
            if (preCondition.test(file.getName(), proposedProps)) {
                properties.add(proposedProps);
            }
        } catch (final Exception e) {
            logger.error("{}: cannot get properties {} because of {}", this, file.getName(),
                e.getMessage(), e);
        }
    }

    @Override
    public Properties getEnvironmentProperties(String name) {
        if (name == null || name.isEmpty()) {
            throw new IllegalArgumentException("environment name must be provided");
        }

        return this.getProperties(Paths.get(this.configurationPath.toString(), name + ENV_FILE_SUFFIX));
    }

    @Override
    public List<Properties> getEnvironmentProperties() {
        return getPropertiesList(ENV_FILE_SUFFIX);
    }

    @Override
    public Properties getSystemProperties(String name) {
        return this.getProperties(name + SYSTEM_PROPERTIES_SUFFIX);
    }

    @Override
    public List<Properties> getSystemProperties() {
        return getPropertiesList(SYSTEM_PROPERTIES_FILE_SUFFIX);
    }

    @Override
    public Properties getEngineProperties() {
        return this.getProperties(PROPERTIES_FILE_ENGINE);
    }

    @Override
    public Properties getControllerProperties(String controllerName) {
        return this.getProperties(controllerName + CONTROLLER_SUFFIX_IDENTIFIER);
    }

    @Override
    public List<Properties> getControllerProperties() {
        return getPropertiesList(PROPERTIES_FILE_CONTROLLER_SUFFIX, this::testControllerName);
    }

    @Override
    public Properties getTopicProperties(String topicName) {
        return this.getProperties(topicName + TOPIC_SUFFIX_IDENTIFIER);
    }

    @Override
    public List<Properties> getTopicProperties() {
        return getPropertiesList(PROPERTIES_FILE_TOPIC_SUFFIX);
    }

    @Override
    public Properties getHttpServerProperties(String serverName) {
        return this.getProperties(serverName + HTTP_SERVER_SUFFIX_IDENTIFIER);
    }

    @Override
    public List<Properties> getHttpServerProperties() {
        return getPropertiesList(PROPERTIES_FILE_HTTP_SERVER_SUFFIX);
    }

    @Override
    public Properties getHttpClientProperties(String clientName) {
        return this.getProperties(clientName + HTTP_CLIENT_SUFFIX_IDENTIFIER);
    }

    @Override
    public List<Properties> getHttpClientProperties() {
        return getPropertiesList(PROPERTIES_FILE_HTTP_CLIENT_SUFFIX);
    }

    private boolean testControllerName(String controllerFilename, Properties controllerProperties) {
        var controllerName = controllerFilename
                .substring(0, controllerFilename.length() - PROPERTIES_FILE_CONTROLLER_SUFFIX.length());
        String controllerPropName = controllerProperties.getProperty(DroolsPropertyConstants.PROPERTY_CONTROLLER_NAME);
        if (controllerPropName == null) {
            controllerProperties.setProperty(DroolsPropertyConstants.PROPERTY_CONTROLLER_NAME, controllerName);
        } else if (!controllerPropName.equals(controllerName)) {
            logger.error("{}: mismatch controller named {} against {} in file {}",
                         this, controllerPropName, controllerName, controllerFilename);
            return false;
        }
        return true;
    }


    @Override
    public boolean backupController(String controllerName) {
        return backup(controllerName, PROPERTIES_FILE_CONTROLLER_SUFFIX);
    }

    @Override
    public boolean backupTopic(String topicName) {
        return backup(topicName, PROPERTIES_FILE_TOPIC_SUFFIX);
    }

    @Override
    public boolean backupHttpServer(String serverName) {
        return backup(serverName, PROPERTIES_FILE_HTTP_SERVER_SUFFIX);
    }

    @Override
    public boolean backupHttpClient(String clientName) {
        return backup(clientName, PROPERTIES_FILE_HTTP_CLIENT_SUFFIX);
    }

    protected boolean backup(String name, String fileSuffix) {
        var path = Paths.get(this.configurationPath.toString(), name + fileSuffix);
        if (Files.exists(path)) {
            try {
                logger.info("{}: there is an existing configuration file @ {} ", this, path);
                var bakPath = Paths.get(this.configurationPath.toString(),
                                            name + fileSuffix + FILE_BACKUP_SUFFIX);
                Files.copy(path, bakPath, StandardCopyOption.REPLACE_EXISTING);
            } catch (Exception e) {
                logger.warn("{}: {} cannot be backed up", this, name, e);
                return false;
            }
        }
        return true;
    }

    @Override
    public boolean storeController(String controllerName, Object configuration) {
        checkPropertiesParam(configuration);
        return store(controllerName, (Properties) configuration, PROPERTIES_FILE_CONTROLLER_SUFFIX);
    }

    @Override
    public boolean storeTopic(String topicName, Object configuration) {
        checkPropertiesParam(configuration);
        return store(topicName, (Properties) configuration, PROPERTIES_FILE_TOPIC_SUFFIX);
    }

    @Override
    public boolean storeHttpServer(String serverName, Object configuration) {
        checkPropertiesParam(configuration);
        return store(serverName, (Properties) configuration, PROPERTIES_FILE_HTTP_SERVER_SUFFIX);
    }

    @Override
    public boolean storeHttpClient(String clientName, Object configuration) {
        checkPropertiesParam(configuration);
        return store(clientName, (Properties) configuration, PROPERTIES_FILE_HTTP_CLIENT_SUFFIX);
    }

    private boolean store(String name, Properties properties, String fileSuffix) {
        var path = Paths.get(this.configurationPath.toString(), name + fileSuffix);
        if (Files.exists(path)) {
            try {
                var oldProperties = PropertyUtil.getProperties(path.toFile());
                if (oldProperties.equals(properties)) {
                    logger.info("{}: noop: a properties file with the same contents exists for controller {}.", this,
                                name);
                    return true;
                } else {
                    this.backupController(name);
                }
            } catch (Exception e) {
                logger.info("{}: no existing {} properties", this, name, e);
                // continue
            }
        }

        var file = path.toFile();
        try (var writer = new FileWriter(file)) {
            properties.store(writer, "Machine created Policy Controller Configuration");
        } catch (Exception e) {
            logger.warn("{}: {} cannot be saved", this, name, e);
            return false;
        }

        return true;
    }

    private void checkPropertiesParam(Object configuration) {
        if (!(configuration instanceof Properties)) {
            throw new IllegalArgumentException(
                "configuration must be of type properties to be handled by this manager");
        }
    }


    @Override
    public boolean deleteController(String controllerName) {
        return delete(controllerName, PROPERTIES_FILE_CONTROLLER_SUFFIX);
    }

    @Override
    public boolean deleteTopic(String topicName) {
        return delete(topicName, PROPERTIES_FILE_TOPIC_SUFFIX);
    }

    @Override
    public boolean deleteHttpServer(String serverName) {
        return delete(serverName, PROPERTIES_FILE_HTTP_SERVER_SUFFIX);
    }

    @Override
    public boolean deleteHttpClient(String clientName) {
        return delete(clientName, PROPERTIES_FILE_HTTP_CLIENT_SUFFIX);
    }

    protected boolean delete(String name, String fileSuffix) {
        var path = Paths.get(this.configurationPath.toString(), name + fileSuffix);

        if (Files.exists(path)) {
            try {
                var bakPath = Paths.get(this.configurationPath.toString(),
                                            name + fileSuffix + FILE_BACKUP_SUFFIX);
                Files.move(path, bakPath, StandardCopyOption.REPLACE_EXISTING);
            } catch (final Exception e) {
                logger.warn("{}: {} cannot be deleted", this, name, e);
                return false;
            }
        }

        return true;
    }

    /**
     * provides a list of files sorted by name in ascending order in the configuration directory.
     */
    private File[] sortedListFiles() {
        File[] dirFiles = this.configurationPath.toFile().listFiles();
        if (dirFiles != null) {
            Arrays.sort(dirFiles, Comparator.comparing(File::getName));
        } else {
            dirFiles = new File[]{};
        }
        return dirFiles;
    }
}