You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@ambari.apache.org by js...@apache.org on 2014/11/10 22:32:08 UTC
[09/11] ambari git commit: AMBARI-7175. Add explicit stack service
inheritance
http://git-wip-us.apache.org/repos/asf/ambari/blob/2fc7adec/ambari-server/src/main/java/org/apache/ambari/server/stack/ConfigurationDirectory.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/stack/ConfigurationDirectory.java b/ambari-server/src/main/java/org/apache/ambari/server/stack/ConfigurationDirectory.java
new file mode 100644
index 0000000..d4c99e5
--- /dev/null
+++ b/ambari-server/src/main/java/org/apache/ambari/server/stack/ConfigurationDirectory.java
@@ -0,0 +1,129 @@
+/**
+ * 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.ambari.server.stack;
+
+import org.apache.ambari.server.api.services.AmbariMetaInfo;
+import org.apache.ambari.server.state.ConfigHelper;
+import org.apache.ambari.server.state.PropertyInfo;
+import org.apache.ambari.server.state.stack.ConfigurationXml;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.xml.namespace.QName;
+import java.io.File;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Encapsulates IO operations on a stack definition configuration directory.
+ */
+public class ConfigurationDirectory extends StackDefinitionDirectory {
+ /**
+ * Used to unmarshal a stack definition configuration to an object representation
+ */
+ private static ModuleFileUnmarshaller unmarshaller = new ModuleFileUnmarshaller();
+
+ /**
+ * Map of configuration type to configuration module.
+ * One entry for each configuration file in this configuration directory.
+ */
+ private Map<String, ConfigurationModule> configurationModules = new HashMap<String, ConfigurationModule>();
+
+ /**
+ * Logger instance
+ */
+ private final static Logger LOG = LoggerFactory.getLogger(ConfigurationDirectory.class);
+
+ /**
+ * Constructor.
+ *
+ * @param directoryName configuration directory name
+ */
+ public ConfigurationDirectory(String directoryName) {
+ super(directoryName);
+ parsePath();
+ }
+
+ /**
+ * Obtain a collection of of configuration modules representing each configuration
+ * file contained in this configuration directory.
+ *
+ * @return collection of configuration modules
+ */
+ public Collection<ConfigurationModule> getConfigurationModules() {
+ return configurationModules.values();
+ }
+
+ /**
+ * Parse the configuration directory.
+ */
+ private void parsePath() {
+ File[] configFiles = directory.listFiles(AmbariMetaInfo.FILENAME_FILTER);
+ if (configFiles != null) {
+ for (File configFile : configFiles) {
+ if (configFile.getName().endsWith(AmbariMetaInfo.SERVICE_CONFIG_FILE_NAME_POSTFIX)) {
+ try {
+ String configType = ConfigHelper.fileNameToConfigType(configFile.getName());
+ ConfigurationXml config = unmarshaller.unmarshal(ConfigurationXml.class, configFile);
+ ConfigurationInfo configInfo = new ConfigurationInfo(parseProperties(config,
+ configFile.getName()), parseAttributes(config));
+ ConfigurationModule module = new ConfigurationModule(configType, configInfo);
+ configurationModules.put(configType, module);
+ } catch (Exception e) {
+ LOG.error("Could not load configuration for " + configFile, e);
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Parse a configurations properties.
+ *
+ * @param configuration object representation of a configuration file
+ * @param fileName configuration file name
+ *
+ * @return collection of properties
+ */
+ private Collection<PropertyInfo> parseProperties(ConfigurationXml configuration, String fileName) {
+ List<PropertyInfo> props = new ArrayList<PropertyInfo>();
+ for (PropertyInfo pi : configuration.getProperties()) {
+ pi.setFilename(fileName);
+ props.add(pi);
+ }
+ return props; }
+
+ /**
+ * Parse a configurations type attributes.
+ *
+ * @param configuration object representation of a configuration file
+ *
+ * @return collection of attributes for the configuration type
+ */
+ private Map<String, String> parseAttributes(ConfigurationXml configuration) {
+ Map<String, String> attributes = new HashMap<String, String>();
+ for (Map.Entry<QName, String> attribute : configuration.getAttributes().entrySet()) {
+ attributes.put(attribute.getKey().getLocalPart(), attribute.getValue());
+ }
+ return attributes;
+ }
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/2fc7adec/ambari-server/src/main/java/org/apache/ambari/server/stack/ConfigurationInfo.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/stack/ConfigurationInfo.java b/ambari-server/src/main/java/org/apache/ambari/server/stack/ConfigurationInfo.java
new file mode 100644
index 0000000..97d57cb
--- /dev/null
+++ b/ambari-server/src/main/java/org/apache/ambari/server/stack/ConfigurationInfo.java
@@ -0,0 +1,164 @@
+/**
+ * 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.ambari.server.stack;
+
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.apache.ambari.server.state.PropertyInfo;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * Encapsulates configuration properties and attributes for a single type.
+ */
+public class ConfigurationInfo {
+ /**
+ * Collection of properties
+ */
+ private Collection<PropertyInfo> properties;
+
+ /**
+ * Map of attribute category to a map of attribute name/value
+ */
+ private Map<String, Map<String, String>> attributes;
+
+ /**
+ * Logger instance
+ */
+ private final static Logger LOG = LoggerFactory.getLogger(ConfigurationInfo.class);
+
+ /**
+ * Constructor.
+ *
+ * @param properties configuration properties
+ * @param attributes configuration attributes
+ */
+ public ConfigurationInfo(Collection<PropertyInfo> properties, Map<String, String> attributes) {
+ this.properties = properties;
+ setAttributes(attributes);
+ }
+
+ /**
+ * Obtain the configuration properties.
+ *
+ * @return collection of properties
+ */
+ public Collection<PropertyInfo> getProperties() {
+ return properties;
+ }
+
+ /**
+ * Obtain the configuration attributes.
+ *
+ * @return map of attribute category to a map of attribute names/values
+ */
+ public Map<String, Map<String, String>> getAttributes() {
+ return attributes;
+ }
+
+ /**
+ * Set the default value of all type attributes which are not already specified.
+ */
+ public void ensureDefaultAttributes() {
+ Map<String, String> supportsAttributes = attributes.get(Supports.KEYWORD);
+ for (Supports supportsProperty : Supports.values()) {
+ String propertyName = supportsProperty.getPropertyName();
+ if (! supportsAttributes.containsKey(propertyName)) {
+ supportsAttributes.put(propertyName, supportsProperty.getDefaultValue());
+ }
+ }
+ }
+
+ /**
+ *
+ * Set the specified configuration type attributes.
+ *
+ * @param specifiedAttributes attributes that have been specified in configuration
+ */
+ private void setAttributes(Map<String, String> specifiedAttributes) {
+ Map<String, Map<String, String>> attributes = new HashMap<String, Map<String, String>>();
+ Map<String, String> supportsAttributes = new HashMap<String, String>();
+ attributes.put(Supports.KEYWORD, supportsAttributes);
+
+ for (Map.Entry<String, String> entry : specifiedAttributes.entrySet()) {
+ String attributeName = entry.getKey();
+ Supports s = Supports.attributeNameValueOf(attributeName);
+ if (s != null) {
+ supportsAttributes.put(s.getPropertyName(),
+ Boolean.valueOf(entry.getValue()).toString());
+ } else {
+ LOG.warn("Unknown configuration type attribute is specified: {}={}", attributeName, entry.getValue());
+ }
+ }
+ this.attributes = attributes;
+ }
+
+
+ /**
+ * Service configuration-types can support different abilities. This
+ * enumerates the various abilities that configuration-types can support.
+ *
+ * For example, Hadoop configuration types like 'core-site' and 'hdfs-site'
+ * can support the ability to define certain configs as 'final'.
+ */
+ public static enum Supports {
+
+ FINAL("supports_final"),
+ ADDING_FORBIDDEN("supports_adding_forbidden"),
+ DO_NOT_EXTEND("supports_do_not_extend");
+
+ public static final String KEYWORD = "supports";
+
+ private String defaultValue;
+ private String xmlAttributeName;
+
+ private Supports(String xmlAttributeName) {
+ this(xmlAttributeName, Boolean.FALSE.toString());
+ }
+
+ private Supports(String xmlAttributeName, String defaultValue) {
+ this.defaultValue = defaultValue;
+ this.xmlAttributeName = xmlAttributeName;
+ }
+
+ public String getDefaultValue() {
+ return defaultValue;
+ }
+
+ public String getXmlAttributeName() {
+ return xmlAttributeName;
+ }
+
+ public String getPropertyName() {
+ return name().toLowerCase();
+ }
+
+ public static Supports attributeNameValueOf(String attributeName) {
+ for (Supports s : values()) {
+ if (s.getXmlAttributeName().equals(attributeName)) {
+ return s;
+ }
+ }
+ return null;
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/2fc7adec/ambari-server/src/main/java/org/apache/ambari/server/stack/ConfigurationModule.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/stack/ConfigurationModule.java b/ambari-server/src/main/java/org/apache/ambari/server/stack/ConfigurationModule.java
new file mode 100644
index 0000000..ff2e930
--- /dev/null
+++ b/ambari-server/src/main/java/org/apache/ambari/server/stack/ConfigurationModule.java
@@ -0,0 +1,170 @@
+/**
+ * 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.ambari.server.stack;
+
+import org.apache.ambari.server.AmbariException;
+import org.apache.ambari.server.state.PropertyInfo;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Map;
+
+
+/**
+ * Configuration module which provides functionality related to parsing and fully
+ * resolving a configuration from the stack definition. Each instance is specific
+ * to a configuration type.
+ */
+public class ConfigurationModule extends BaseModule<ConfigurationModule, ConfigurationInfo> {
+ /**
+ * Configuration type
+ */
+ private String configType;
+
+ /**
+ * Associated configuration info
+ */
+ ConfigurationInfo info;
+
+ /**
+ * Specifies whether this configuration is marked as deleted
+ */
+ private boolean isDeleted;
+
+
+ /**
+ * Constructor.
+ *
+ * @param configType configuration type
+ * @param info configuration info
+ */
+ public ConfigurationModule(String configType, ConfigurationInfo info) {
+ this.configType = configType;
+ this.info = info;
+ }
+
+ @Override
+ public void resolve(ConfigurationModule parent, Map<String, StackModule> allStacks) throws AmbariException {
+ // merge properties also removes deleted props so should be called even if extension is disabled
+ mergeProperties(parent);
+
+ if (isExtensionEnabled()) {
+ mergeAttributes(parent);
+ }
+ }
+
+ @Override
+ public ConfigurationInfo getModuleInfo() {
+ return info;
+ }
+
+ @Override
+ public boolean isDeleted() {
+ return isDeleted;
+ }
+
+ @Override
+ public String getId() {
+ return getConfigType();
+ }
+
+ /**
+ * Obtain the configuration type.
+ *
+ * @return configuration type
+ */
+ public String getConfigType() {
+ return configType;
+ }
+
+
+ /**
+ * Set the deleted flag.
+ *
+ * @param isDeleted whether the configuration has been marked for deletion
+ */
+ public void setDeleted(boolean isDeleted) {
+ this.isDeleted = isDeleted;
+ }
+
+ /**
+ * Merge configuration properties with the configurations parent.
+ *
+ * @param parent parent configuration module
+ */
+ private void mergeProperties(ConfigurationModule parent) {
+ Collection<String> existingProps = new HashSet<String>();
+ Iterator<PropertyInfo> iter = info.getProperties().iterator();
+ while (iter.hasNext()) {
+ PropertyInfo prop = iter.next();
+ existingProps.add(prop.getFilename() + "/" + prop.getName());
+ if (prop.isDeleted()) {
+ iter.remove();
+ }
+ }
+
+ if (isExtensionEnabled()) {
+ for (PropertyInfo prop : parent.info.getProperties()) {
+ if (! existingProps.contains(prop.getFilename() + "/" + prop.getName())) {
+ info.getProperties().add(prop);
+ }
+ }
+ }
+ }
+
+ /**
+ * Merge configuration attributes with the parent configuration.
+ *
+ * @param parent parent configuration module
+ */
+ private void mergeAttributes(ConfigurationModule parent) {
+
+ for (Map.Entry<String, Map<String, String>> parentCategoryEntry : parent.info.getAttributes().entrySet()) {
+ String category = parentCategoryEntry.getKey();
+ Map<String, String> categoryAttributeMap = info.getAttributes().get(category);
+ if (categoryAttributeMap == null) {
+ categoryAttributeMap = new HashMap<String, String>();
+ info.getAttributes().put(category, categoryAttributeMap);
+ }
+ for (Map.Entry<String, String> parentAttributeEntry : parentCategoryEntry.getValue().entrySet()) {
+ String attributeName = parentAttributeEntry.getKey();
+ if (! categoryAttributeMap.containsKey(attributeName)) {
+ categoryAttributeMap.put(attributeName, parentAttributeEntry.getValue());
+ }
+ }
+ }
+ }
+
+ /**
+ * Determine if the configuration should extend the parents configuration.
+ *
+ * @return true if this configuration should extend the parents; false otherwise
+ */
+ //todo: is this valuable as a generic module concept?
+ private boolean isExtensionEnabled() {
+ Map<String, String> supportsMap = getModuleInfo().getAttributes().get(ConfigurationInfo.Supports.KEYWORD);
+ if (supportsMap == null) {
+ return true;
+ }
+
+ String val = supportsMap.get(ConfigurationInfo.Supports.DO_NOT_EXTEND.getPropertyName());
+ return val == null || val.equals("false");
+ }
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/2fc7adec/ambari-server/src/main/java/org/apache/ambari/server/stack/ModuleFileUnmarshaller.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/stack/ModuleFileUnmarshaller.java b/ambari-server/src/main/java/org/apache/ambari/server/stack/ModuleFileUnmarshaller.java
new file mode 100644
index 0000000..aa8e17b
--- /dev/null
+++ b/ambari-server/src/main/java/org/apache/ambari/server/stack/ModuleFileUnmarshaller.java
@@ -0,0 +1,77 @@
+/**
+ * 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.ambari.server.stack;
+
+import org.apache.ambari.server.state.stack.ConfigurationXml;
+import org.apache.ambari.server.state.stack.RepositoryXml;
+import org.apache.ambari.server.state.stack.ServiceMetainfoXml;
+import org.apache.ambari.server.state.stack.StackMetainfoXml;
+import org.apache.ambari.server.state.stack.UpgradePack;
+
+import javax.xml.bind.JAXBContext;
+import javax.xml.bind.JAXBException;
+import javax.xml.bind.Unmarshaller;
+import java.io.File;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * Provides functionality to unmarshal stack definition files to their
+ * corresponding object representations.
+ */
+class ModuleFileUnmarshaller {
+ /**
+ * Map of class to JAXB context
+ */
+ private static final Map<Class<?>, JAXBContext> jaxbContexts = new HashMap<Class<?>, JAXBContext>();
+
+ /**
+ * Unmarshal a file to it's corresponding object type.
+ *
+ * @param clz class of the object representation
+ * @param file file to unmarshal
+ *
+ * @return object representation of the specified file
+ * @throws JAXBException if unable to unmarshal the file
+ */
+ public <T> T unmarshal(Class<T> clz, File file) throws JAXBException {
+ Unmarshaller u = jaxbContexts.get(clz).createUnmarshaller();
+
+ return clz.cast(u.unmarshal(file));
+ }
+
+ /**
+ * statically register the JAXB contexts
+ */
+ static {
+ try {
+ // three classes define the top-level element "metainfo", so we need 3 contexts.
+ JAXBContext ctx = JAXBContext.newInstance(StackMetainfoXml.class, RepositoryXml.class,
+ ConfigurationXml.class, UpgradePack.class);
+
+ jaxbContexts.put(StackMetainfoXml.class, ctx);
+ jaxbContexts.put(RepositoryXml.class, ctx);
+ jaxbContexts.put(ConfigurationXml.class, ctx);
+ jaxbContexts.put(UpgradePack.class, ctx);
+ jaxbContexts.put(ServiceMetainfoXml.class, JAXBContext.newInstance(ServiceMetainfoXml.class));
+ } catch (JAXBException e) {
+ throw new RuntimeException (e);
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/2fc7adec/ambari-server/src/main/java/org/apache/ambari/server/stack/ServiceDirectory.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/stack/ServiceDirectory.java b/ambari-server/src/main/java/org/apache/ambari/server/stack/ServiceDirectory.java
new file mode 100644
index 0000000..843df0b
--- /dev/null
+++ b/ambari-server/src/main/java/org/apache/ambari/server/stack/ServiceDirectory.java
@@ -0,0 +1,181 @@
+/**
+ * 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.ambari.server.stack;
+
+import org.apache.ambari.server.AmbariException;
+import org.apache.ambari.server.api.services.AmbariMetaInfo;
+import org.apache.ambari.server.state.stack.ServiceMetainfoXml;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.xml.bind.JAXBException;
+import java.io.File;
+
+/**
+ * Encapsulates IO operations on a stack definition service directory.
+ */
+public class ServiceDirectory extends StackDefinitionDirectory {
+ /**
+ * metrics file
+ */
+ private File metricsFile;
+
+ /**
+ * alerts file
+ */
+ private File alertsFile;
+
+ /**
+ * package directory path
+ */
+ private String packageDir;
+
+ /**
+ * service metainfo file object representation
+ */
+ private ServiceMetainfoXml metaInfoXml;
+
+ /**
+ * services root directory name
+ */
+ public static final String SERVICES_FOLDER_NAME = "services";
+
+ /**
+ * package directory name
+ */
+ private static final String PACKAGE_FOLDER_NAME = "package";
+
+ /**
+ * service metainfo file name
+ */
+ private static final String SERVICE_METAINFO_FILE_NAME = "metainfo.xml";
+
+ /**
+ * stack definition file unmarshaller
+ */
+ ModuleFileUnmarshaller unmarshaller = new ModuleFileUnmarshaller();
+
+ /**
+ * logger instance
+ */
+ private final static Logger LOG = LoggerFactory.getLogger(ServiceDirectory.class);
+
+
+ /**
+ * Constructor.
+ *
+ * @param servicePath path of the service directory
+ * @throws AmbariException if unable to parse the service directory
+ */
+ public ServiceDirectory(String servicePath) throws AmbariException {
+ super(servicePath);
+ parsePath();
+
+ File mf = new File(directory.getAbsolutePath()
+ + File.separator + AmbariMetaInfo.SERVICE_METRIC_FILE_NAME);
+ metricsFile = mf.exists() ? mf : null;
+
+ File af = new File(directory.getAbsolutePath()
+ + File.separator + AmbariMetaInfo.SERVICE_ALERT_FILE_NAME);
+ alertsFile = af.exists() ? af : null;
+ }
+
+ /**
+ * Obtain the package directory path.
+ *
+ * @return package directory path
+ */
+ public String getPackageDir() {
+ return packageDir;
+ }
+
+ /**
+ * Obtain the metrics file.
+ *
+ * @return metrics file
+ */
+ public File getMetricsFile() {
+ return metricsFile;
+ }
+
+ /**
+ * Obtain the alerts file.
+ *
+ * @return alerts file
+ */
+ public File getAlertsFile() {
+ return alertsFile;
+ }
+
+ /**
+ * Obtain the service metainfo file object representation.
+ *
+ * @return
+ * Obtain the service metainfo file object representation
+ */
+ public ServiceMetainfoXml getMetaInfoFile() {
+ return metaInfoXml;
+ }
+
+ /**
+ * Parse the service directory.
+ *
+ * @throws AmbariException if unable to parse the service directory
+ */
+ private void parsePath() throws AmbariException {
+
+ File serviceDir = new File(getAbsolutePath());
+ File stackVersionDir = serviceDir.getParentFile().getParentFile();
+ File stackDir = stackVersionDir.getParentFile();
+
+ String stackId = String.format("%s-%s", stackDir.getName(), stackVersionDir.getName());
+
+ File absPackageDir = new File(getAbsolutePath() + File.separator + PACKAGE_FOLDER_NAME);
+ if (absPackageDir.isDirectory()) {
+ packageDir = absPackageDir.getPath().substring(stackDir.getParentFile().getPath().length() + 1);
+ LOG.debug(String.format("Service package folder for service %s for stack %s has been resolved to %s",
+ serviceDir.getName(), stackId, packageDir));
+ } else {
+ //todo: this seems like it should be an error case
+ LOG.debug(String.format("Service package folder %s for service %s for stack %s does not exist.",
+ absPackageDir, serviceDir.getName(), stackId));
+ }
+ parseMetaInfoFile();
+ }
+
+ /**
+ * Unmarshal the metainfo file into its object representation.
+ *
+ * @throws AmbariException if the metainfo file doesn't exist or
+ * unable to unmarshal the metainfo file
+ */
+ private void parseMetaInfoFile() throws AmbariException {
+ File f = new File(getAbsolutePath() + File.separator + SERVICE_METAINFO_FILE_NAME);
+ if (! f.exists()) {
+ throw new AmbariException(String.format("Stack Definition Service at '%s' doesn't contain a metainfo.xml file",
+ f.getAbsolutePath()));
+ }
+
+ try {
+ metaInfoXml = unmarshaller.unmarshal(ServiceMetainfoXml.class, f);
+ } catch (JAXBException e) {
+ throw new AmbariException(String.format("Unable to parse service metainfo.xml file '%s' ", f.getAbsolutePath()), e);
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/2fc7adec/ambari-server/src/main/java/org/apache/ambari/server/stack/ServiceModule.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/stack/ServiceModule.java b/ambari-server/src/main/java/org/apache/ambari/server/stack/ServiceModule.java
new file mode 100644
index 0000000..279361b
--- /dev/null
+++ b/ambari-server/src/main/java/org/apache/ambari/server/stack/ServiceModule.java
@@ -0,0 +1,289 @@
+/**
+ * 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.ambari.server.stack;
+
+import org.apache.ambari.server.AmbariException;
+import org.apache.ambari.server.api.services.AmbariMetaInfo;
+import org.apache.ambari.server.state.ComponentInfo;
+import org.apache.ambari.server.state.CustomCommandDefinition;
+import org.apache.ambari.server.state.PropertyInfo;
+import org.apache.ambari.server.state.ServiceInfo;
+
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Service module which provides all functionality related to parsing and fully
+ * resolving services from the stack definition.
+ */
+public class ServiceModule extends BaseModule<ServiceModule, ServiceInfo> {
+ /**
+ * Corresponding service info
+ */
+ private ServiceInfo serviceInfo;
+
+ /**
+ * Context which provides modules access to external functionality
+ */
+ private StackContext stackContext;
+
+ /**
+ * Map of child configuration modules keyed by configuration type
+ */
+ private Map<String, ConfigurationModule> configurationModules =
+ new HashMap<String, ConfigurationModule>();
+
+ /**
+ * Map of child component modules keyed by component name
+ */
+ private Map<String, ComponentModule> componentModules =
+ new HashMap<String, ComponentModule>();
+
+ /**
+ * Encapsulates IO operations on service directory
+ */
+ private ServiceDirectory serviceDirectory;
+
+
+ /**
+ * Constructor.
+ *
+ * @param stackContext stack context which provides module access to external functionality
+ * @param serviceInfo associated service info
+ * @param serviceDirectory used for all IO interaction with service directory in stack definition
+ */
+ public ServiceModule(StackContext stackContext, ServiceInfo serviceInfo, ServiceDirectory serviceDirectory) {
+ this.serviceInfo = serviceInfo;
+ this.stackContext = stackContext;
+ this.serviceDirectory = serviceDirectory;
+
+ serviceInfo.setMetricsFile(serviceDirectory.getMetricsFile());
+ serviceInfo.setAlertsFile(serviceDirectory.getAlertsFile());
+ serviceInfo.setSchemaVersion(AmbariMetaInfo.SCHEMA_VERSION_2);
+ serviceInfo.setServicePackageFolder(serviceDirectory.getPackageDir());
+
+ populateComponentModules();
+ populateConfigurationModules();
+ }
+
+ @Override
+ public ServiceInfo getModuleInfo() {
+ return serviceInfo;
+ }
+
+ @Override
+ public void resolve(ServiceModule parentModule, Map<String, StackModule> allStacks) throws AmbariException {
+ ServiceInfo parent = parentModule.getModuleInfo();
+
+ if (serviceInfo.getComment() == null) {
+ serviceInfo.setComment(parent.getComment());
+ }
+ if (serviceInfo.getDisplayName() == null) {
+ serviceInfo.setDisplayName(parent.getDisplayName());
+ }
+
+ if (serviceInfo.getRequiredServices() == null) {
+ serviceInfo.setRequiredServices(parent.getRequiredServices() != null ?
+ parent.getRequiredServices() :
+ Collections.<String>emptyList());
+ }
+
+ if (serviceInfo.isRestartRequiredAfterChange() == null) {
+ serviceInfo.setRestartRequiredAfterChange(parent.isRestartRequiredAfterChange());
+ }
+ if (serviceInfo.isMonitoringService() == null) {
+ serviceInfo.setMonitoringService(parent.isMonitoringService());
+ }
+ if (serviceInfo.getOsSpecifics().isEmpty() ) {
+ serviceInfo.setOsSpecifics(parent.getOsSpecifics());
+ }
+ if (serviceInfo.getCommandScript() == null) {
+ serviceInfo.setCommandScript(parent.getCommandScript());
+ }
+ if (serviceInfo.getServicePackageFolder() == null) {
+ serviceInfo.setServicePackageFolder(parent.getServicePackageFolder());
+ }
+ if (serviceInfo.getMetricsFile() == null) {
+ serviceInfo.setMetricsFile(parent.getMetricsFile());
+ }
+ if (serviceInfo.getAlertsFile() == null) {
+ serviceInfo.setAlertsFile(parent.getAlertsFile());
+ }
+
+ mergeCustomCommands(parent.getCustomCommands(), serviceInfo.getCustomCommands());
+ mergeConfigDependencies(parent);
+ mergeComponents(parentModule, allStacks);
+ mergeConfigurations(parentModule, allStacks);
+ }
+
+ @Override
+ public boolean isDeleted() {
+ return serviceInfo.isDeleted();
+ }
+
+ @Override
+ public String getId() {
+ return serviceInfo.getName();
+ }
+
+ @Override
+ public void finalizeModule() {
+ finalizeChildModules(configurationModules.values());
+ finalizeChildModules(componentModules.values());
+ finalizeConfiguration();
+ if(serviceInfo.getCommandScript() != null && ! isDeleted()) {
+ stackContext.registerServiceCheck(getId());
+ }
+ }
+
+ /**
+ * Parse and populate child component modules.
+ */
+ private void populateComponentModules() {
+ for (ComponentInfo component : serviceInfo.getComponents()) {
+ componentModules.put(component.getName(), new ComponentModule(component));
+ }
+ }
+
+ /**
+ * Parse and populate child configuration modules.
+ */
+ private void populateConfigurationModules() {
+ ConfigurationDirectory configDirectory = serviceDirectory.getConfigurationDirectory(
+ serviceInfo.getConfigDir());
+
+ if (configDirectory != null) {
+ for (ConfigurationModule config : configDirectory.getConfigurationModules()) {
+ if (! serviceInfo.getExcludedConfigTypes().contains(config.getConfigType())) {
+ ConfigurationInfo info = config.getModuleInfo();
+ serviceInfo.getProperties().addAll(info.getProperties());
+ serviceInfo.setTypeAttributes(config.getConfigType(), info.getAttributes());
+ configurationModules.put(config.getConfigType(), config);
+ }
+ }
+
+ for (String excludedType : serviceInfo.getExcludedConfigTypes()) {
+ if (! configurationModules.containsKey(excludedType)) {
+ ConfigurationInfo configInfo = new ConfigurationInfo(
+ Collections.<PropertyInfo>emptyList(), Collections.<String, String>emptyMap());
+ ConfigurationModule config = new ConfigurationModule(excludedType, configInfo);
+
+ config.setDeleted(true);
+ configurationModules.put(excludedType, config);
+ }
+ }
+ }
+ }
+
+ /**
+ * Merge configuration dependencies with parent. Child values override parent values.
+ *
+ * @param parent parent service module
+ */
+ private void mergeConfigDependencies(ServiceInfo parent) {
+ //currently there is no way to remove an inherited config dependency
+ List<String> configDependencies = serviceInfo.getConfigDependencies();
+ List<String> parentConfigDependencies = parent.getConfigDependencies() != null ?
+ parent.getConfigDependencies() : Collections.<String>emptyList();
+
+ if (configDependencies == null) {
+ serviceInfo.setConfigDependencies(parentConfigDependencies);
+ } else {
+ for (String parentDependency : parentConfigDependencies) {
+ if (! configDependencies.contains(parentDependency)) {
+ configDependencies.add(parentDependency);
+ }
+ }
+ }
+ }
+
+ /**
+ * Merge configurations with the parent configurations.
+ * This will update the child configuration module set as well as the underlying info instances.
+ *
+ * @param parent parent service module
+ * @param stacks all stack modules
+ */
+ private void mergeConfigurations(ServiceModule parent, Map<String, StackModule> stacks) throws AmbariException {
+ serviceInfo.getProperties().clear();
+ serviceInfo.setAllConfigAttributes(new HashMap<String, Map<String, Map<String, String>>>());
+
+ Collection<ConfigurationModule> mergedModules = mergeChildModules(
+ stacks, configurationModules, parent.configurationModules);
+
+ for (ConfigurationModule module : mergedModules) {
+ configurationModules.put(module.getId(), module);
+ serviceInfo.getProperties().addAll(module.getModuleInfo().getProperties());
+ serviceInfo.setTypeAttributes(module.getConfigType(), module.getModuleInfo().getAttributes());
+ }
+ }
+
+ /**
+ * Merge components with the parent configurations.
+ * This will update the child component module set as well as the underlying info instances.
+ */
+ private void mergeComponents(ServiceModule parent, Map<String, StackModule> stacks) throws AmbariException {
+ serviceInfo.getComponents().clear();
+ Collection<ComponentModule> mergedModules = mergeChildModules(
+ stacks, componentModules, parent.componentModules);
+
+ for (ComponentModule module : mergedModules) {
+ componentModules.put(module.getId(), module);
+ serviceInfo.getComponents().add(module.getModuleInfo());
+ }
+ }
+
+ /**
+ * Merge custom commands with the parent custom commands.
+ *
+ * @param parentCmds parent custom command collection
+ * @param childCmds child custom command collection
+ */
+ //todo: duplicated in Component Module. Can we use mergeChildModules?
+ private void mergeCustomCommands(Collection<CustomCommandDefinition> parentCmds,
+ Collection<CustomCommandDefinition> childCmds) {
+
+ Collection<String> existingNames = new HashSet<String>();
+
+ for (CustomCommandDefinition childCmd : childCmds) {
+ existingNames.add(childCmd.getName());
+ }
+ for (CustomCommandDefinition parentCmd : parentCmds) {
+ if (! existingNames.contains(parentCmd.getName())) {
+ childCmds.add(parentCmd);
+ }
+ }
+ }
+
+ /**
+ * Finalize service configurations.
+ * Ensure that all default type attributes are set.
+ */
+ private void finalizeConfiguration() {
+ for (ConfigurationModule config : configurationModules.values()) {
+ ConfigurationInfo configInfo = config.getModuleInfo();
+ configInfo.ensureDefaultAttributes();
+ serviceInfo.setTypeAttributes(config.getConfigType(), configInfo.getAttributes());
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/2fc7adec/ambari-server/src/main/java/org/apache/ambari/server/stack/StackContext.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/stack/StackContext.java b/ambari-server/src/main/java/org/apache/ambari/server/stack/StackContext.java
new file mode 100644
index 0000000..5d1d098
--- /dev/null
+++ b/ambari-server/src/main/java/org/apache/ambari/server/stack/StackContext.java
@@ -0,0 +1,196 @@
+/**
+ * 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.ambari.server.stack;
+
+import org.apache.ambari.server.metadata.ActionMetadata;
+import org.apache.ambari.server.orm.dao.MetainfoDAO;
+import org.apache.ambari.server.orm.entities.MetainfoEntity;
+import org.apache.ambari.server.state.stack.LatestRepoCallable;
+import org.apache.ambari.server.state.stack.OsFamily;
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.ThreadFactory;
+
+/**
+ * Provides external functionality to the Stack framework.
+ */
+public class StackContext {
+ /**
+ * Metainfo data access object
+ */
+ private MetainfoDAO metaInfoDAO;
+
+ /**
+ * Action meta data functionality
+ */
+ private ActionMetadata actionMetaData;
+
+ /**
+ * Operating System families
+ */
+ private OsFamily osFamily;
+
+ /**
+ * Executor used to get latest repo url's
+ */
+ private LatestRepoQueryExecutor repoUpdateExecutor = new LatestRepoQueryExecutor();
+
+ /**
+ * Repository XML base url property name
+ */
+ private static final String REPOSITORY_XML_PROPERTY_BASEURL = "baseurl";
+
+
+ /**
+ * Constructor.
+ *
+ * @param metaInfoDAO metainfo data access object
+ * @param actionMetaData action meta data
+ * @param osFamily OS family information
+ */
+ public StackContext(MetainfoDAO metaInfoDAO, ActionMetadata actionMetaData, OsFamily osFamily) {
+ this.metaInfoDAO = metaInfoDAO;
+ this.actionMetaData = actionMetaData;
+ this.osFamily = osFamily;
+ }
+
+ /**
+ * Register a service check.
+ *
+ * @param serviceName name of the service
+ */
+ public void registerServiceCheck(String serviceName) {
+ actionMetaData.addServiceCheckAction(serviceName);
+ }
+
+ /**
+ * Obtain an updated url for the repo.
+ * This will check the database for a user update of the repo url.
+ *
+ * @param repoName repository name
+ * @param stackVersion stack version
+ * @param osType OS type
+ * @param repoId repo id
+ *
+ * @return an update url or null if the url has not been updated
+ */
+ public String getUpdatedRepoUrl(String repoName, String stackVersion, String osType, String repoId) {
+ StringBuilder sb = new StringBuilder("repo:/");
+ sb.append(repoName).append('/');
+ sb.append(stackVersion).append('/');
+ sb.append(osType).append('/');
+ sb.append(repoId);
+ sb.append(':').append(REPOSITORY_XML_PROPERTY_BASEURL);
+
+ MetainfoEntity entity = metaInfoDAO.findByKey(sb.toString());
+ return entity != null ? entity.getMetainfoValue() : null;
+ }
+
+ /**
+ * Register a task to obtain the latest repo url from an external location.
+ *
+ * @param url external repo information URL
+ * @param stack stack module
+ */
+ public void registerRepoUpdateTask(String url, StackModule stack) {
+ repoUpdateExecutor.addTask(new LatestRepoCallable(url,
+ new File(stack.getStackDirectory().getRepoDir()), stack.getModuleInfo(), osFamily));
+ }
+
+ /**
+ * Execute the registered repo update tasks.
+ */
+ public void executeRepoTasks() {
+ repoUpdateExecutor.execute();
+ }
+
+ /**
+ * Determine if all registered repo update tasks have completed.
+ *
+ * @return true if all tasks have completed; false otherwise
+ */
+ public boolean haveAllRepoTasksCompleted() {
+ return repoUpdateExecutor.hasCompleted();
+ }
+
+
+ /**
+ * Executor used to execute repository update tasks.
+ * Tasks will be executed in a single executor thread.
+ */
+ public static class LatestRepoQueryExecutor {
+ /**
+ * Registered tasks
+ */
+ private Collection<LatestRepoCallable> tasks = new ArrayList<LatestRepoCallable>();
+
+ /**
+ * Task futures
+ */
+ Collection<Future<Void>> futures = new ArrayList<Future<Void>>();
+ /**
+ * Underlying executor
+ */
+ private ExecutorService executor = Executors.newSingleThreadExecutor(new ThreadFactory() {
+ @Override
+ public Thread newThread(Runnable r) {
+ return new Thread(r, "Stack Version Loading Thread");
+ }
+ });
+
+
+ /**
+ * Add a task.
+ *
+ * @param task task to be added
+ */
+ public void addTask(LatestRepoCallable task) {
+ tasks.add(task);
+ }
+
+ /**
+ * Execute all tasks.
+ */
+ public void execute() {
+ for (LatestRepoCallable task : tasks) {
+ futures.add(executor.submit(task));
+ }
+ executor.shutdown();
+ }
+
+ /**
+ * Determine whether all tasks have completed.
+ *
+ * @return true if all tasks have completed; false otherwise
+ */
+ public boolean hasCompleted() {
+ for (Future<Void> f : futures) {
+ if (! f.isDone()) {
+ return false;
+ }
+ }
+ return true;
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/2fc7adec/ambari-server/src/main/java/org/apache/ambari/server/stack/StackDefinitionDirectory.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/stack/StackDefinitionDirectory.java b/ambari-server/src/main/java/org/apache/ambari/server/stack/StackDefinitionDirectory.java
new file mode 100644
index 0000000..8f81b5a
--- /dev/null
+++ b/ambari-server/src/main/java/org/apache/ambari/server/stack/StackDefinitionDirectory.java
@@ -0,0 +1,106 @@
+/**
+ * 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.ambari.server.stack;
+
+
+import java.io.File;
+import java.io.FilenameFilter;
+
+/**
+ * Base stack definition directory.
+ * Contains functionality common across directory types.
+ */
+public abstract class StackDefinitionDirectory {
+ /**
+ * xml filename filter
+ */
+ protected static final FilenameFilter XML_FILENAME_FILTER = new FilenameFilter() {
+ @Override
+ public boolean accept(File folder, String fileName) {
+ return fileName.toLowerCase().endsWith(".xml");
+ }
+ };
+
+ /**
+ * underlying directory
+ */
+ protected File directory;
+
+
+ /**
+ * Constructor.
+ *
+ * @param directory underlying directory
+ */
+ public StackDefinitionDirectory(String directory) {
+ //todo: handle non-existent dir
+ this.directory = new File(directory);
+ }
+
+ /**
+ * Obtain the configuration sub-directory instance for the specified path.
+ *
+ * @param directoryName name of the configuration directory
+ * @return ConfigurationDirectory instance for the specified configuration directory name
+ */
+ public ConfigurationDirectory getConfigurationDirectory(String directoryName) {
+ ConfigurationDirectory configDirectory = null;
+ File configDirFile = new File(directory.getAbsolutePath() + File.separator + directoryName);
+ if (configDirFile.exists() && configDirFile.isDirectory()) {
+ configDirectory = new ConfigurationDirectory(configDirFile.getAbsolutePath());
+ }
+ return configDirectory;
+ }
+
+ /**
+ * Obtain the path for this directory instance.
+ *
+ * @return the path represented by this directory
+ */
+ public String getPath() {
+ return directory.getPath();
+ }
+
+ /**
+ * Obtain the absolute path for this directory instance.
+ *
+ * @return the absolute path represented by this directory
+ */
+ public String getAbsolutePath() {
+ return directory.getAbsolutePath();
+ }
+
+ /**
+ * Obtain the name of the directory.
+ *
+ * @return name of the directory
+ */
+ public String getName() {
+ return directory.getName();
+ }
+
+ /**
+ * Obtain the underlying directory.
+ *
+ * @return the underlying directory file
+ */
+ protected File getDirectory() {
+ return directory;
+ }
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/2fc7adec/ambari-server/src/main/java/org/apache/ambari/server/stack/StackDefinitionModule.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/stack/StackDefinitionModule.java b/ambari-server/src/main/java/org/apache/ambari/server/stack/StackDefinitionModule.java
new file mode 100644
index 0000000..cc088e3
--- /dev/null
+++ b/ambari-server/src/main/java/org/apache/ambari/server/stack/StackDefinitionModule.java
@@ -0,0 +1,69 @@
+/**
+ * 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.ambari.server.stack;
+
+
+import org.apache.ambari.server.AmbariException;
+
+import java.util.Map;
+
+/**
+ * Stack Definition Module.
+ * Represents a module within a stack definition tree. For each stack version specified in
+ * a stack definition a tree will exist with a stack module being the root node. Each module
+ * may have a parent as well as child modules. Each module has an associated "info" object
+ * which contains the underlying state that is being wrapped by the module.
+ */
+public interface StackDefinitionModule <T, I> {
+ /**
+ * Resolve the module state with the specified parent.
+ *
+ * @param parent the parent that this module will be merged with
+ * @param allStacks collection of all stack modules in the tree
+ *
+ * @throws AmbariException if resolution fails
+ */
+ public void resolve(T parent, Map<String, StackModule> allStacks) throws AmbariException;
+
+ /**
+ * Obtain the associated module information.
+ *
+ * @return associated module information
+ */
+ public I getModuleInfo();
+
+ /**
+ * Determine whether the module has been marked for deletion.
+ *
+ * @return true if the module is marked for deletion; otherwise false
+ */
+ public boolean isDeleted();
+
+ /**
+ * Obtain the id of the module.
+ *
+ * @return module id
+ */
+ public String getId();
+
+ /**
+ * Lifecycle even which is called when the associated stack has been fully resolved.
+ */
+ public void finalizeModule();
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/2fc7adec/ambari-server/src/main/java/org/apache/ambari/server/stack/StackDirectory.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/stack/StackDirectory.java b/ambari-server/src/main/java/org/apache/ambari/server/stack/StackDirectory.java
new file mode 100644
index 0000000..2a30e40
--- /dev/null
+++ b/ambari-server/src/main/java/org/apache/ambari/server/stack/StackDirectory.java
@@ -0,0 +1,365 @@
+/**
+ * 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.ambari.server.stack;
+
+import org.apache.ambari.server.AmbariException;
+import org.apache.ambari.server.api.services.AmbariMetaInfo;
+import org.apache.ambari.server.state.stack.RepositoryXml;
+import org.apache.ambari.server.state.stack.StackMetainfoXml;
+import org.apache.ambari.server.state.stack.UpgradePack;
+import org.apache.commons.io.FilenameUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.xml.bind.JAXBException;
+import java.io.File;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+
+/**
+ * Encapsulates IO operations on a stack definition stack directory.
+ */
+//todo: Normalize all path return values.
+//todo: Currently some are relative and some are absolute.
+//todo: Current values were dictated by the StackInfo expectations.
+public class StackDirectory extends StackDefinitionDirectory {
+ /**
+ * hooks directory path
+ */
+ private String hooksDir;
+
+ /**
+ * upgrades directory path
+ */
+ private String upgradesDir;
+
+ /**
+ * rco file path
+ */
+ private String rcoFilePath;
+
+ /**
+ * repository file
+ */
+ private RepositoryXml repoFile;
+
+ /**
+ * repository directory
+ */
+ private String repoDir;
+
+ /**
+ * collection of service directories
+ */
+ private Collection<ServiceDirectory> serviceDirectories;
+
+ /**
+ * map of upgrade pack name to upgrade pack
+ */
+ //todo: should be a collection but upgrade pack doesn't have a name attribute
+ private Map<String, UpgradePack> upgradePacks;
+
+ /**
+ * metainfo file representation
+ */
+ private StackMetainfoXml metaInfoXml;
+
+ /**
+ * file unmarshaller
+ */
+ ModuleFileUnmarshaller unmarshaller = new ModuleFileUnmarshaller();
+
+ /**
+ * name of the hooks directory
+ */
+ public static final String HOOKS_FOLDER_NAME = "hooks";
+
+ /**
+ * repository directory name
+ */
+ private final static String REPOSITORY_FOLDER_NAME = "repos";
+
+ /**
+ * repository file name
+ */
+ private final static String REPOSITORY_FILE_NAME = "repoinfo.xml";
+
+ /**
+ * metainfo file name
+ */
+ private static final String STACK_METAINFO_FILE_NAME = "metainfo.xml";
+
+ /**
+ * upgrades directory name
+ */
+ private static final String UPGRADE_PACK_FOLDER_NAME = "upgrades";
+
+ /**
+ * logger instance
+ */
+ private final static Logger LOG = LoggerFactory.getLogger(StackDirectory.class);
+
+
+ /**
+ * Constructor.
+ *
+ * @param directory stack directory
+ * @throws AmbariException if unable to parse the stack directory
+ */
+ public StackDirectory(String directory) throws AmbariException {
+ super(directory);
+ parsePath();
+ }
+
+ /**
+ * Obtain the stack directory name.
+ *
+ * @return stack directory name
+ */
+ public String getStackDirName() {
+ return getDirectory().getParentFile().getName();
+ }
+
+ /**
+ * Obtain the hooks directory path.
+ *
+ * @return hooks directory path
+ */
+ public String getHooksDir() {
+ return hooksDir;
+ }
+
+ /**
+ * Obtain the upgrades directory path.
+ *
+ * @return upgrades directory path
+ */
+ public String getUpgradesDir() {
+ return upgradesDir;
+ }
+
+ /**
+ * Obtain the rco file path.
+ *
+ * @return rco file path
+ */
+ public String getRcoFilePath() {
+ return rcoFilePath;
+ }
+
+ /**
+ * Obtain the repository directory path.
+ *
+ * @return repository directory path
+ */
+ public String getRepoDir() {
+ return repoDir;
+ }
+
+ /**
+ * Obtain the repository file object representation.
+ *
+ * @return repository file object representation
+ */
+ public RepositoryXml getRepoFile() {
+ return repoFile;
+ }
+
+ /**
+ * Obtain the object representation of the stack metainfo.xml file.
+ *
+ * @return object representation of the stack metainfo.xml file
+ */
+ public StackMetainfoXml getMetaInfoFile() {
+ return metaInfoXml;
+ }
+
+ /**
+ * Obtain a collection of all service directories.
+ *
+ * @return collection of all service directories
+ */
+ public Collection<ServiceDirectory> getServiceDirectories() {
+ return serviceDirectories;
+ }
+
+ /**
+ * Obtain a map of all upgrade packs.
+ *
+ * @return map of upgrade pack name to upgrade pack or null if no packs available
+ */
+ public Map<String, UpgradePack> getUpgradePacks() {
+ return upgradePacks;
+ }
+
+ /**
+ * Parse the stack directory.
+ *
+ * @throws AmbariException if unable to parse the directory
+ */
+ private void parsePath() throws AmbariException {
+ Collection<String> subDirs = Arrays.asList(directory.list());
+ if (subDirs.contains(HOOKS_FOLDER_NAME)) {
+ // hooksDir is expected to be relative to stack root
+ hooksDir = getStackDirName() + File.separator + getName() +
+ File.separator + HOOKS_FOLDER_NAME;
+ } else {
+ LOG.debug("Hooks folder " + getAbsolutePath() + File.separator +
+ HOOKS_FOLDER_NAME + " does not exist");
+ }
+
+ if (subDirs.contains(AmbariMetaInfo.RCO_FILE_NAME)) {
+ // rcoFile is expected to be absolute
+ rcoFilePath = getAbsolutePath() + File.separator + AmbariMetaInfo.RCO_FILE_NAME;
+ }
+
+ parseUpgradePacks(subDirs);
+ parseServiceDirectories(subDirs);
+ parseRepoFile(subDirs);
+ parseMetaInfoFile();
+ }
+
+ /**
+ * Parse the repository file.
+ *
+ * @param subDirs stack directory sub directories
+ * @throws AmbariException if unable to parse the repository file
+ */
+ private void parseRepoFile(Collection<String> subDirs) throws AmbariException {
+ File repositoryFile;
+
+ if (subDirs.contains(REPOSITORY_FOLDER_NAME)) {
+ repoDir = getAbsolutePath() + File.separator + REPOSITORY_FOLDER_NAME;
+ repositoryFile = new File(getPath()+ File.separator +
+ REPOSITORY_FOLDER_NAME + File.separator + REPOSITORY_FILE_NAME);
+
+ if (repositoryFile.exists()) {
+ try {
+ repoFile = unmarshaller.unmarshal(RepositoryXml.class, repositoryFile);
+ } catch (JAXBException e) {
+ throw new AmbariException("Unable to parse repo file at location: " +
+ repositoryFile.getAbsolutePath(), e);
+ }
+ }
+ }
+
+ if (repoFile == null) {
+ LOG.warn("No repository information defined for "
+ + ", stackName=" + getStackDirName()
+ + ", stackVersion=" + getPath()
+ + ", repoFolder=" + getPath() + File.separator + REPOSITORY_FOLDER_NAME);
+ }
+ }
+
+ /**
+ * Parse the stack metainfo file.
+ *
+ * @throws AmbariException if unable to parse the stack metainfo file
+ */
+ private void parseMetaInfoFile() throws AmbariException {
+ File stackMetaInfoFile = new File(getAbsolutePath()
+ + File.separator + STACK_METAINFO_FILE_NAME);
+
+ //todo: is it ok for this file not to exist?
+ if (stackMetaInfoFile.exists()) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Reading stack version metainfo from file " + stackMetaInfoFile.getAbsolutePath());
+ }
+
+ try {
+ metaInfoXml = unmarshaller.unmarshal(StackMetainfoXml.class, stackMetaInfoFile);
+ } catch (JAXBException e) {
+ throw new AmbariException("Unable to parse stack metainfo.xml file at location: " +
+ stackMetaInfoFile.getAbsolutePath(), e);
+ }
+ }
+ }
+
+ /**
+ * Parse the stacks service directories.
+ *
+ * @param subDirs stack sub directories
+ * @throws AmbariException if unable to parse the service directories
+ */
+ private void parseServiceDirectories(Collection<String> subDirs) throws AmbariException {
+ Collection<ServiceDirectory> dirs = new HashSet<ServiceDirectory>();
+
+ if (subDirs.contains(ServiceDirectory.SERVICES_FOLDER_NAME)) {
+ String servicesDir = getAbsolutePath() + File.separator + ServiceDirectory.SERVICES_FOLDER_NAME;
+ File baseServiceDir = new File(servicesDir);
+ File[] serviceFolders = baseServiceDir.listFiles(AmbariMetaInfo.FILENAME_FILTER);
+ if (serviceFolders != null) {
+ for (File d : serviceFolders) {
+ if (d.isDirectory()) {
+ try {
+ dirs.add(new ServiceDirectory(d.getAbsolutePath()));
+ } catch (AmbariException e) {
+ //todo: this seems as though we should propagate this exception
+ //todo: eating it now to keep backwards compatibility
+ LOG.warn(String.format("Unable to parse stack definition service at '%s'. Ignoring service. : %s",
+ d.getAbsolutePath(), e.toString()));
+ }
+ }
+ }
+ }
+ }
+
+ if (dirs.isEmpty()) {
+ //todo: what does it mean for a stack to have no services?
+ LOG.info("The stack defined at '" + getAbsolutePath() + "' contains no services");
+ }
+ serviceDirectories = dirs;
+ }
+
+ /**
+ * Parse all stack upgrade files for the stack.
+ *
+ * @param subDirs stack sub directories
+ * @throws AmbariException if unable to parse stack upgrade file
+ */
+ private void parseUpgradePacks(Collection<String> subDirs) throws AmbariException {
+ Map<String, UpgradePack> upgradeMap = new HashMap<String, UpgradePack>();
+ if (subDirs.contains(UPGRADE_PACK_FOLDER_NAME)) {
+ File f = new File(getAbsolutePath() + File.separator + UPGRADE_PACK_FOLDER_NAME);
+ if (f.isDirectory()) {
+ upgradesDir = f.getAbsolutePath();
+ for (File upgradeFile : f.listFiles(XML_FILENAME_FILTER)) {
+ try {
+ upgradeMap.put(FilenameUtils.removeExtension(upgradeFile.getName()),
+ unmarshaller.unmarshal(UpgradePack.class, upgradeFile));
+ } catch (JAXBException e) {
+ throw new AmbariException("Unable to parse stack upgrade file at location: " +
+ upgradeFile.getAbsolutePath(), e);
+ }
+ }
+ }
+ }
+
+ if (upgradesDir == null) {
+ LOG.info("Stack '{}' doesn't contain an upgrade directory ", getPath());
+ }
+
+ if (! upgradeMap.isEmpty()) {
+ upgradePacks = upgradeMap;
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/2fc7adec/ambari-server/src/main/java/org/apache/ambari/server/stack/StackManager.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/stack/StackManager.java b/ambari-server/src/main/java/org/apache/ambari/server/stack/StackManager.java
new file mode 100644
index 0000000..2a14f51
--- /dev/null
+++ b/ambari-server/src/main/java/org/apache/ambari/server/stack/StackManager.java
@@ -0,0 +1,175 @@
+/**
+ * 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.ambari.server.stack;
+
+import org.apache.ambari.server.AmbariException;
+import org.apache.ambari.server.api.services.AmbariMetaInfo;
+import org.apache.ambari.server.configuration.Configuration;
+import org.apache.ambari.server.state.StackInfo;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.File;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+
+
+/**
+ * Manages all stack related behavior including parsing of stacks and providing access to
+ * stack information.
+ */
+public class StackManager {
+ /**
+ * Provides access to non-stack server functionality
+ */
+ private StackContext stackContext;
+
+ /**
+ * Logger
+ */
+ private final static Logger LOG = LoggerFactory.getLogger(StackManager.class);
+
+ /**
+ * Map of stack name to stack info
+ */
+ private Map<String, StackInfo> stackMap = new HashMap<String, StackInfo>();
+
+
+ /**
+ * Constructor.
+ *
+ * @param stackRoot stack root directory
+ * @param stackContext context which provides external functionality
+ *
+ * @throws AmbariException if an exception occurs while processing the stacks
+ */
+ public StackManager(File stackRoot, StackContext stackContext) throws AmbariException {
+ validateStackDirectory(stackRoot);
+
+ this.stackContext = stackContext;
+ Map<String, StackModule> stackModules = new HashMap<String, StackModule>();
+ File[] stackFiles = stackRoot.listFiles(AmbariMetaInfo.FILENAME_FILTER);
+ for (File stack : stackFiles) {
+ if (stack.isFile()) {
+ continue;
+ }
+ for (File stackFolder : stack.listFiles(AmbariMetaInfo.FILENAME_FILTER)) {
+ if (stackFolder.isFile()) {
+ continue;
+ }
+ String stackName = stackFolder.getParentFile().getName();
+ String stackVersion = stackFolder.getName();
+
+ StackModule stackModule = new StackModule(new StackDirectory(stackFolder.getPath()),stackContext);
+ stackModules.put(stackName + stackVersion, stackModule);
+ stackMap.put(stackName + stackVersion, stackModule.getModuleInfo());
+ }
+ }
+
+ if (stackMap.isEmpty()) {
+ throw new AmbariException("Unable to find stack definitions under " +
+ "stackRoot = " + stackRoot.getAbsolutePath());
+ }
+
+ fullyResolveStacks(stackModules);
+ }
+
+ /**
+ * Obtain the stack info specified by name and version.
+ *
+ * @param name name of the stack
+ * @param version version of the stack
+ * @return The stack corresponding to the specified name and version.
+ * If no matching stack exists, null is returned.
+ */
+ public StackInfo getStack(String name, String version) {
+ return stackMap.get(name + version);
+ }
+
+ /**
+ * Obtain all stacks for the given name.
+ *
+ * @param name stack name
+ * @return A collection of all stacks with the given name.
+ * If no stacks match the specified name, an empty collection is returned.
+ */
+ public Collection<StackInfo> getStacks(String name) {
+ Collection<StackInfo> stacks = new HashSet<StackInfo>();
+ for (StackInfo stack: stackMap.values()) {
+ if (stack.getName().equals(name)) {
+ stacks.add(stack);
+ }
+ }
+ return stacks;
+ }
+
+ /**
+ * Obtain all stacks.
+ *
+ * @return collection of all stacks
+ */
+ public Collection<StackInfo> getStacks() {
+ return stackMap.values();
+ }
+
+ /**
+ * Determine if all tasks which update stack repo urls have completed.
+ *
+ * @return true if all of the repo update tasks have completed; false otherwise
+ */
+ public boolean haveAllRepoUrlsBeenResolved() {
+ return stackContext.haveAllRepoTasksCompleted();
+ }
+
+ /**
+ * Fully resolve all stacks.
+ *
+ * @param stackModules map of stack id which contains name and version to stack module.
+ * @throws AmbariException if unable to resolve all stacks
+ */
+ private void fullyResolveStacks(Map<String, StackModule> stackModules) throws AmbariException {
+ for (StackModule stack : stackModules.values()) {
+ if (stack.getResolutionState() == StackModule.State.INIT) {
+ stack.resolve(null, stackModules);
+ }
+ }
+ // execute all of the repo tasks in a single thread executor
+ stackContext.executeRepoTasks();
+ }
+
+ /**
+ * Validate that the specified stack root is a valid directory.
+ * @param stackRoot the stack root directory to validate
+ * @throws AmbariException if the specified stack root directory is invalid
+ */
+ private void validateStackDirectory(File stackRoot) throws AmbariException {
+ String stackRootAbsPath = stackRoot.getAbsolutePath();
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Loading stack information"
+ + ", stackRoot = " + stackRootAbsPath);
+ }
+
+ if (!stackRoot.isDirectory() && !stackRoot.exists())
+ throw new AmbariException("" + Configuration.METADETA_DIR_PATH
+ + " should be a directory with stack"
+ + ", stackRoot = " + stackRootAbsPath);
+ }
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/2fc7adec/ambari-server/src/main/java/org/apache/ambari/server/stack/StackModule.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/stack/StackModule.java b/ambari-server/src/main/java/org/apache/ambari/server/stack/StackModule.java
new file mode 100644
index 0000000..20dba84
--- /dev/null
+++ b/ambari-server/src/main/java/org/apache/ambari/server/stack/StackModule.java
@@ -0,0 +1,498 @@
+/**
+ * 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.ambari.server.stack;
+
+import org.apache.ambari.server.AmbariException;
+import org.apache.ambari.server.api.services.AmbariMetaInfo;
+import org.apache.ambari.server.state.RepositoryInfo;
+import org.apache.ambari.server.state.ServiceInfo;
+import org.apache.ambari.server.state.StackInfo;
+import org.apache.ambari.server.state.stack.RepositoryXml;
+import org.apache.ambari.server.state.stack.ServiceMetainfoXml;
+import org.apache.ambari.server.state.stack.StackMetainfoXml;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Stack module which provides all functionality related to parsing and fully
+ * resolving stacks from the stack definition.
+ *
+ * <p>
+ * Each stack node is identified by name and version, contains service and configuration
+ * child nodes and may extend a single parent stack.
+ * </p>
+ *
+ * <p>
+ * Resolution of a stack is a depth first traversal up the inheritance chain where each stack node
+ * calls resolve on its parent before resolving itself. After the parent resolve call returns, all
+ * ancestors in the inheritance tree are fully resolved. The act of resolving the stack includes
+ * resolution of the configuration and services children of the stack as well as merging of other stack
+ * state with the fully resolved parent.
+ * </p>
+ *
+ * <p>
+ * Configuration child node resolution involves merging configuration types, properties and attributes
+ * with the fully resolved parent.
+ * </p>
+ *
+ * <p>
+ * Because a service may explicitly extend another service in a stack outside of the inheritance tree,
+ * service child node resolution involves a depth first resolution of the stack associated with the
+ * services explicit parent, if any. This follows the same steps defined above fore stack node
+ * resolution. After the services explicit parent is fully resolved, the services state is merged
+ * with it's parent.
+ * </p>
+ *
+ * <p>
+ * If a cycle in a stack definition is detected, an exception is thrown from the resolve call.
+ * </p>
+ *
+ */
+public class StackModule extends BaseModule<StackModule, StackInfo> {
+ /**
+ * Visitation state enum used for cycle detection
+ */
+ public enum State { INIT, VISITED, RESOLVED }
+
+ /**
+ * Visitation state of the stack
+ */
+ private State resolutionState = State.INIT;
+
+ /**
+ * Context which provides access to external functionality
+ */
+ private StackContext stackContext;
+
+ /**
+ * Map of child configuration modules keyed by configuration type
+ */
+ private Map<String, ConfigurationModule> configurationModules = new HashMap<String, ConfigurationModule>();
+
+ /**
+ * Map of child service modules keyed by service name
+ */
+ private Map<String, ServiceModule> serviceModules = new HashMap<String, ServiceModule>();
+
+ /**
+ * Corresponding StackInfo instance
+ */
+ private StackInfo stackInfo;
+
+ /**
+ * Encapsulates IO operations on stack directory
+ */
+ private StackDirectory stackDirectory;
+
+ /**
+ * Stack id which is in the form stackName:stackVersion
+ */
+ private String id;
+
+ /**
+ * Logger
+ */
+ private final static Logger LOG = LoggerFactory.getLogger(StackModule.class);
+
+ /**
+ * Constructor.
+ * @param stackDirectory represents stack directory
+ * @param stackContext general stack context
+ */
+ public StackModule(StackDirectory stackDirectory, StackContext stackContext) {
+ this.stackDirectory = stackDirectory;
+ this.stackContext = stackContext;
+ this.stackInfo = new StackInfo();
+ populateStackInfo();
+ }
+
+ /**
+ * Fully resolve the stack. See stack resolution description in the class documentation.
+ * If the stack has a parent, this stack will be merged against its fully resolved parent
+ * if one is specified.Merging applies to all stack state including child service and
+ * configuration modules. Services may extend a service in another version in the
+ * same stack hierarchy or may explicitly extend a service in a stack in a different
+ * hierarchy.
+ *
+ * @param parentModule not used. Each stack determines its own parent since stacks don't
+ * have containing modules
+ * @param allStacks all stacks modules contained in the stack definition
+ *
+ * @throws AmbariException if an exception occurs during stack resolution
+ */
+ @Override
+ public void resolve(StackModule parentModule, Map<String, StackModule> allStacks) throws AmbariException {
+ resolutionState = State.VISITED;
+ String parentVersion = stackInfo.getParentStackVersion();
+ // merge with parent version of same stack definition
+ if (parentVersion != null) {
+ mergeStackWithParent(allStacks, parentVersion);
+ }
+ mergeServicesWithExplicitParent(allStacks);
+ processRepositories();
+ resolutionState = State.RESOLVED;
+
+ finalizeModule();
+ }
+
+ @Override
+ public StackInfo getModuleInfo() {
+ return stackInfo;
+ }
+
+ @Override
+ public boolean isDeleted() {
+ return false;
+ }
+
+ @Override
+ public String getId() {
+ return id;
+ }
+
+ @Override
+ public void finalizeModule() {
+ finalizeChildModules(serviceModules.values());
+ finalizeChildModules(configurationModules.values());
+ }
+
+ /**
+ * Get the associated stack directory.
+ *
+ * @return associated stack directory
+ */
+ public StackDirectory getStackDirectory() {
+ return stackDirectory;
+ }
+
+ /**
+ * Stack resolution state.
+ * Initial state is INIT.
+ * When resolve is called state is set to VISITED.
+ * When resolve completes, state is set to RESOLVED.
+ *
+ * @return the stacks resolution state
+ */
+ public State getResolutionState() {
+ return resolutionState;
+ }
+
+ /**
+ * Merge the stack with its parent.
+ *
+ * @param allStacks all stacks in stack definition
+ * @param parentVersion version of the stacks parent
+ *
+ * @throws AmbariException if an exception occurs merging with the parent
+ */
+ private void mergeStackWithParent(Map<String, StackModule> allStacks, String parentVersion) throws AmbariException {
+ String parentStackKey = stackInfo.getName() + parentVersion;
+ StackModule parentStack = allStacks.get(parentStackKey);
+
+ if (parentStack == null) {
+ throw new AmbariException("Stack '" + stackInfo.getName() + ":" + stackInfo.getVersion() +
+ "' specifies a parent that doesn't exist");
+ }
+
+ resolveStack(parentStack, allStacks);
+ mergeConfigurations(parentStack, allStacks);
+
+ if (stackInfo.getStackHooksFolder() == null) {
+ stackInfo.setStackHooksFolder(parentStack.getModuleInfo().getStackHooksFolder());
+ }
+ mergeServicesWithParent(allStacks, parentStack);
+ }
+
+ /**
+ * Merge child services with parent stack.
+ *
+ * @param stacks all stacks in stack definition
+ * @param parentStack parent stack module
+ *
+ * @throws AmbariException if an exception occurs merging the child services with the parent stack
+ */
+ private void mergeServicesWithParent(Map<String, StackModule> stacks, StackModule parentStack) throws AmbariException {
+ stackInfo.getServices().clear();
+ Collection<ServiceModule> mergedModules = mergeChildModules(stacks, serviceModules, parentStack.serviceModules);
+ for (ServiceModule module : mergedModules) {
+ serviceModules.put(module.getId(), module);
+ stackInfo.getServices().add(module.getModuleInfo());
+ }
+ }
+
+ /**
+ * Merge services with their explicitly specified parent if one has been specified.
+ *
+ * @param stacks all stacks specified in the stack definition
+ *
+ * @throws AmbariException if an exception occurs while merging child services with their explicit parents
+ */
+ private void mergeServicesWithExplicitParent(Map<String, StackModule> stacks) throws AmbariException {
+ for (ServiceModule service : serviceModules.values()) {
+ ServiceInfo serviceInfo = service.getModuleInfo();
+ String parent = serviceInfo.getParent();
+ if (parent != null) {
+ mergeServiceWithExplicitParent(stacks, service, parent);
+ }
+ }
+ }
+
+ /**
+ * Merge a service with its explicitly specified parent.
+ * @param stacks all stacks specified in the stack definition
+ * @param service the service to merge
+ * @param parent the explicitly specified parent service
+ *
+ * @throws AmbariException if an exception occurs merging a service with its explicit parent
+ */
+ private void mergeServiceWithExplicitParent(Map<String, StackModule> stacks, ServiceModule service, String parent)
+ throws AmbariException {
+
+ ServiceInfo serviceInfo = service.getModuleInfo();
+ String[] parentToks = parent.split("/");
+ String baseStackKey = parentToks[0] + parentToks[1];
+ StackModule baseStack = stacks.get(baseStackKey);
+ if (baseStack == null) {
+ throw new AmbariException("The service '" + serviceInfo.getName() + "' in stack '" + stackInfo.getName() + ":"
+ + stackInfo.getVersion() + "' extends a service in a non-existent stack: '" + baseStackKey + "'");
+ }
+
+ resolveStack(baseStack, stacks);
+
+ ServiceModule baseService = baseStack.serviceModules.get(parentToks[2]);
+ if (baseService == null) {
+ throw new AmbariException("The service '" + serviceInfo.getName() + "' in stack '" + stackInfo.getName() + ":"
+ + stackInfo.getVersion() + "' extends a non-existent service: '" + parent + "'");
+ }
+ service.resolve(baseService, stacks);
+ }
+
+
+ /**
+ * Populate the stack module and info from the stack definition.
+ */
+ private void populateStackInfo() {
+ stackInfo.setName(stackDirectory.getStackDirName());
+ stackInfo.setVersion(stackDirectory.getName());
+
+ id = String.format("%s:%s", stackInfo.getName(), stackInfo.getVersion());
+
+ LOG.debug("Adding new stack to known stacks"
+ + ", stackName = " + stackInfo.getName()
+ + ", stackVersion = " + stackInfo.getVersion());
+
+
+ //odo: give additional thought on handling missing metainfo.xml
+ StackMetainfoXml smx = stackDirectory.getMetaInfoFile();
+ if (smx != null) {
+ stackInfo.setMinUpgradeVersion(smx.getVersion().getUpgrade());
+ stackInfo.setActive(smx.getVersion().isActive());
+ stackInfo.setParentStackVersion(smx.getExtends());
+ stackInfo.setStackHooksFolder(stackDirectory.getHooksDir());
+ stackInfo.setRcoFileLocation(stackDirectory.getRcoFilePath());
+ stackInfo.setUpgradesFolder(stackDirectory.getUpgradesDir());
+ stackInfo.setUpgradePacks(stackDirectory.getUpgradePacks());
+ populateConfigurationModules();
+ }
+
+ try {
+ // Read the service and available configs for this stack
+ populateServices();
+ //todo: shouldn't blindly catch Exception, re-evaluate this.
+ } catch (Exception e) {
+ LOG.error("Exception caught while populating services for stack: " +
+ stackInfo.getName() + "-" + stackInfo.getVersion());
+ e.printStackTrace();
+ }
+ }
+
+ /**
+ * Populate the child services.
+ */
+ private void populateServices()throws AmbariException {
+ for (ServiceDirectory serviceDir : stackDirectory.getServiceDirectories()) {
+ populateService(serviceDir);
+ }
+ }
+
+ /**
+ * Populate a child service.
+ *
+ * @param serviceDirectory the child service directory
+ */
+ private void populateService(ServiceDirectory serviceDirectory) {
+ Collection<ServiceModule> serviceModules = new ArrayList<ServiceModule>();
+ // unfortunately, we allow multiple services to be specified in the same metainfo.xml,
+ // so we can't move the unmarshal logic into ServiceModule
+ ServiceMetainfoXml metaInfoXml = serviceDirectory.getMetaInfoFile();
+ List<ServiceInfo> serviceInfos = metaInfoXml.getServices();
+
+ for (ServiceInfo serviceInfo : serviceInfos) {
+ serviceModules.add(new ServiceModule(stackContext, serviceInfo, serviceDirectory));
+ }
+ addServices(serviceModules);
+ }
+
+ /**
+ * Populate the child configurations.
+ */
+ private void populateConfigurationModules() {
+ //todo: can't exclude types in stack config
+ ConfigurationDirectory configDirectory = stackDirectory.getConfigurationDirectory(
+ AmbariMetaInfo.SERVICE_CONFIG_FOLDER_NAME);
+
+ if (configDirectory != null) {
+ for (ConfigurationModule config : configDirectory.getConfigurationModules()) {
+ stackInfo.getProperties().addAll(config.getModuleInfo().getProperties());
+ stackInfo.setConfigTypeAttributes(config.getConfigType(), config.getModuleInfo().getAttributes());
+ configurationModules.put(config.getConfigType(), config);
+ }
+ }
+ }
+
+ /**
+ * Merge configurations with the parent configurations.
+ *
+ * @param parent parent stack module
+ * @param stacks all stack modules
+ */
+ private void mergeConfigurations(StackModule parent, Map<String, StackModule> stacks) throws AmbariException {
+ stackInfo.getProperties().clear();
+ stackInfo.setAllConfigAttributes(new HashMap<String, Map<String, Map<String, String>>>());
+
+ Collection<ConfigurationModule> mergedModules = mergeChildModules(
+ stacks, configurationModules, parent.configurationModules);
+ for (ConfigurationModule module : mergedModules) {
+ configurationModules.put(module.getId(), module);
+ stackInfo.getProperties().addAll(module.getModuleInfo().getProperties());
+ stackInfo.setConfigTypeAttributes(module.getConfigType(), module.getModuleInfo().getAttributes());
+ }
+ }
+
+ /**
+ * Resolve another stack module.
+ *
+ * @param stackToBeResolved stack module to be resolved
+ * @param stacks all stack modules in stack definition
+ * @throws AmbariException if unable to resolve the stack
+ */
+ private void resolveStack(StackModule stackToBeResolved, Map<String, StackModule> stacks) throws AmbariException {
+ if (stackToBeResolved.getResolutionState() == State.INIT) {
+ stackToBeResolved.resolve(null, stacks);
+ } else if (stackToBeResolved.getResolutionState() == State.VISITED) {
+ //todo: provide more information to user about cycle
+ throw new AmbariException("Cycle detected while parsing stack definition");
+ }
+ }
+
+ /**
+ * Add a child service module to the stack.
+ *
+ * @param service service module to add
+ */
+ private void addService(ServiceModule service) {
+ ServiceInfo serviceInfo = service.getModuleInfo();
+ Object previousValue = serviceModules.put(service.getId(), service);
+ if (previousValue == null) {
+ stackInfo.getServices().add(serviceInfo);
+ }
+ }
+
+ /**
+ * Add child service modules to the stack.
+ *
+ * @param services collection of service modules to add
+ */
+ private void addServices(Collection<ServiceModule> services) {
+ for (ServiceModule service : services) {
+ addService(service);
+ }
+ }
+
+ /**
+ * Process repositories associated with the stack.
+ * @throws AmbariException if unable to fully process the stack repositories
+ */
+ private void processRepositories() throws AmbariException {
+ RepositoryXml rxml = stackDirectory.getRepoFile();
+ if (rxml == null) {
+ return;
+ }
+
+ LOG.debug("Adding repositories to stack" +
+ ", stackName=" + stackInfo.getName() +
+ ", stackVersion=" + stackInfo.getVersion() +
+ ", repoFolder=" + stackDirectory.getRepoDir());
+
+ List<RepositoryInfo> repos = new ArrayList<RepositoryInfo>();
+
+ for (RepositoryXml.Os o : rxml.getOses()) {
+ String osFamily = o.getFamily();
+ for (String os : osFamily.split(",")) {
+ for (RepositoryXml.Repo r : o.getRepos()) {
+ repos.add(processRepository(osFamily, os, r));
+ }
+ }
+ }
+
+ stackInfo.getRepositories().addAll(repos);
+
+ if (null != rxml.getLatestURI() && repos.size() > 0) {
+ stackContext.registerRepoUpdateTask(rxml.getLatestURI(), this);
+ }
+ }
+
+ /**
+ * Process a repository associated with the stack.
+ *
+ * @param osFamily OS family
+ * @param osType OS type
+ * @param r repo
+ */
+ private RepositoryInfo processRepository(String osFamily, String osType, RepositoryXml.Repo r) {
+ RepositoryInfo ri = new RepositoryInfo();
+ ri.setBaseUrl(r.getBaseUrl());
+ ri.setDefaultBaseUrl(r.getBaseUrl());
+ ri.setMirrorsList(r.getMirrorsList());
+ ri.setOsType(osType.trim());
+ ri.setRepoId(r.getRepoId());
+ ri.setRepoName(r.getRepoName());
+ ri.setLatestBaseUrl(r.getBaseUrl());
+
+ LOG.debug("Checking for override for base_url");
+ String updatedUrl = stackContext.getUpdatedRepoUrl(r.getRepoName(), stackInfo.getVersion(),
+ osFamily, r.getRepoId());
+
+ if (null != updatedUrl) {
+ ri.setBaseUrl(updatedUrl);
+ }
+
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Adding repo to stack"
+ + ", repoInfo=" + ri.toString());
+ }
+ return ri;
+ }
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/2fc7adec/ambari-server/src/main/java/org/apache/ambari/server/state/AutoDeployInfo.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/state/AutoDeployInfo.java b/ambari-server/src/main/java/org/apache/ambari/server/state/AutoDeployInfo.java
index 9e97d5f..56f1dbc 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/state/AutoDeployInfo.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/state/AutoDeployInfo.java
@@ -72,4 +72,24 @@ public class AutoDeployInfo {
public String getCoLocate() {
return m_coLocate;
}
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+
+ AutoDeployInfo that = (AutoDeployInfo) o;
+
+ if (m_enabled != that.m_enabled) return false;
+ if (m_coLocate != null ? !m_coLocate.equals(that.m_coLocate) : that.m_coLocate != null) return false;
+
+ return true;
+ }
+
+ @Override
+ public int hashCode() {
+ int result = (m_enabled ? 1 : 0);
+ result = 31 * result + (m_coLocate != null ? m_coLocate.hashCode() : 0);
+ return result;
+ }
}