You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@knox.apache.org by GitBox <gi...@apache.org> on 2020/01/17 21:13:08 UTC
[GitHub] [knox] pzampino opened a new pull request #239: KNOX-2153 - CM
discovery - Monitor Cloudera Manager
pzampino opened a new pull request #239: KNOX-2153 - CM discovery - Monitor Cloudera Manager
URL: https://github.com/apache/knox/pull/239
## What changes were proposed in this pull request?
This change adds the ability for Knox to monitor ClouderaManager-managed clusters for configuration changes, and respond by re-generating topologies based on the most recent configuration.
When Knox performs service discovery against a CM-managed cluster to generate a topology, it registers that cluster data with the monitor, which will periodically check that cluster for service restart events. In CM, config changes are meaningless unless the associated service is restarted.
When Knox identifies a restart event, it will query the current config for the restarted service, and compare it with its previous record from the last discovery thereof. If there are changes, it will trigger rediscovery of the affected topologies.
## How was this patch tested?
So far, this has been tested manually. There will be a subsequent commit with tests added to this PR prior to merging. Given the magnitude of this change, I've created the PR without tests to facilitate early review.
----------------------------------------------------------------
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:
users@infra.apache.org
With regards,
Apache Git Services
[GitHub] [knox] risdenk commented on a change in pull request #239:
KNOX-2153 - CM discovery - Monitor Cloudera Manager
Posted by GitBox <gi...@apache.org>.
risdenk commented on a change in pull request #239: KNOX-2153 - CM discovery - Monitor Cloudera Manager
URL: https://github.com/apache/knox/pull/239#discussion_r368155347
##########
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);
Review comment:
This is same as readObject, should use JSON or something to avoid serializing Java classes directly.
----------------------------------------------------------------
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:
users@infra.apache.org
With regards,
Apache Git Services
[GitHub] [knox] pzampino commented on issue #239: KNOX-2153 - CM discovery -
Monitor Cloudera Manager
Posted by GitBox <gi...@apache.org>.
pzampino commented on issue #239: KNOX-2153 - CM discovery - Monitor Cloudera Manager
URL: https://github.com/apache/knox/pull/239#issuecomment-576977028
Still working on the tests...
----------------------------------------------------------------
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:
users@infra.apache.org
With regards,
Apache Git Services
[GitHub] [knox] pzampino commented on a change in pull request #239:
KNOX-2153 - CM discovery - Monitor Cloudera Manager
Posted by GitBox <gi...@apache.org>.
pzampino commented on a change in pull request #239: KNOX-2153 - CM discovery - Monitor Cloudera Manager
URL: https://github.com/apache/knox/pull/239#discussion_r369847151
##########
File path: gateway-discovery-cm/src/main/java/org/apache/knox/gateway/topology/discovery/cm/monitor/ClouderaManagerClusterConfigurationMonitor.java
##########
@@ -0,0 +1,876 @@
+/*
+ * 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.monitor;
+
+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.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 com.google.common.util.concurrent.ThreadFactoryBuilder;
+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 org.apache.knox.gateway.topology.discovery.cm.ClouderaManagerCluster;
+import org.apache.knox.gateway.topology.discovery.cm.ClouderaManagerServiceDiscoveryMessages;
+import org.apache.knox.gateway.topology.discovery.cm.DiscoveryApiClient;
+import org.apache.knox.gateway.topology.discovery.cm.ServiceModel;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+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.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ThreadFactory;
+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.toLowerCase(Locale.getDefault()) + "-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 static final ThreadLocal<DateFormat> eventQueryTimestampFormat =
+ ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'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 final Map<String, DiscoveryApiClient> clients = new ConcurrentHashMap<>();
+
+ // ClouderaManager address
+ // clusterName -> ServiceDiscoveryConfig
+ //
+ private final Map<String, Map<String, ServiceDiscoveryConfig>> clusterMonitorConfigurations = new ConcurrentHashMap<>();
+
+ // ClouderaManager address
+ // clusterName
+ // serviceType -> Properties
+ //
+ private final Map<String, Map<String, Map<String, ServiceConfigurationModel>>> clusterServiceConfigurations =
+ new ConcurrentHashMap<>();
+
+ private final ReadWriteLock serviceConfigurationsLock = new ReentrantReadWriteLock();
+
+ private final 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;
+
+ private ExecutorService executorService;
+
+ public static String getType() {
+ return TYPE;
+ }
+
+ ClouderaManagerClusterConfigurationMonitor(final GatewayConfig config, final AliasService aliasService) {
+ this.gatewayConfig = config;
+ this.aliasService = aliasService;
+
+ eventQueryTimestampFormat.get().setTimeZone(TimeZone.getTimeZone("UTC"));
+
+ ThreadFactory tf = (new ThreadFactoryBuilder()).setNameFormat("ClouderaManagerConfigurationMonitor-%d").build();
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:
users@infra.apache.org
With regards,
Apache Git Services
[GitHub] [knox] risdenk commented on a change in pull request #239:
KNOX-2153 - CM discovery - Monitor Cloudera Manager
Posted by GitBox <gi...@apache.org>.
risdenk commented on a change in pull request #239: KNOX-2153 - CM discovery - Monitor Cloudera Manager
URL: https://github.com/apache/knox/pull/239#discussion_r369834718
##########
File path: gateway-discovery-cm/src/main/java/org/apache/knox/gateway/topology/discovery/cm/monitor/ClouderaManagerClusterConfigurationMonitor.java
##########
@@ -0,0 +1,876 @@
+/*
+ * 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.monitor;
+
+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.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 com.google.common.util.concurrent.ThreadFactoryBuilder;
+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 org.apache.knox.gateway.topology.discovery.cm.ClouderaManagerCluster;
+import org.apache.knox.gateway.topology.discovery.cm.ClouderaManagerServiceDiscoveryMessages;
+import org.apache.knox.gateway.topology.discovery.cm.DiscoveryApiClient;
+import org.apache.knox.gateway.topology.discovery.cm.ServiceModel;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+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.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ThreadFactory;
+import java.util.concurrent.locks.ReadWriteLock;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
+
+/**
+ * ClusterConfigurationMonitor implementation for clusters managed by ClouderaManager.
+ */
+public class ClouderaManagerClusterConfigurationMonitor implements ClusterConfigurationMonitor {
Review comment:
So overall I think this class is doing too much. It would probably be best to split out the classes that are in here to separate classes.
The locking is weird too it would be better to split out the required locking concerns into its own class and encapsulate what is happening. I think this would be easier to check for correctness.
----------------------------------------------------------------
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:
users@infra.apache.org
With regards,
Apache Git Services
[GitHub] [knox] smolnar82 commented on issue #239: KNOX-2153 - CM discovery
- Monitor Cloudera Manager
Posted by GitBox <gi...@apache.org>.
smolnar82 commented on issue #239: KNOX-2153 - CM discovery - Monitor Cloudera Manager
URL: https://github.com/apache/knox/pull/239#issuecomment-576838272
Just an idea you may consider: a new DAO interface should be declared with one implementation (e.g. `ClouderaManagerClusterConfigurationFileSystemDAO implements ClouderaManagerClusterConfigurationDAO`) and all the persist/load methods are moved into the DAO layer for better separation of the business logic and file system operations.
----------------------------------------------------------------
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:
users@infra.apache.org
With regards,
Apache Git Services
[GitHub] [knox] risdenk commented on a change in pull request #239:
KNOX-2153 - CM discovery - Monitor Cloudera Manager
Posted by GitBox <gi...@apache.org>.
risdenk commented on a change in pull request #239: KNOX-2153 - CM discovery - Monitor Cloudera Manager
URL: https://github.com/apache/knox/pull/239#discussion_r368156315
##########
File path: gateway-discovery-cm/src/main/java/org/apache/knox/gateway/topology/discovery/cm/model/hive/HiveOnTezServiceModelGenerator.java
##########
@@ -16,20 +16,45 @@
*/
package org.apache.knox.gateway.topology.discovery.cm.model.hive;
+import com.cloudera.api.swagger.client.ApiException;
import com.cloudera.api.swagger.model.ApiConfigList;
+import com.cloudera.api.swagger.model.ApiRole;
+import com.cloudera.api.swagger.model.ApiService;
+import com.cloudera.api.swagger.model.ApiServiceConfig;
+import org.apache.knox.gateway.topology.discovery.cm.ServiceModel;
public class HiveOnTezServiceModelGenerator extends HiveServiceModelGenerator {
public static final String SERVICE_TYPE = "HIVE_ON_TEZ";
+ private static final String HOT_TRANSPORT_MODE = TRANSPORT_MODE.replaceAll("\\.", "_");
Review comment:
`HOT` must be Hive on Tez, but definitely isn't clear from reading.
----------------------------------------------------------------
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:
users@infra.apache.org
With regards,
Apache Git Services
[GitHub] [knox] pzampino commented on a change in pull request #239:
KNOX-2153 - CM discovery - Monitor Cloudera Manager
Posted by GitBox <gi...@apache.org>.
pzampino commented on a change in pull request #239: KNOX-2153 - CM discovery - Monitor Cloudera Manager
URL: https://github.com/apache/knox/pull/239#discussion_r369007438
##########
File path: gateway-discovery-cm/src/main/java/org/apache/knox/gateway/topology/discovery/cm/model/hive/HiveOnTezServiceModelGenerator.java
##########
@@ -16,20 +16,45 @@
*/
package org.apache.knox.gateway.topology.discovery.cm.model.hive;
+import com.cloudera.api.swagger.client.ApiException;
import com.cloudera.api.swagger.model.ApiConfigList;
+import com.cloudera.api.swagger.model.ApiRole;
+import com.cloudera.api.swagger.model.ApiService;
+import com.cloudera.api.swagger.model.ApiServiceConfig;
+import org.apache.knox.gateway.topology.discovery.cm.ServiceModel;
public class HiveOnTezServiceModelGenerator extends HiveServiceModelGenerator {
public static final String SERVICE_TYPE = "HIVE_ON_TEZ";
+ private static final String HOT_TRANSPORT_MODE = TRANSPORT_MODE.replaceAll("\\.", "_");
Review comment:
Fair enough
----------------------------------------------------------------
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:
users@infra.apache.org
With regards,
Apache Git Services
[GitHub] [knox] smolnar82 commented on a change in pull request #239:
KNOX-2153 - CM discovery - Monitor Cloudera Manager
Posted by GitBox <gi...@apache.org>.
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_r368865384
##########
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();
Review comment:
Using an executor instead of a Thread?
----------------------------------------------------------------
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:
users@infra.apache.org
With regards,
Apache Git Services
[GitHub] [knox] pzampino commented on a change in pull request #239:
KNOX-2153 - CM discovery - Monitor Cloudera Manager
Posted by GitBox <gi...@apache.org>.
pzampino commented on a change in pull request #239: KNOX-2153 - CM discovery - Monitor Cloudera Manager
URL: https://github.com/apache/knox/pull/239#discussion_r369852300
##########
File path: gateway-discovery-cm/pom.xml
##########
@@ -48,10 +52,29 @@
<groupId>com.squareup.okhttp</groupId>
<artifactId>okhttp</artifactId>
</dependency>
+ <dependency>
+ <groupId>commons-io</groupId>
+ <artifactId>commons-io</artifactId>
+ </dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
</dependency>
+ <dependency>
+ <groupId>com.fasterxml.jackson.core</groupId>
+ <artifactId>jackson-core</artifactId>
+ <scope>compile</scope>
+ </dependency>
+ <dependency>
+ <groupId>com.fasterxml.jackson.core</groupId>
+ <artifactId>jackson-databind</artifactId>
+ <scope>compile</scope>
+ </dependency>
+ <dependency>
+ <groupId>com.google.guava</groupId>
+ <artifactId>guava</artifactId>
+ <scope>compile</scope>
+ </dependency>
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:
users@infra.apache.org
With regards,
Apache Git Services
[GitHub] [knox] risdenk commented on a change in pull request #239:
KNOX-2153 - CM discovery - Monitor Cloudera Manager
Posted by GitBox <gi...@apache.org>.
risdenk commented on a change in pull request #239: KNOX-2153 - CM discovery - Monitor Cloudera Manager
URL: https://github.com/apache/knox/pull/239#discussion_r369832496
##########
File path: gateway-discovery-cm/src/test/java/org/apache/knox/gateway/topology/discovery/cm/monitor/ServiceConfigurationRecordObjectMapperTest.java
##########
@@ -0,0 +1,240 @@
+/*
+ * 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.monitor;
+
+import org.junit.Test;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.nio.charset.StandardCharsets;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+public class ServiceConfigurationRecordObjectMapperTest {
+
+ @Test
+ public void testSerializationOfEmptyModel() {
+ ServiceConfigurationRecord record = new ServiceConfigurationRecord();
+
+ String serialized = doTestSerialization(record);
+ assertNotNull(serialized);
+ assertEquals("{\"clusterName\":null,\"discoveryAddress\":null,\"configs\":null}", serialized);
+ }
+
+ @Test
+ public void testDeserializationOfEmptyModel() {
+ final String serializedEmptyModel = "{\"clusterName\":null,\"discoveryAddress\":null,\"configs\":null}";
+
+ ServiceConfigurationRecord record = doTestDeserialization(serializedEmptyModel);
+ assertNull(record.getClusterName());
+ assertNull(record.getDiscoveryAddress());
+ assertNull(record.getConfigs());
+ }
+
+ @Test
+ public void testSerializationNoConfigs() {
+ ServiceConfigurationRecord record = new ServiceConfigurationRecord();
+ record.setClusterName("myCluster");
+ record.setDiscoveryAddress("http://localhost:7180/");
+ record.setConfigs(Collections.emptyMap());
+
+ String serialized = doTestSerialization(record);
+ assertNotNull(serialized);
+ final String expectedSerialization =
+ createTestJSON(record.getClusterName(), record.getDiscoveryAddress(), record.getConfigs());
+ assertEquals(expectedSerialization, serialized);
+ }
+
+ @Test
+ public void testDeserializationNoConfigs() {
+ final String clusterName = "testCluster";
+ final String discoveryAddress = "http://myhost:1234";
+ final String serialized = createTestJSON(clusterName, discoveryAddress, null);
+
+ ServiceConfigurationRecord record = doTestDeserialization(serialized);
+ assertNotNull(record);
+ assertEquals(clusterName, record.getClusterName());
+ assertEquals(discoveryAddress, record.getDiscoveryAddress());
+ Map<String, ServiceConfigurationModel> configs = record.getConfigs();
+ assertNull("Expect no configs entry", configs);
+ }
+
+ @Test
+ public void testRoundTrip() {
+ final String clusterName = "Cluster 1";
+ final String address = "http://cmhost:7180/";
+ final Map<String, ServiceConfigurationModel> configs = new HashMap<>();
+ ServiceConfigurationModel model1 = new ServiceConfigurationModel();
+ model1.addServiceProperty("svc1.prop1", "svc1.prop1.value");
+ model1.addServiceProperty("svc1.prop2", "svc1.prop2.value");
+ model1.addRoleProperty("Role1", "r1.prop1", "r1.prop1.value");
+ model1.addRoleProperty("Role1", "r1.prop2", "r1.prop2.value");
+ model1.addRoleProperty("Role2", "r2.prop1", "r2.prop1.value");
+ configs.put("Service1", model1);
+
+ ServiceConfigurationModel model2 = new ServiceConfigurationModel();
+ model2.addServiceProperty("svc1.prop1", "svc1.prop1.value");
+ model2.addRoleProperty("Role1", "r1.prop1", "r1.prop1.value");
+ model2.addRoleProperty("Role2", "r2.prop1", "r2.prop1.value");
+ model2.addRoleProperty("Role2", "r2.prop2", "r2.prop2.value");
+ configs.put("Service2", model2);
+
+ ServiceConfigurationRecord record = new ServiceConfigurationRecord();
+ record.setClusterName(clusterName);
+ record.setDiscoveryAddress(address);
+ record.setConfigs(configs);
+
+ String serialized = doTestSerialization(record);
+ ServiceConfigurationRecord deserialized = doTestDeserialization(serialized);
+
+ assertEquals(clusterName, deserialized.getClusterName());
+ assertEquals(address, deserialized.getDiscoveryAddress());
+ Map<String, ServiceConfigurationModel> deserializedConfigs = deserialized.getConfigs();
+ assertNotNull(deserializedConfigs);
+ assertEquals(2, deserializedConfigs.size());
+ assertTrue(deserializedConfigs.containsKey("Service1"));
+ assertTrue(deserializedConfigs.containsKey("Service2"));
+
+ ServiceConfigurationModel service1 = deserializedConfigs.get("Service1");
+ Map<String, String> svc1Props = service1.getServiceProps();
+ assertEquals(2, svc1Props.size());
+ assertEquals(model1.getServiceProps().get("svc1.prop1"), svc1Props.get("svc1.prop1"));
+ assertEquals(model1.getServiceProps().get("svc1.prop2"), svc1Props.get("svc1.prop2"));
+ assertEquals(2, service1.getRoleTypes().size());
+ assertEquals(model1.getRoleProps("Role1").get("r1.prop1"), service1.getRoleProps("Role1").get("r1.prop1"));
+ assertEquals(model1.getRoleProps("Role1").get("r1.prop2"), service1.getRoleProps("Role1").get("r1.prop2"));
+ assertEquals(model1.getRoleProps("Role2").get("r2.prop1"), service1.getRoleProps("Role2").get("r2.prop1"));
+ assertEquals(model1.getRoleProps("Role2").get("r2.prop1"), service1.getRoleProps("Role2").get("r2.prop1"));
+
+
+ ServiceConfigurationModel service2 = deserializedConfigs.get("Service2");
+ Map<String, String> svc2Props = service2.getServiceProps();
+ assertEquals(1, svc2Props.size());
+ assertEquals(model2.getServiceProps().get("svc2.prop1"), svc2Props.get("svc2.prop1"));
+ assertEquals(2, service2.getRoleTypes().size());
+ assertEquals(model2.getRoleProps("Role1").get("r1.prop1"), service2.getRoleProps("Role1").get("r1.prop1"));
+ assertEquals(model2.getRoleProps("Role2").get("r2.prop1"), service2.getRoleProps("Role2").get("r2.prop1"));
+ assertEquals(model2.getRoleProps("Role2").get("r2.prop2"), service2.getRoleProps("Role2").get("r2.prop2"));
+ }
+
+ private String doTestSerialization(final ServiceConfigurationRecord record) {
+ String serialized = null;
+ try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
+ (new ServiceConfigurationRecordObjectMapper()).writeValue(out, record);
+ serialized = out.toString(StandardCharsets.UTF_8.name());
+ } catch (Exception e) {
+ fail(e.getMessage());
+ }
+ return serialized;
+ }
+
+ private ServiceConfigurationRecord doTestDeserialization(final String serialized) {
+ ServiceConfigurationRecord deserialized = null;
+ try (ByteArrayInputStream in = new ByteArrayInputStream(serialized.getBytes(StandardCharsets.UTF_8))) {
+ deserialized =
+ (new ServiceConfigurationRecordObjectMapper()).readValue(in, ServiceConfigurationRecord.class);
+ } catch (Exception e) {
+ fail(e.getMessage());
+ }
+ return deserialized;
+ }
+
+ @SuppressWarnings({"PMD.AppendCharacterWithChar", "PMD.ConsecutiveLiteralAppends"})
Review comment:
Not sure why these are suppressed? It would be better to actually do what it says. One of the simple ones is use `'` around literals. ie: `'{'` or `'"'`
----------------------------------------------------------------
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:
users@infra.apache.org
With regards,
Apache Git Services
[GitHub] [knox] pzampino commented on a change in pull request #239:
KNOX-2153 - CM discovery - Monitor Cloudera Manager
Posted by GitBox <gi...@apache.org>.
pzampino commented on a change in pull request #239: KNOX-2153 - CM discovery - Monitor Cloudera Manager
URL: https://github.com/apache/knox/pull/239#discussion_r369287062
##########
File path: gateway-discovery-cm/src/main/java/org/apache/knox/gateway/topology/discovery/cm/ClouderaManagerServiceDiscovery.java
##########
@@ -63,6 +68,9 @@
static final String DEFAULT_USER_ALIAS = "cm.discovery.user";
static final String DEFAULT_PWD_ALIAS = "cm.discovery.password";
+ private static final String GATEWAY_SERVICES_ACCESSOR_CLASS = "org.apache.knox.gateway.GatewayServer";
Review comment:
Added a dependency on gateway-server to facilitate the proposed change.
----------------------------------------------------------------
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:
users@infra.apache.org
With regards,
Apache Git Services
[GitHub] [knox] pzampino commented on a change in pull request #239:
KNOX-2153 - CM discovery - Monitor Cloudera Manager
Posted by GitBox <gi...@apache.org>.
pzampino commented on a change in pull request #239: KNOX-2153 - CM discovery - Monitor Cloudera Manager
URL: https://github.com/apache/knox/pull/239#discussion_r369852154
##########
File path: gateway-discovery-cm/src/main/java/org/apache/knox/gateway/topology/discovery/cm/monitor/ClouderaManagerClusterConfigurationMonitor.java
##########
@@ -0,0 +1,876 @@
+/*
+ * 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.monitor;
+
+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.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 com.google.common.util.concurrent.ThreadFactoryBuilder;
+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 org.apache.knox.gateway.topology.discovery.cm.ClouderaManagerCluster;
+import org.apache.knox.gateway.topology.discovery.cm.ClouderaManagerServiceDiscoveryMessages;
+import org.apache.knox.gateway.topology.discovery.cm.DiscoveryApiClient;
+import org.apache.knox.gateway.topology.discovery.cm.ServiceModel;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+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.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ThreadFactory;
+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.toLowerCase(Locale.getDefault()) + "-clusters";
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:
users@infra.apache.org
With regards,
Apache Git Services
[GitHub] [knox] pzampino commented on a change in pull request #239:
KNOX-2153 - CM discovery - Monitor Cloudera Manager
Posted by GitBox <gi...@apache.org>.
pzampino commented on a change in pull request #239: KNOX-2153 - CM discovery - Monitor Cloudera Manager
URL: https://github.com/apache/knox/pull/239#discussion_r369022687
##########
File path: gateway-discovery-cm/src/main/java/org/apache/knox/gateway/topology/discovery/cm/ClouderaManagerServiceDiscovery.java
##########
@@ -63,6 +68,9 @@
static final String DEFAULT_USER_ALIAS = "cm.discovery.user";
static final String DEFAULT_PWD_ALIAS = "cm.discovery.password";
+ private static final String GATEWAY_SERVICES_ACCESSOR_CLASS = "org.apache.knox.gateway.GatewayServer";
Review comment:
This module doesn't depend on gateway-server...I think the services would have to be passed down to avoid this
----------------------------------------------------------------
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:
users@infra.apache.org
With regards,
Apache Git Services
[GitHub] [knox] pzampino commented on a change in pull request #239:
KNOX-2153 - CM discovery - Monitor Cloudera Manager
Posted by GitBox <gi...@apache.org>.
pzampino commented on a change in pull request #239: KNOX-2153 - CM discovery - Monitor Cloudera Manager
URL: https://github.com/apache/knox/pull/239#discussion_r369267760
##########
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
Review comment:
I would like to consider that as another JIRA (e.g., improvement) beyond the scope of this one.
----------------------------------------------------------------
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:
users@infra.apache.org
With regards,
Apache Git Services
[GitHub] [knox] smolnar82 commented on a change in pull request #239:
KNOX-2153 - CM discovery - Monitor Cloudera Manager
Posted by GitBox <gi...@apache.org>.
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_r368881057
##########
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
Review comment:
We know that CM is able to trigger `refreshable` configuration changes. In these cases, a service restart is not required, but the configuration change may, or may not, be a relevant configuration change. I'm not familiar with CM's API, but I'd check if there is a `Refresh Cluster` event which we can also capture here.
----------------------------------------------------------------
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:
users@infra.apache.org
With regards,
Apache Git Services
[GitHub] [knox] risdenk commented on a change in pull request #239:
KNOX-2153 - CM discovery - Monitor Cloudera Manager
Posted by GitBox <gi...@apache.org>.
risdenk commented on a change in pull request #239: KNOX-2153 - CM discovery - Monitor Cloudera Manager
URL: https://github.com/apache/knox/pull/239#discussion_r369834394
##########
File path: gateway-discovery-cm/src/main/java/org/apache/knox/gateway/topology/discovery/cm/monitor/ClouderaManagerClusterConfigurationMonitor.java
##########
@@ -0,0 +1,876 @@
+/*
+ * 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.monitor;
+
+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.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 com.google.common.util.concurrent.ThreadFactoryBuilder;
+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 org.apache.knox.gateway.topology.discovery.cm.ClouderaManagerCluster;
+import org.apache.knox.gateway.topology.discovery.cm.ClouderaManagerServiceDiscoveryMessages;
+import org.apache.knox.gateway.topology.discovery.cm.DiscoveryApiClient;
+import org.apache.knox.gateway.topology.discovery.cm.ServiceModel;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+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.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ThreadFactory;
+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.toLowerCase(Locale.getDefault()) + "-clusters";
Review comment:
Most likely want `Locale.ROOT` to avoid weirdness in the TYPE lowercasing.
----------------------------------------------------------------
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:
users@infra.apache.org
With regards,
Apache Git Services
[GitHub] [knox] smolnar82 commented on a change in pull request #239:
KNOX-2153 - CM discovery - Monitor Cloudera Manager
Posted by GitBox <gi...@apache.org>.
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_r368862828
##########
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<>();
Review comment:
nit: they may be final
----------------------------------------------------------------
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:
users@infra.apache.org
With regards,
Apache Git Services
[GitHub] [knox] risdenk commented on a change in pull request #239:
KNOX-2153 - CM discovery - Monitor Cloudera Manager
Posted by GitBox <gi...@apache.org>.
risdenk commented on a change in pull request #239: KNOX-2153 - CM discovery - Monitor Cloudera Manager
URL: https://github.com/apache/knox/pull/239#discussion_r368155182
##########
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:
I don't think we should have a serializable class. Maybe a jackson pojo for json?
----------------------------------------------------------------
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:
users@infra.apache.org
With regards,
Apache Git Services
[GitHub] [knox] pzampino commented on a change in pull request #239:
KNOX-2153 - CM discovery - Monitor Cloudera Manager
Posted by GitBox <gi...@apache.org>.
pzampino commented on a change in pull request #239: KNOX-2153 - CM discovery - Monitor Cloudera Manager
URL: https://github.com/apache/knox/pull/239#discussion_r369287943
##########
File path: gateway-discovery-cm/src/main/java/org/apache/knox/gateway/topology/discovery/cm/model/oozie/OozieServiceModelGenerator.java
##########
@@ -59,15 +63,22 @@ public ServiceModel generateService(ApiService service,
String hostname = role.getHostRef().getHostname();
String scheme;
String port;
- boolean sslEnabled = Boolean.parseBoolean(getServiceConfigValue(serviceConfig, "oozie_use_ssl"));
- if(sslEnabled) {
+ String sslEnabled = getServiceConfigValue(serviceConfig, USE_SSL);
+ if(Boolean.parseBoolean(sslEnabled)) {
scheme = "https";
- port = getRoleConfigValue(roleConfig, "oozie_https_port");
+ port = getRoleConfigValue(roleConfig, HTTPS_PORT);
} else {
scheme = "http";
- port = getRoleConfigValue(roleConfig, "oozie_http_port");
+ port = getRoleConfigValue(roleConfig, HTTP_PORT);
}
Review comment:
Since that is an existing condition, I would like to defer that kind of change to a subsequent JIRA.
----------------------------------------------------------------
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:
users@infra.apache.org
With regards,
Apache Git Services
[GitHub] [knox] smolnar82 commented on a change in pull request #239:
KNOX-2153 - CM discovery - Monitor Cloudera Manager
Posted by GitBox <gi...@apache.org>.
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_r368878478
##########
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);
Review comment:
See the previously referenced GatewayServerLifecycleListener. You may consider changing its lifeCycleStarted method to notify you when the Knox Gateway server is actually up&running (which means all services, including Toplogy Service, is fully functional)
----------------------------------------------------------------
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:
users@infra.apache.org
With regards,
Apache Git Services
[GitHub] [knox] risdenk commented on a change in pull request #239:
KNOX-2153 - CM discovery - Monitor Cloudera Manager
Posted by GitBox <gi...@apache.org>.
risdenk commented on a change in pull request #239: KNOX-2153 - CM discovery - Monitor Cloudera Manager
URL: https://github.com/apache/knox/pull/239#discussion_r369828766
##########
File path: gateway-discovery-cm/pom.xml
##########
@@ -48,10 +52,29 @@
<groupId>com.squareup.okhttp</groupId>
<artifactId>okhttp</artifactId>
</dependency>
+ <dependency>
+ <groupId>commons-io</groupId>
+ <artifactId>commons-io</artifactId>
+ </dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
</dependency>
+ <dependency>
+ <groupId>com.fasterxml.jackson.core</groupId>
+ <artifactId>jackson-core</artifactId>
+ <scope>compile</scope>
+ </dependency>
+ <dependency>
+ <groupId>com.fasterxml.jackson.core</groupId>
+ <artifactId>jackson-databind</artifactId>
+ <scope>compile</scope>
Review comment:
`<scope>compile</scope>` not needed
----------------------------------------------------------------
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:
users@infra.apache.org
With regards,
Apache Git Services
[GitHub] [knox] smolnar82 commented on a change in pull request #239:
KNOX-2153 - CM discovery - Monitor Cloudera Manager
Posted by GitBox <gi...@apache.org>.
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_r370130698
##########
File path: gateway-discovery-cm/src/main/java/org/apache/knox/gateway/topology/discovery/cm/monitor/ClouderaManagerClusterConfigurationMonitor.java
##########
@@ -0,0 +1,876 @@
+/*
+ * 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.monitor;
+
+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.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 com.google.common.util.concurrent.ThreadFactoryBuilder;
+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 org.apache.knox.gateway.topology.discovery.cm.ClouderaManagerCluster;
+import org.apache.knox.gateway.topology.discovery.cm.ClouderaManagerServiceDiscoveryMessages;
+import org.apache.knox.gateway.topology.discovery.cm.DiscoveryApiClient;
+import org.apache.knox.gateway.topology.discovery.cm.ServiceModel;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+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.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ThreadFactory;
+import java.util.concurrent.locks.ReadWriteLock;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
+
+/**
+ * ClusterConfigurationMonitor implementation for clusters managed by ClouderaManager.
+ */
+public class ClouderaManagerClusterConfigurationMonitor implements ClusterConfigurationMonitor {
Review comment:
I'm with Kevin here (see my previous comment on creating a DAO to load/persist data into the disk) as well as separating at least one other class out.
----------------------------------------------------------------
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:
users@infra.apache.org
With regards,
Apache Git Services
[GitHub] [knox] smolnar82 commented on a change in pull request #239:
KNOX-2153 - CM discovery - Monitor Cloudera Manager
Posted by GitBox <gi...@apache.org>.
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_r368874928
##########
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)) {
Review comment:
What if a property has been removed? Would not `currentProps.getProperty(name)` return `null`? In this case, a NPE would be thrown here. Consider changing this line to `!prevValue.equals(currValue)` to be `null-safe`
----------------------------------------------------------------
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:
users@infra.apache.org
With regards,
Apache Git Services
[GitHub] [knox] smolnar82 commented on a change in pull request #239:
KNOX-2153 - CM discovery - Monitor Cloudera Manager
Posted by GitBox <gi...@apache.org>.
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_r368886079
##########
File path: gateway-discovery-cm/src/main/java/org/apache/knox/gateway/topology/discovery/cm/model/oozie/OozieServiceModelGenerator.java
##########
@@ -59,15 +63,22 @@ public ServiceModel generateService(ApiService service,
String hostname = role.getHostRef().getHostname();
String scheme;
String port;
- boolean sslEnabled = Boolean.parseBoolean(getServiceConfigValue(serviceConfig, "oozie_use_ssl"));
- if(sslEnabled) {
+ String sslEnabled = getServiceConfigValue(serviceConfig, USE_SSL);
+ if(Boolean.parseBoolean(sslEnabled)) {
scheme = "https";
- port = getRoleConfigValue(roleConfig, "oozie_https_port");
+ port = getRoleConfigValue(roleConfig, HTTPS_PORT);
} else {
scheme = "http";
- port = getRoleConfigValue(roleConfig, "oozie_http_port");
+ port = getRoleConfigValue(roleConfig, HTTP_PORT);
}
Review comment:
This is a recurring code in many of the different service implementation. You may consider implementing a method in `AbstractServiceModelGenerator` which returns the correct scheme and the port.
----------------------------------------------------------------
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:
users@infra.apache.org
With regards,
Apache Git Services
[GitHub] [knox] risdenk commented on a change in pull request #239:
KNOX-2153 - CM discovery - Monitor Cloudera Manager
Posted by GitBox <gi...@apache.org>.
risdenk commented on a change in pull request #239: KNOX-2153 - CM discovery - Monitor Cloudera Manager
URL: https://github.com/apache/knox/pull/239#discussion_r369829054
##########
File path: gateway-discovery-cm/pom.xml
##########
@@ -48,10 +52,29 @@
<groupId>com.squareup.okhttp</groupId>
<artifactId>okhttp</artifactId>
</dependency>
+ <dependency>
+ <groupId>commons-io</groupId>
+ <artifactId>commons-io</artifactId>
+ </dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
</dependency>
+ <dependency>
+ <groupId>com.fasterxml.jackson.core</groupId>
+ <artifactId>jackson-core</artifactId>
+ <scope>compile</scope>
+ </dependency>
+ <dependency>
+ <groupId>com.fasterxml.jackson.core</groupId>
+ <artifactId>jackson-databind</artifactId>
+ <scope>compile</scope>
+ </dependency>
+ <dependency>
+ <groupId>com.google.guava</groupId>
+ <artifactId>guava</artifactId>
+ <scope>compile</scope>
+ </dependency>
Review comment:
We should REALLY try to avoid guava. I'll try to see what we can do about it. I've tried to limit its usage where possible since it tends to be a PITA dependency.
----------------------------------------------------------------
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:
users@infra.apache.org
With regards,
Apache Git Services
[GitHub] [knox] risdenk commented on a change in pull request #239:
KNOX-2153 - CM discovery - Monitor Cloudera Manager
Posted by GitBox <gi...@apache.org>.
risdenk commented on a change in pull request #239: KNOX-2153 - CM discovery - Monitor Cloudera Manager
URL: https://github.com/apache/knox/pull/239#discussion_r368154958
##########
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);
Review comment:
The 20 is what in seconds? This should be waiting on some specific event not just some time.
----------------------------------------------------------------
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:
users@infra.apache.org
With regards,
Apache Git Services
[GitHub] [knox] risdenk commented on a change in pull request #239:
KNOX-2153 - CM discovery - Monitor Cloudera Manager
Posted by GitBox <gi...@apache.org>.
risdenk commented on a change in pull request #239: KNOX-2153 - CM discovery - Monitor Cloudera Manager
URL: https://github.com/apache/knox/pull/239#discussion_r368155895
##########
File path: gateway-discovery-cm/src/main/java/org/apache/knox/gateway/topology/discovery/cm/ClouderaManagerServiceDiscovery.java
##########
@@ -105,6 +116,34 @@ private DiscoveryApiClient getClient(ServiceDiscoveryConfig discoveryConfig) {
return client;
}
+ /**
+ * Get the ClouderaManager configuration change monitor from the associated gateway service.
+ */
+ private ClouderaManagerClusterConfigurationMonitor getConfigurationChangeMonitor() {
Review comment:
I thought GatewayServices is already a public static object that is accessible from GatewayServer or elsewhere. I don't think we need to go through all this effort to try to use reflection here.
----------------------------------------------------------------
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:
users@infra.apache.org
With regards,
Apache Git Services
[GitHub] [knox] pzampino commented on issue #239: KNOX-2153 - CM discovery -
Monitor Cloudera Manager
Posted by GitBox <gi...@apache.org>.
pzampino commented on issue #239: KNOX-2153 - CM discovery - Monitor Cloudera Manager
URL: https://github.com/apache/knox/pull/239#issuecomment-576976964
> The biggest concern I have is the java serialization that doesn't seem entirely necessary.
>
> The other item that seems confusing is there a bunch of `model/*` cleanup as far as constants and fixing variables. It would be cleaner to separate this so its easier to tell exactly what changed for monitoring the CM API.
I believe I've addressed the object serialization concerns, and the ServiceModel changes are intended to facilitate the determination of relevant config changes. The constants were added because the values are now being referenced in multiple places.
----------------------------------------------------------------
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:
users@infra.apache.org
With regards,
Apache Git Services
[GitHub] [knox] pzampino commented on a change in pull request #239:
KNOX-2153 - CM discovery - Monitor Cloudera Manager
Posted by GitBox <gi...@apache.org>.
pzampino commented on a change in pull request #239: KNOX-2153 - CM discovery - Monitor Cloudera Manager
URL: https://github.com/apache/knox/pull/239#discussion_r369287300
##########
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();
Review comment:
Agreed
----------------------------------------------------------------
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:
users@infra.apache.org
With regards,
Apache Git Services
[GitHub] [knox] pzampino commented on a change in pull request #239:
KNOX-2153 - CM discovery - Monitor Cloudera Manager
Posted by GitBox <gi...@apache.org>.
pzampino commented on a change in pull request #239: KNOX-2153 - CM discovery - Monitor Cloudera Manager
URL: https://github.com/apache/knox/pull/239#discussion_r370707475
##########
File path: gateway-discovery-cm/src/main/java/org/apache/knox/gateway/topology/discovery/cm/monitor/ClouderaManagerClusterConfigurationMonitor.java
##########
@@ -0,0 +1,876 @@
+/*
+ * 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.monitor;
+
+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.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 com.google.common.util.concurrent.ThreadFactoryBuilder;
+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 org.apache.knox.gateway.topology.discovery.cm.ClouderaManagerCluster;
+import org.apache.knox.gateway.topology.discovery.cm.ClouderaManagerServiceDiscoveryMessages;
+import org.apache.knox.gateway.topology.discovery.cm.DiscoveryApiClient;
+import org.apache.knox.gateway.topology.discovery.cm.ServiceModel;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+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.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ThreadFactory;
+import java.util.concurrent.locks.ReadWriteLock;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
+
+/**
+ * ClusterConfigurationMonitor implementation for clusters managed by ClouderaManager.
+ */
+public class ClouderaManagerClusterConfigurationMonitor implements ClusterConfigurationMonitor {
Review comment:
I've made some changes along these lines.
----------------------------------------------------------------
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:
users@infra.apache.org
With regards,
Apache Git Services
[GitHub] [knox] pzampino commented on a change in pull request #239:
KNOX-2153 - CM discovery - Monitor Cloudera Manager
Posted by GitBox <gi...@apache.org>.
pzampino commented on a change in pull request #239: KNOX-2153 - CM discovery - Monitor Cloudera Manager
URL: https://github.com/apache/knox/pull/239#discussion_r369008000
##########
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)) {
Review comment:
Good catch.
----------------------------------------------------------------
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:
users@infra.apache.org
With regards,
Apache Git Services
[GitHub] [knox] risdenk commented on a change in pull request #239:
KNOX-2153 - CM discovery - Monitor Cloudera Manager
Posted by GitBox <gi...@apache.org>.
risdenk commented on a change in pull request #239: KNOX-2153 - CM discovery - Monitor Cloudera Manager
URL: https://github.com/apache/knox/pull/239#discussion_r369830892
##########
File path: gateway-discovery-cm/src/test/java/org/apache/knox/gateway/topology/discovery/cm/ClouderaManagerServiceDiscoveryTest.java
##########
@@ -988,8 +999,17 @@ private void doTestSolrDiscovery(final boolean isSSL) {
private ServiceDiscovery.Cluster doTestLivyDiscovery(final String hostName,
final String port,
final boolean isSSL) {
+ return doTestLivyDiscovery(hostName, port, isSSL, "http");
+ }
+
+
+ private ServiceDiscovery.Cluster doTestLivyDiscovery(final String hostName,
+ final String port,
+ final Boolean isSSL,
+ final String transportMode) {
// Configure the role
Map<String, String> roleProperties = new HashMap<>();
+ roleProperties.put("livy_server_thrift_transport_mode", transportMode);
Review comment:
We shouldn't care about this. Livy has a thrift server which is completely separate from the HTTP API.
----------------------------------------------------------------
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:
users@infra.apache.org
With regards,
Apache Git Services
[GitHub] [knox] risdenk commented on a change in pull request #239:
KNOX-2153 - CM discovery - Monitor Cloudera Manager
Posted by GitBox <gi...@apache.org>.
risdenk commented on a change in pull request #239: KNOX-2153 - CM discovery - Monitor Cloudera Manager
URL: https://github.com/apache/knox/pull/239#discussion_r368155577
##########
File path: gateway-discovery-cm/src/main/java/org/apache/knox/gateway/topology/discovery/cm/ClouderaManagerServiceDiscovery.java
##########
@@ -63,6 +68,9 @@
static final String DEFAULT_USER_ALIAS = "cm.discovery.user";
static final String DEFAULT_PWD_ALIAS = "cm.discovery.password";
+ private static final String GATEWAY_SERVICES_ACCESSOR_CLASS = "org.apache.knox.gateway.GatewayServer";
Review comment:
Use `GatewayServer.class...` to get the name instead of hardcoding the string.
----------------------------------------------------------------
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:
users@infra.apache.org
With regards,
Apache Git Services
[GitHub] [knox] risdenk commented on a change in pull request #239:
KNOX-2153 - CM discovery - Monitor Cloudera Manager
Posted by GitBox <gi...@apache.org>.
risdenk commented on a change in pull request #239: KNOX-2153 - CM discovery - Monitor Cloudera Manager
URL: https://github.com/apache/knox/pull/239#discussion_r369838665
##########
File path: gateway-discovery-cm/src/main/java/org/apache/knox/gateway/topology/discovery/cm/monitor/ClouderaManagerClusterConfigurationMonitor.java
##########
@@ -0,0 +1,876 @@
+/*
+ * 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.monitor;
+
+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.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 com.google.common.util.concurrent.ThreadFactoryBuilder;
+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 org.apache.knox.gateway.topology.discovery.cm.ClouderaManagerCluster;
+import org.apache.knox.gateway.topology.discovery.cm.ClouderaManagerServiceDiscoveryMessages;
+import org.apache.knox.gateway.topology.discovery.cm.DiscoveryApiClient;
+import org.apache.knox.gateway.topology.discovery.cm.ServiceModel;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+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.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ThreadFactory;
+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.toLowerCase(Locale.getDefault()) + "-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 static final ThreadLocal<DateFormat> eventQueryTimestampFormat =
+ ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'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 final Map<String, DiscoveryApiClient> clients = new ConcurrentHashMap<>();
+
+ // ClouderaManager address
+ // clusterName -> ServiceDiscoveryConfig
+ //
+ private final Map<String, Map<String, ServiceDiscoveryConfig>> clusterMonitorConfigurations = new ConcurrentHashMap<>();
+
+ // ClouderaManager address
+ // clusterName
+ // serviceType -> Properties
+ //
+ private final Map<String, Map<String, Map<String, ServiceConfigurationModel>>> clusterServiceConfigurations =
+ new ConcurrentHashMap<>();
+
+ private final ReadWriteLock serviceConfigurationsLock = new ReentrantReadWriteLock();
+
+ private final 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;
+
+ private ExecutorService executorService;
+
+ public static String getType() {
+ return TYPE;
+ }
+
+ ClouderaManagerClusterConfigurationMonitor(final GatewayConfig config, final AliasService aliasService) {
+ this.gatewayConfig = config;
+ this.aliasService = aliasService;
+
+ eventQueryTimestampFormat.get().setTimeZone(TimeZone.getTimeZone("UTC"));
+
+ ThreadFactory tf = (new ThreadFactoryBuilder()).setNameFormat("ClouderaManagerConfigurationMonitor-%d").build();
+ this.executorService = Executors.newSingleThreadExecutor(tf);
+
+ internalMonitor = new PollingConfigAnalyzer(this);
+
+ // 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
+ public void start() {
+ log.startingClouderaManagerConfigMonitor();
+ executorService.execute(internalMonitor);
+ }
+
+ @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.
+ */
+ public 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, ServiceConfigurationModel> scpMap = new HashMap<>();
+ for (String service : serviceModels.keySet()) {
+ for (ServiceModel model : serviceModels.get(service)) {
+ ServiceConfigurationModel scp =
+ scpMap.computeIfAbsent(model.getServiceType(), p -> new ServiceConfigurationModel());
+
+ 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, ServiceConfigurationModel> 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 (InputStream in = Files.newInputStream(persisted.toPath())) {
+ ServiceConfigurationRecord record =
+ (new ServiceConfigurationRecordObjectMapper()).readValue(in, ServiceConfigurationRecord.class);
+ addServiceConfiguration(record.getDiscoveryAddress(), record.getClusterName(), record.getConfigs());
+ } 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, ServiceConfigurationModel> getClusterServiceConfigurations(String address,
+ String clusterName) {
+ Map<String, ServiceConfigurationModel> 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 ServiceConfigurationModel object with the configuration properties associated with the specified
+ * service.
+ */
+ private ServiceConfigurationModel getCurrentServiceConfiguration(final String address,
+ final String clusterName,
+ final String service) {
+ ServiceConfigurationModel 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 ServiceConfigurationModel(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.get().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;
+ }
Review comment:
Nit: It might be cleaner to use `Path` and Java NIO here. This would cascade to the rest of the `File` usages.
----------------------------------------------------------------
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:
users@infra.apache.org
With regards,
Apache Git Services
[GitHub] [knox] risdenk commented on a change in pull request #239:
KNOX-2153 - CM discovery - Monitor Cloudera Manager
Posted by GitBox <gi...@apache.org>.
risdenk commented on a change in pull request #239: KNOX-2153 - CM discovery - Monitor Cloudera Manager
URL: https://github.com/apache/knox/pull/239#discussion_r369830514
##########
File path: gateway-discovery-cm/src/test/java/org/apache/knox/gateway/topology/discovery/cm/ClouderaManagerServiceDiscoveryTest.java
##########
@@ -331,6 +331,17 @@ public void testLivyDiscoverySSL() {
assertEquals("https://" + hostName + ":" + port, livyURLs.get(0));
}
+ @Test
+ public void testLivyDiscoveryWhenTransportModeIsBinary() {
+ final String hostName = "livy-host";
+ final String port = "8998";
+ ServiceDiscovery.Cluster cluster = doTestLivyDiscovery(hostName, port, false, "binary");
Review comment:
This doesn't make much sense to me. Livy discovery should be on the HTTP endpoint. Binary vs HTTP would be on the thrift server not on the HTTP endpoint....
----------------------------------------------------------------
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:
users@infra.apache.org
With regards,
Apache Git Services
[GitHub] [knox] risdenk commented on a change in pull request #239:
KNOX-2153 - CM discovery - Monitor Cloudera Manager
Posted by GitBox <gi...@apache.org>.
risdenk commented on a change in pull request #239: KNOX-2153 - CM discovery - Monitor Cloudera Manager
URL: https://github.com/apache/knox/pull/239#discussion_r369837792
##########
File path: gateway-discovery-cm/src/main/java/org/apache/knox/gateway/topology/discovery/cm/monitor/ServiceConfigurationRecordObjectMapper.java
##########
@@ -0,0 +1,111 @@
+/*
+ * 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.monitor;
+
+import com.fasterxml.jackson.core.JsonGenerator;
+import com.fasterxml.jackson.core.JsonParser;
+import com.fasterxml.jackson.core.Version;
+import com.fasterxml.jackson.databind.DeserializationContext;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.SerializerProvider;
+import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
+import com.fasterxml.jackson.databind.module.SimpleModule;
+import com.fasterxml.jackson.databind.ser.std.StdSerializer;
+
+import java.io.IOException;
+import java.util.Iterator;
+
+/**
+ * Custom ObjectMapper implementation for serializing/deserializing ServiceConfigurationRecord objects.
+ */
+class ServiceConfigurationRecordObjectMapper extends ObjectMapper {
Review comment:
So this could be ignorance regarding Jackson, but I thought we could just annotate the class instead of having to write custom serialize/deserialize stuff. We use Jackson elsewhere and no where else do we `extends ObjectMapper`
----------------------------------------------------------------
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:
users@infra.apache.org
With regards,
Apache Git Services
[GitHub] [knox] pzampino commented on a change in pull request #239:
KNOX-2153 - CM discovery - Monitor Cloudera Manager
Posted by GitBox <gi...@apache.org>.
pzampino commented on a change in pull request #239: KNOX-2153 - CM discovery - Monitor Cloudera Manager
URL: https://github.com/apache/knox/pull/239#discussion_r370163109
##########
File path: gateway-discovery-cm/src/main/java/org/apache/knox/gateway/topology/discovery/cm/monitor/ServiceConfigurationRecordObjectMapper.java
##########
@@ -0,0 +1,111 @@
+/*
+ * 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.monitor;
+
+import com.fasterxml.jackson.core.JsonGenerator;
+import com.fasterxml.jackson.core.JsonParser;
+import com.fasterxml.jackson.core.Version;
+import com.fasterxml.jackson.databind.DeserializationContext;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.SerializerProvider;
+import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
+import com.fasterxml.jackson.databind.module.SimpleModule;
+import com.fasterxml.jackson.databind.ser.std.StdSerializer;
+
+import java.io.IOException;
+import java.util.Iterator;
+
+/**
+ * Custom ObjectMapper implementation for serializing/deserializing ServiceConfigurationRecord objects.
+ */
+class ServiceConfigurationRecordObjectMapper extends ObjectMapper {
Review comment:
I had encountered some difficulty employing annotations, which led me to the current solution. This could be my ignorance of Jackson.
----------------------------------------------------------------
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:
users@infra.apache.org
With regards,
Apache Git Services
[GitHub] [knox] pzampino commented on a change in pull request #239:
KNOX-2153 - CM discovery - Monitor Cloudera Manager
Posted by GitBox <gi...@apache.org>.
pzampino commented on a change in pull request #239: KNOX-2153 - CM discovery - Monitor Cloudera Manager
URL: https://github.com/apache/knox/pull/239#discussion_r370161541
##########
File path: gateway-discovery-cm/src/test/java/org/apache/knox/gateway/topology/discovery/cm/ClouderaManagerServiceDiscoveryTest.java
##########
@@ -331,6 +331,17 @@ public void testLivyDiscoverySSL() {
assertEquals("https://" + hostName + ":" + port, livyURLs.get(0));
}
+ @Test
+ public void testLivyDiscoveryWhenTransportModeIsBinary() {
+ final String hostName = "livy-host";
+ final String port = "8998";
+ ServiceDiscovery.Cluster cluster = doTestLivyDiscovery(hostName, port, false, "binary");
Review comment:
Ok
----------------------------------------------------------------
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:
users@infra.apache.org
With regards,
Apache Git Services
[GitHub] [knox] smolnar82 commented on a change in pull request #239:
KNOX-2153 - CM discovery - Monitor Cloudera Manager
Posted by GitBox <gi...@apache.org>.
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_r368864779
##########
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());
Review comment:
`SimpleDateFormat` is not thread-safe; you may consider binding it to local thread. See one sample [here](https://github.com/apache/knox/blob/master/gateway-server/src/main/java/org/apache/knox/gateway/GatewayServerLifecycleListener.java#L38).
----------------------------------------------------------------
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:
users@infra.apache.org
With regards,
Apache Git Services
[GitHub] [knox] risdenk commented on a change in pull request #239:
KNOX-2153 - CM discovery - Monitor Cloudera Manager
Posted by GitBox <gi...@apache.org>.
risdenk commented on a change in pull request #239: KNOX-2153 - CM discovery - Monitor Cloudera Manager
URL: https://github.com/apache/knox/pull/239#discussion_r369828734
##########
File path: gateway-discovery-cm/pom.xml
##########
@@ -48,10 +52,29 @@
<groupId>com.squareup.okhttp</groupId>
<artifactId>okhttp</artifactId>
</dependency>
+ <dependency>
+ <groupId>commons-io</groupId>
+ <artifactId>commons-io</artifactId>
+ </dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
</dependency>
+ <dependency>
+ <groupId>com.fasterxml.jackson.core</groupId>
+ <artifactId>jackson-core</artifactId>
+ <scope>compile</scope>
Review comment:
`<scope>compile</scope>` not needed
----------------------------------------------------------------
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:
users@infra.apache.org
With regards,
Apache Git Services
[GitHub] [knox] smolnar82 commented on a change in pull request #239:
KNOX-2153 - CM discovery - Monitor Cloudera Manager
Posted by GitBox <gi...@apache.org>.
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:
users@infra.apache.org
With regards,
Apache Git Services
[GitHub] [knox] pzampino commented on a change in pull request #239:
KNOX-2153 - CM discovery - Monitor Cloudera Manager
Posted by GitBox <gi...@apache.org>.
pzampino commented on a change in pull request #239: KNOX-2153 - CM discovery - Monitor Cloudera Manager
URL: https://github.com/apache/knox/pull/239#discussion_r369286476
##########
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();
Review comment:
Added JSON serialization format instead
----------------------------------------------------------------
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:
users@infra.apache.org
With regards,
Apache Git Services
[GitHub] [knox] pzampino commented on a change in pull request #239:
KNOX-2153 - CM discovery - Monitor Cloudera Manager
Posted by GitBox <gi...@apache.org>.
pzampino commented on a change in pull request #239: KNOX-2153 - CM discovery - Monitor Cloudera Manager
URL: https://github.com/apache/knox/pull/239#discussion_r369286839
##########
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);
Review comment:
Leveraged the separation of the init() and start() lifecycle events in the gateway services to achieve what I was trying to accomplish.
----------------------------------------------------------------
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:
users@infra.apache.org
With regards,
Apache Git Services
[GitHub] [knox] risdenk commented on a change in pull request #239:
KNOX-2153 - CM discovery - Monitor Cloudera Manager
Posted by GitBox <gi...@apache.org>.
risdenk commented on a change in pull request #239: KNOX-2153 - CM discovery - Monitor Cloudera Manager
URL: https://github.com/apache/knox/pull/239#discussion_r369836470
##########
File path: gateway-discovery-cm/src/main/java/org/apache/knox/gateway/topology/discovery/cm/monitor/ClouderaManagerClusterConfigurationMonitor.java
##########
@@ -0,0 +1,876 @@
+/*
+ * 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.monitor;
+
+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.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 com.google.common.util.concurrent.ThreadFactoryBuilder;
+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 org.apache.knox.gateway.topology.discovery.cm.ClouderaManagerCluster;
+import org.apache.knox.gateway.topology.discovery.cm.ClouderaManagerServiceDiscoveryMessages;
+import org.apache.knox.gateway.topology.discovery.cm.DiscoveryApiClient;
+import org.apache.knox.gateway.topology.discovery.cm.ServiceModel;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+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.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ThreadFactory;
+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.toLowerCase(Locale.getDefault()) + "-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 static final ThreadLocal<DateFormat> eventQueryTimestampFormat =
+ ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'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 final Map<String, DiscoveryApiClient> clients = new ConcurrentHashMap<>();
+
+ // ClouderaManager address
+ // clusterName -> ServiceDiscoveryConfig
+ //
+ private final Map<String, Map<String, ServiceDiscoveryConfig>> clusterMonitorConfigurations = new ConcurrentHashMap<>();
+
+ // ClouderaManager address
+ // clusterName
+ // serviceType -> Properties
+ //
+ private final Map<String, Map<String, Map<String, ServiceConfigurationModel>>> clusterServiceConfigurations =
+ new ConcurrentHashMap<>();
+
+ private final ReadWriteLock serviceConfigurationsLock = new ReentrantReadWriteLock();
+
+ private final 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;
+
+ private ExecutorService executorService;
+
+ public static String getType() {
+ return TYPE;
+ }
+
+ ClouderaManagerClusterConfigurationMonitor(final GatewayConfig config, final AliasService aliasService) {
+ this.gatewayConfig = config;
+ this.aliasService = aliasService;
+
+ eventQueryTimestampFormat.get().setTimeZone(TimeZone.getTimeZone("UTC"));
+
+ ThreadFactory tf = (new ThreadFactoryBuilder()).setNameFormat("ClouderaManagerConfigurationMonitor-%d").build();
Review comment:
Looks like this is the only usage of Guava. We already have a pattern for doing this with commons-lang3 instead?
https://github.com/apache/knox/blob/master/gateway-cm-integration/src/main/java/org/apache/knox/gateway/cm/descriptor/ClouderaManagerDescriptorMonitor.java#L59
Another option is potentially a custom thread factory.
----------------------------------------------------------------
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:
users@infra.apache.org
With regards,
Apache Git Services
[GitHub] [knox] risdenk commented on a change in pull request #239:
KNOX-2153 - CM discovery - Monitor Cloudera Manager
Posted by GitBox <gi...@apache.org>.
risdenk commented on a change in pull request #239: KNOX-2153 - CM discovery - Monitor Cloudera Manager
URL: https://github.com/apache/knox/pull/239#discussion_r368154171
##########
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();
Review comment:
Does this need to be Objects? Can't this be a JSON file or something else?
----------------------------------------------------------------
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:
users@infra.apache.org
With regards,
Apache Git Services
[GitHub] [knox] pzampino merged pull request #239: KNOX-2153 - CM discovery
- Monitor Cloudera Manager
Posted by GitBox <gi...@apache.org>.
pzampino merged pull request #239: KNOX-2153 - CM discovery - Monitor Cloudera Manager
URL: https://github.com/apache/knox/pull/239
----------------------------------------------------------------
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:
users@infra.apache.org
With regards,
Apache Git Services
[GitHub] [knox] smolnar82 commented on a change in pull request #239:
KNOX-2153 - CM discovery - Monitor Cloudera Manager
Posted by GitBox <gi...@apache.org>.
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_r369016886
##########
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();
Review comment:
One more advantage: using an executor does not require creating a Thread -> the PMD warning suppression would not be necessary
----------------------------------------------------------------
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:
users@infra.apache.org
With regards,
Apache Git Services
[GitHub] [knox] pzampino commented on a change in pull request #239:
KNOX-2153 - CM discovery - Monitor Cloudera Manager
Posted by GitBox <gi...@apache.org>.
pzampino commented on a change in pull request #239: KNOX-2153 - CM discovery - Monitor Cloudera Manager
URL: https://github.com/apache/knox/pull/239#discussion_r370161727
##########
File path: gateway-discovery-cm/src/test/java/org/apache/knox/gateway/topology/discovery/cm/ClouderaManagerServiceDiscoveryTest.java
##########
@@ -988,8 +999,17 @@ private void doTestSolrDiscovery(final boolean isSSL) {
private ServiceDiscovery.Cluster doTestLivyDiscovery(final String hostName,
final String port,
final boolean isSSL) {
+ return doTestLivyDiscovery(hostName, port, isSSL, "http");
+ }
+
+
+ private ServiceDiscovery.Cluster doTestLivyDiscovery(final String hostName,
+ final String port,
+ final Boolean isSSL,
+ final String transportMode) {
// Configure the role
Map<String, String> roleProperties = new HashMap<>();
+ roleProperties.put("livy_server_thrift_transport_mode", transportMode);
Review comment:
Understood
----------------------------------------------------------------
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:
users@infra.apache.org
With regards,
Apache Git Services
[GitHub] [knox] pzampino commented on a change in pull request #239:
KNOX-2153 - CM discovery - Monitor Cloudera Manager
Posted by GitBox <gi...@apache.org>.
pzampino commented on a change in pull request #239: KNOX-2153 - CM discovery - Monitor Cloudera Manager
URL: https://github.com/apache/knox/pull/239#discussion_r369007060
##########
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();
Review comment:
Good point. I suppose I was rushing a bit to get this finished. It would be better to use an alternative serialization format.
----------------------------------------------------------------
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:
users@infra.apache.org
With regards,
Apache Git Services
[GitHub] [knox] risdenk commented on a change in pull request #239:
KNOX-2153 - CM discovery - Monitor Cloudera Manager
Posted by GitBox <gi...@apache.org>.
risdenk commented on a change in pull request #239: KNOX-2153 - CM discovery - Monitor Cloudera Manager
URL: https://github.com/apache/knox/pull/239#discussion_r368154377
##########
File path: build-tools/src/main/resources/build-tools/spotbugs-filter.xml
##########
@@ -71,4 +71,9 @@ limitations under the License.
<Bug pattern="NM_SAME_SIMPLE_NAME_AS_SUPERCLASS" />
</Match>
+ <Match>
+ <Class name="org.apache.knox.gateway.topology.discovery.cm.ClouderaManagerClusterConfigurationMonitor" />
+ <Bug pattern="OBJECT_DESERIALIZATION" />
Review comment:
This is super concerning. If this is required (I'm not sure it is based on looking at this class), can this be limited to a single method instead of the whole class?
----------------------------------------------------------------
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:
users@infra.apache.org
With regards,
Apache Git Services