incubator-ambari-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From maha...@apache.org
Subject [29/30] AMBARI-3266. Contribute Ambari-SCOM. (Tom Beerbower via mahadev)
Date Fri, 18 Oct 2013 00:25:51 GMT
http://git-wip-us.apache.org/repos/asf/incubator-ambari/blob/873b3502/contrib/ambari-scom/ambari-scom-server/src/main/java/org/apache/ambari/msi/HostComponentProvider.java
----------------------------------------------------------------------
diff --git a/contrib/ambari-scom/ambari-scom-server/src/main/java/org/apache/ambari/msi/HostComponentProvider.java b/contrib/ambari-scom/ambari-scom-server/src/main/java/org/apache/ambari/msi/HostComponentProvider.java
new file mode 100644
index 0000000..784089e
--- /dev/null
+++ b/contrib/ambari-scom/ambari-scom-server/src/main/java/org/apache/ambari/msi/HostComponentProvider.java
@@ -0,0 +1,112 @@
+/**
+ * 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.msi;
+
+import org.apache.ambari.server.controller.internal.ResourceImpl;
+import org.apache.ambari.server.controller.spi.Predicate;
+import org.apache.ambari.server.controller.spi.Request;
+import org.apache.ambari.server.controller.spi.Resource;
+import org.apache.ambari.server.controller.utilities.PropertyHelper;
+
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * A host component resource provider for a MSI defined cluster.
+ */
+public class HostComponentProvider extends BaseResourceProvider {
+
+  // Host Components
+  protected static final String HOST_COMPONENT_CLUSTER_NAME_PROPERTY_ID   = PropertyHelper.getPropertyId("HostRoles", "cluster_name");
+  protected static final String HOST_COMPONENT_SERVICE_NAME_PROPERTY_ID   = PropertyHelper.getPropertyId("HostRoles", "service_name");
+  protected static final String HOST_COMPONENT_COMPONENT_NAME_PROPERTY_ID = PropertyHelper.getPropertyId("HostRoles", "component_name");
+  protected static final String HOST_COMPONENT_HOST_NAME_PROPERTY_ID      = PropertyHelper.getPropertyId("HostRoles", "host_name");
+  protected static final String HOST_COMPONENT_STATE_PROPERTY_ID          = PropertyHelper.getPropertyId("HostRoles", "state");
+  protected static final String HOST_COMPONENT_DESIRED_STATE_PROPERTY_ID  = PropertyHelper.getPropertyId("HostRoles", "desired_state");
+
+
+  // ----- Constructors ------------------------------------------------------
+
+  /**
+   * Construct a resource provider based on the given cluster definition.
+   *
+   * @param clusterDefinition  the cluster definition
+   */
+  public HostComponentProvider(ClusterDefinition clusterDefinition) {
+    super(Resource.Type.HostComponent, clusterDefinition);
+    initHostComponentResources();
+  }
+
+
+  // ----- AbstractResourceProvider ------------------------------------------
+
+  @Override
+  public void updateProperties(Resource resource, Request request, Predicate predicate) {
+    Set<String> propertyIds = getRequestPropertyIds(request, predicate);
+    if (contains(propertyIds, HOST_COMPONENT_STATE_PROPERTY_ID) ||
+        contains(propertyIds, HOST_COMPONENT_DESIRED_STATE_PROPERTY_ID)) {
+      String componentName = (String) resource.getPropertyValue(HOST_COMPONENT_COMPONENT_NAME_PROPERTY_ID);
+      String hostName      = (String) resource.getPropertyValue(HOST_COMPONENT_HOST_NAME_PROPERTY_ID);
+
+      String hostComponentState = getClusterDefinition().getHostComponentState(hostName, componentName);
+
+      resource.setProperty(HOST_COMPONENT_STATE_PROPERTY_ID, hostComponentState);
+      resource.setProperty(HOST_COMPONENT_DESIRED_STATE_PROPERTY_ID, hostComponentState);
+    }
+  }
+
+  @Override
+  public int updateProperties(Resource resource, Map<String, Object> properties) {
+    int requestId = -1;
+    if (properties.containsKey(HOST_COMPONENT_STATE_PROPERTY_ID)) {
+      String state         = (String) properties.get(HOST_COMPONENT_STATE_PROPERTY_ID);
+      String componentName = (String) resource.getPropertyValue(HOST_COMPONENT_COMPONENT_NAME_PROPERTY_ID);
+      String hostName      = (String) resource.getPropertyValue(HOST_COMPONENT_HOST_NAME_PROPERTY_ID);
+
+      requestId = getClusterDefinition().setHostComponentState(hostName, componentName, state);
+    }
+    return requestId;
+  }
+
+
+  // ----- helper methods ----------------------------------------------------
+
+  /**
+   * Create the resources based on the cluster definition.
+   */
+  private void initHostComponentResources() {
+    String      clusterName = getClusterDefinition().getClusterName();
+    Set<String> services    = getClusterDefinition().getServices();
+    for (String serviceName : services) {
+      Set<String> hosts = getClusterDefinition().getHosts();
+      for (String hostName : hosts) {
+        Set<String> hostComponents = getClusterDefinition().getHostComponents(serviceName, hostName);
+        for (String componentName : hostComponents) {
+          Resource hostComponent = new ResourceImpl(Resource.Type.HostComponent);
+          hostComponent.setProperty(HOST_COMPONENT_CLUSTER_NAME_PROPERTY_ID, clusterName);
+          hostComponent.setProperty(HOST_COMPONENT_SERVICE_NAME_PROPERTY_ID, serviceName);
+          hostComponent.setProperty(HOST_COMPONENT_COMPONENT_NAME_PROPERTY_ID, componentName);
+          hostComponent.setProperty(HOST_COMPONENT_HOST_NAME_PROPERTY_ID, hostName);
+
+          addResource(hostComponent);
+        }
+      }
+    }
+  }
+}

http://git-wip-us.apache.org/repos/asf/incubator-ambari/blob/873b3502/contrib/ambari-scom/ambari-scom-server/src/main/java/org/apache/ambari/msi/HostProvider.java
----------------------------------------------------------------------
diff --git a/contrib/ambari-scom/ambari-scom-server/src/main/java/org/apache/ambari/msi/HostProvider.java b/contrib/ambari-scom/ambari-scom-server/src/main/java/org/apache/ambari/msi/HostProvider.java
new file mode 100644
index 0000000..e0ddd9d
--- /dev/null
+++ b/contrib/ambari-scom/ambari-scom-server/src/main/java/org/apache/ambari/msi/HostProvider.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.ambari.msi;
+
+import org.apache.ambari.server.controller.internal.ResourceImpl;
+import org.apache.ambari.server.controller.spi.Predicate;
+import org.apache.ambari.server.controller.spi.Request;
+import org.apache.ambari.server.controller.spi.Resource;
+import org.apache.ambari.server.controller.spi.SystemException;
+import org.apache.ambari.server.controller.utilities.PropertyHelper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * A host resource provider for a MSI defined cluster.
+ */
+public class HostProvider extends BaseResourceProvider {
+
+  // Hosts
+  protected static final String HOST_CLUSTER_NAME_PROPERTY_ID =
+      PropertyHelper.getPropertyId("Hosts", "cluster_name");
+  protected static final String HOST_NAME_PROPERTY_ID =
+      PropertyHelper.getPropertyId("Hosts", "host_name");
+  protected static final String HOST_STATE_PROPERTY_ID =
+      PropertyHelper.getPropertyId("Hosts", "host_state");
+  protected static final String HOST_IP_PROPERTY_ID =
+      PropertyHelper.getPropertyId("Hosts", "ip");
+
+
+  // ----- Constants ---------------------------------------------------------
+
+  protected final static Logger LOG =
+      LoggerFactory.getLogger(HostProvider.class);
+
+
+  // ----- Constructors ------------------------------------------------------
+
+  /**
+   * Construct a resource provider based on the given cluster definition.
+   *
+   * @param clusterDefinition  the cluster definition
+   */
+  public HostProvider(ClusterDefinition clusterDefinition) {
+    super(Resource.Type.Host, clusterDefinition);
+    initHostResources();
+  }
+
+
+  // ----- AbstractResourceProvider ------------------------------------------
+
+  @Override
+  public void updateProperties(Resource resource, Request request, Predicate predicate) {
+    Set<String> propertyIds = getRequestPropertyIds(request, predicate);
+    if (contains(propertyIds, HOST_STATE_PROPERTY_ID)) {
+      String hostName = (String) resource.getPropertyValue(HOST_NAME_PROPERTY_ID);
+      resource.setProperty(HOST_STATE_PROPERTY_ID, getClusterDefinition().getHostState(hostName));
+    }
+  }
+
+  @Override
+  public int updateProperties(Resource resource, Map<String, Object> properties) {
+    // Do nothing
+    return -1;
+  }
+
+
+  // ----- helper methods ----------------------------------------------------
+
+  /**
+   * Create the resources based on the cluster definition.
+   */
+  private void initHostResources() {
+    ClusterDefinition clusterDefinition = getClusterDefinition();
+    String            clusterName       = clusterDefinition.getClusterName();
+    Set<String>       hosts             = clusterDefinition.getHosts();
+
+    for (String hostName : hosts) {
+      Resource host = new ResourceImpl(Resource.Type.Host);
+      host.setProperty(HOST_CLUSTER_NAME_PROPERTY_ID, clusterName);
+      host.setProperty(HOST_NAME_PROPERTY_ID, hostName);
+      try {
+        host.setProperty(HOST_IP_PROPERTY_ID, clusterDefinition.getHostInfoProvider().getHostAddress(hostName));
+      } catch (SystemException e) {
+        if (LOG.isErrorEnabled()) {
+          LOG.error("Can't set host ip address : caught exception", e);
+        }
+      }
+
+      addResource(host);
+    }
+  }
+}

http://git-wip-us.apache.org/repos/asf/incubator-ambari/blob/873b3502/contrib/ambari-scom/ambari-scom-server/src/main/java/org/apache/ambari/msi/NoOpProvider.java
----------------------------------------------------------------------
diff --git a/contrib/ambari-scom/ambari-scom-server/src/main/java/org/apache/ambari/msi/NoOpProvider.java b/contrib/ambari-scom/ambari-scom-server/src/main/java/org/apache/ambari/msi/NoOpProvider.java
new file mode 100644
index 0000000..c5fc58f
--- /dev/null
+++ b/contrib/ambari-scom/ambari-scom-server/src/main/java/org/apache/ambari/msi/NoOpProvider.java
@@ -0,0 +1,67 @@
+/**
+ * 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.msi;
+
+import org.apache.ambari.server.controller.spi.Predicate;
+import org.apache.ambari.server.controller.spi.Request;
+import org.apache.ambari.server.controller.spi.Resource;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * A NO-OP resource provider for a MSI defined cluster.
+ */
+public class NoOpProvider extends BaseResourceProvider {
+
+  private final Map<Resource.Type, String> keyPropertyIds = new HashMap<Resource.Type, String>();
+
+  // ----- AbstractResourceProvider ------------------------------------------
+
+  @Override
+  public void updateProperties(Resource resource, Request request, Predicate predicate) {
+    // Do nothing
+  }
+
+  @Override
+  public int updateProperties(Resource resource, Map<String, Object> properties) {
+    // Do nothing
+    return -1;
+  }
+
+
+  // ----- Constructors ------------------------------------------------------
+
+  public NoOpProvider(Resource.Type type, ClusterDefinition clusterDefinition) {
+    super(type, clusterDefinition);
+    keyPropertyIds.put(type, "id");
+  }
+
+
+  @Override
+  public Map<Resource.Type, String> getKeyPropertyIds() {
+    return keyPropertyIds;
+  }
+
+  @Override
+  public Set<String> checkPropertyIds(Set<String> propertyIds) {
+    return Collections.emptySet();
+  }
+}

http://git-wip-us.apache.org/repos/asf/incubator-ambari/blob/873b3502/contrib/ambari-scom/ambari-scom-server/src/main/java/org/apache/ambari/msi/RequestProvider.java
----------------------------------------------------------------------
diff --git a/contrib/ambari-scom/ambari-scom-server/src/main/java/org/apache/ambari/msi/RequestProvider.java b/contrib/ambari-scom/ambari-scom-server/src/main/java/org/apache/ambari/msi/RequestProvider.java
new file mode 100644
index 0000000..b38c5c0
--- /dev/null
+++ b/contrib/ambari-scom/ambari-scom-server/src/main/java/org/apache/ambari/msi/RequestProvider.java
@@ -0,0 +1,68 @@
+/**
+ * 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.msi;
+
+import org.apache.ambari.server.controller.spi.Predicate;
+import org.apache.ambari.server.controller.spi.Request;
+import org.apache.ambari.server.controller.spi.Resource;
+import org.apache.ambari.server.controller.utilities.PropertyHelper;
+
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * A request resource provider for a MSI defined cluster.
+ */
+public class RequestProvider extends AbstractResourceProvider {
+
+  // Request properties
+  protected static final String REQUEST_CLUSTER_NAME_PROPERTY_ID = PropertyHelper.getPropertyId("Requests", "cluster_name");
+  protected static final String REQUEST_ID_PROPERTY_ID           = PropertyHelper.getPropertyId("Requests", "id");
+  protected static final String REQUEST_CONTEXT_ID               = PropertyHelper.getPropertyId("Requests", "request_context");
+
+  // ----- Constructors ------------------------------------------------------
+
+  /**
+   * Construct a resource provider based on the given cluster definition.
+   *
+   * @param clusterDefinition  the cluster definition
+   */
+  public RequestProvider(ClusterDefinition clusterDefinition) {
+    super(Resource.Type.Request, clusterDefinition);
+  }
+
+
+  // ----- AbstractResourceProvider ------------------------------------------
+
+  @Override
+  protected Set<Resource> getResources() {
+    return getClusterDefinition().getRequestResources();
+  }
+
+  @Override
+  public void updateProperties(Resource resource, Request request, Predicate predicate) {
+    //Do nothing
+  }
+
+  @Override
+  public int updateProperties(Resource resource, Map<String, Object> properties) {
+    //Do nothing
+    return -1;
+  }
+}

http://git-wip-us.apache.org/repos/asf/incubator-ambari/blob/873b3502/contrib/ambari-scom/ambari-scom-server/src/main/java/org/apache/ambari/msi/ServiceProvider.java
----------------------------------------------------------------------
diff --git a/contrib/ambari-scom/ambari-scom-server/src/main/java/org/apache/ambari/msi/ServiceProvider.java b/contrib/ambari-scom/ambari-scom-server/src/main/java/org/apache/ambari/msi/ServiceProvider.java
new file mode 100644
index 0000000..023fbf0
--- /dev/null
+++ b/contrib/ambari-scom/ambari-scom-server/src/main/java/org/apache/ambari/msi/ServiceProvider.java
@@ -0,0 +1,95 @@
+/**
+ * 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.msi;
+
+import org.apache.ambari.server.controller.internal.ResourceImpl;
+import org.apache.ambari.server.controller.spi.Predicate;
+import org.apache.ambari.server.controller.spi.Request;
+import org.apache.ambari.server.controller.spi.Resource;
+import org.apache.ambari.server.controller.utilities.PropertyHelper;
+
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * A service resource provider for a MSI defined cluster.
+ */
+public class ServiceProvider extends BaseResourceProvider {
+
+  // Services
+  protected static final String SERVICE_CLUSTER_NAME_PROPERTY_ID    = PropertyHelper.getPropertyId("ServiceInfo", "cluster_name");
+  protected static final String SERVICE_SERVICE_NAME_PROPERTY_ID    = PropertyHelper.getPropertyId("ServiceInfo", "service_name");
+  protected static final String SERVICE_SERVICE_STATE_PROPERTY_ID   = PropertyHelper.getPropertyId("ServiceInfo", "state");
+
+
+  // ----- Constructors ------------------------------------------------------
+
+  /**
+   * Construct a resource provider based on the given cluster definition.
+   *
+   * @param clusterDefinition  the cluster definition
+   */
+  public ServiceProvider(ClusterDefinition clusterDefinition) {
+    super(Resource.Type.Service, clusterDefinition);
+    initServiceResources();
+  }
+
+
+  // ----- AbstractResourceProvider ------------------------------------------
+
+  @Override
+  public void updateProperties(Resource resource, Request request, Predicate predicate) {
+    Set<String> propertyIds = getRequestPropertyIds(request, predicate);
+    if (contains(propertyIds, SERVICE_SERVICE_STATE_PROPERTY_ID)) {
+      String serviceName = (String) resource.getPropertyValue(SERVICE_SERVICE_NAME_PROPERTY_ID);
+      resource.setProperty(SERVICE_SERVICE_STATE_PROPERTY_ID, getClusterDefinition().getServiceState(serviceName));
+    }
+  }
+
+  @Override
+  public int updateProperties(Resource resource, Map<String, Object> properties) {
+    int requestId = -1;
+    if (properties.containsKey(SERVICE_SERVICE_STATE_PROPERTY_ID)) {
+      String state       = (String) properties.get(SERVICE_SERVICE_STATE_PROPERTY_ID);
+      String serviceName = (String) resource.getPropertyValue(SERVICE_SERVICE_NAME_PROPERTY_ID);
+
+      requestId = getClusterDefinition().setServiceState(serviceName, state);
+    }
+    return requestId;
+  }
+
+
+  // ----- helper methods ----------------------------------------------------
+
+  /**
+   * Create the resources based on the cluster definition.
+   */
+  private void initServiceResources() {
+    String      clusterName = getClusterDefinition().getClusterName();
+    Set<String> services    = getClusterDefinition().getServices();
+
+    for (String serviceName : services) {
+      Resource service = new ResourceImpl(Resource.Type.Service);
+      service.setProperty(SERVICE_CLUSTER_NAME_PROPERTY_ID, clusterName);
+      service.setProperty(SERVICE_SERVICE_NAME_PROPERTY_ID, serviceName);
+
+      addResource(service);
+    }
+  }
+}

http://git-wip-us.apache.org/repos/asf/incubator-ambari/blob/873b3502/contrib/ambari-scom/ambari-scom-server/src/main/java/org/apache/ambari/msi/StateProvider.java
----------------------------------------------------------------------
diff --git a/contrib/ambari-scom/ambari-scom-server/src/main/java/org/apache/ambari/msi/StateProvider.java b/contrib/ambari-scom/ambari-scom-server/src/main/java/org/apache/ambari/msi/StateProvider.java
new file mode 100644
index 0000000..dc4b028
--- /dev/null
+++ b/contrib/ambari-scom/ambari-scom-server/src/main/java/org/apache/ambari/msi/StateProvider.java
@@ -0,0 +1,65 @@
+/**
+ * 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.msi;
+
+/**
+ * Interface to provide component state to the MSI resource provider.
+ */
+public interface StateProvider {
+  /**
+   * Determine whether or not the host component identified by the given host name
+   * and component name is running.
+   *
+   * @param hostName       the host name
+   * @param componentName  the component name
+   *
+   * @return true if the host component is healthy
+   */
+  public State getRunningState(String hostName, String componentName);
+
+  /**
+   * Set the running state of the given component.
+   *
+   * @param hostName       the host name
+   * @param componentName  the component name
+   * @param state          the desired state
+   */
+  public Process setRunningState(String hostName, String componentName, State state);
+
+  /**
+   * Enum of possible states.
+   */
+  public enum State {
+    Stopped,
+    Running,
+    Paused,
+    Unknown
+  }
+
+  public interface Process {
+    public boolean isRunning();
+
+    public int getExitCode();
+
+    public String getOutput();
+
+    public String getError();
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-ambari/blob/873b3502/contrib/ambari-scom/ambari-scom-server/src/main/java/org/apache/ambari/msi/TaskProvider.java
----------------------------------------------------------------------
diff --git a/contrib/ambari-scom/ambari-scom-server/src/main/java/org/apache/ambari/msi/TaskProvider.java b/contrib/ambari-scom/ambari-scom-server/src/main/java/org/apache/ambari/msi/TaskProvider.java
new file mode 100644
index 0000000..25b531d
--- /dev/null
+++ b/contrib/ambari-scom/ambari-scom-server/src/main/java/org/apache/ambari/msi/TaskProvider.java
@@ -0,0 +1,92 @@
+/**
+ * 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.msi;
+
+import org.apache.ambari.server.controller.spi.Predicate;
+import org.apache.ambari.server.controller.spi.Request;
+import org.apache.ambari.server.controller.spi.Resource;
+import org.apache.ambari.server.controller.utilities.PropertyHelper;
+
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * A task resource provider for a MSI defined cluster.
+ */
+public class TaskProvider extends AbstractResourceProvider {
+
+  // Tasks properties
+  protected static final String TASK_CLUSTER_NAME_PROPERTY_ID = PropertyHelper.getPropertyId("Tasks", "cluster_name");
+  protected static final String TASK_REQUEST_ID_PROPERTY_ID   = PropertyHelper.getPropertyId("Tasks", "request_id");
+  protected static final String TASK_ID_PROPERTY_ID           = PropertyHelper.getPropertyId("Tasks", "id");
+  protected static final String TASK_STATUS_PROPERTY_ID       = PropertyHelper.getPropertyId("Tasks", "status");
+  protected static final String TASK_EXIT_CODE_PROPERTY_ID    = PropertyHelper.getPropertyId("Tasks", "exit_code");
+  protected static final String TASK_STDERR_PROPERTY_ID       = PropertyHelper.getPropertyId("Tasks", "stderr");
+  protected static final String TASK_STOUT_PROPERTY_ID        = PropertyHelper.getPropertyId("Tasks", "stdout");
+
+
+  // ----- Constructors ------------------------------------------------------
+
+  /**
+   * Construct a resource provider based on the given cluster definition.
+   *
+   * @param clusterDefinition  the cluster definition
+   */
+  public TaskProvider(ClusterDefinition clusterDefinition) {
+    super(Resource.Type.Task, clusterDefinition);
+  }
+
+
+  // ----- AbstractResourceProvider ------------------------------------------
+
+  @Override
+  protected Set<Resource> getResources() {
+    return getClusterDefinition().getTaskResources();
+  }
+
+  @Override
+  public void updateProperties(Resource resource, Request request, Predicate predicate) {
+
+    Integer taskId = (Integer) resource.getPropertyValue(TASK_ID_PROPERTY_ID);
+
+    StateProvider.Process process = getClusterDefinition().getProcess(taskId);
+
+    if (process != null) {
+      resource.setProperty(TASK_STATUS_PROPERTY_ID, process.isRunning() ? "IN_PROGRESS" : "COMPLETED");
+
+      Set<String> propertyIds = getRequestPropertyIds(request, predicate);
+
+      if (contains(propertyIds, TASK_EXIT_CODE_PROPERTY_ID)) {
+        resource.setProperty(TASK_EXIT_CODE_PROPERTY_ID, process.getExitCode());
+      }
+      if (contains(propertyIds, TASK_STDERR_PROPERTY_ID)) {
+        resource.setProperty(TASK_STDERR_PROPERTY_ID, process.getError());
+      }
+      if (contains(propertyIds, TASK_STOUT_PROPERTY_ID)) {
+        resource.setProperty(TASK_STOUT_PROPERTY_ID, process.getOutput());
+      }
+    }
+  }
+
+  @Override
+  public int updateProperties(Resource resource, Map<String, Object> properties) {
+    //Do nothing
+    return -1;
+  }
+}

http://git-wip-us.apache.org/repos/asf/incubator-ambari/blob/873b3502/contrib/ambari-scom/ambari-scom-server/src/main/java/org/apache/ambari/scom/AmbariServer.java
----------------------------------------------------------------------
diff --git a/contrib/ambari-scom/ambari-scom-server/src/main/java/org/apache/ambari/scom/AmbariServer.java b/contrib/ambari-scom/ambari-scom-server/src/main/java/org/apache/ambari/scom/AmbariServer.java
new file mode 100644
index 0000000..9c0b420
--- /dev/null
+++ b/contrib/ambari-scom/ambari-scom-server/src/main/java/org/apache/ambari/scom/AmbariServer.java
@@ -0,0 +1,449 @@
+
+/**
+ * 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.scom;
+
+
+import com.google.gson.Gson;
+import com.google.inject.AbstractModule;
+import com.google.inject.Guice;
+import com.google.inject.Inject;
+import com.google.inject.Injector;
+import com.google.inject.Scopes;
+import com.google.inject.Singleton;
+import com.google.inject.persist.Transactional;
+import com.google.inject.persist.jpa.JpaPersistModule;
+import com.sun.jersey.spi.container.servlet.ServletContainer;
+import org.apache.ambari.server.AmbariException;
+import org.apache.ambari.server.api.AmbariPersistFilter;
+import org.apache.ambari.server.configuration.ComponentSSLConfiguration;
+import org.apache.ambari.server.configuration.Configuration;
+import org.apache.ambari.server.controller.HostsMap;
+import org.apache.ambari.server.orm.GuiceJpaInitializer;
+import org.apache.ambari.server.orm.PersistenceType;
+import org.apache.ambari.server.security.authorization.AmbariLdapAuthenticationProvider;
+import org.apache.ambari.server.security.authorization.AmbariLocalUserDetailsService;
+import org.apache.ambari.server.security.authorization.Users;
+import org.eclipse.jetty.server.Server;
+import org.eclipse.jetty.server.nio.SelectChannelConnector;
+import org.eclipse.jetty.server.ssl.SslSelectChannelConnector;
+import org.eclipse.jetty.servlet.DefaultServlet;
+import org.eclipse.jetty.servlet.FilterHolder;
+import org.eclipse.jetty.servlet.ServletContextHandler;
+import org.eclipse.jetty.servlet.ServletHolder;
+import org.eclipse.jetty.util.ssl.SslContextFactory;
+import org.eclipse.jetty.util.thread.QueuedThreadPool;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
+import org.springframework.context.support.ClassPathXmlApplicationContext;
+import org.springframework.security.crypto.password.PasswordEncoder;
+import org.springframework.security.crypto.password.StandardPasswordEncoder;
+import org.springframework.web.context.WebApplicationContext;
+import org.springframework.web.context.support.GenericWebApplicationContext;
+import org.springframework.web.filter.DelegatingFilterProxy;
+
+import javax.crypto.BadPaddingException;
+import java.io.File;
+import java.net.BindException;
+import java.util.Map;
+import java.util.Properties;
+
+/**
+ * Main Ambari server class.
+ */
+@Singleton
+public class AmbariServer {
+  /**
+   * The Jetty server.
+   */
+  private Server server = null;
+
+  /**
+   * The Ambari configuration.
+   */
+  @Inject
+  Configuration configuration;
+
+  /**
+   * The Guice injector.
+   */
+  @Inject
+  Injector injector;
+
+
+  // Set the SQLProviderModule for the API providers.
+  static {
+    System.setProperty("provider.module.class", "org.apache.ambari.scom.SQLProviderModule");
+  }
+
+  // ----- Constants ---------------------------------------------------------
+
+  private static final String CONTEXT_PATH = "/";
+
+  private static final String SPRING_CONTEXT_LOCATION =
+      "classpath:META-INF/spring-security.xml";
+
+  /**
+   * The logger.
+   */
+  private static final Logger LOG = LoggerFactory.getLogger(AmbariServer.class);
+
+
+  // ----- AmbariServer ------------------------------------------------------
+
+  public static void main(String[] args) throws Exception {
+    Injector injector = Guice.createInjector(new ControllerModule());
+    injector.getInstance(GuiceJpaInitializer.class);
+
+    AmbariServer ambariServer = null;
+    try {
+      LOG.info("Getting the controller");
+      ambariServer = injector.getInstance(AmbariServer.class);
+
+      ComponentSSLConfiguration.instance().init(ambariServer.configuration);
+      SinkConnectionFactory.instance().init(ambariServer.configuration);
+      ClusterDefinitionProvider.instance().init(ambariServer.configuration);
+
+      ambariServer.run();
+    } catch (Throwable t) {
+      LOG.error("Failed to run the Ambari Server", t);
+      if (ambariServer != null) {
+        ambariServer.stop();
+      }
+      System.exit(-1);
+    }
+  }
+
+
+  // ----- helper methods ----------------------------------------------------
+
+  // Run the server
+  private void run() throws Exception {
+    addInMemoryUsers();
+
+    server = new Server();
+
+    try {
+      ClassPathXmlApplicationContext parentSpringAppContext =
+          new ClassPathXmlApplicationContext();
+      parentSpringAppContext.refresh();
+      ConfigurableListableBeanFactory factory = parentSpringAppContext.
+          getBeanFactory();
+      factory.registerSingleton("guiceInjector",
+          injector);
+      factory.registerSingleton("passwordEncoder",
+          injector.getInstance(PasswordEncoder.class));
+      factory.registerSingleton("ambariLocalUserService",
+          injector.getInstance(AmbariLocalUserDetailsService.class));
+      factory.registerSingleton("ambariLdapAuthenticationProvider",
+          injector.getInstance(AmbariLdapAuthenticationProvider.class));
+
+      //Spring Security xml config depends on this Bean
+      String[] contextLocations = {SPRING_CONTEXT_LOCATION};
+      ClassPathXmlApplicationContext springAppContext = new
+          ClassPathXmlApplicationContext(contextLocations, parentSpringAppContext);
+
+      //setting ambari web context
+      ServletContextHandler root = new ServletContextHandler(server, CONTEXT_PATH,
+          ServletContextHandler.SECURITY | ServletContextHandler.SESSIONS);
+
+      //Changing session cookie name to avoid conflicts
+      root.getSessionHandler().getSessionManager().setSessionCookie("AMBARISESSIONID");
+
+      GenericWebApplicationContext springWebAppContext = new GenericWebApplicationContext();
+      springWebAppContext.setServletContext(root.getServletContext());
+      springWebAppContext.setParent(springAppContext);
+      /* Configure web app context */
+      root.setResourceBase(configuration.getWebAppDir());
+
+      root.getServletContext().setAttribute(
+          WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,
+          springWebAppContext);
+
+      ServletHolder rootServlet = root.addServlet(DefaultServlet.class, "/");
+      rootServlet.setInitOrder(1);
+
+      //Spring Security Filter initialization
+      DelegatingFilterProxy springSecurityFilter = new DelegatingFilterProxy();
+      springSecurityFilter.setTargetBeanName("springSecurityFilterChain");
+
+      //session-per-request strategy for api
+      root.addFilter(new FilterHolder(injector.getInstance(AmbariPersistFilter.class)), "/api/*", 1);
+
+      if (configuration.getApiAuthentication()) {
+        root.addFilter(new FilterHolder(springSecurityFilter), "/api/*", 1);
+      }
+
+      //Secured connector for 2-way auth
+      SslSelectChannelConnector sslConnectorTwoWay = new
+          SslSelectChannelConnector();
+      sslConnectorTwoWay.setPort(configuration.getTwoWayAuthPort());
+
+      Map<String, String> configsMap = configuration.getConfigsMap();
+      String keystore = configsMap.get(Configuration.SRVR_KSTR_DIR_KEY) +
+          File.separator + configsMap.get(Configuration.KSTR_NAME_KEY);
+      String srvrCrtPass = configsMap.get(Configuration.SRVR_CRT_PASS_KEY);
+      sslConnectorTwoWay.setKeystore(keystore);
+      sslConnectorTwoWay.setTruststore(keystore);
+      sslConnectorTwoWay.setPassword(srvrCrtPass);
+      sslConnectorTwoWay.setKeyPassword(srvrCrtPass);
+      sslConnectorTwoWay.setTrustPassword(srvrCrtPass);
+      sslConnectorTwoWay.setKeystoreType("PKCS12");
+      sslConnectorTwoWay.setTruststoreType("PKCS12");
+      sslConnectorTwoWay.setNeedClientAuth(configuration.getTwoWaySsl());
+
+      //Secured connector for 1-way auth
+      SslContextFactory contextFactory = new SslContextFactory(true);
+      contextFactory.setKeyStorePath(keystore);
+      contextFactory.setTrustStore(keystore);
+      contextFactory.setKeyStorePassword(srvrCrtPass);
+      contextFactory.setKeyManagerPassword(srvrCrtPass);
+      contextFactory.setTrustStorePassword(srvrCrtPass);
+      contextFactory.setKeyStoreType("PKCS12");
+      contextFactory.setTrustStoreType("PKCS12");
+
+      contextFactory.setNeedClientAuth(false);
+      SslSelectChannelConnector sslConnectorOneWay = new SslSelectChannelConnector(contextFactory);
+      sslConnectorOneWay.setPort(configuration.getOneWayAuthPort());
+      sslConnectorOneWay.setAcceptors(2);
+      sslConnectorTwoWay.setAcceptors(2);
+
+      ServletHolder sh = new ServletHolder(ServletContainer.class);
+      sh.setInitParameter("com.sun.jersey.config.property.resourceConfigClass",
+          "com.sun.jersey.api.core.PackagesResourceConfig");
+      sh.setInitParameter("com.sun.jersey.config.property.packages",
+          "org.apache.ambari.server.api.rest;" +
+              "org.apache.ambari.server.api.services;" +
+              "org.apache.ambari.eventdb.webservice;" +
+              "org.apache.ambari.server.api");
+      sh.setInitParameter("com.sun.jersey.api.json.POJOMappingFeature",
+          "true");
+      root.addServlet(sh, "/api/v1/*");
+      sh.setInitOrder(2);
+
+
+      //Set jetty thread pool
+      server.setThreadPool(new QueuedThreadPool(25));
+
+      /* Configure the API server to use the NIO connectors */
+      SelectChannelConnector apiConnector;
+
+      if (configuration.getApiSSLAuthentication()) {
+        String httpsKeystore = configsMap.get(Configuration.CLIENT_API_SSL_KSTR_DIR_NAME_KEY) +
+            File.separator + configsMap.get(Configuration.CLIENT_API_SSL_KSTR_NAME_KEY);
+        LOG.info("API SSL Authentication is turned on. Keystore - " + httpsKeystore);
+
+        String httpsCrtPass = configsMap.get(Configuration.CLIENT_API_SSL_CRT_PASS_KEY);
+
+        SslSelectChannelConnector sapiConnector = new SslSelectChannelConnector();
+        sapiConnector.setPort(configuration.getClientSSLApiPort());
+        sapiConnector.setKeystore(httpsKeystore);
+        sapiConnector.setTruststore(httpsKeystore);
+        sapiConnector.setPassword(httpsCrtPass);
+        sapiConnector.setKeyPassword(httpsCrtPass);
+        sapiConnector.setTrustPassword(httpsCrtPass);
+        sapiConnector.setKeystoreType("PKCS12");
+        sapiConnector.setTruststoreType("PKCS12");
+        sapiConnector.setMaxIdleTime(configuration.getConnectionMaxIdleTime());
+        apiConnector = sapiConnector;
+      } else {
+        apiConnector = new SelectChannelConnector();
+        apiConnector.setPort(configuration.getClientApiPort());
+        apiConnector.setMaxIdleTime(configuration.getConnectionMaxIdleTime());
+      }
+
+      server.addConnector(apiConnector);
+
+      server.setStopAtShutdown(true);
+      springAppContext.start();
+
+      String osType = configuration.getServerOsType();
+      if (osType == null || osType.isEmpty()) {
+        throw new RuntimeException(Configuration.OS_VERSION_KEY + " is not "
+            + " set in the ambari.properties file");
+      }
+
+      /*
+       * Start the server after controller state is recovered.
+       */
+      server.start();
+      LOG.info("********* Started Server **********");
+
+      server.join();
+      LOG.info("Joined the Server");
+    } catch (BadPaddingException bpe) {
+
+      LOG.error("Bad keystore or private key password. " +
+          "HTTPS certificate re-importing may be required.");
+      throw bpe;
+    } catch (BindException bindException) {
+
+      LOG.error("Could not bind to server port - instance may already be running. " +
+          "Terminating this instance.", bindException);
+      throw bindException;
+    }
+  }
+
+  // Creates default users and roles if in-memory database is used
+  @Transactional
+  private void addInMemoryUsers() {
+    if (getPersistenceType(configuration) == PersistenceType.IN_MEMORY &&
+        configuration.getApiAuthentication()) {
+      LOG.info("In-memory database is used - creating default users");
+      Users users = injector.getInstance(Users.class);
+
+      users.createDefaultRoles();
+      users.createUser("admin", "admin");
+      users.createUser("user", "user");
+      try {
+        users.promoteToAdmin(users.getLocalUser("admin"));
+      } catch (AmbariException e) {
+        throw new RuntimeException(e);
+      }
+    }
+  }
+
+  // Stop the server
+  private void stop() throws Exception {
+    try {
+      server.stop();
+    } catch (Exception e) {
+      LOG.error("Error stopping the server", e);
+    }
+  }
+
+  // get the persistence type for the given configuration
+  private static PersistenceType getPersistenceType(Configuration configuration) {
+    String value = configuration.getProperty(Configuration.SERVER_PERSISTENCE_TYPE_KEY);
+    return value == null ? PersistenceType.IN_MEMORY : PersistenceType.fromString(value);
+  }
+
+
+  // ----- inner class : ControllerModule ------------------------------------
+
+  /**
+   * Used for injection purposes.
+   */
+  private static class ControllerModule extends AbstractModule {
+
+    private final Configuration configuration;
+    private final HostsMap hostsMap;
+
+
+    // ----- Constructors ----------------------------------------------------
+
+    /**
+     * Construct a controller module.
+     */
+    public ControllerModule(){
+      configuration = new Configuration();
+      hostsMap      = new HostsMap(configuration);
+    }
+
+
+    // ----- AbstractModule --------------------------------------------------
+
+    @Override
+    protected void configure() {
+      bind(Configuration.class).toInstance(configuration);
+      bind(HostsMap.class).toInstance(hostsMap);
+      bind(PasswordEncoder.class).toInstance(new StandardPasswordEncoder());
+
+      install(buildJpaPersistModule());
+      bind(Gson.class).in(Scopes.SINGLETON);
+    }
+
+
+    // ----- helper methods --------------------------------------------------
+
+    // Create the JPA persistence module
+    private JpaPersistModule buildJpaPersistModule() {
+      PersistenceType  persistenceType  = getPersistenceType(configuration);
+      JpaPersistModule jpaPersistModule = new JpaPersistModule(Configuration.JDBC_UNIT_NAME);
+      Properties       properties       = new Properties();
+      String           databaseDriver;
+      String           databaseUrl;
+
+      if (persistenceType == PersistenceType.LOCAL) {
+        databaseDriver = configuration.getLocalDatabaseUrl();
+        databaseUrl    = Configuration.JDBC_LOCAL_DRIVER;
+
+      } else {
+        databaseDriver = configuration.getDatabaseDriver();
+        databaseUrl    = configuration.getDatabaseUrl();
+
+        if (persistenceType == PersistenceType.IN_MEMORY) {
+          if(databaseDriver == null){
+            databaseDriver = Configuration.JDBC_IN_MEMROY_DRIVER;
+          }
+          if (databaseUrl == null) {
+            databaseUrl = Configuration.JDBC_IN_MEMORY_URL;
+          }
+        }
+      }
+      if (databaseDriver != null && databaseUrl != null) {
+
+        properties.setProperty("javax.persistence.jdbc.url",    databaseUrl);
+        properties.setProperty("javax.persistence.jdbc.driver", databaseDriver);
+
+        properties.setProperty("eclipselink.logging.level",  "INFO");
+        properties.setProperty("eclipselink.logging.logger", "org.apache.ambari.scom.logging.JpaLogger");
+
+        // custom jdbc properties
+        Map<String, String> custom = configuration.getDatabaseCustomProperties();
+
+        if (0 != custom.size()) {
+          for (Map.Entry<String, String> entry : custom.entrySet()) {
+            properties.setProperty("eclipselink.jdbc.property." + entry.getKey(),
+                entry.getValue());
+          }
+        }
+
+        if (persistenceType == PersistenceType.IN_MEMORY) {
+          properties.setProperty("eclipselink.ddl-generation",       "drop-and-create-tables");
+          properties.setProperty("eclipselink.orm.throw.exceptions", "true");
+          jpaPersistModule.properties(properties);
+        } else {
+          properties.setProperty("javax.persistence.jdbc.user",   configuration.getDatabaseUser());
+          properties.setProperty("javax.persistence.jdbc.password",
+              configuration.getProperty(Configuration.SERVER_JDBC_USER_PASSWD_KEY));
+
+          switch (configuration.getJPATableGenerationStrategy()) {
+            case CREATE:
+              properties.setProperty("eclipselink.ddl-generation", "create-tables");
+              break;
+            case DROP_AND_CREATE:
+              properties.setProperty("eclipselink.ddl-generation", "drop-and-create-tables");
+              break;
+            default:
+              break;
+          }
+          properties.setProperty("eclipselink.ddl-generation.output-mode", "both");
+          properties.setProperty("eclipselink.create-ddl-jdbc-file-name",  "DDL-create.jdbc");
+          properties.setProperty("eclipselink.drop-ddl-jdbc-file-name",    "DDL-drop.jdbc");
+
+          jpaPersistModule.properties(properties);
+        }
+      }
+      return jpaPersistModule;
+    }
+  }
+}
+

http://git-wip-us.apache.org/repos/asf/incubator-ambari/blob/873b3502/contrib/ambari-scom/ambari-scom-server/src/main/java/org/apache/ambari/scom/ClusterDefinitionProvider.java
----------------------------------------------------------------------
diff --git a/contrib/ambari-scom/ambari-scom-server/src/main/java/org/apache/ambari/scom/ClusterDefinitionProvider.java b/contrib/ambari-scom/ambari-scom-server/src/main/java/org/apache/ambari/scom/ClusterDefinitionProvider.java
new file mode 100644
index 0000000..e1f038d
--- /dev/null
+++ b/contrib/ambari-scom/ambari-scom-server/src/main/java/org/apache/ambari/scom/ClusterDefinitionProvider.java
@@ -0,0 +1,176 @@
+/**
+ * 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.scom;
+
+import org.apache.ambari.server.configuration.Configuration;
+
+import java.io.InputStream;
+
+/**
+ * Provider for a input stream to the cluster definition file.
+ */
+public class ClusterDefinitionProvider {
+
+  /**
+   * The file name.
+   */
+  private String fileName;
+
+  /**
+   * The cluster name.
+   */
+  private String clusterName;
+
+  /**
+   * The hadoop version Id.
+   */
+  private String versionId;
+
+  /**
+   * The singleton.
+   */
+  private static ClusterDefinitionProvider singleton = new ClusterDefinitionProvider();
+
+  // ----- Constants ---------------------------------------------------------
+
+  protected static final String SCOM_CLUSTER_DEFINITION_FILENAME         = "scom.cluster.definition.filename";
+  protected static final String DEFAULT_SCOM_CLUSTER_DEFINITION_FILENAME = "clusterproperties.txt";
+
+  protected static final String SCOM_CLUSTER_NAME    = "scom.cluster.name";
+  protected static final String DEFAULT_CLUSTER_NAME = "ambari";
+
+  protected static final String SCOM_VERSION_ID    = "scom.version.id";
+  protected static final String DEFAULT_VERSION_ID = "HDP-1.3.0";
+
+
+  // ----- Constructor -------------------------------------------------------
+
+  protected ClusterDefinitionProvider() {
+  }
+
+
+  // ----- ClusterDefinitionProvider -----------------------------------
+
+  /**
+   * Initialize with the given configuration.
+   *
+   * @param configuration  the configuration
+   */
+  public void init(Configuration configuration) {
+    fileName = configuration.getProperty(SCOM_CLUSTER_DEFINITION_FILENAME);
+    if (fileName == null) {
+      fileName = DEFAULT_SCOM_CLUSTER_DEFINITION_FILENAME;
+    }
+
+    clusterName = configuration.getProperty(SCOM_CLUSTER_NAME);
+    if (clusterName == null) {
+      clusterName = DEFAULT_CLUSTER_NAME;
+    }
+
+    versionId = configuration.getProperty(SCOM_VERSION_ID);
+    if (versionId == null) {
+      versionId = DEFAULT_VERSION_ID;
+    }
+  }
+
+  /**
+   * Get the singleton instance.
+   *
+   * @return the singleton instance
+   */
+  public static ClusterDefinitionProvider instance() {
+    return singleton;
+  }
+
+  /**
+   * Get the cluster definition file name.
+   *
+   * @return the file name
+   */
+  public String getFileName() {
+    return fileName;
+  }
+
+  /**
+   * Get the cluster name.
+   *
+   * @return the cluster name
+   */
+  public String getClusterName() {
+    return clusterName;
+  }
+
+  /**
+   * Get the hadoop version Id.
+   *
+   * @return the version Id
+   */
+  public String getVersionId() {
+    return versionId;
+  }
+
+  /**
+   * Set the associated filename.
+   *
+   * @param fileName  the file name
+   */
+  protected void setFileName(String fileName) {
+    this.fileName = fileName;
+  }
+
+  /**
+   * Set the cluster name.
+   *
+   * @param clusterName  the cluster name
+   */
+  protected void setClusterName(String clusterName) {
+    this.clusterName = clusterName;
+  }
+
+  /**
+   * Set the version id.
+   *
+   * @param versionId  the version id
+   */
+  protected void setVersionId(String versionId) {
+    this.versionId = versionId;
+  }
+
+  /**
+   * Get an input stream to the cluster definition file.
+   *
+   * @return an input stream
+   */
+  public InputStream getInputStream() {
+    InputStream is;
+    String name = this.fileName == null ? DEFAULT_SCOM_CLUSTER_DEFINITION_FILENAME : this.fileName;
+
+    try {
+      is = this.getClass().getClassLoader().getResourceAsStream(name);
+
+      if (is == null) {
+        throw new IllegalStateException("Can't find the resource " + name + " in the classpath.");
+      }
+    } catch (Exception e) {
+      String msg = "Caught exception reading " + name + ".";
+      throw new IllegalStateException(msg, e);
+    }
+    return is;
+  }
+}

http://git-wip-us.apache.org/repos/asf/incubator-ambari/blob/873b3502/contrib/ambari-scom/ambari-scom-server/src/main/java/org/apache/ambari/scom/HostInfoProvider.java
----------------------------------------------------------------------
diff --git a/contrib/ambari-scom/ambari-scom-server/src/main/java/org/apache/ambari/scom/HostInfoProvider.java b/contrib/ambari-scom/ambari-scom-server/src/main/java/org/apache/ambari/scom/HostInfoProvider.java
new file mode 100644
index 0000000..46061a9
--- /dev/null
+++ b/contrib/ambari-scom/ambari-scom-server/src/main/java/org/apache/ambari/scom/HostInfoProvider.java
@@ -0,0 +1,63 @@
+/**
+ * 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.scom;
+
+import org.apache.ambari.server.controller.spi.SystemException;
+
+/**
+ * Provider of host information.
+ */
+public interface HostInfoProvider {
+
+  /**
+   * Get the host name for the given cluster name and component name.
+   *
+   * @param clusterName    the cluster name
+   * @param componentName  the component name
+   *
+   * @return the host name
+   *
+   * @throws SystemException if unable to get the host name
+   */
+  public String getHostName(String clusterName, String componentName)
+      throws SystemException;
+
+  /**
+   * Get the host name.
+   *
+   * @param id  the host identifier
+   *
+   * @return the host name
+   *
+   * @throws SystemException if unable to get the host name
+   */
+  public String getHostName(String id)
+      throws SystemException;
+
+  /**
+   * Get the host ip address.
+   *
+   * @param id  the host identifier
+   *
+   * @return the host ip address
+   *
+   * @throws SystemException if unable to get the host address
+   */
+  public String getHostAddress(String id)
+      throws SystemException;
+}

http://git-wip-us.apache.org/repos/asf/incubator-ambari/blob/873b3502/contrib/ambari-scom/ambari-scom-server/src/main/java/org/apache/ambari/scom/SQLPropertyProvider.java
----------------------------------------------------------------------
diff --git a/contrib/ambari-scom/ambari-scom-server/src/main/java/org/apache/ambari/scom/SQLPropertyProvider.java b/contrib/ambari-scom/ambari-scom-server/src/main/java/org/apache/ambari/scom/SQLPropertyProvider.java
new file mode 100644
index 0000000..49508ea
--- /dev/null
+++ b/contrib/ambari-scom/ambari-scom-server/src/main/java/org/apache/ambari/scom/SQLPropertyProvider.java
@@ -0,0 +1,304 @@
+/**
+ * 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.scom;
+
+import org.apache.ambari.server.controller.internal.AbstractPropertyProvider;
+import org.apache.ambari.server.controller.internal.PropertyInfo;
+import org.apache.ambari.server.controller.jdbc.ConnectionFactory;
+import org.apache.ambari.server.controller.spi.Predicate;
+import org.apache.ambari.server.controller.spi.Request;
+import org.apache.ambari.server.controller.spi.Resource;
+import org.apache.ambari.server.controller.spi.SystemException;
+import org.apache.ambari.server.controller.spi.TemporalInfo;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.Serializable;
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.text.NumberFormat;
+import java.text.ParsePosition;
+import java.util.HashSet;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * SQL based property/metrics provider required for ambari-scom.
+ */
+public class SQLPropertyProvider extends AbstractPropertyProvider {
+
+  private final HostInfoProvider hostProvider;
+
+  private final String clusterNamePropertyId;
+
+  private final String hostNamePropertyId;
+
+  private final String componentNamePropertyId;
+
+  private final ConnectionFactory connectionFactory;
+
+
+  // ----- Constants ---------------------------------------------------------
+
+  private static final String GET_METRICS_STATEMENT = "select * from dbo.ufGetMetrics(?, ?, ?, ?, ?, ?, ?)";
+
+  protected final static Logger LOG =
+      LoggerFactory.getLogger(SQLPropertyProvider.class);
+
+
+  // ----- Constructors ------------------------------------------------------
+
+  public SQLPropertyProvider(
+      Map<String, Map<String, PropertyInfo>> componentPropertyInfoMap,
+      HostInfoProvider hostProvider,
+      String clusterNamePropertyId,
+      String hostNamePropertyId,
+      String componentNamePropertyId,
+      ConnectionFactory connectionFactory) {
+    super(componentPropertyInfoMap);
+    this.hostProvider             = hostProvider;
+    this.clusterNamePropertyId    = clusterNamePropertyId;
+    this.hostNamePropertyId       = hostNamePropertyId;
+    this.componentNamePropertyId  = componentNamePropertyId;
+    this.connectionFactory        = connectionFactory;
+  }
+
+
+  // ----- PropertyProvider --------------------------------------------------
+
+  @Override
+  public Set<Resource> populateResources(Set<Resource> resources, Request request, Predicate predicate)
+      throws SystemException {
+    Set<Resource> keepers = new HashSet<Resource>();
+    try {
+      Connection connection = connectionFactory.getConnection();
+      try {
+        PreparedStatement preparedStatement = connection.prepareStatement(GET_METRICS_STATEMENT);
+        try {
+          for (Resource resource : resources) {
+            if (populateResource(resource, request, predicate, preparedStatement)) {
+              keepers.add(resource);
+            }
+          }
+        } finally {
+          preparedStatement.close();
+        }
+      } finally {
+        connection.close();
+      }
+    } catch (SQLException e) {
+      if (LOG.isErrorEnabled()) {
+        LOG.error("Error during populateResources call : caught exception", e);
+      }
+      throw new SystemException("Error during populateResources call : caught exception", e);
+    }
+    return keepers;
+  }
+
+
+  // ----- helper methods ----------------------------------------------------
+
+  // Populate the given resource
+  private boolean populateResource(Resource resource, Request request, Predicate predicate, PreparedStatement preparedStatement) throws SystemException {
+
+    Set<String> ids = getRequestPropertyIds(request, predicate);
+    if (ids.isEmpty()) {
+      // no properties requested ... nothing to do.
+      return true;
+    }
+
+    String componentName = (String) resource.getPropertyValue(componentNamePropertyId);
+
+    if (getComponentMetrics().get(componentName) == null) {
+      // no metrics defined for the given component ... nothing to do.
+      return true;
+    }
+
+    String clusterName = (String) resource.getPropertyValue(clusterNamePropertyId);
+    String hostName    = getHost(resource, clusterName, componentName);
+
+    if (hostName == null) {
+      throw new SystemException(
+          "Unable to get metrics.  No host name for " + componentName, null);
+    }
+
+    for (String id : ids) {
+      Map<String, PropertyInfo> propertyInfoMap = getPropertyInfoMap(componentName, id);
+
+      for (Map.Entry<String, PropertyInfo> entry: propertyInfoMap.entrySet()) {
+        String       propertyKey  = entry.getKey();
+        PropertyInfo propertyInfo = entry.getValue();
+        String       propertyId   = propertyInfo.getPropertyId();
+        TemporalInfo temporalInfo = request.getTemporalInfo(id);
+
+        if ((propertyInfo.isPointInTime() && temporalInfo == null) ||
+            (propertyInfo.isTemporal()    && temporalInfo != null)) {
+
+          long startTime;
+          long endTime;
+
+          if (temporalInfo != null) {
+            Long endTimeSeconds = temporalInfo.getEndTime();
+
+            endTime   = endTimeSeconds != -1 ? endTimeSeconds * 1000 : Long.MAX_VALUE;
+            startTime = temporalInfo.getStartTime() * 1000;
+          } else {
+            startTime = 0L;
+            endTime   = Long.MAX_VALUE;
+          }
+
+          String[] parts = propertyId.split("\\.");
+          int      size  = parts.length;
+
+          if (size >= 3) {
+            List<DataPoint> dataPoints = getMetric(startTime, endTime, parts[size - 3], parts[size - 2], parts[size - 1],
+                                                   componentName.toLowerCase(), hostName, preparedStatement);
+
+            if (dataPoints != null) {
+              if (temporalInfo == null){
+                // return the value of the last data point
+                int          length = dataPoints.size();
+                Serializable value  = length > 0 ? dataPoints.get(length - 1).getValue() : 0;
+                resource.setProperty(propertyKey, value);
+              } else {
+
+                Number[][] dp = new Number[dataPoints.size()][2];
+                for (int i = 0; i < dp.length; i++) {
+                  dp[i][0] = dataPoints.get(i).getValue();
+                  dp[i][1] = dataPoints.get(i).getTimestamp();
+                }
+                resource.setProperty(propertyKey, dp);
+              }
+            }
+          } else {
+            if (LOG.isWarnEnabled()) {
+              LOG.warn("Can't get metrics for " + id + " : " + propertyId);
+            }
+          }
+        }
+      }
+    }
+
+    return true;
+  }
+
+  // get a metric from a sql connection
+  private List<DataPoint> getMetric(long startTime, long endTime, String recordTypeContext,
+                        String recordTypeName, String metricName, String serviceName, String nodeName,
+                        PreparedStatement preparedStatement) throws SystemException {
+
+    if (recordTypeContext == null || recordTypeName == null || nodeName == null) {
+      return null;
+    }
+
+    int columnId = 1;
+    List<DataPoint> results;
+    try {
+      preparedStatement.clearParameters();
+
+      preparedStatement.setLong(columnId++, startTime);
+      preparedStatement.setLong(columnId++, endTime);
+      preparedStatement.setNString(columnId++, recordTypeContext);
+      preparedStatement.setNString(columnId++, recordTypeName);
+      preparedStatement.setNString(columnId++, metricName);
+      preparedStatement.setNString(columnId++, serviceName);
+      preparedStatement.setNString(columnId, nodeName);
+
+      ResultSet rs = preparedStatement.executeQuery();
+
+      results = new LinkedList<DataPoint>();
+
+      if (rs != null) {
+
+        //(RecordTimeStamp bigint, MetricValue NVARCHAR(512))
+        while (rs.next()) {
+
+          ParsePosition parsePosition = new ParsePosition(0);
+          NumberFormat  numberFormat  = NumberFormat.getInstance();
+          Number        parsedNumber  = numberFormat.parse(rs.getNString("MetricValue"), parsePosition);
+
+          results.add(new DataPoint(rs.getLong("RecordTimeStamp"), parsedNumber));
+        }
+      }
+    } catch (SQLException e) {
+      throw new SystemException("Error during getMetric call : caught exception - ", e);
+    }
+    return results;
+  }
+
+  // get the hostname for a given resource
+  private String getHost(Resource resource, String clusterName, String componentName) throws SystemException {
+    return hostNamePropertyId == null ?
+        hostProvider.getHostName(clusterName, componentName) :
+        hostProvider.getHostName((String) resource.getPropertyValue(hostNamePropertyId));
+  }
+
+
+  // ----- inner class : DataPoint -------------------------------------------
+
+  /**
+   * Structure to hold a single datapoint (value/timestamp pair) retrieved from the db.
+   */
+  private static class DataPoint {
+    private final long timestamp;
+    private final Number value;
+
+    // ----- Constructor -------------------------------------------------
+
+    /**
+     * Construct a data point from the given value and timestamp.
+     *
+     * @param timestamp  the timestamp
+     * @param value      the value
+     */
+    private DataPoint(long timestamp, Number value) {
+      this.timestamp = timestamp;
+      this.value = value;
+    }
+
+    // ----- DataPoint ---------------------------------------------------
+
+    /**
+     * Get the timestamp value.
+     * @return the timestamp
+     */
+    public long getTimestamp() {
+      return timestamp;
+    }
+
+    /**
+     * Get the value.
+     * @return the value
+     */
+    public Number getValue() {
+      return value;
+    }
+
+    // ----- Object overrides --------------------------------------------
+
+    @Override
+    public String toString() {
+      return "{" +value + " : " + timestamp + "}";
+    }
+  }
+}

http://git-wip-us.apache.org/repos/asf/incubator-ambari/blob/873b3502/contrib/ambari-scom/ambari-scom-server/src/main/java/org/apache/ambari/scom/SQLProviderModule.java
----------------------------------------------------------------------
diff --git a/contrib/ambari-scom/ambari-scom-server/src/main/java/org/apache/ambari/scom/SQLProviderModule.java b/contrib/ambari-scom/ambari-scom-server/src/main/java/org/apache/ambari/scom/SQLProviderModule.java
new file mode 100644
index 0000000..b51f97a
--- /dev/null
+++ b/contrib/ambari-scom/ambari-scom-server/src/main/java/org/apache/ambari/scom/SQLProviderModule.java
@@ -0,0 +1,332 @@
+/**
+ * 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.scom;
+
+import org.apache.ambari.msi.AbstractResourceProvider;
+import org.apache.ambari.msi.ClusterDefinition;
+import org.apache.ambari.msi.StateProvider;
+import org.apache.ambari.server.configuration.ComponentSSLConfiguration;
+import org.apache.ambari.server.controller.internal.DefaultProviderModule;
+import org.apache.ambari.server.controller.internal.URLStreamProvider;
+import org.apache.ambari.server.controller.jdbc.ConnectionFactory;
+import org.apache.ambari.server.controller.jmx.JMXPropertyProvider;
+import org.apache.ambari.server.controller.spi.PropertyProvider;
+import org.apache.ambari.server.controller.spi.Resource;
+import org.apache.ambari.server.controller.spi.ResourceProvider;
+import org.apache.ambari.server.controller.spi.SystemException;
+import org.apache.ambari.server.controller.utilities.PropertyHelper;
+
+import java.io.BufferedReader;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.net.InetAddress;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Provider module used to install PropertyProviders required for ambari-scom.
+ */
+public class SQLProviderModule extends DefaultProviderModule implements HostInfoProvider, StateProvider {
+  private final ClusterDefinition clusterDefinition;
+
+  // TODO : these elements should be injected...
+  private final ConnectionFactory connectionFactory = SinkConnectionFactory.instance();
+  private final ComponentSSLConfiguration sslConfiguration = ComponentSSLConfiguration.instance();
+  private final URLStreamProvider urlStreamProvider = new URLStreamProvider(5000, 10000,
+      sslConfiguration.getTruststorePath(), sslConfiguration.getTruststorePassword(), sslConfiguration.getTruststoreType());
+
+
+  // ----- Constants ---------------------------------------------------------
+
+  private static Map<String, String> serviceNames = new HashMap<String, String>();
+
+  static {
+    serviceNames.put("NAMENODE",           "namenode");
+    serviceNames.put("SECONDARY_NAMENODE", "secondarynamenode");
+    serviceNames.put("JOBTRACKER",         "jobtracker");
+    serviceNames.put("HISTORY_SERVER",     "historyserver");
+    serviceNames.put("HIVE_SERVER",        "hiveserver");
+    serviceNames.put("HIVE_SERVER2",       "hiveserver2");
+    serviceNames.put("HIVE_METASTORE",     "metastore");
+    serviceNames.put("HIVE_CLIENT",        "hwi");
+    serviceNames.put("OOZIE_SERVER",       "oozieservice");
+    serviceNames.put("FLUME_SERVER",       "flumagent");
+    serviceNames.put("HBASE_MASTER",       "master");
+    serviceNames.put("HBASE_REGIONSERVER", "regionserver");
+    serviceNames.put("ZOOKEEPER_SERVER",   "zkServer");
+    serviceNames.put("DATANODE",           "datanode");
+    serviceNames.put("TASKTRACKER",        "tasktracker");
+    serviceNames.put("WEBHCAT_SERVER",     "templeton");
+  }
+
+  private static final String STATE_PREFIX = "STATE              : ";
+
+
+  // ----- Constructor -------------------------------------------------------
+
+  public SQLProviderModule() {
+    clusterDefinition = new ClusterDefinition(this, ClusterDefinitionProvider.instance(), this);
+  }
+
+
+  // ----- AbstractProviderModule --------------------------------------------
+
+  @Override
+  protected ResourceProvider createResourceProvider(Resource.Type type) {
+    return AbstractResourceProvider.getResourceProvider(type, clusterDefinition);
+  }
+
+  @Override
+  protected void createPropertyProviders(Resource.Type type) {
+
+    List<PropertyProvider> providers = new LinkedList<PropertyProvider>();
+
+    switch (type) {
+      case Component:
+
+        providers.add(new JMXPropertyProvider(
+            PropertyHelper.getJMXPropertyIds(type, PropertyHelper.MetricsVersion.HDP1),
+            urlStreamProvider,
+            this,
+            PropertyHelper.getPropertyId("ServiceComponentInfo", "cluster_name"),
+            null,
+            PropertyHelper.getPropertyId("ServiceComponentInfo", "component_name"),
+            PropertyHelper.getPropertyId("ServiceComponentInfo", "state"),
+            Collections.singleton("STARTED")));
+
+        providers.add(new SQLPropertyProvider(
+            PropertyHelper.getGangliaPropertyIds(type, PropertyHelper.MetricsVersion.HDP1),
+            this,
+            PropertyHelper.getPropertyId("ServiceComponentInfo", "cluster_name"),
+            null,
+            PropertyHelper.getPropertyId("ServiceComponentInfo", "component_name"),
+            connectionFactory));
+        break;
+      case HostComponent:
+
+        providers.add(new JMXPropertyProvider(
+            PropertyHelper.getJMXPropertyIds(type, PropertyHelper.MetricsVersion.HDP1),
+            urlStreamProvider,
+            this,
+            PropertyHelper.getPropertyId("HostRoles", "cluster_name"),
+            PropertyHelper.getPropertyId("HostRoles", "host_name"),
+            PropertyHelper.getPropertyId("HostRoles", "component_name"),
+            PropertyHelper.getPropertyId("HostRoles", "state"),
+            Collections.singleton("STARTED")));
+
+        providers.add(new SQLPropertyProvider(
+            PropertyHelper.getGangliaPropertyIds(type, PropertyHelper.MetricsVersion.HDP1),
+            this,
+            PropertyHelper.getPropertyId("HostRoles", "cluster_name"),
+            PropertyHelper.getPropertyId("HostRoles", "host_name"),
+            PropertyHelper.getPropertyId("HostRoles", "component_name"),
+            connectionFactory));
+        break;
+      default:
+        break;
+    }
+    putPropertyProviders(type, providers);
+  }
+
+  // ----- HostProvider ------------------------------------------------------
+
+  @Override
+  public String getHostName(String clusterName, String componentName) throws SystemException {
+    return getClusterNodeName(super.getHostName(clusterName, componentName));
+  }
+
+  @Override
+  public String getHostName(String id) throws SystemException {
+    return getClusterNodeName(id);
+  }
+
+  @Override
+  public String getHostAddress(String id) throws SystemException {
+    return getClusterHostAddress(id);
+  }
+
+
+  // ----- StateProvider -----------------------------------------------------
+
+  @Override
+  public State getRunningState(String hostName, String componentName) {
+    String serviceName = getServiceName(componentName);
+    if (serviceName != null) {
+      String[] cmdStrings = {"sc", "\\\\" + hostName, "query", "\"" + serviceName + "\""}; // Windows specific command
+
+      java.lang.Process process = runProcess(cmdStrings);
+
+      if (process.exitValue() == 0) {
+
+        String response = getProcessResponse(process.getInputStream());
+
+        int i = response.indexOf(STATE_PREFIX);
+        if (i >= 0) {
+          int state = Integer.parseInt(response.substring(i + STATE_PREFIX.length(), i + STATE_PREFIX.length() + 1));
+          switch (state) {
+            case (1): // service stopped
+              return State.Stopped;
+            case (4): // service started
+              return State.Running;
+          }
+        }
+      }
+    }
+    return State.Unknown;
+  }
+
+  @Override
+  public Process setRunningState(String hostName, String componentName, State state) {
+    String serviceName = getServiceName(componentName);
+    if (serviceName != null) {
+      String command = state == State.Running ? "start" : "stop";
+      String[] cmdStrings = {"sc", "\\\\" + hostName, command, "\"" + serviceName + "\""};  // Windows specific command
+
+      return new StateProcess(runProcess(cmdStrings));
+    }
+    return null;
+  }
+
+
+  // ----- utility methods ---------------------------------------------------
+
+  // get the hostname
+  private String getClusterNodeName(String hostname) throws SystemException {
+    try {
+      if (hostname.equalsIgnoreCase("localhost")) {
+        return InetAddress.getLocalHost().getCanonicalHostName();
+      }
+      return InetAddress.getByName(hostname).getCanonicalHostName();
+    } catch (Exception e) {
+      throw new SystemException("Error getting hostname.", e);
+    }
+  }
+
+  // get the hostname
+  private String getClusterHostAddress(String hostname) throws SystemException {
+    try {
+      if (hostname.equalsIgnoreCase("localhost")) {
+        return InetAddress.getLocalHost().getHostAddress();
+      }
+      return InetAddress.getByName(hostname).getHostAddress();
+    } catch (Exception e) {
+      throw new SystemException("Error getting ip address.", e);
+    }
+  }
+
+  // get the Windows service name from the given component name
+  private String getServiceName(String componentName) {
+    return serviceNames.get(componentName);
+  }
+
+  // run a process specified by the given command strings
+  private java.lang.Process runProcess(String... commands) {
+    Runtime runtime = Runtime.getRuntime();
+    java.lang.Process process;
+    try {
+      process = runtime.exec(commands);
+
+      process.waitFor();
+    } catch (Exception e) {
+      return null;
+    }
+    return process;
+  }
+
+  // get the response text from a completed process stream
+  private static String getProcessResponse(InputStream stream) {
+
+    StringBuilder  sb       = new StringBuilder();
+    BufferedReader stdInput = new BufferedReader(new InputStreamReader(stream));
+
+    try {
+
+      String line;
+
+      while ((line = stdInput.readLine()) != null) {
+        sb.append(line);
+      }
+
+    } catch (Exception e) {
+      return null;
+    }
+    return sb.toString();
+  }
+
+
+  // ----- inner class : StateProcess ----------------------------------------
+
+  public static class StateProcess implements Process {
+    private final java.lang.Process process;
+    private String output = null;
+    private String error = null;
+
+    public StateProcess(java.lang.Process process) {
+      this.process = process;
+    }
+
+    @Override
+    public boolean isRunning() {
+      try {
+        process.exitValue();
+      } catch (IllegalThreadStateException e) {
+        return true;
+      }
+      return false;
+    }
+
+    @Override
+    public int getExitCode() {
+      return process.exitValue();
+    }
+
+    @Override
+    public String getOutput() {
+      if (output != null) {
+        return output;
+      }
+
+      String processResponse = getProcessResponse(process.getInputStream());
+
+      if (!isRunning()){
+        output = processResponse;
+      }
+
+      return processResponse;
+    }
+
+    @Override
+    public String getError() {
+      if (error != null) {
+        return error;
+      }
+
+      String processResponse = getProcessResponse(process.getErrorStream());
+
+      if (!isRunning()){
+        error = processResponse;
+      }
+
+      return processResponse;
+    }
+  }
+}

http://git-wip-us.apache.org/repos/asf/incubator-ambari/blob/873b3502/contrib/ambari-scom/ambari-scom-server/src/main/java/org/apache/ambari/scom/SinkConnectionFactory.java
----------------------------------------------------------------------
diff --git a/contrib/ambari-scom/ambari-scom-server/src/main/java/org/apache/ambari/scom/SinkConnectionFactory.java b/contrib/ambari-scom/ambari-scom-server/src/main/java/org/apache/ambari/scom/SinkConnectionFactory.java
new file mode 100644
index 0000000..2729797
--- /dev/null
+++ b/contrib/ambari-scom/ambari-scom-server/src/main/java/org/apache/ambari/scom/SinkConnectionFactory.java
@@ -0,0 +1,120 @@
+/**
+ * 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.scom;
+
+import org.apache.ambari.server.configuration.Configuration;
+import org.apache.ambari.server.controller.jdbc.ConnectionFactory;
+
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.SQLException;
+
+/**
+ * Factory for the sink database connection.
+ */
+public class SinkConnectionFactory implements ConnectionFactory {
+
+  /**
+   * The database URL.
+   */
+  private String databaseUrl;
+
+  /**
+   * The database driver.
+   */
+  private String databaseDriver;
+
+  /**
+   * Indicates whether or not the driver has been initialized
+   */
+  private boolean connectionInitialized = false;
+
+  /**
+   * The singleton.
+   */
+  private static SinkConnectionFactory singleton = new SinkConnectionFactory();
+
+  // ----- Constants ---------------------------------------------------------
+
+  protected static final String SCOM_SINK_DB_URL    = "scom.sink.db.url";
+  protected static final String SCOM_SINK_DB_DRIVER = "scom.sink.db.driver";
+
+
+  // ----- Constructor -------------------------------------------------------
+
+  protected SinkConnectionFactory() {
+  }
+
+
+  // ----- SinkConnectionFactory ---------------------------------------------
+
+  /**
+   * Initialize with the given configuration.
+   *
+   * @param configuration  the configuration
+   */
+  public void init(Configuration configuration) {
+    this.databaseUrl    = configuration.getProperty(SCOM_SINK_DB_URL);
+    this.databaseDriver = configuration.getProperty(SCOM_SINK_DB_DRIVER);
+  }
+
+  /**
+   * Get the singleton instance.
+   *
+   * @return the singleton instance
+   */
+  public static SinkConnectionFactory instance() {
+    return singleton;
+  }
+
+  /**
+   * Get the database URL.
+   *
+   * @return the database URL
+   */
+  public String getDatabaseUrl() {
+    return databaseUrl;
+  }
+
+  /**
+   * Get the database driver.
+   *
+   * @return the database driver
+   */
+  public String getDatabaseDriver() {
+    return databaseDriver;
+  }
+
+// ----- ConnectionFactory -----------------------------------------------
+
+  @Override
+  public Connection getConnection() throws SQLException {
+    synchronized (this) {
+      if (!connectionInitialized) {
+        connectionInitialized = true;
+        try {
+          Class.forName(databaseDriver);
+        } catch (ClassNotFoundException e) {
+          throw new SQLException("Can't load the driver class.", e);
+        }
+      }
+    }
+    return DriverManager.getConnection(databaseUrl);
+  }
+}

http://git-wip-us.apache.org/repos/asf/incubator-ambari/blob/873b3502/contrib/ambari-scom/ambari-scom-server/src/main/java/org/apache/ambari/scom/logging/JpaLogger.java
----------------------------------------------------------------------
diff --git a/contrib/ambari-scom/ambari-scom-server/src/main/java/org/apache/ambari/scom/logging/JpaLogger.java b/contrib/ambari-scom/ambari-scom-server/src/main/java/org/apache/ambari/scom/logging/JpaLogger.java
new file mode 100644
index 0000000..c9d7bdf
--- /dev/null
+++ b/contrib/ambari-scom/ambari-scom-server/src/main/java/org/apache/ambari/scom/logging/JpaLogger.java
@@ -0,0 +1,185 @@
+/**
+ * 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.scom.logging;
+
+import org.eclipse.persistence.logging.AbstractSessionLog;
+import org.eclipse.persistence.logging.EclipseLinkLogRecord;
+import org.eclipse.persistence.logging.SessionLogEntry;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.logging.Formatter;
+import java.util.logging.Level;
+import java.util.logging.SimpleFormatter;
+
+/**
+ * Logger for JPA log messages.
+ */
+public class JpaLogger extends AbstractSessionLog {
+
+  /**
+   * The formatter.
+   */
+  private final Formatter formatter = new SimpleFormatter();
+
+  /**
+   * The log level.
+   */
+  public Level logLevel = Level.WARNING;
+
+
+  // ----- Constants ---------------------------------------------------------
+
+  /**
+   * The logger.
+   */
+  private static final org.slf4j.Logger LOG = LoggerFactory.getLogger(JpaLogger.class);
+
+  /**
+   * The java log levels.
+   */
+  public static final Level[] JAVA_LOG_LEVELS = new Level[]{
+      Level.ALL,     Level.FINEST, Level.FINER,
+      Level.FINE,    Level.CONFIG, Level.INFO,
+      Level.WARNING, Level.SEVERE, Level.OFF
+  };
+
+
+  // ----- AbstractSessionLog ------------------------------------------------
+
+  @Override
+  public void log(SessionLogEntry sessionLogEntry) {
+
+    Logger logger = getLogger();
+
+    switch (sessionLogEntry.getLevel()) {
+      case SEVERE:
+        logger.error(getLogMessage(sessionLogEntry));
+        break;
+
+      case WARNING:
+        logger.warn(getLogMessage(sessionLogEntry));
+        break;
+
+      case INFO:
+      case CONFIG:
+        logger.info(getLogMessage(sessionLogEntry));
+        break;
+
+      case FINE:
+      case FINER:
+      case FINEST:
+        logger.debug(getLogMessage(sessionLogEntry));
+        break;
+
+      case ALL:
+        logger.trace(getLogMessage(sessionLogEntry));
+        break;
+    }
+  }
+
+  @Override
+  public void throwing(Throwable throwable) {
+    getLogger().error(null, throwable);
+  }
+
+  @Override
+  public boolean shouldLog(int level, String category) {
+    return getJavaLogLevel(level).intValue() >= logLevel.intValue();
+  }
+
+
+// ----- accessors ---------------------------------------------------------
+
+  /**
+   * Get the log level.
+   *
+   * @return the log level
+   */
+  public Level getLogLevel() {
+    return logLevel;
+  }
+
+  /**
+   * Set the log level.
+   *
+   * @param logLevel the log level
+   */
+  public void setLogLevel(Level logLevel) {
+    this.logLevel = logLevel;
+  }
+
+  /**
+   * Get the associated logger.
+   *
+   * @return the logger
+   */
+  protected org.slf4j.Logger getLogger() {
+    return LOG;
+  }
+
+  /**
+   * Get the associated formatter.
+   *
+   * @return the formatter
+   */
+  protected Formatter getFormatter() {
+    return formatter;
+  }
+
+
+  // ----- helper methods ----------------------------------------------------
+
+  // gets the log message from the given session log entry
+  private String getLogMessage(SessionLogEntry sessionLogEntry) {
+    return getFormatter().format(getLogRecord(sessionLogEntry,
+        getJavaLogLevel(sessionLogEntry.getLevel())));
+  }
+
+  // get a log record for the given session log entry
+  private EclipseLinkLogRecord getLogRecord(SessionLogEntry sessionLogEntry, Level level) {
+    EclipseLinkLogRecord logRecord =
+        new EclipseLinkLogRecord(level, formatMessage(sessionLogEntry));
+
+    logRecord.setLoggerName(sessionLogEntry.getNameSpace());
+    logRecord.setShouldPrintDate(shouldPrintDate());
+    logRecord.setShouldPrintThread(shouldPrintThread());
+
+    Throwable exception = sessionLogEntry.getException();
+    if (exception != null) {
+      logRecord.setThrown(exception);
+      logRecord.setShouldLogExceptionStackTrace(shouldLogExceptionStackTrace());
+    }
+
+    if (shouldPrintConnection()) {
+      logRecord.setConnection(sessionLogEntry.getConnection());
+    }
+
+    if (shouldPrintSession()) {
+      logRecord.setSessionString(getSessionString(sessionLogEntry.getSession()));
+    }
+
+    return logRecord;
+  }
+
+  // get the Java log level for the given eclipse log level
+  private static Level getJavaLogLevel(int level) {
+    return level >= ALL && level <= OFF ? JAVA_LOG_LEVELS[level] : Level.OFF;
+  }
+}


Mime
View raw message