aboutsummaryrefslogtreecommitdiffstats
path: root/policy-management/src/main/java/org/onap/policy/drools/persistence/FileSystemPersistence.java
blob: b1e49ec2f96a3e82aa373ff442f0d104bea3145a (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
/*
 * ============LICENSE_START=======================================================
 * policy-management
 * ================================================================================
 * Copyright (C) 2017-2018 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.List;
import java.util.Properties;

import org.onap.policy.drools.properties.DroolsProperties;
import org.onap.policy.drools.utils.PropertyUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Properties based Persistence
 */
public class FileSystemPersistence implements SystemPersistence {
  /**
   * policy controllers suffix
   */
  public static final String CONTROLLER_SUFFIX_IDENTIFIER = "-controller";

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

  /**
   * policy controller properties file suffix
   */
  public static final String PROPERTIES_FILE_CONTROLLER_BACKUP_SUFFIX =
      CONTROLLER_SUFFIX_IDENTIFIER + ".properties.bak";

  /**
   * policy engine properties file name
   */
  public static final String PROPERTIES_FILE_ENGINE = "policy-engine.properties";

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

  /**
   * configuration directory
   */
  protected Path configurationDirectory = Paths.get(DEFAULT_CONFIGURATION_DIR);

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


  @Override
  public void setConfigurationDir(String configDir) {
    String tempConfigDir = configDir;
    
    if (tempConfigDir == null) {
        tempConfigDir = DEFAULT_CONFIGURATION_DIR;
      this.configurationDirectory = Paths.get(DEFAULT_CONFIGURATION_DIR);
    }

    if (!tempConfigDir.equals(DEFAULT_CONFIGURATION_DIR))
      this.configurationDirectory = Paths.get(tempConfigDir);

    if (Files.notExists(this.configurationDirectory)) {
      try {
        Files.createDirectories(this.configurationDirectory);
      } catch (final IOException e) {
        throw new IllegalStateException("cannot create " + this.configurationDirectory, e);
      }
    }

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

  @Override
  public Path getConfigurationPath() {
    return this.configurationDirectory;
  }

  @Override
  public Properties getEngineProperties() {
    final Path policyEnginePath =
        Paths.get(this.configurationDirectory.toString(), PROPERTIES_FILE_ENGINE);
    try {
      if (Files.exists(policyEnginePath))
        return PropertyUtil.getProperties(policyEnginePath.toFile());
    } catch (final Exception e) {
      logger.warn("{}: could not find {}", this, policyEnginePath, e);
    }

    return null;
  }

  @Override
  public boolean backupController(String controllerName) {
    final Path controllerPropertiesPath = Paths.get(this.configurationDirectory.toString(),
        controllerName + PROPERTIES_FILE_CONTROLLER_SUFFIX);

    if (Files.exists(controllerPropertiesPath)) {
      try {
        logger.info("{}: there is an existing configuration file @ {} ", this,
            controllerPropertiesPath);
        final Path controllerPropertiesBakPath = Paths.get(this.configurationDirectory.toString(),
            controllerName + PROPERTIES_FILE_CONTROLLER_BACKUP_SUFFIX);
        Files.copy(controllerPropertiesPath, controllerPropertiesBakPath,
            StandardCopyOption.REPLACE_EXISTING);
      } catch (final Exception e) {
        logger.warn("{}: {} cannot be backed up", this, controllerName, e);
        return false;
      }
    }

    return true;
  }

  @Override
  public boolean storeController(String controllerName, Object configuration) {
    if (!(configuration instanceof Properties))
      throw new IllegalArgumentException(
          "configuration must be of type properties to be handled by this manager");

    final Properties properties = (Properties) configuration;

    final Path controllerPropertiesPath = Paths.get(this.configurationDirectory.toString(),
        controllerName + PROPERTIES_FILE_CONTROLLER_SUFFIX);
    if (Files.exists(controllerPropertiesPath)) {
      try {
        final Properties oldProperties =
            PropertyUtil.getProperties(controllerPropertiesPath.toFile());
        if (oldProperties.equals(properties)) {
          logger.info(
              "{}: noop: a properties file with the same contents exists for controller {}.", this,
              controllerName);
          return true;
        } else {
          this.backupController(controllerName);
        }
      } catch (final Exception e) {
        logger.info("{}: no existing {} properties {}", this, controllerName, e);
        // continue
      }
    }

    final File controllerPropertiesFile = controllerPropertiesPath.toFile();
    try (FileWriter writer = new FileWriter(controllerPropertiesFile)) {
      properties.store(writer, "Machine created Policy Controller Configuration");
    } catch (final Exception e) {
      logger.warn("{}: {} cannot be saved", this, controllerName, e);
      return false;
    }

    return true;
  }

  @Override
  public boolean deleteController(String controllerName) {
    final Path controllerPropertiesPath = Paths.get(this.configurationDirectory.toString(),
        controllerName + PROPERTIES_FILE_CONTROLLER_SUFFIX);

    if (Files.exists(controllerPropertiesPath)) {
      try {
        final Path controllerPropertiesBakPath = Paths.get(this.configurationDirectory.toString(),
            controllerName + PROPERTIES_FILE_CONTROLLER_BACKUP_SUFFIX);
        Files.move(controllerPropertiesPath, controllerPropertiesBakPath,
            StandardCopyOption.REPLACE_EXISTING);
      } catch (final Exception e) {
        logger.warn("{}: {} cannot be deleted", this, controllerName, e);
        return false;
      }
    }

    return true;
  }

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

  @Override
  public List<Properties> getControllerProperties() {
    final List<Properties> controllers = new ArrayList<>();
    final File[] controllerFiles = this.sortedListFiles();
    for (final File controllerFile : controllerFiles) {
      if (controllerFile.getName().endsWith(PROPERTIES_FILE_CONTROLLER_SUFFIX)) {
        final int idxSuffix = controllerFile.getName().indexOf(PROPERTIES_FILE_CONTROLLER_SUFFIX);
        final int lastIdxSuffix =
            controllerFile.getName().lastIndexOf(PROPERTIES_FILE_CONTROLLER_SUFFIX);
        if (idxSuffix != lastIdxSuffix)
          throw new IllegalArgumentException(
              "Improper naming of controller properties file: " + "Expected <controller-name>"
                  + FileSystemPersistence.PROPERTIES_FILE_CONTROLLER_SUFFIX);

        final String name = controllerFile.getName().substring(0, lastIdxSuffix);
        try {
          final Properties controllerProperties = this.getControllerProperties(name);
          final String controllerName =
              controllerProperties.getProperty(DroolsProperties.PROPERTY_CONTROLLER_NAME);
          if (controllerName == null) {
            controllerProperties.setProperty(DroolsProperties.PROPERTY_CONTROLLER_NAME, name);
          } else if (!controllerName.equals(name)) {
            logger.error("{}: mismatch controller named {} with file name {}", this, controllerName,
                controllerFile.getName());
            continue;
          }
          controllers.add(this.getControllerProperties(name));
        } catch (final Exception e) {
          logger.error("{}: cannot obtain properties for controller {} because of {}", name,
              e.getMessage(), e);
        }
      }
    }
    return controllers;
  }

  @Override
  public Properties getProperties(String name) {
    final Path propertiesPath =
        Paths.get(this.configurationDirectory.toString(), name + ".properties");

    if (!Files.exists(propertiesPath)) {
      throw new IllegalArgumentException("properties for " + name + " are not persisted.");
    }

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

  @Override
  public List<Properties> getEnvironmentProperties() {
    final List<Properties> envs = new ArrayList<>();
    final File[] envFiles = this.sortedListFiles();
    for (final File envFile : envFiles) {
      if (envFile.getName().endsWith(ENV_SUFFIX)) {
        final String name = envFile.getName().substring(0, envFile.getName().indexOf(ENV_SUFFIX));
        try {
          envs.add(this.getEnvironmentProperties(name));
        } catch (final Exception e) {
          logger.error("{}: cannot get environment {} because of {}", name, e.getMessage(), e);
        }
      }
    }
    return envs;
  }

  @Override
  public Properties getEnvironmentProperties(String name) {
    final Path envPath = Paths.get(this.configurationDirectory.toString(), name + ENV_SUFFIX);
    if (!Files.exists(envPath)) {
      throw new IllegalArgumentException("{} environment" + name + " cannot be retrieved");
    }

    try {
      return PropertyUtil.getProperties(envPath.toFile());
    } catch (final Exception e) {
      throw new IllegalArgumentException("cannot read environment " + name, e);
    }
  }

  /**
   * provides a list of files sorted by name in ascending order in the configuration directory
   */
  protected File[] sortedListFiles() {
    final File[] dirFiles = this.configurationDirectory.toFile().listFiles();
    Arrays.sort(dirFiles, (a, b) -> a.getName().compareTo(b.getName()));
    return dirFiles;
  }

  @Override
  public String toString() {
    final StringBuilder builder = new StringBuilder();
    builder.append("FileSystemPersistence [configurationDirectory=")
        .append(this.configurationDirectory).append("]");
    return builder.toString();
  }
}