| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393 |
- package cz.senslog.watchdog.config;
- import org.apache.logging.log4j.LogManager;
- import org.apache.logging.log4j.Logger;
- import org.yaml.snakeyaml.Yaml;
- import java.io.FileNotFoundException;
- import java.io.IOException;
- import java.io.InputStream;
- import java.nio.file.Files;
- import java.nio.file.Path;
- import java.nio.file.Paths;
- import java.util.*;
- import static java.util.Collections.emptyList;
- import static java.util.Collections.singletonList;
- public class Configuration {
- private static final Logger logger = LogManager.getLogger(Configuration.class);
- private final GeneralConfig generalConfig;
- private final Collection<ExecutableGroup> execGroups;
- private final Collection<ExecutableSuperGroup> execSuperGroups;
- private final Collection<MessageBrokerConfig> messageBrokerConfigs;
- private final Collection<EmailServerConfig> emailServerConfigs;
- private final Collection<SensLogServerConfig> sensLogServerConfigs;
- private final Collection<DataProviderConfig> dataProviderConfigs;
- private Configuration(
- GeneralConfig generalConfig,
- Collection<ExecutableGroup> executableGroups,
- Collection<ExecutableSuperGroup> execSGroups,
- Collection<EmailServerConfig> emailServerConfigs,
- Collection<MessageBrokerConfig> messageBrokerConfigs,
- Collection<SensLogServerConfig> sensLogServerConfigs,
- Collection<DataProviderConfig> dataProviderConfigs
- ){
- this.generalConfig = generalConfig;
- this.execGroups = executableGroups;
- this.execSuperGroups = execSGroups;
- this.messageBrokerConfigs = messageBrokerConfigs;
- this.emailServerConfigs = emailServerConfigs;
- this.sensLogServerConfigs = sensLogServerConfigs;
- this.dataProviderConfigs = dataProviderConfigs;
- }
- private static Configuration make(
- GeneralConfig generalConfig,
- List<TempUnitConfig> monitoredObjects,
- Map<String, EmailServerConfig> emailServers,
- Map<String, MessageBrokerConfig> messageBrokers,
- Map<String, SensLogServerConfig> sensLogServers,
- Map<String, DataProviderConfig> dataProviders,
- Map<String, GroupConfig> groups,
- Map<String, SuperGroupConfig> superGroups
- ) {
- Map<String, ExecutableGroup> executableGroupsMap = new HashMap<>();
- for (TempUnitConfig mObject : monitoredObjects) {
- Set<String> unitGroups = mObject.groups;
- List<TempSensorConfig> sensors = mObject.sensors;
- if (unitGroups.isEmpty() && sensors.isEmpty()) {
- throw new IllegalStateException("The monitored object '"+mObject.id+"' is not assigned to any groups.");
- }
- sensors = !sensors.isEmpty() ? sensors : singletonList(new TempAllSensorsConfig(mObject.period));
- for (TempSensorConfig sensor : sensors) {
- String sensorId = sensor.id != null ? sensor.id : mObject.id;
- Set<String> sensorGroups = sensor.groups;
- if (unitGroups.isEmpty() && sensorGroups.isEmpty()) {
- throw new IllegalStateException("The monitored object '"+sensorId+"' is not assigned to any groups.");
- }
- sensorGroups.addAll(unitGroups);
- for (String groupId : sensorGroups) {
- GroupConfig groupConfig = groups.get(groupId);
- if (groupConfig == null) {
- throw new IllegalStateException(
- "Assigned group '"+groupId+"' to the monitored object '"+sensorId+"' does not exist."
- );
- }
- Integer period = groupConfig.getPeriod() != null ? groupConfig.getPeriod() : mObject.period;
- period = period != null ? period : sensor.period;
- if (period == null) {
- throw new IllegalStateException(
- "The monitored object '"+sensor.id+"' does not contain a valid 'period' value."
- );
- }
- if (!dataProviders.containsKey(groupConfig.getDataProviderId())) {
- throw new IllegalStateException(
- "Assigned data provider '"+groupConfig.getDataProviderId()+"' does not exist."
- );
- }
- if (!messageBrokers.containsKey(groupConfig.getMessageBrokerId())) {
- throw new IllegalStateException(
- "Assigned message broker '"+groupConfig.getMessageBrokerId()+"' does not exist."
- );
- }
- ExecutableGroup executableGroup = executableGroupsMap.computeIfAbsent(
- groupId, k -> new ExecutableGroup(groupConfig)
- );
- MonitoredObject sensorMObj = sensor.id != null ? new MonitoredObject(sensor.id, period) : new AllMonitoredObjects(period);
- executableGroup.swapPeriod(sensorMObj.getPeriod());
- executableGroup.computeIfAbsent(mObject.id, MonitoredObject::new)
- .addNode(sensorMObj.getId(), sensorMObj);
- }
- }
- }
- for (Map.Entry<String, GroupConfig> groupEntry : groups.entrySet()) {
- String groupId = groupEntry.getKey();
- GroupConfig groupConfig = groupEntry.getValue();
- if (!executableGroupsMap.containsKey(groupId)) {
- MonitoredObject allSensors = new AllMonitoredObjects(groupConfig.getPeriod());
- executableGroupsMap.computeIfAbsent(groupId, k -> new ExecutableGroup(groupConfig))
- .computeIfAbsent(groupId, k -> new AllMonitoredObjects(groupConfig.getPeriod()))
- .addNode(allSensors.getId(), allSensors);
- }
- }
- Map<String, ExecutableSuperGroup> executableSGroupsMap = new HashMap<>();
- for (SuperGroupConfig sGConfig : superGroups.values()) {
- if (sGConfig.getPeriod() == null) {
- throw new IllegalStateException(
- "The monitored object '"+sGConfig.getId()+"' does not contain a valid 'period' value."
- );
- }
- ExecutableSuperGroup executableSuperGroup = new ExecutableSuperGroup(sGConfig);
- for (String groupId : sGConfig.getGroups()) {
- ExecutableGroup group = executableGroupsMap.get(groupId);
- if (group == null) {
- throw new IllegalStateException("Assigned group '"+groupId+"' does not exist.");
- }
- GroupConfig gConfig = group.getConfig();
- GroupConfig newGConfig = new GroupConfig(gConfig.getId(), gConfig.getName(), true,
- gConfig.getDataProviderId(), gConfig.getMessageBrokerId(), sGConfig.getPeriod()
- );
- executableSuperGroup.addNode(groupId, ExecutableGroup.copy(group, newGConfig));
- }
- executableSGroupsMap.put(sGConfig.getId(), executableSuperGroup);
- }
- Collection<ExecutableGroup> execGroups = executableGroupsMap.values();
- Collection<ExecutableSuperGroup> execSGroups = executableSGroupsMap.values();
- Collection<EmailServerConfig> emailServerConfigs = emailServers.values();
- Collection<SensLogServerConfig> sensLogServerConfigs = sensLogServers.values();
- Collection<DataProviderConfig> dataProviderConfigs = dataProviders.values();
- Collection<MessageBrokerConfig> messageBrokerConfigs = messageBrokers.values();
- return new Configuration(generalConfig, execGroups, execSGroups,
- emailServerConfigs, messageBrokerConfigs,
- sensLogServerConfigs, dataProviderConfigs
- );
- }
- public static Configuration load(String fileName) throws IOException {
- logger.info("Loading '{}' configuration file.", fileName);
- if (!fileName.toLowerCase().endsWith(".yaml")) {
- throw new IllegalArgumentException(fileName + "does not contain .yaml extension.");
- }
- Path filePath = Paths.get(fileName);
- if (Files.notExists(filePath)) {
- throw new FileNotFoundException(fileName + " does not exist");
- }
- Map<Object, Object> properties;
- logger.debug("Opening the file '{}'.", fileName);
- try (InputStream fileStream = Files.newInputStream(filePath)) {
- logger.debug("Parsing the yaml file '{}'.", fileName);
- properties = new Yaml().load(fileStream);
- logger.debug("The configuration yaml file '{}' was parsed successfully.", fileName);
- }
- if (properties == null || properties.isEmpty()) {
- throw new IOException(String.format(
- "The configuration yaml file %s is empty or was not loaded successfully. ", fileName
- ));
- }
- try {
- return make(
- parseGeneralConfig(createPropertyConfig(properties, "general")),
- parseMonitoredObjects(createPropertyConfig(properties, "monitoredObjects")),
- parseEmailServers(createPropertyConfig(properties, "emailServers")),
- parseMessageBrokers(createPropertyConfig(properties, "messageBrokers")),
- parseSensLogServers(createPropertyConfig(properties, "senslogServers")),
- parseDataProviders(createPropertyConfig(properties, "dataProviders")),
- parseGroups(createPropertyConfig(properties, "groups")),
- parseSuperGroups(createPropertyConfig(properties, "superGroups"))
- );
- } catch (IOException e) {
- throw new IOException(String.format(
- "Configuration file '%s' contains an error at '%s' attribute.", fileName, e.getMessage()
- ));
- }
- }
- private static GeneralConfig parseGeneralConfig(PropertyConfig config) {
- return new GeneralConfig(config);
- }
- private static Map<String, EmailServerConfig> parseEmailServers(PropertyConfig config) {
- Set<String> serverIds = config.getAttributes();
- Map<String, EmailServerConfig> emailServers = new HashMap<>();
- for (String id : serverIds) {
- PropertyConfig serverConfig = config.getPropertyConfig(id);
- emailServers.put(id, EmailServerConfig.create(serverConfig));
- }
- return emailServers;
- }
- private static Map<String, MessageBrokerConfig> parseMessageBrokers(PropertyConfig config) {
- Set<String> brokerIds = config.getAttributes();
- Map<String, MessageBrokerConfig> messageBrokers = new HashMap<>(brokerIds.size());
- for (String id : brokerIds) {
- PropertyConfig brokerConfig = config.getPropertyConfig(id);
- MessageBrokerType type = MessageBrokerType.of(brokerConfig.getStringProperty("type"));
- messageBrokers.put(id, type.createConfig(id, brokerConfig.getPropertyConfig("config"))
- );
- }
- return messageBrokers;
- }
- private static Map<String, SensLogServerConfig> parseSensLogServers(PropertyConfig config) {
- Set<String> serverIds = config.getAttributes();
- Map<String, SensLogServerConfig> serverConfigs = new HashMap<>(serverIds.size());
- for (String id : serverIds) {
- PropertyConfig serverConfig = config.getPropertyConfig(id);
- serverConfigs.put(id, SensLogServerConfig.create(serverConfig));
- }
- return serverConfigs;
- }
- private static Map<String, DataProviderConfig> parseDataProviders(PropertyConfig config) {
- Set<String> providerIds = config.getAttributes();
- Map<String, DataProviderConfig> dataProviders = new HashMap<>(providerIds.size());
- for (String id : providerIds) {
- PropertyConfig providerConfig = config.getPropertyConfig(id);
- DataProviderType type = DataProviderType.of(providerConfig.getStringProperty("type"));
- dataProviders.put(id, type.createConfig(id, providerConfig.getPropertyConfig("config")));
- }
- return dataProviders;
- }
- private static Map<String, GroupConfig> parseGroups(PropertyConfig config) {
- Set<String> groupIds = config.getAttributes();
- Map<String, GroupConfig> groups = new HashMap<>(groupIds.size());
- for (String id : groupIds) {
- PropertyConfig groupConfig = config.getPropertyConfig(id);
- groups.put(id, GroupConfig.create(groupConfig));
- }
- return groups;
- }
- private static Map<String, SuperGroupConfig> parseSuperGroups(PropertyConfig config) {
- Set<String> groupIds = config.getAttributes();
- Map<String, SuperGroupConfig> groups = new HashMap<>(groupIds.size());
- for (String id : groupIds) {
- PropertyConfig groupConfig = config.getPropertyConfig(id);
- List<String> subGroupList = groupConfig.getArrayPropertyOf("groups", String.class);
- Set<String> subGroupNames = new HashSet<>(subGroupList);
- groups.put(id, new SuperGroupConfig(id,
- groupConfig.getStringProperty("name"),
- groupConfig.getStringProperty("messageBroker"),
- groupConfig.getOptionalProperty("period", Integer.class).orElse(null),
- subGroupNames
- ));
- }
- return groups;
- }
- private static List<TempUnitConfig> parseMonitoredObjects(PropertyConfig config) {
- Set<String> unitIds = config.getAttributes();
- List<TempUnitConfig> unitConfigs = new ArrayList<>(unitIds.size());
- for (String unitId : unitIds) {
- PropertyConfig unitConfig = config.getPropertyConfig(unitId);
- Integer unitPeriod = unitConfig.getOptionalProperty("period", Integer.class).orElse(null);
- List<String> unitGroupList = unitConfig.containsProperty("groups") ? unitConfig.getArrayPropertyOf("groups", String.class) : null;
- Set<String> unitGroups = unitGroupList != null ? new HashSet<>(unitGroupList) : new HashSet<>();
- List<TempSensorConfig> sensorConfigList = new ArrayList<>();
- if (unitConfig.containsProperty("sensors")) {
- Object sensorsObj = unitConfig.getProperty("sensors");
- if (sensorsObj instanceof List) {
- List<Integer> sensors = unitConfig.getArrayPropertyOf("sensors", Integer.class);
- for (Integer sensorId : sensors) {
- sensorConfigList.add(new TempSensorConfig(Integer.toString(sensorId), unitPeriod, new HashSet<>()));
- }
- } else if (sensorsObj instanceof Map) {
- PropertyConfig sensorsConfig = unitConfig.getPropertyConfig("sensors");
- Set<String> sensorIds = sensorsConfig.getAttributes();
- for (String sensorId : sensorIds) {
- PropertyConfig sensorConfig = sensorsConfig.getPropertyConfig(sensorId);
- Integer sensorPeriod = sensorConfig.getOptionalProperty("period", Integer.class).orElse(unitPeriod);
- List<String> sensorGroupList = sensorConfig.containsProperty("groups") ? sensorConfig.getArrayPropertyOf("groups", String.class) : emptyList();
- sensorConfigList.add(new TempSensorConfig(sensorId, sensorPeriod, new HashSet<>(sensorGroupList)));
- }
- }
- }
- unitConfigs.add(new TempUnitConfig(unitId, unitPeriod, sensorConfigList, unitGroups));
- }
- return unitConfigs;
- }
- private static PropertyConfig createPropertyConfig(Map<Object, Object> properties, String propertyName) throws IOException {
- Object generalConfig = properties.get(propertyName);
- if (generalConfig == null) {
- return new PropertyConfig(propertyName, propertyName);
- }
- if (!(generalConfig instanceof Map)) {
- throw new IOException(propertyName);
- }
- Map<?, ?> generalConfigMap = (Map<?, ?>) generalConfig;
- PropertyConfig propertyConfig = new PropertyConfig(propertyName, propertyName);
- for (Map.Entry<?, ?> entry : generalConfigMap.entrySet()) {
- String keyName = entry.getKey().toString();
- propertyConfig.setProperty(keyName, entry.getValue());
- }
- return propertyConfig;
- }
- public Collection<MessageBrokerConfig> getMessageBrokerConfigs() {
- return messageBrokerConfigs;
- }
- public Collection<EmailServerConfig> getEmailServerConfigs() {
- return emailServerConfigs;
- }
- public Collection<SensLogServerConfig> getSensLogServerConfigs() {
- return sensLogServerConfigs;
- }
- public Collection<DataProviderConfig> getDataProviderConfigs() {
- return dataProviderConfigs;
- }
- public Collection<ExecutableGroup> getExecGroups() {
- return execGroups;
- }
- public GeneralConfig getGeneralConfig() {
- return generalConfig;
- }
- public Collection<ExecutableSuperGroup> getSuperGroupsConfig() {
- return execSuperGroups;
- }
- private static class TempUnitConfig {
- private final String id;
- private final Integer period;
- private final List<TempSensorConfig> sensors;
- private final Set<String> groups;
- private TempUnitConfig(String id, Integer period, List<TempSensorConfig> sensors, Set<String> groups) {
- this.id = id;
- this.period = period;
- this.sensors = sensors;
- this.groups = groups;
- }
- }
- private static class TempSensorConfig {
- private final String id;
- private final Integer period;
- private final Set<String> groups;
- private TempSensorConfig(String id, Integer period, Set<String> groups) {
- this.id = id;
- this.period = period;
- this.groups = groups;
- }
- }
- private static class TempAllSensorsConfig extends TempSensorConfig {
- private TempAllSensorsConfig(Integer period) {
- super(null, period, new HashSet<>());
- }
- }
- }
|