cloudstack-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From wid...@apache.org
Subject git commit: updated refs/heads/master to 840c2fd
Date Tue, 11 Nov 2014 12:22:40 GMT
Repository: cloudstack
Updated Branches:
  refs/heads/master 2685ed36c -> 840c2fda8


CLOUDSTACK-7583: Send VmStats to Graphite host when configured

This allows external processing of VmStats information without using
the usage server of CloudStack

Statistics are being send to Graphite using UDP and not TCP.

UDP is used to prevent the management server waiting for TCP timeouts
when the Graphite server is unavailable


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

Branch: refs/heads/master
Commit: 840c2fda852b86f51245a31e7cd91cdb0ad4bf49
Parents: 2685ed3
Author: Wido den Hollander <wido@widodh.nl>
Authored: Fri Sep 19 16:58:00 2014 +0200
Committer: Wido den Hollander <wido@widodh.nl>
Committed: Tue Nov 11 13:04:43 2014 +0100

----------------------------------------------------------------------
 server/src/com/cloud/configuration/Config.java  |   5 +-
 server/src/com/cloud/server/StatsCollector.java | 102 +++++++++++++++
 setup/db/db/schema-441to450.sql                 |   1 -
 setup/db/db/schema-450to460.sql                 |   2 +
 .../utils/graphite/GraphiteClient.java          | 125 +++++++++++++++++++
 .../utils/graphite/GraphiteException.java       |  31 +++++
 6 files changed, 264 insertions(+), 2 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/840c2fda/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 5ac0e90..435b0d8 100755
--- a/server/src/com/cloud/configuration/Config.java
+++ b/server/src/com/cloud/configuration/Config.java
@@ -2056,7 +2056,10 @@ 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.uri",
"", "URI to additionally send StatsCollector statistics to", null);
 
     private final String _category;
     private final Class<?> _componentClass;

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/840c2fda/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..40f78dd 100755
--- a/server/src/com/cloud/server/StatsCollector.java
+++ b/server/src/com/cloud/server/StatsCollector.java
@@ -29,6 +29,9 @@ import java.util.concurrent.Executors;
 import java.util.concurrent.ScheduledExecutorService;
 import java.util.concurrent.TimeUnit;
 
+import java.net.URI;
+import java.net.URISyntaxException;
+
 import javax.inject.Inject;
 
 import org.apache.log4j.Logger;
@@ -43,6 +46,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;
@@ -120,6 +125,20 @@ import com.cloud.vm.dao.VMInstanceDao;
 @Component
 public class StatsCollector extends ManagerBase implements ComponentMethodInterceptable {
 
+    public static enum externalStatsProtocol {
+        NONE("none"), GRAPHITE("graphite");
+        String _type;
+
+        externalStatsProtocol(String type) {
+            _type = type;
+        }
+
+        @Override
+        public String toString() {
+            return _type;
+        }
+    }
+
     public static final Logger s_logger = Logger.getLogger(StatsCollector.class.getName());
 
     private static StatsCollector s_instance = null;
@@ -194,6 +213,12 @@ public class StatsCollector extends ManagerBase implements ComponentMethodInterc
     int vmDiskStatsInterval = 0;
     List<Long> hostIds = null;
 
+    String externalStatsPrefix = "";
+    String externalStatsHost = null;
+    int externalStatsPort = -1;
+    boolean externalStatsEnabled = false;
+    externalStatsProtocol externalStatsType = externalStatsProtocol.NONE;
+
     private ScheduledExecutorService _diskStatsUpdateExecutor;
     private int _usageAggregationRange = 1440;
     private String _usageTimeZone = "GMT";
@@ -233,6 +258,36 @@ 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);
 
+        /* URI to send statistics to. Currently only Graphite is supported */
+        String externalStatsUri = configs.get("stats.output.uri");
+        if (externalStatsUri != null) {
+            try {
+                URI uri = new URI(externalStatsUri);
+                String scheme = uri.getScheme();
+
+                try {
+                    externalStatsType = externalStatsProtocol.valueOf(scheme.toUpperCase());
+                } catch (IllegalArgumentException e) {
+                    s_logger.info(scheme + " is not a valid protocol for external statistics.
No statistics will be send.");
+                }
+
+                externalStatsHost = uri.getHost();
+                externalStatsPort = uri.getPort();
+                externalStatsPrefix = uri.getPath().substring(1);
+
+                /* Append a dot (.) to the prefix if it is set */
+                if (externalStatsPrefix != null && !externalStatsPrefix.equals(""))
{
+                    externalStatsPrefix += ".";
+                } else {
+                    externalStatsPrefix = "";
+                }
+
+                externalStatsEnabled = true;
+            } catch (URISyntaxException e) {
+                s_logger.debug("Failed to parse external statistics URI: " + e.getMessage());
+            }
+        }
+
         if (hostStatsInterval > 0) {
             _executor.scheduleWithFixedDelay(new HostCollector(), 15000L, hostStatsInterval,
TimeUnit.MILLISECONDS);
         }
@@ -372,6 +427,9 @@ public class StatsCollector extends ManagerBase implements ComponentMethodInterc
                 sc.addAnd("type", SearchCriteria.Op.NEQ, Host.Type.SecondaryStorageVM.toString());
                 List<HostVO> hosts = _hostDao.search(sc, null);
 
+                /* HashMap for metrics to be send to Graphite */
+                HashMap metrics = new HashMap<String, Integer>();
+
                 for (HostVO host : hosts) {
                     List<UserVmVO> vms = _userVmDao.listRunningByHostId(host.getId());
                     List<Long> vmIds = new ArrayList<Long>();
@@ -407,6 +465,50 @@ public class StatsCollector extends ManagerBase implements ComponentMethodInterc
 
                                     _VmStats.put(vmId, statsInMemory);
                                 }
+
+                                /**
+                                 * Add statistics to HashMap only when they should be send
to a external stats collector
+                                 * Performance wise it seems best to only append to the HashMap
when needed
+                                */
+                                if (externalStatsEnabled) {
+                                    VMInstanceVO vmVO = _vmInstance.findById(vmId);
+                                    String vmName = vmVO.getUuid();
+
+                                    metrics.put(externalStatsPrefix + "cloudstack.stats.instances."
+ vmName + ".cpu.num", statsForCurrentIteration.getNumCPUs());
+                                    metrics.put(externalStatsPrefix + "cloudstack.stats.instances."
+ vmName + ".cpu.utilization", statsForCurrentIteration.getCPUUtilization());
+                                    metrics.put(externalStatsPrefix + "cloudstack.stats.instances."
+ vmName + ".network.read_kbs", statsForCurrentIteration.getNetworkReadKBs());
+                                    metrics.put(externalStatsPrefix + "cloudstack.stats.instances."
+ vmName + ".network.write_kbs", statsForCurrentIteration.getNetworkWriteKBs());
+                                    metrics.put(externalStatsPrefix + "cloudstack.stats.instances."
+ vmName + ".disk.write_kbs", statsForCurrentIteration.getDiskWriteKBs());
+                                    metrics.put(externalStatsPrefix + "cloudstack.stats.instances."
+ vmName + ".disk.read_kbs", statsForCurrentIteration.getDiskReadKBs());
+                                    metrics.put(externalStatsPrefix + "cloudstack.stats.instances."
+ vmName + ".disk.write_iops", statsForCurrentIteration.getDiskWriteIOs());
+                                    metrics.put(externalStatsPrefix + "cloudstack.stats.instances."
+ vmName + ".disk.read_iops", statsForCurrentIteration.getDiskReadIOs());
+                                }
+
+                            }
+
+                            /**
+                             * Send the metrics to a external stats collector
+                             * We send it on a per-host basis to prevent that we flood the
host
+                             * Currently only Graphite is supported
+                             */
+                            if (!metrics.isEmpty()) {
+                                if (externalStatsType != null && externalStatsType
== externalStatsProtocol.GRAPHITE) {
+
+                                    if (externalStatsPort == -1) {
+                                        externalStatsPort = 2003;
+                                    }
+
+                                    s_logger.debug("Sending VmStats of host " + host.getId()
+ " to Graphite host " + externalStatsHost + ":" + externalStatsPort);
+
+                                    try {
+                                        GraphiteClient g = new GraphiteClient(externalStatsHost,
externalStatsPort);
+                                        g.sendMetrics(metrics);
+                                    } catch (GraphiteException e) {
+                                        s_logger.debug("Failed sending VmStats to Graphite
host " + externalStatsHost + ":" + externalStatsPort + ": " + e.getMessage());
+                                    }
+
+                                    metrics.clear();
+                                }
                             }
                         }
 

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/840c2fda/setup/db/db/schema-441to450.sql
----------------------------------------------------------------------
diff --git a/setup/db/db/schema-441to450.sql b/setup/db/db/schema-441to450.sql
index 0ee6c7f..93d867b 100644
--- a/setup/db/db/schema-441to450.sql
+++ b/setup/db/db/schema-441to450.sql
@@ -769,4 +769,3 @@ ALTER TABLE `cloud_usage`.`usage_vpn_user` CHANGE `user_name` `user_name`
VARCHA
 
 --Increase key value size generated from RSA-8192 to be stored.
 ALTER TABLE `cloud`.`user_vm_details` MODIFY `value` VARCHAR(5120);
-

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/840c2fda/setup/db/db/schema-450to460.sql
----------------------------------------------------------------------
diff --git a/setup/db/db/schema-450to460.sql b/setup/db/db/schema-450to460.sql
index 8da5486..8480c85 100644
--- a/setup/db/db/schema-450to460.sql
+++ b/setup/db/db/schema-450to460.sql
@@ -18,3 +18,5 @@
 --
 -- Schema upgrade from 4.5.0 to 4.6.0
 --
+
+INSERT IGNORE INTO `cloud`.`configuration` VALUES ("Advanced", 'DEFAULT', 'management-server',
"stats.output.uri", "", "URI to additionally send StatsCollector statistics to", "", NULL,
NULL, 0);
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/840c2fda/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..5dca8cb
--- /dev/null
+++ b/utils/src/org/apache/cloudstack/utils/graphite/GraphiteClient.java
@@ -0,0 +1,125 @@
+//
+// 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.net.DatagramPacket;
+import java.net.DatagramSocket;
+import java.net.InetAddress;
+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 UDP 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;
+    }
+
+    /**
+     * 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 {
+            DatagramSocket sock = new DatagramSocket();
+            InetAddress addr = InetAddress.getByName(this.graphiteHost);
+
+            for (Map.Entry<String, Integer> metric: metrics.entrySet()) {
+                byte[] message = new String(metric.getKey() + " " + metric.getValue() + "
" + timeStamp + "\n").getBytes();
+                DatagramPacket packet = new DatagramPacket(message, message.length, addr,
this.graphitePort);
+                sock.send(packet);
+            }
+
+            sock.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/840c2fda/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


Mime
View raw message