cloudstack-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From bfede...@apache.org
Subject [17/50] [abbrv] git commit: updated refs/heads/ui-restyle to 326b3a6
Date Tue, 10 Dec 2013 23:51:57 GMT
move cloudstack_pluginlib


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

Branch: refs/heads/ui-restyle
Commit: c7dab82dc48b1e33683122ae6663a7bda7fb7ac7
Parents: 32c55e6
Author: tuna <ng.tuna@gmail.com>
Authored: Wed Oct 30 16:32:19 2013 +0700
Committer: tuna <ng.tuna@gmail.com>
Committed: Mon Dec 9 23:33:15 2013 +0700

----------------------------------------------------------------------
 .../kvm/resource/LibvirtComputingResource.java  |  29 +--
 .../vm/hypervisor/kvm/cloudstack_pluginlib.py   | 219 -------------------
 scripts/vm/network/vnet/cloudstack_pluginlib.py | 219 +++++++++++++++++++
 scripts/vm/network/vnet/ovstunnel.py            |  81 +++++--
 4 files changed, 290 insertions(+), 258 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/c7dab82d/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
index 9a680ac..cbe4de3 100755
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
@@ -1344,14 +1344,12 @@ public class LibvirtComputingResource extends ServerResourceBase implements
Serv
 			cmd.add("destroy_ovs_bridge");
 			cmd.add("--bridge", bridge);
 			String result = cmd.execute();
-			String[] res = result.split(":");
-			if (res.length != 2 || !res[0].equalsIgnoreCase("SUCCESS")) {
+			if (result != null) {
 				// TODO: Should make this error not fatal?
 				// Can Concurrent VM shutdown/migration/reboot events can cause
 				// this method
 				// to be executed on a bridge which has already been removed?
-				throw new CloudRuntimeException("Unable to remove OVS bridge "
-						+ bridge + ":" + res);
+				throw new CloudRuntimeException("Unable to remove OVS bridge " + bridge);
 			}
 			return;
 		} catch (Exception e) {
@@ -1360,16 +1358,10 @@ public class LibvirtComputingResource extends ServerResourceBase implements
Serv
 		}
 	}
 
-	private boolean networkExist(String nwName) {
-		Script.runSimpleBashScript("ifconfig " + nwName);
-		String result = Script.runSimpleBashScript("echo $?");
-		return result.equals("0");
-	}
-
 	private synchronized boolean findOrCreateTunnelNetwork(long key) {
 		try {
 			String nwName = "OVSTunnel" + key;
-			if (networkExist(nwName)) {
+			if (checkNetwork(nwName)) {
 				return true;
 			}
 			// if not found, create a new one
@@ -1377,7 +1369,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements
Serv
 			otherConfig.put("ovs-host-setup", "");
 			Script.runSimpleBashScript("ovs-vsctl -- --may-exist add-br "
 					+ nwName + " -- set bridge " + nwName
-					+ " other_config:ovs_host_setup=\" \"");
+					+ " other_config:ovs_host_setup='-1'");
 			s_logger.debug("### KVM network for tunnels created:" + nwName);
 		} catch (Exception e) {
 			s_logger.warn("createTunnelNetwork failed", e);
@@ -1410,12 +1402,10 @@ public class LibvirtComputingResource extends ServerResourceBase implements
Serv
 				cmd.add("--cs_host_id", ((Long) hostId).toString());
 				cmd.add("--bridge", nwName);
 				String result = cmd.execute();
-				String[] res = result.split(":");
-				if (res.length != 2 || !res[0].equalsIgnoreCase("SUCCESS")) {
+				if (result != null) {
 					throw new CloudRuntimeException(
 							"Unable to pre-configure OVS bridge " + nwName
-									+ " for network ID:" + networkId + " - "
-									+ res);
+									+ " for network ID:" + networkId);
 				}
 			}
 		} catch (Exception e) {
@@ -1445,9 +1435,8 @@ public class LibvirtComputingResource extends ServerResourceBase implements
Serv
 			command.add("--dst_host", cmd.getTo().toString());
 
 			String result = command.execute();
-			String[] res = result.split(":");
-			if (res.length == 2 && res[0].equalsIgnoreCase("SUCCESS")) {
-				return new OvsCreateTunnelAnswer(cmd, true, result, res[1],
+			if (result != null) {
+				return new OvsCreateTunnelAnswer(cmd, true, result, null,
 						bridge);
 			} else {
 				return new OvsCreateTunnelAnswer(cmd, false, result, bridge);
@@ -1473,7 +1462,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements
Serv
 			command.add("--bridge", bridge);
 			command.add("--iface_name", cmd.getInPortName());
 			String result = command.execute();
-			if (result.equalsIgnoreCase("SUCCESS")) {
+			if (result == null) {
 				return new Answer(cmd, true, result);
 			} else {
 				return new Answer(cmd, false, result);

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/c7dab82d/scripts/vm/hypervisor/kvm/cloudstack_pluginlib.py
----------------------------------------------------------------------
diff --git a/scripts/vm/hypervisor/kvm/cloudstack_pluginlib.py b/scripts/vm/hypervisor/kvm/cloudstack_pluginlib.py
deleted file mode 100755
index f886aa3..0000000
--- a/scripts/vm/hypervisor/kvm/cloudstack_pluginlib.py
+++ /dev/null
@@ -1,219 +0,0 @@
-# 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.
-
-# cloudstack_pluginlib for openvswitch on KVM hypervisor
-
-import ConfigParser
-import logging
-import os
-import subprocess
-
-from time import localtime, asctime
-
-DEFAULT_LOG_FORMAT = "%(asctime)s %(levelname)8s [%(name)s] %(message)s"
-DEFAULT_LOG_DATE_FORMAT = "%Y-%m-%d %H:%M:%S"
-DEFAULT_LOG_FILE = "/var/log/cloudstack_plugins.log"
-
-PLUGIN_CONFIG_PATH = "/usr/share/cloudstack-common/scripts/vm/hypervisor/xenserver/cloudstack_plugins.conf"
-OVSDB_PID_PATH = "/var/run/openvswitch/ovsdb-server.pid"
-OVSDB_DAEMON_PATH = "ovsdb-server"
-OVS_PID_PATH = "/var/run/openvswitch/ovs-vswitchd.pid"
-OVS_DAEMON_PATH = "ovs-vswitchd"
-VSCTL_PATH = "/usr/bin/ovs-vsctl"
-OFCTL_PATH = "/usr/bin/ovs-ofctl"
-
-class PluginError(Exception):
-    """Base Exception class for all plugin errors."""
-    def __init__(self, *args):
-        Exception.__init__(self, *args)
-
-
-def setup_logging(log_file=None):
-    debug = False
-    verbose = False
-    log_format = DEFAULT_LOG_FORMAT
-    log_date_format = DEFAULT_LOG_DATE_FORMAT
-    # try to read plugin configuration file
-    if os.path.exists(PLUGIN_CONFIG_PATH):
-        config = ConfigParser.ConfigParser()
-        config.read(PLUGIN_CONFIG_PATH)
-        try:
-            options = config.options('LOGGING')
-            if 'debug' in options:
-                debug = config.getboolean('LOGGING', 'debug')
-            if 'verbose' in options:
-                verbose = config.getboolean('LOGGING', 'verbose')
-            if 'format' in options:
-                log_format = config.get('LOGGING', 'format')
-            if 'date_format' in options:
-                log_date_format = config.get('LOGGING', 'date_format')
-            if 'file' in options:
-                log_file_2 = config.get('LOGGING', 'file')
-        except ValueError:
-            # configuration file contained invalid attributes
-            # ignore them
-            pass
-        except ConfigParser.NoSectionError:
-            # Missing 'Logging' section in configuration file
-            pass
-
-    root_logger = logging.root
-    if debug:
-        root_logger.setLevel(logging.DEBUG)
-    elif verbose:
-        root_logger.setLevel(logging.INFO)
-    else:
-        root_logger.setLevel(logging.WARNING)
-    formatter = logging.Formatter(log_format, log_date_format)
-
-    log_filename = log_file or log_file_2 or DEFAULT_LOG_FILE
-
-    logfile_handler = logging.FileHandler(log_filename)
-    logfile_handler.setFormatter(formatter)
-    root_logger.addHandler(logfile_handler)
-
-
-def do_cmd(cmd):
-    """Abstracts out the basics of issuing system commands. If the command
-    returns anything in stderr, a PluginError is raised with that information.
-    Otherwise, the output from stdout is returned.
-    """
-
-    pipe = subprocess.PIPE
-    logging.debug("Executing:%s", cmd)
-    proc = subprocess.Popen(cmd, shell=False, stdin=pipe, stdout=pipe,
-                            stderr=pipe, close_fds=True)
-    ret_code = proc.wait()
-    err = proc.stderr.read()
-    if ret_code:
-        logging.debug("The command exited with the error code: " +
-                      "%s (stderr output:%s)" % (ret_code, err))
-        raise PluginError(err)
-    output = proc.stdout.read()
-    if output.endswith('\n'):
-        output = output[:-1]
-    return output
-
-
-def _is_process_run(pidFile, name):
-    try:
-        fpid = open(pidFile, "r")
-        pid = fpid.readline()
-        fpid.close()
-    except IOError, e:
-        return -1
-
-    pid = pid[:-1]
-    ps = os.popen("ps -ae")
-    for l in ps:
-        if pid in l and name in l:
-            ps.close()
-            return 0
-
-    ps.close()
-    return -2
-
-
-def _is_tool_exist(name):
-    if os.path.exists(name):
-        return 0
-    return -1
-
-
-def check_switch():
-    global result
-
-    ret = _is_process_run(OVSDB_PID_PATH, OVSDB_DAEMON_PATH)
-    if ret < 0:
-        if ret == -1:
-            return "NO_DB_PID_FILE"
-        if ret == -2:
-            return "DB_NOT_RUN"
-
-    ret = _is_process_run(OVS_PID_PATH, OVS_DAEMON_PATH)
-    if ret < 0:
-        if ret == -1:
-            return "NO_SWITCH_PID_FILE"
-        if ret == -2:
-            return "SWITCH_NOT_RUN"
-
-    if _is_tool_exist(VSCTL_PATH) < 0:
-        return "NO_VSCTL"
-
-    if _is_tool_exist(OFCTL_PATH) < 0:
-        return "NO_OFCTL"
-
-    return "SUCCESS"
-
-
-def _build_flow_expr(**kwargs):
-    is_delete_expr = kwargs.get('delete', False)
-    flow = ""
-    if not is_delete_expr:
-        flow = "hard_timeout=%s,idle_timeout=%s,priority=%s"\
-                % (kwargs.get('hard_timeout', '0'),
-                   kwargs.get('idle_timeout', '0'),
-                   kwargs.get('priority', '1'))
-    in_port = 'in_port' in kwargs and ",in_port=%s" % kwargs['in_port'] or ''
-    dl_type = 'dl_type' in kwargs and ",dl_type=%s" % kwargs['dl_type'] or ''
-    dl_src = 'dl_src' in kwargs and ",dl_src=%s" % kwargs['dl_src'] or ''
-    dl_dst = 'dl_dst' in kwargs and ",dl_dst=%s" % kwargs['dl_dst'] or ''
-    nw_src = 'nw_src' in kwargs and ",nw_src=%s" % kwargs['nw_src'] or ''
-    nw_dst = 'nw_dst' in kwargs and ",nw_dst=%s" % kwargs['nw_dst'] or ''
-    proto = 'proto' in kwargs and ",%s" % kwargs['proto'] or ''
-    ip = ('nw_src' in kwargs or 'nw_dst' in kwargs) and ',ip' or ''
-    flow = (flow + in_port + dl_type + dl_src + dl_dst +
-            (ip or proto) + nw_src + nw_dst)
-    return flow
-
-
-def add_flow(bridge, **kwargs):
-    """
-    Builds a flow expression for **kwargs and adds the flow entry
-    to an Open vSwitch instance
-    """
-    flow = _build_flow_expr(**kwargs)
-    actions = 'actions' in kwargs and ",actions=%s" % kwargs['actions'] or ''
-    flow = flow + actions
-    addflow = [OFCTL_PATH, "add-flow", bridge, flow]
-    do_cmd(addflow)
-
-
-def del_flows(bridge, **kwargs):
-    """
-    Removes flows according to criteria passed as keyword.
-    """
-    flow = _build_flow_expr(delete=True, **kwargs)
-    # out_port condition does not exist for all flow commands
-    out_port = ("out_port" in kwargs and
-                ",out_port=%s" % kwargs['out_port'] or '')
-    flow = flow + out_port
-    delFlow = [OFCTL_PATH, 'del-flows', bridge, flow]
-    do_cmd(delFlow)
-
-
-def del_all_flows(bridge):
-    delFlow = [OFCTL_PATH, "del-flows", bridge]
-    do_cmd(delFlow)
-
-    normalFlow = "priority=0 idle_timeout=0 hard_timeout=0 actions=normal"
-    add_flow(bridge, normalFlow)
-
-
-def del_port(bridge, port):
-    delPort = [VSCTL_PATH, "del-port", bridge, port]
-    do_cmd(delPort)

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/c7dab82d/scripts/vm/network/vnet/cloudstack_pluginlib.py
----------------------------------------------------------------------
diff --git a/scripts/vm/network/vnet/cloudstack_pluginlib.py b/scripts/vm/network/vnet/cloudstack_pluginlib.py
new file mode 100755
index 0000000..f886aa3
--- /dev/null
+++ b/scripts/vm/network/vnet/cloudstack_pluginlib.py
@@ -0,0 +1,219 @@
+# 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.
+
+# cloudstack_pluginlib for openvswitch on KVM hypervisor
+
+import ConfigParser
+import logging
+import os
+import subprocess
+
+from time import localtime, asctime
+
+DEFAULT_LOG_FORMAT = "%(asctime)s %(levelname)8s [%(name)s] %(message)s"
+DEFAULT_LOG_DATE_FORMAT = "%Y-%m-%d %H:%M:%S"
+DEFAULT_LOG_FILE = "/var/log/cloudstack_plugins.log"
+
+PLUGIN_CONFIG_PATH = "/usr/share/cloudstack-common/scripts/vm/hypervisor/xenserver/cloudstack_plugins.conf"
+OVSDB_PID_PATH = "/var/run/openvswitch/ovsdb-server.pid"
+OVSDB_DAEMON_PATH = "ovsdb-server"
+OVS_PID_PATH = "/var/run/openvswitch/ovs-vswitchd.pid"
+OVS_DAEMON_PATH = "ovs-vswitchd"
+VSCTL_PATH = "/usr/bin/ovs-vsctl"
+OFCTL_PATH = "/usr/bin/ovs-ofctl"
+
+class PluginError(Exception):
+    """Base Exception class for all plugin errors."""
+    def __init__(self, *args):
+        Exception.__init__(self, *args)
+
+
+def setup_logging(log_file=None):
+    debug = False
+    verbose = False
+    log_format = DEFAULT_LOG_FORMAT
+    log_date_format = DEFAULT_LOG_DATE_FORMAT
+    # try to read plugin configuration file
+    if os.path.exists(PLUGIN_CONFIG_PATH):
+        config = ConfigParser.ConfigParser()
+        config.read(PLUGIN_CONFIG_PATH)
+        try:
+            options = config.options('LOGGING')
+            if 'debug' in options:
+                debug = config.getboolean('LOGGING', 'debug')
+            if 'verbose' in options:
+                verbose = config.getboolean('LOGGING', 'verbose')
+            if 'format' in options:
+                log_format = config.get('LOGGING', 'format')
+            if 'date_format' in options:
+                log_date_format = config.get('LOGGING', 'date_format')
+            if 'file' in options:
+                log_file_2 = config.get('LOGGING', 'file')
+        except ValueError:
+            # configuration file contained invalid attributes
+            # ignore them
+            pass
+        except ConfigParser.NoSectionError:
+            # Missing 'Logging' section in configuration file
+            pass
+
+    root_logger = logging.root
+    if debug:
+        root_logger.setLevel(logging.DEBUG)
+    elif verbose:
+        root_logger.setLevel(logging.INFO)
+    else:
+        root_logger.setLevel(logging.WARNING)
+    formatter = logging.Formatter(log_format, log_date_format)
+
+    log_filename = log_file or log_file_2 or DEFAULT_LOG_FILE
+
+    logfile_handler = logging.FileHandler(log_filename)
+    logfile_handler.setFormatter(formatter)
+    root_logger.addHandler(logfile_handler)
+
+
+def do_cmd(cmd):
+    """Abstracts out the basics of issuing system commands. If the command
+    returns anything in stderr, a PluginError is raised with that information.
+    Otherwise, the output from stdout is returned.
+    """
+
+    pipe = subprocess.PIPE
+    logging.debug("Executing:%s", cmd)
+    proc = subprocess.Popen(cmd, shell=False, stdin=pipe, stdout=pipe,
+                            stderr=pipe, close_fds=True)
+    ret_code = proc.wait()
+    err = proc.stderr.read()
+    if ret_code:
+        logging.debug("The command exited with the error code: " +
+                      "%s (stderr output:%s)" % (ret_code, err))
+        raise PluginError(err)
+    output = proc.stdout.read()
+    if output.endswith('\n'):
+        output = output[:-1]
+    return output
+
+
+def _is_process_run(pidFile, name):
+    try:
+        fpid = open(pidFile, "r")
+        pid = fpid.readline()
+        fpid.close()
+    except IOError, e:
+        return -1
+
+    pid = pid[:-1]
+    ps = os.popen("ps -ae")
+    for l in ps:
+        if pid in l and name in l:
+            ps.close()
+            return 0
+
+    ps.close()
+    return -2
+
+
+def _is_tool_exist(name):
+    if os.path.exists(name):
+        return 0
+    return -1
+
+
+def check_switch():
+    global result
+
+    ret = _is_process_run(OVSDB_PID_PATH, OVSDB_DAEMON_PATH)
+    if ret < 0:
+        if ret == -1:
+            return "NO_DB_PID_FILE"
+        if ret == -2:
+            return "DB_NOT_RUN"
+
+    ret = _is_process_run(OVS_PID_PATH, OVS_DAEMON_PATH)
+    if ret < 0:
+        if ret == -1:
+            return "NO_SWITCH_PID_FILE"
+        if ret == -2:
+            return "SWITCH_NOT_RUN"
+
+    if _is_tool_exist(VSCTL_PATH) < 0:
+        return "NO_VSCTL"
+
+    if _is_tool_exist(OFCTL_PATH) < 0:
+        return "NO_OFCTL"
+
+    return "SUCCESS"
+
+
+def _build_flow_expr(**kwargs):
+    is_delete_expr = kwargs.get('delete', False)
+    flow = ""
+    if not is_delete_expr:
+        flow = "hard_timeout=%s,idle_timeout=%s,priority=%s"\
+                % (kwargs.get('hard_timeout', '0'),
+                   kwargs.get('idle_timeout', '0'),
+                   kwargs.get('priority', '1'))
+    in_port = 'in_port' in kwargs and ",in_port=%s" % kwargs['in_port'] or ''
+    dl_type = 'dl_type' in kwargs and ",dl_type=%s" % kwargs['dl_type'] or ''
+    dl_src = 'dl_src' in kwargs and ",dl_src=%s" % kwargs['dl_src'] or ''
+    dl_dst = 'dl_dst' in kwargs and ",dl_dst=%s" % kwargs['dl_dst'] or ''
+    nw_src = 'nw_src' in kwargs and ",nw_src=%s" % kwargs['nw_src'] or ''
+    nw_dst = 'nw_dst' in kwargs and ",nw_dst=%s" % kwargs['nw_dst'] or ''
+    proto = 'proto' in kwargs and ",%s" % kwargs['proto'] or ''
+    ip = ('nw_src' in kwargs or 'nw_dst' in kwargs) and ',ip' or ''
+    flow = (flow + in_port + dl_type + dl_src + dl_dst +
+            (ip or proto) + nw_src + nw_dst)
+    return flow
+
+
+def add_flow(bridge, **kwargs):
+    """
+    Builds a flow expression for **kwargs and adds the flow entry
+    to an Open vSwitch instance
+    """
+    flow = _build_flow_expr(**kwargs)
+    actions = 'actions' in kwargs and ",actions=%s" % kwargs['actions'] or ''
+    flow = flow + actions
+    addflow = [OFCTL_PATH, "add-flow", bridge, flow]
+    do_cmd(addflow)
+
+
+def del_flows(bridge, **kwargs):
+    """
+    Removes flows according to criteria passed as keyword.
+    """
+    flow = _build_flow_expr(delete=True, **kwargs)
+    # out_port condition does not exist for all flow commands
+    out_port = ("out_port" in kwargs and
+                ",out_port=%s" % kwargs['out_port'] or '')
+    flow = flow + out_port
+    delFlow = [OFCTL_PATH, 'del-flows', bridge, flow]
+    do_cmd(delFlow)
+
+
+def del_all_flows(bridge):
+    delFlow = [OFCTL_PATH, "del-flows", bridge]
+    do_cmd(delFlow)
+
+    normalFlow = "priority=0 idle_timeout=0 hard_timeout=0 actions=normal"
+    add_flow(bridge, normalFlow)
+
+
+def del_port(bridge, port):
+    delPort = [VSCTL_PATH, "del-port", bridge, port]
+    do_cmd(delPort)

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/c7dab82d/scripts/vm/network/vnet/ovstunnel.py
----------------------------------------------------------------------
diff --git a/scripts/vm/network/vnet/ovstunnel.py b/scripts/vm/network/vnet/ovstunnel.py
index 67ef89b..225876a 100755
--- a/scripts/vm/network/vnet/ovstunnel.py
+++ b/scripts/vm/network/vnet/ovstunnel.py
@@ -27,16 +27,16 @@ import os
 import sys
 import subprocess
 import time
+from optparse import OptionParser, OptionGroup, OptParseError, BadOptionError, OptionError,
OptionConflictError, OptionValueError
 
 from time import localtime as _localtime, asctime as _asctime
 
-lib.setup_logging("/var/log/ovstunnel.log")
-
 def setup_ovs_bridge(bridge, key, cs_host_id):
 
     res = lib.check_switch()
     if res != "SUCCESS":
-        return "FAILURE:%s" % res
+        #return "FAILURE:%s" % res
+	return 'false'
 
     logging.debug("About to manually create the bridge:%s" % bridge)
     #set gre_key to bridge
@@ -44,15 +44,18 @@ def setup_ovs_bridge(bridge, key, cs_host_id):
                                      "other_config:gre_key=%s" % key])
     logging.debug("Bridge has been manually created:%s" % res)
     if res:
-        result = "FAILURE:%s" % res
+#        result = "FAILURE:%s" % res
+	result = 'false'
     else:
         # Verify the bridge actually exists, with the gre_key properly set
         res = lib.do_cmd([lib.VSCTL_PATH, "get", "bridge",
                                           bridge, "other_config:gre_key"])
         if key in res:
-            result = "SUCCESS:%s" % bridge
+#            result = "SUCCESS:%s" % bridge
+            result = 'true'
         else:
-            result = "FAILURE:%s" % res
+#            result = "FAILURE:%s" % res
+            result = 'false'
 
 	lib.do_cmd([lib.VSCTL_PATH, "set", "bridge", bridge, "other_config:is-ovs-tun-network=True"])
 	#get list of hosts using this bridge
@@ -69,29 +72,34 @@ def destroy_ovs_bridge(bridge):
 
     res = lib.check_switch()
     if res != "SUCCESS":
-        return res
+#        return res
+        return 'false'
+
     res = lib.do_cmd([lib.VSCTL_PATH, "del-br", bridge])
     logging.debug("Bridge has been manually removed:%s" % res)
     if res:
-        result = "FAILURE:%s" % res
+#        result = "FAILURE:%s" % res
+        result = 'false'
     else:
-        result = "SUCCESS:%s" % bridge
+#        result = "SUCCESS:%s" % bridge
+        result = 'true'
 
     logging.debug("Destroy_ovs_bridge completed with result:%s" % result)
     return result
 
-def create_tunnel(bridge, remote_ip, gre_key, src_host, dst_host):
+def create_tunnel(bridge, remote_ip, key, src_host, dst_host):
 
     logging.debug("Entering create_tunnel")
 
     res = lib.check_switch()
     if res != "SUCCESS":
         logging.debug("Openvswitch running: NO")
-        return "FAILURE:%s" % res
+#        return "FAILURE:%s" % res
+        return 'false'
 
     # We need to keep the name below 14 characters
     # src and target are enough - consider a fixed length hash
-    name = "t%s-%s-%s" % (gre_key, src_host, dst_host)
+    name = "t%s-%s-%s" % (key, src_host, dst_host)
 
     # Verify the bridge to be created
     # NOTE: Timeout should not be necessary anymore
@@ -101,7 +109,9 @@ def create_tunnel(bridge, remote_ip, gre_key, src_host, dst_host):
     if bridge not in res:
         logging.debug("WARNING:Can't find bridge %s for creating " +
                                   "tunnel!" % bridge)
-        return "FAILURE:NO_BRIDGE"
+#        return "FAILURE:NO_BRIDGE"
+        return 'false'
+
     logging.debug("bridge %s for creating tunnel - VERIFIED" % bridge)
     tunnel_setup = False
     drop_flow_setup = False
@@ -109,7 +119,7 @@ def create_tunnel(bridge, remote_ip, gre_key, src_host, dst_host):
         # Create a port and configure the tunnel interface for it
         add_tunnel = [lib.VSCTL_PATH, "add-port", bridge,
                                   name, "--", "set", "interface",
-                                  name, "type=gre", "options:key=%s" % gre_key,
+                                  name, "type=gre", "options:key=%s" % key,
                                   "options:remote_ip=%s" % remote_ip]
         lib.do_cmd(add_tunnel)
         tunnel_setup = True
@@ -123,7 +133,8 @@ def create_tunnel(bridge, remote_ip, gre_key, src_host, dst_host):
         if len(iface_list) != 1:
             logging.debug("WARNING: Unexpected output while verifying " +
                                       "port %s on bridge %s" % (name, bridge))
-            return "FAILURE:VERIFY_PORT_FAILED"
+#            return "FAILURE:VERIFY_PORT_FAILED"
+            return 'false'
 
         # verify interface
         iface_uuid = iface_list[0]
@@ -135,10 +146,12 @@ def create_tunnel(bridge, remote_ip, gre_key, src_host, dst_host):
         key_validation = lib.do_cmd(verify_interface_key)
         ip_validation = lib.do_cmd(verify_interface_ip)
 
-        if not gre_key in key_validation or not remote_ip in ip_validation:
+        if not key in key_validation or not remote_ip in ip_validation:
             logging.debug("WARNING: Unexpected output while verifying " +
                           "interface %s on bridge %s" % (name, bridge))
-            return "FAILURE:VERIFY_INTERFACE_FAILED"
+#            return "FAILURE:VERIFY_INTERFACE_FAILED"
+            return 'false'
+
         logging.debug("Tunnel interface validated:%s" % verify_interface_ip)
         cmd_tun_ofport = [lib.VSCTL_PATH, "get", "interface",
                                           iface_uuid, "ofport"]
@@ -153,7 +166,8 @@ def create_tunnel(bridge, remote_ip, gre_key, src_host, dst_host):
                      nw_dst='224.0.0.0/24', actions='drop')
         drop_flow_setup = True
         logging.debug("Broadcast drop rules added")
-        return "SUCCESS:%s" % name
+#        return "SUCCESS:%s" % name
+        return 'true'
     except:
         logging.debug("An unexpected error occured. Rolling back")
         if tunnel_setup:
@@ -174,9 +188,38 @@ def destroy_tunnel(bridge, iface_name):
     ofport = get_field_of_interface(iface_name, "ofport")
     lib.del_flows(bridge, in_port=ofport)
     lib.del_port(bridge, iface_name)
-    return "SUCCESS"
+#    return "SUCCESS"
+    return 'true'
 
 def get_field_of_interface(iface_name, field):
     get_iface_cmd = [lib.VSCTL_PATH, "get", "interface", iface_name, field]
     res = lib.do_cmd(get_iface_cmd)
     return res
+
+if __name__ == '__main__':
+    logging.basicConfig(filename="/var/log/cloudstack/agent/ovstunnel.log", format="%(asctime)s
- %(message)s", level=logging.DEBUG)
+    parser = OptionParser()
+    parser.add_option("--key", dest="key")
+    parser.add_option("--cs_host_id", dest="cs_host_id")
+    parser.add_option("--bridge", dest="bridge")
+    parser.add_option("--remote_ip", dest="remote_ip")
+    parser.add_option("--src_host", dest="src_host")
+    parser.add_option("--dst_host", dest="dst_host")
+    parser.add_option("--iface_name", dest="iface_name")
+    (option, args) = parser.parse_args()
+    if len(args) == 0:
+        logging.debug("No command to execute")
+        sys.exit(1)
+    cmd = args[0]
+    if cmd == "setup_ovs_bridge":
+        setup_ovs_bridge(option.bridge, option.key, option.cs_host_id)
+    elif cmd == "destroy_ovs_bridge":
+        destroy_ovs_bridge(option.bridge)
+    elif cmd == "create_tunnel":
+        create_tunnel(option.bridge, option.remote_ip, option.key, option.src_host, option.dst_host)
+    elif cmd == "destroy_tunnel":
+        destroy_tunnel(option.bridge, option.iface_name)
+    else:
+        logging.debug("Unknown command: " + cmd)
+        sys.exit(1)
+


Mime
View raw message