You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cloudstack.apache.org by wi...@apache.org on 2014/09/19 16:58:35 UTC

git commit: updated refs/heads/statscollector-graphite to 81c3855

Repository: cloudstack
Updated Branches:
  refs/heads/statscollector-graphite [created] 81c3855e5


CLOUDSTACK-7583: Send VmStats to Graphite host when configured


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/81c3855e
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/81c3855e
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/81c3855e

Branch: refs/heads/statscollector-graphite
Commit: 81c3855e57004951ae104c0b99bceb7f61047099
Parents: 6687727
Author: Wido den Hollander <wi...@widodh.nl>
Authored: Fri Sep 19 16:58:00 2014 +0200
Committer: Wido den Hollander <wi...@widodh.nl>
Committed: Fri Sep 19 16:58:00 2014 +0200

----------------------------------------------------------------------
 server/src/com/cloud/configuration/Config.java  |   7 +-
 server/src/com/cloud/server/StatsCollector.java |  36 ++++++
 .../utils/graphite/GraphiteClient.java          | 129 +++++++++++++++++++
 .../utils/graphite/GraphiteException.java       |  31 +++++
 4 files changed, 202 insertions(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/81c3855e/server/src/com/cloud/configuration/Config.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/configuration/Config.java b/server/src/com/cloud/configuration/Config.java
index 9309e3a..1aa8d3b 100755
--- a/server/src/com/cloud/configuration/Config.java
+++ b/server/src/com/cloud/configuration/Config.java
@@ -2057,7 +2057,12 @@ public enum Config {
     PublishAlertEvent("Advanced", ManagementServer.class, Boolean.class, "publish.alert.events", "true", "enable or disable publishing of alert events on the event bus", null),
     PublishResourceStateEvent("Advanced", ManagementServer.class, Boolean.class, "publish.resource.state.events", "true", "enable or disable publishing of alert events on the event bus", null),
     PublishUsageEvent("Advanced", ManagementServer.class, Boolean.class, "publish.usage.events", "true", "enable or disable publishing of usage events on the event bus", null),
-    PublishAsynJobEvent("Advanced", ManagementServer.class, Boolean.class, "publish.async.job.events", "true", "enable or disable publishing of usage events on the event bus", null);
+    PublishAsynJobEvent("Advanced", ManagementServer.class, Boolean.class, "publish.async.job.events", "true", "enable or disable publishing of usage events on the event bus", null),
+
+    // StatsCollector
+    StatsOutPutGraphiteHost("Advanced", ManagementServer.class, String.class, "stats.output.graphite.host", "", "Graphite host to send statistics to", null),
+    StatsOutPutGraphitePort("Advanced", ManagementServer.class, Integer.class, "stats.output.graphite.port", "2003", "The port of the graphite host to send statistics to", null),
+    StatsOutPutGraphitePrefix("Advanced", ManagementServer.class, String.class, "stats.output.graphite.prefix", "", "Prefix to append to statistics going to Graphite", null);
 
     private final String _category;
     private final Class<?> _componentClass;

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/81c3855e/server/src/com/cloud/server/StatsCollector.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/server/StatsCollector.java b/server/src/com/cloud/server/StatsCollector.java
index 9f4c14e..ff2a69d 100755
--- a/server/src/com/cloud/server/StatsCollector.java
+++ b/server/src/com/cloud/server/StatsCollector.java
@@ -43,6 +43,8 @@ import org.apache.cloudstack.managed.context.ManagedContextRunnable;
 import org.apache.cloudstack.storage.datastore.db.ImageStoreDao;
 import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao;
 import org.apache.cloudstack.storage.datastore.db.StoragePoolVO;
+import org.apache.cloudstack.graphite.GraphiteClient;
+import org.apache.cloudstack.graphite.GraphiteException;
 
 import com.cloud.agent.AgentManager;
 import com.cloud.agent.api.Answer;
@@ -194,6 +196,10 @@ public class StatsCollector extends ManagerBase implements ComponentMethodInterc
     int vmDiskStatsInterval = 0;
     List<Long> hostIds = null;
 
+    String graphiteHost = null;
+    int graphitePort = -1;
+    String graphitePrefix = null;
+
     private ScheduledExecutorService _diskStatsUpdateExecutor;
     private int _usageAggregationRange = 1440;
     private String _usageTimeZone = "GMT";
@@ -233,6 +239,14 @@ public class StatsCollector extends ManagerBase implements ComponentMethodInterc
         autoScaleStatsInterval = NumbersUtil.parseLong(configs.get("autoscale.stats.interval"), 60000L);
         vmDiskStatsInterval = NumbersUtil.parseInt(configs.get("vm.disk.stats.interval"), 0);
 
+        graphiteHost = configs.get("stats.output.graphite.host");
+        graphitePort = NumbersUtil.parseInt(configs.get("stats.output.graphite.port"), 2003);
+        graphitePrefix = configs.get("stats.output.graphite.prefix");
+
+        if (!graphitePrefix.equals("")) {
+            graphitePrefix += ".";
+        }
+
         if (hostStatsInterval > 0) {
             _executor.scheduleWithFixedDelay(new HostCollector(), 15000L, hostStatsInterval, TimeUnit.MILLISECONDS);
         }
@@ -407,6 +421,28 @@ public class StatsCollector extends ManagerBase implements ComponentMethodInterc
 
                                     _VmStats.put(vmId, statsInMemory);
                                 }
+
+                                if (!graphiteHost.equals("")) {
+                                    s_logger.debug("Sending VmStats to Graphite host " + graphiteHost + ":" + graphitePort);
+                                    HashMap metrics = new HashMap<String, Integer>();
+
+                                    metrics.put(graphitePrefix + "cloudstack.stats.instances." + vmId +".cpu.num", statsForCurrentIteration.getNumCPUs());
+                                    metrics.put(graphitePrefix + "cloudstack.stats.instances." + vmId +".cpu.utilization", statsForCurrentIteration.getCPUUtilization());
+                                    metrics.put(graphitePrefix + "cloudstack.stats.instances." + vmId +".network.read_kbs", statsForCurrentIteration.getNetworkReadKBs());
+                                    metrics.put(graphitePrefix + "cloudstack.stats.instances." + vmId +".network.write_kbs", statsForCurrentIteration.getNetworkWriteKBs());
+                                    metrics.put(graphitePrefix + "cloudstack.stats.instances." + vmId +".disk.write_kbs", statsForCurrentIteration.getDiskWriteKBs());
+                                    metrics.put(graphitePrefix + "cloudstack.stats.instances." + vmId +".disk.read_kbs", statsForCurrentIteration.getDiskReadKBs());
+                                    metrics.put(graphitePrefix + "cloudstack.stats.instances." + vmId +".disk.write_iops", statsForCurrentIteration.getDiskWriteIOs());
+                                    metrics.put(graphitePrefix + "cloudstack.stats.instances." + vmId +".disk.read_iops", statsForCurrentIteration.getDiskReadIOs());
+                                    try {
+                                        GraphiteClient g = new GraphiteClient(graphiteHost, graphitePort);
+                                        g.sendMetrics(metrics);
+                                        s_logger.debug("Completed sending VmStats to Graphite host " + graphiteHost + ":" + graphitePort);
+                                    } catch (GraphiteException e) {
+                                        s_logger.debug("Failed sending VmStats to Graphite host " + graphiteHost + ":" + graphitePort + ": " + e.getMessage());
+                                    }
+                                }
+
                             }
                         }
 

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/81c3855e/utils/src/org/apache/cloudstack/utils/graphite/GraphiteClient.java
----------------------------------------------------------------------
diff --git a/utils/src/org/apache/cloudstack/utils/graphite/GraphiteClient.java b/utils/src/org/apache/cloudstack/utils/graphite/GraphiteClient.java
new file mode 100644
index 0000000..8db434c
--- /dev/null
+++ b/utils/src/org/apache/cloudstack/utils/graphite/GraphiteClient.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.cloudstack.graphite;
+
+import java.io.IOException;
+import java.io.DataOutputStream;
+import java.net.Socket;
+import java.net.UnknownHostException;
+import java.util.HashMap;
+import java.util.Map;
+
+public class GraphiteClient {
+
+    private String graphiteHost;
+    private int graphitePort;
+
+    /**
+     * Create a new Graphite client
+     *
+     * @param graphiteHost Hostname of the Graphite host
+     * @param graphitePort TCP port of the Graphite host
+     */
+    public GraphiteClient(String graphiteHost, int graphitePort) {
+        this.graphiteHost = graphiteHost;
+        this.graphitePort = graphitePort;
+    }
+
+    /**
+     * Create a new Graphite client
+     *
+     * @param graphiteHost Hostname of the Graphite host. Will default to port 2003
+     */
+    public GraphiteClient(String graphiteHost) {
+        this.graphiteHost = graphiteHost;
+        this.graphitePort = 2003;
+    }
+
+    /**
+     * Get the current system timestamp to pass to Graphite
+     *
+     * @return Seconds passed since epoch (01-01-1970)
+     */
+    protected long getCurrentSystemTime() {
+        return System.currentTimeMillis() / 1000;
+    }
+
+    /**
+     * Connect to the Graphite host over TCP
+     *
+     * @return A Socket to the Graphite host
+     */
+    protected Socket connect() throws UnknownHostException, IOException {
+        return new Socket(this.graphiteHost, this.graphitePort);
+    }
+
+    /**
+     * Send a array of metrics to graphite.
+     *
+     * @param metrics the metrics as key-value-pairs
+     */
+    public void sendMetrics(Map<String, Integer> metrics) {
+        sendMetrics(metrics, this.getCurrentSystemTime());
+    }
+
+    /**
+     * Send a array of metrics with a given timestamp to graphite.
+     *
+     * @param metrics the metrics as key-value-pairs
+     * @param timeStamp the timestamp
+     */
+    public void sendMetrics(Map<String, Integer> metrics, long timeStamp) {
+        try {
+            Socket conn = connect();
+            DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
+            for (Map.Entry<String, Integer> metric: metrics.entrySet()) {
+                dos.writeBytes(metric.getKey() + " " + metric.getValue() + " " + timeStamp + "\n");
+            }
+            conn.close();
+        } catch (UnknownHostException e) {
+            throw new GraphiteException("Unknown host: " + graphiteHost);
+        } catch (IOException e) {
+            throw new GraphiteException("Error while writing to graphite: " + e.getMessage(), e);
+        }
+    }
+
+    /**
+     * Send a single metric with the current time as timestamp to graphite.
+     *
+     * @param key The metric key
+     * @param value the metric value
+     *
+     * @throws GraphiteException if sending data to graphite failed
+     */
+    public void sendMetric(String key, int value) {
+        sendMetric(key, value, this.getCurrentSystemTime());
+    }
+
+    /**
+     * Send a single metric with a given timestamp to graphite.
+     *
+     * @param key The metric key
+     * @param value The metric value
+     * @param timeStamp the timestamp to use
+     *
+     * @throws GraphiteException if sending data to graphite failed
+     */
+    public void sendMetric(final String key, final int value, long timeStamp) {
+        HashMap metrics = new HashMap<String, Integer>();
+        metrics.put(key, value);
+        sendMetrics(metrics, timeStamp);
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/81c3855e/utils/src/org/apache/cloudstack/utils/graphite/GraphiteException.java
----------------------------------------------------------------------
diff --git a/utils/src/org/apache/cloudstack/utils/graphite/GraphiteException.java b/utils/src/org/apache/cloudstack/utils/graphite/GraphiteException.java
new file mode 100644
index 0000000..b11532e
--- /dev/null
+++ b/utils/src/org/apache/cloudstack/utils/graphite/GraphiteException.java
@@ -0,0 +1,31 @@
+//
+// 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.cloudstack.graphite;
+
+public class GraphiteException extends RuntimeException {
+
+    public GraphiteException(String message) {
+        super(message);
+    }
+
+    public GraphiteException(String message, Throwable cause) {
+        super(message, cause);
+    }
+}
\ No newline at end of file