smolnar82 commented on a change in pull request #239: KNOX-2153 - CM discovery - Monitor Cloudera Manager URL: https://github.com/apache/knox/pull/239#discussion_r368881744
########## File path: gateway-discovery-cm/src/main/java/org/apache/knox/gateway/topology/discovery/cm/ClouderaManagerClusterConfigurationMonitor.java ########## @@ -0,0 +1,940 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with this + * work for additional information regarding copyright ownership. The ASF + * licenses this file to you 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.apache.knox.gateway.topology.discovery.cm; + +import com.cloudera.api.swagger.EventsResourceApi; +import com.cloudera.api.swagger.RolesResourceApi; +import com.cloudera.api.swagger.ServicesResourceApi; +import com.cloudera.api.swagger.client.ApiClient; +import com.cloudera.api.swagger.client.ApiException; +import com.cloudera.api.swagger.model.ApiConfig; +import com.cloudera.api.swagger.model.ApiConfigList; +import com.cloudera.api.swagger.model.ApiEvent; +import com.cloudera.api.swagger.model.ApiEventAttribute; +import com.cloudera.api.swagger.model.ApiEventCategory; +import com.cloudera.api.swagger.model.ApiEventQueryResult; +import com.cloudera.api.swagger.model.ApiRole; +import com.cloudera.api.swagger.model.ApiRoleList; +import com.cloudera.api.swagger.model.ApiServiceConfig; +import org.apache.commons.io.FileUtils; +import org.apache.knox.gateway.config.GatewayConfig; +import org.apache.knox.gateway.i18n.messages.MessagesFactory; +import org.apache.knox.gateway.services.security.AliasService; +import org.apache.knox.gateway.topology.discovery.ClusterConfigurationMonitor; +import org.apache.knox.gateway.topology.discovery.ServiceDiscoveryConfig; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.OutputStream; +import java.io.Serializable; +import java.nio.file.Files; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Properties; +import java.util.Set; +import java.util.TimeZone; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.locks.ReadWriteLock; +import java.util.concurrent.locks.ReentrantReadWriteLock; + +/** + * ClusterConfigurationMonitor implementation for clusters managed by ClouderaManager. + */ +public class ClouderaManagerClusterConfigurationMonitor implements ClusterConfigurationMonitor { + + private static final String TYPE = "CM"; + + private static final String CLUSTERS_DATA_DIR_NAME = TYPE + "-clusters"; + + private static final String PERSISTED_FILE_COMMENT = "Generated File. Do Not Edit!"; + + private static final String PROP_CLUSTER_PREFIX = "cluster."; + private static final String PROP_CLUSTER_SOURCE = PROP_CLUSTER_PREFIX + "source"; + private static final String PROP_CLUSTER_NAME = PROP_CLUSTER_PREFIX + "name"; + private static final String PROP_CLUSTER_USER = PROP_CLUSTER_PREFIX + "user"; + private static final String PROP_CLUSTER_ALIAS = PROP_CLUSTER_PREFIX + "pwd.alias"; + + private static final ClouderaManagerServiceDiscoveryMessages log = + MessagesFactory.get(ClouderaManagerServiceDiscoveryMessages.class); + + + // The format of the filter employed when restart events are queried from ClouderaManager + private static final String RESTART_EVENTS_QUERY_FORMAT = "category==" + ApiEventCategory.AUDIT_EVENT.getValue() + + ";attributes.command==Restart" + + ";attributes.command_status==SUCCEEDED" + + ";attributes.cluster==\"%s\"%s"; + + // The format of the timestamp element of the restart events query filter + private static final String EVENTS_QUERY_TIMESTAMP_FORMAT = ";timeOccurred=gt=%s"; + + // The default amount of time before "now" the monitor will check for restart events the first time + private static final long DEFAULT_EVENT_QUERY_DEFAULT_TIMESTAMP_OFFSET = (60 * 60 * 1000); // one hour + + // ISO 8601 datetime format for restart event query filtering + private DateFormat eventQueryTimestampFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'", Locale.getDefault()); + + private GatewayConfig gatewayConfig; + private AliasService aliasService; + private PollingConfigAnalyzer internalMonitor; + private List<ConfigurationChangeListener> changeListeners = new ArrayList<>(); + + // Cache of ClouderaManager API clients, keyed by discovery address + private Map<String, DiscoveryApiClient> clients = new ConcurrentHashMap<>(); + + // ClouderaManager address + // clusterName -> ServiceDiscoveryConfig + // + private Map<String, Map<String, ServiceDiscoveryConfig>> clusterMonitorConfigurations = new ConcurrentHashMap<>(); + + // ClouderaManager address + // clusterName + // serviceType -> Properties + // + private Map<String, Map<String, Map<String, ServiceConfigurationProperties>>> clusterServiceConfigurations = + new ConcurrentHashMap<>(); + + private ReadWriteLock serviceConfigurationsLock = new ReentrantReadWriteLock(); + + private ReadWriteLock clusterMonitorConfigurationsLock = new ReentrantReadWriteLock(); + + // Timestamp records of the most recent restart event query per discovery address + private Map<String, String> eventQueryTimestamps = new ConcurrentHashMap<>(); + + // The amount of time before "now" the monitor will check for restart events the first time + private long eventQueryDefaultTimestampOffset = DEFAULT_EVENT_QUERY_DEFAULT_TIMESTAMP_OFFSET; + + static String getType() { + return TYPE; + } + + ClouderaManagerClusterConfigurationMonitor(final GatewayConfig config, final AliasService aliasService) { + this.gatewayConfig = config; + this.aliasService = aliasService; + this.internalMonitor = new PollingConfigAnalyzer(this); + + eventQueryTimestampFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + + // Override the default polling interval if it has been configured + // (org.apache.knox.gateway.topology.discovery.cm.monitor.interval) + int interval = config.getClusterMonitorPollingInterval(getType()); + if (interval > 0) { + setPollingInterval(interval); + } + + init(); + } + + @Override + @SuppressWarnings("PMD.DoNotUseThreads") + public void start() { + log.startingClouderaManagerConfigMonitor(); + (new Thread(internalMonitor, "ClouderaManagerConfigurationMonitor")).start(); + } + + @Override + public void stop() { + log.stoppingClouderaManagerConfigMonitor(); + internalMonitor.stop(); + } + + @Override + public void setPollingInterval(int interval) { + internalMonitor.setInterval(interval); + } + + @Override + public void addListener(final ConfigurationChangeListener listener) { + changeListeners.add(listener); + } + + @Override + public void clearCache(String source, String clusterName) { + removeServiceConfiguration(source, clusterName); + } + + /** + * Add the specified cluster service configurations to the monitor. + * + * @param cluster The cluster to be added. + * @param discoveryConfig The discovery configuration associated with the cluster. + */ + void addServiceConfiguration(final ClouderaManagerCluster cluster, + final ServiceDiscoveryConfig discoveryConfig) { + + String address = discoveryConfig.getAddress(); + String clusterName = cluster.getName(); + + // Disregard restart events, which occurred before now in future polling + setEventQueryTimestamp(address, clusterName, new Date()); + + persistDiscoveryConfiguration(clusterName, discoveryConfig); + addDiscoveryConfig(clusterName, discoveryConfig); + + Map<String, List<ServiceModel>> serviceModels = cluster.getServiceModels(); + + // Process the service models + Map<String, ServiceConfigurationProperties> scpMap = new HashMap<>(); + for (String service : serviceModels.keySet()) { + for (ServiceModel model : serviceModels.get(service)) { + ServiceConfigurationProperties scp = + scpMap.computeIfAbsent(model.getServiceType(), p -> new ServiceConfigurationProperties()); + + Map<String, String> serviceProps = model.getServiceProperties(); + for (Map.Entry<String, String> entry : serviceProps.entrySet()) { + scp.addServiceProperty(entry.getKey(), entry.getValue()); + } + + Map<String, Map<String, String>> roleProps = model.getRoleProperties(); + for (String roleName : roleProps.keySet()) { + Map<String, String> rp = roleProps.get(roleName); + for (Map.Entry<String, String> entry : rp.entrySet()) { + scp.addRoleProperty(roleName, entry.getKey(), entry.getValue()); + } + } + } + } + + // Persist the service configurations + persistServiceConfiguration(address, clusterName, scpMap); + + // Add the service configurations + addServiceConfiguration(address, clusterName, scpMap); + } + + private void addServiceConfiguration(final String address, + final String cluster, + final Map<String, ServiceConfigurationProperties> configs) { + serviceConfigurationsLock.writeLock().lock(); + try { + clusterServiceConfigurations.computeIfAbsent(address, k -> new HashMap<>()).put(cluster, configs); + } finally { + serviceConfigurationsLock.writeLock().unlock(); + } + } + + private void init() { + // Load any persisted discovery configuration data + loadDiscoveryConfiguration(); + + // Load any persisted cluster service configuration data + loadServiceConfiguration(); + } + + /** + * Get a DiscoveryApiClient for the ClouderaManager instance described by the specified discovery configuration. + * + * @param discoveryConfig The discovery configuration for interacting with a ClouderaManager instance. + */ + private DiscoveryApiClient getApiClient(final ServiceDiscoveryConfig discoveryConfig) { + return clients.computeIfAbsent(discoveryConfig.getAddress(), + c -> new DiscoveryApiClient(discoveryConfig, aliasService)); + } + + /** + * Load any previously-persisted service discovery configurations. + */ + private void loadDiscoveryConfiguration() { + File persistenceDir = getPersistenceDir(); + if (persistenceDir != null) { + Collection<File> persistedConfigs = FileUtils.listFiles(persistenceDir, new String[]{"conf"}, false); + for (File persisted : persistedConfigs) { + Properties props = new Properties(); + try (InputStream in = Files.newInputStream(persisted.toPath())) { + props.load(in); + + addDiscoveryConfig(props.getProperty(PROP_CLUSTER_NAME), new ServiceDiscoveryConfig() { + @Override + public String getAddress() { + return props.getProperty(PROP_CLUSTER_SOURCE); + } + + @Override + public String getUser() { + return props.getProperty(PROP_CLUSTER_USER); + } + + @Override + public String getPasswordAlias() { + return props.getProperty(PROP_CLUSTER_ALIAS); + } + }); + } catch (IOException e) { + log.failedToLoadClusterMonitorServiceDiscoveryConfig(getType(), e); + } + } + } + } + + /** + * Load any previously-persisted cluster service configuration data records, so the monitor can check + * previously-deployed topologies against the current cluster configuration, even across gateway restarts. + */ + private void loadServiceConfiguration() { + File persistenceDir = getPersistenceDir(); + if (persistenceDir != null) { + Collection<File> persistedConfigs = FileUtils.listFiles(persistenceDir, new String[]{"ver"}, false); + for (File persisted : persistedConfigs) { + try (ObjectInputStream in = new ObjectInputStream(Files.newInputStream(persisted.toPath()))) { + String clusterName = (String) in.readObject(); + String discoveryAddress = (String) in.readObject(); + Map<String, ServiceConfigurationProperties> configs = + (Map<String, ServiceConfigurationProperties>) in.readObject(); + + addServiceConfiguration(discoveryAddress, clusterName, configs); + } catch (Exception e) { + log.failedToLoadClusterMonitorServiceConfigurations(getType(), e); + } + } + } + } + + /** + * Add discovery configuration details for the specified cluster, so the monitor knows how to connect to check for + * changes. + * + * @param clusterName The name of the cluster. + * @param config The associated service discovery configuration. + */ + private void addDiscoveryConfig(final String clusterName, final ServiceDiscoveryConfig config) { + clusterMonitorConfigurationsLock.writeLock().lock(); + try { + clusterMonitorConfigurations.computeIfAbsent(config.getAddress(), k -> new HashMap<>()).put(clusterName, config); + } finally { + clusterMonitorConfigurationsLock.writeLock().unlock(); + } + } + + /** + * Get the service discovery configuration associated with the specified ClouderaManager instance and cluster. + * + * @param address An ClouderaManager instance address. + * @param clusterName The name of a cluster associated with the ClouderaManager instance. + * + * @return The associated ServiceDiscoveryConfig object. + */ + private ServiceDiscoveryConfig getDiscoveryConfig(final String address, final String clusterName) { + ServiceDiscoveryConfig config = null; + clusterMonitorConfigurationsLock.readLock().lock(); + try { + if (clusterMonitorConfigurations.containsKey(address)) { + config = clusterMonitorConfigurations.get(address).get(clusterName); + } + } finally { + clusterMonitorConfigurationsLock.readLock().unlock(); + } + return config; + } + + /** + * Get the service configuration details for the specified cluster and ClouderaManager instance. + * + * @param address A ClouderaManager instance address. + * @param clusterName The name of a cluster associated with the ClouderaManager instance. + * + * @return A Map of service types to their corresponding configuration properties. + */ + private Map<String, ServiceConfigurationProperties> getClusterServiceConfigurations(String address, + String clusterName) { + Map<String, ServiceConfigurationProperties> result = new HashMap<>(); + + serviceConfigurationsLock.readLock().lock(); + try { + if (clusterServiceConfigurations.containsKey(address)) { + result.putAll(clusterServiceConfigurations.get(address).get(clusterName)); + } + } finally { + serviceConfigurationsLock.readLock().unlock(); + } + + return result; + } + + /** + * Remove the specified cluster from monitoring. + * + * @param address The address of the ClouderaManager instance. + * @param clusterName The name of the cluster. + */ + private void removeServiceConfiguration(final String address, final String clusterName) { + serviceConfigurationsLock.writeLock().lock(); + try { + clusterServiceConfigurations.get(address).remove(clusterName); + } finally { + serviceConfigurationsLock.writeLock().unlock(); + } + + // Delete the associated persisted record + File persisted = getServiceConfigsPersistenceFile(address, clusterName); + if (persisted.exists()) { + persisted.delete(); + } + } + + /** + * Get the current configuration for the specified service. + * + * @param address The address of the ClouderaManager instance. + * @param clusterName The name of the cluster. + * @param service The name of the service. + * + * @return A ServiceConfigurationProperties object with the configuration properties associated with the specified + * service. + */ + private ServiceConfigurationProperties getCurrentServiceConfiguration(final String address, + final String clusterName, + final String service) { + ServiceConfigurationProperties currentConfig = null; + + log.gettingCurrentClusterConfiguration(service, clusterName, address); + + ApiClient apiClient = getApiClient(getDiscoveryConfig(address, clusterName)); + ServicesResourceApi api = new ServicesResourceApi(apiClient); + try { + ApiServiceConfig svcConfig = api.readServiceConfig(clusterName, service, "full"); + + Map<ApiRole, ApiConfigList> roleConfigs = new HashMap<>(); + RolesResourceApi rolesApi = (new RolesResourceApi(apiClient)); + ApiRoleList roles = rolesApi.readRoles(clusterName, service, "", "full"); + for (ApiRole role : roles.getItems()) { + ApiConfigList config = rolesApi.readRoleConfig(clusterName, role.getName(), service, "full"); + roleConfigs.put(role, config); + } + currentConfig = new ServiceConfigurationProperties(svcConfig, roleConfigs); + } catch (ApiException e) { + log.clouderaManagerConfigurationAPIError(e); + } + return currentConfig; + } + + /** + * Get restart events for the specified ClouderaManager cluster. + * + * @param address The address of the ClouderaManager instance. + * @param clusterName The name of the cluster. + * + * @return A List of RestartEvent objects for service restart events since the last time they were queried. + */ + private List<RestartEvent> getRestartEvents(final String address, final String clusterName) { + List<RestartEvent> restartEvents = new ArrayList<>(); + + // Get the last event query timestamp + String lastTimestamp = getEventQueryTimestamp(address, clusterName); + + if (lastTimestamp == null) { + Date ts = new Date(); + ts.setTime(System.currentTimeMillis() - eventQueryDefaultTimestampOffset); + lastTimestamp = eventQueryTimestampFormat.format(ts); + } + + log.queryingRestartEventsFromCluster(clusterName, address, lastTimestamp); + + // Record the new event query timestamp for this address/cluster + setEventQueryTimestamp(address, clusterName, new Date()); + + // Query the event log from CM for service/cluster restart events + List<ApiEvent> events = queryRestartEvents(getApiClient(getDiscoveryConfig(address, clusterName)), + clusterName, + lastTimestamp); + for (ApiEvent event : events) { + restartEvents.add(new RestartEvent(event)); + } + + return restartEvents; + } + + private void persist(final Properties props, final File dest) { + try (OutputStream out = Files.newOutputStream(dest.toPath())) { + props.store(out, PERSISTED_FILE_COMMENT); + out.flush(); + } catch (Exception e) { + log.failedToPersistClusterMonitorData(getType(), dest.getAbsolutePath(), e); + } + } + + private File getPersistenceDir() { + File persistenceDir = null; + + File dataDir = new File(gatewayConfig.getGatewayDataDir()); + if (dataDir.exists()) { + File clustersDir = new File(dataDir, CLUSTERS_DATA_DIR_NAME); + if (!clustersDir.exists()) { + if (!clustersDir.mkdirs()) { + log.failedToCreatePersistenceDirectory(clustersDir.getAbsolutePath()); + } + } + persistenceDir = clustersDir; + } + + return persistenceDir; + } + + /** + * Notify registered change listeners. + * + * @param source The address of the ClouderaManager instance from which the cluster details were determined. + * @param clusterName The name of the cluster whose configuration details have changed. + */ + private void notifyChangeListeners(final String source, final String clusterName) { + for (ConfigurationChangeListener listener : changeListeners) { + listener.onConfigurationChange(source, clusterName); + } + } + + private void persistDiscoveryConfiguration(final String clusterName, final ServiceDiscoveryConfig sdc) { + File persistenceDir = getPersistenceDir(); + if (persistenceDir != null) { + + Properties props = new Properties(); + props.setProperty(PROP_CLUSTER_NAME, clusterName); + props.setProperty(PROP_CLUSTER_SOURCE, sdc.getAddress()); + + String username = sdc.getUser(); + if (username != null) { + props.setProperty(PROP_CLUSTER_USER, username); + } + String pwdAlias = sdc.getPasswordAlias(); + if (pwdAlias != null) { + props.setProperty(PROP_CLUSTER_ALIAS, pwdAlias); + } + + persist(props, getDiscoveryConfigPersistenceFile(sdc.getAddress(), clusterName)); + } + } + + private void persistServiceConfiguration(final String discoveryAddress, + final String cluster, + final Map<String, ServiceConfigurationProperties> configs) { + File persistenceDir = getPersistenceDir(); + if (persistenceDir != null) { + File persistenceFile = getServiceConfigsPersistenceFile(discoveryAddress, cluster); + try ( ObjectOutputStream out = new ObjectOutputStream(Files.newOutputStream(persistenceFile.toPath())) ) { + out.writeObject(cluster); + out.writeObject(discoveryAddress); + out.writeObject(configs); + } catch (Exception e) { + log.failedToPersistClusterMonitorData(getType(), persistenceFile.getAbsolutePath(), e); + } + } + } + + private File getDiscoveryConfigPersistenceFile(final String address, final String clusterName) { + return getPersistenceFile(address, clusterName.replaceAll(" ", "_"), "conf"); + } + + private File getServiceConfigsPersistenceFile(final String address, final String clusterName) { + return getPersistenceFile(address, clusterName.replaceAll(" ", "_"), "ver"); + } + + private File getPersistenceFile(final String address, final String clusterName, final String ext) { + String fileName = address.replace(":", "_").replace("/", "_") + "-" + clusterName + "." + ext; + return new File(getPersistenceDir(), fileName); + } + + /** + * Get all the clusters the monitor knows about. + * + * @return A Map of ClouderaManager instance addresses to associated cluster names. + */ + private Map<String, List<String>> getClusterNames() { + Map<String, List<String>> result = new HashMap<>(); + + serviceConfigurationsLock.readLock().lock(); + try { + for (Map.Entry<String, Map<String, Map<String, ServiceConfigurationProperties>>> configs : + clusterServiceConfigurations.entrySet()) { + List<String> clusterNames = new ArrayList<>(configs.getValue().keySet()); + result.put(configs.getKey(), clusterNames); + } + } finally { + serviceConfigurationsLock.readLock().unlock(); + } + + return result; + } + + private void setEventQueryTimestamp(final String address, final String cluster, final Date timestamp) { + eventQueryTimestamps.put((address + ":" + cluster), eventQueryTimestampFormat.format(timestamp)); + } + + private String getEventQueryTimestamp(final String address, final String cluster) { + return eventQueryTimestamps.get(address + ":" + cluster); + } + + /** + * Query the ClouderaManager instance associated with the specified client for any service restart events in the + * specified cluster since the specified time. + * + * @param client A ClouderaManager API client. + * @param clusterName The name of the cluster for which events should be queried. + * @param since The ISO8601 timestamp indicating from which time to query. + * + * @return A List of ApiEvent objects representing the relevant events since the specified time. + */ + private List<ApiEvent> queryRestartEvents(final ApiClient client, final String clusterName, final String since) { + List<ApiEvent> events = new ArrayList<>(); + + // Setup the query for restart events + String timeFilter = + (since != null) ? String.format(Locale.getDefault(), EVENTS_QUERY_TIMESTAMP_FORMAT, since) : ""; + + String queryString = String.format(Locale.getDefault(), + RESTART_EVENTS_QUERY_FORMAT, + clusterName, + timeFilter); + + try { + ApiEventQueryResult eventsResult = (new EventsResourceApi(client)).readEvents(20, queryString, 0); + events.addAll(eventsResult.getItems()); + } catch (ApiException e) { + log.clouderaManagerEventsAPIError(e); + } + + return events; + } + + /** + * Examine the ServiceConfigurationProperties objects for significant differences. + * + * @param previous The previously-recorded service configuration properties. + * @param current The current service configuration properties. + * + * @return true, if the current service configuration values differ from those properties defined in the previous + * service configuration; Otherwise, false. + */ + private boolean hasConfigurationChanged(final ServiceConfigurationProperties previous, + final ServiceConfigurationProperties current) { + boolean hasChanged = false; + + // Compare the service configuration properties first + Properties previousProps = previous.getServiceProps(); + Properties currentProps = current.getServiceProps(); + for (String name : previousProps.stringPropertyNames()) { + String prevValue = previousProps.getProperty(name); + String currValue = currentProps.getProperty(name); + if (!currValue.equals(prevValue)) { + log.serviceConfigurationPropertyHasChanged(name, prevValue, currValue); + hasChanged = true; + break; + } + } + + // If service config has not changed, check the role configuration properties + if (!hasChanged) { + Set<String> previousRoleTypes = previous.getRoleTypes(); + Set<String> currentRoleTypes = current.getRoleTypes(); + for (String roleType : previousRoleTypes) { + if (!currentRoleTypes.contains(roleType)) { + log.roleTypeRemoved(roleType); + hasChanged = true; + break; + } else { + previousProps = previous.getRoleProps(roleType); + currentProps = current.getRoleProps(roleType); + for (String name : previousProps.stringPropertyNames()) { + String prevValue = previousProps.getProperty(name); + String currValue = currentProps.getProperty(name); + if (currValue == null) { // A missing/removed property + if (!(prevValue == null || "null".equals(prevValue))) { + log.roleConfigurationPropertyHasChanged(name, prevValue, "null"); + hasChanged = true; + break; + } + } else if (!currValue.equals(prevValue)) { + log.roleConfigurationPropertyHasChanged(name, prevValue, currValue); + hasChanged = true; + break; + } + } + } + } + } + + return hasChanged; + } + + + /** + * The thread that polls ClouderaManager for service restart events for clusters associated with discovered + * topologies, compares the current service configuration values against the previously-recorded values, and notifies + * any listeners when significant configuration differences are discovered. + */ + @SuppressWarnings("PMD.DoNotUseThreads") + private static final class PollingConfigAnalyzer implements Runnable { + + private static final int DEFAULT_POLLING_INTERVAL = 60; + + // Polling interval in seconds + private int interval; + + private ClouderaManagerClusterConfigurationMonitor monitor; + + private boolean isActive; + + PollingConfigAnalyzer(final ClouderaManagerClusterConfigurationMonitor monitor) { + this(monitor, PollingConfigAnalyzer.DEFAULT_POLLING_INTERVAL); + } + + PollingConfigAnalyzer(final ClouderaManagerClusterConfigurationMonitor monitor, int interval) { + this.monitor = monitor; + this. interval = interval; + } + + void setInterval(int interval) { + this.interval = interval; + } + + void stop() { + isActive = false; + } + + private void waitFor(long seconds) { + try { + Thread.sleep(seconds * 1000L); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + + @Override + public void run() { + isActive = true; + + // Initial delay to allow other gateway services (e.g., Topology Service) to be fully ready, so restart events + // which occurred while Knox was down are not missed/mishandled. + waitFor(20); + + log.startedClouderaManagerConfigMonitor(interval); + + while (isActive) { + for (Map.Entry<String, List<String>> entry : monitor.getClusterNames().entrySet()) { + String address = entry.getKey(); + for (String clusterName : entry.getValue()) { + log.checkingClusterConfiguration(clusterName, address); + + // Configuration changes don't mean anything without corresponding service restarts. Therefore, monitor + // restart events, and check the configuration only of the restarted service(s) to identify changes + // that should trigger re-discovery. + List<RestartEvent> restartEvents = monitor.getRestartEvents(address, clusterName); + + // If there are no recent restart events, then nothing to do now + if (!restartEvents.isEmpty()) { + boolean configHasChanged = false; + + // If there are restart events, then check the previously-recorded properties for the same service to + // identify if the configuration has changed + Map<String, ServiceConfigurationProperties> serviceConfigurations = + monitor.getClusterServiceConfigurations(address, clusterName); + + // Those services for which a restart even has been handled + List<String> handledServiceTypes = new ArrayList<>(); + + for (RestartEvent re : restartEvents) { + String serviceType = re.getServiceType(); + + // Determine if we've already handled a restart event for this service type + if (!handledServiceTypes.contains(serviceType)) { + + // Get the previously-recorded configuration + ServiceConfigurationProperties serviceConfig = serviceConfigurations.get(re.getServiceType()); + + if (serviceConfig != null) { + // Get the current config for the restarted service, and compare with the previously-recorded config + ServiceConfigurationProperties currentConfig = + monitor.getCurrentServiceConfiguration(address, clusterName, re.getService()); + + if (currentConfig != null) { + log.analyzingCurrentServiceConfiguration(re.getService()); + try { + configHasChanged = monitor.hasConfigurationChanged(serviceConfig, currentConfig); + } catch (Exception e) { + log.errorAnalyzingCurrentServiceConfiguration(re.getService(), e); + } + } + } else { + // A new service (no prior config) represent a config change, since a descriptor may have referenced + // the "new" service, but discovery had previously not succeeded because the service had not been + // configured (appropriately) at that time. + log.serviceEnabled(re.getService()); + configHasChanged = true; + } + + handledServiceTypes.add(serviceType); + } + + if (configHasChanged) { + break; // No need to continue checking once we've identified one reason to perform discovery again + } + } + + // If a change has occurred, notify the listeners + if (configHasChanged) { + monitor.notifyChangeListeners(address, clusterName); + } + } + } + } + + waitFor(interval); + } + } + } + + + /** + * Internal representation of a ClouderaManager service restart event + */ + private static final class RestartEvent { + + private static final String ATTR_CLUSTER = "CLUSTER"; + private static final String ATTR_SERVICE_TYPE = "SERVICE_TYPE"; + private static final String ATTR_SERVICE = "SERVICE"; + + private static List<String> attrsOfInterest = new ArrayList<>(); + static { + attrsOfInterest.add(ATTR_CLUSTER); + attrsOfInterest.add(ATTR_SERVICE_TYPE); + attrsOfInterest.add(ATTR_SERVICE); + } + + private ApiEvent auditEvent; + private String clusterName; + private String serviceType; + private String service; + + RestartEvent(final ApiEvent auditEvent) { + if (ApiEventCategory.AUDIT_EVENT != auditEvent.getCategory()) { + throw new IllegalArgumentException("Invalid event category " + auditEvent.getCategory().getValue()); + } + this.auditEvent = auditEvent; + for (ApiEventAttribute attribute : auditEvent.getAttributes()) { + if (attrsOfInterest.contains(attribute.getName())) { + setPropertyFromAttribute(attribute); + } + } + } + + String getTimestamp() { + return auditEvent.getTimeOccurred(); + } + + String getClusterName() { + return clusterName; + } + + String getServiceType() { + return serviceType; + } + + String getService() { + return service; + } + + private void setPropertyFromAttribute(ApiEventAttribute attribute) { + switch (attribute.getName()) { + case ATTR_CLUSTER: + clusterName = attribute.getValues().get(0); + break; + case ATTR_SERVICE_TYPE: + serviceType = attribute.getValues().get(0); + break; + case ATTR_SERVICE: + service = attribute.getValues().get(0); + break; + default: + } + } + } + + + /** + * Service configuration properties container + */ + private static final class ServiceConfigurationProperties implements Serializable { Review comment: +1 ---------------------------------------------------------------- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. For queries about this service, please contact Infrastructure at: [email protected] With regards, Apache Git Services
