python/ovs/socket_util: Fix error path in set_nonblocking.
[openvswitch] / python / ovs / socket_util.py
index 83c82046e903515078c20a084157fc3c4b63fead..f54b9040ae051da61d6382d8fdda29152075ef6e 100644 (file)
@@ -1,4 +1,4 @@
-# Copyright (c) 2010 Nicira Networks
+# Copyright (c) 2010, 2012 Nicira, Inc.
 #
 # Licensed under the Apache License, Version 2.0 (the "License");
 # you may not use this file except in compliance with the License.
@@ -19,6 +19,7 @@ import socket
 import sys
 
 import ovs.fatal_signal
+import ovs.poller
 import ovs.vlog
 
 vlog = ovs.vlog.Vlog("socket_util")
@@ -69,24 +70,55 @@ def make_unix_socket(style, nonblock, bind_path, connect_path):
         return 0, sock
     except socket.error, e:
         sock.close()
-        try:
-            os.unlink(bind_path)
-        except OSError, e:
-            pass
         if bind_path is not None:
-            ovs.fatal_signal.add_file_to_unlink(bind_path)
+            ovs.fatal_signal.unlink_file_now(bind_path)
         return get_exception_errno(e), None
 
 
 def check_connection_completion(sock):
-    p = select.poll()
-    p.register(sock, select.POLLOUT)
+    p = ovs.poller.SelectPoll()
+    p.register(sock, ovs.poller.POLLOUT)
     if len(p.poll(0)) == 1:
         return get_socket_error(sock)
     else:
         return errno.EAGAIN
 
 
+def inet_parse_active(target, default_port):
+    address = target.split(":")
+    host_name = address[0]
+    if not host_name:
+        raise ValueError("%s: bad peer name format" % target)
+    if len(address) >= 2:
+        port = int(address[1])
+    elif default_port:
+        port = default_port
+    else:
+        raise ValueError("%s: port number must be specified" % target)
+    return (host_name, port)
+
+
+def inet_open_active(style, target, default_port, dscp):
+    address = inet_parse_active(target, default_port)
+    try:
+        sock = socket.socket(socket.AF_INET, style, 0)
+    except socket.error, e:
+        return get_exception_errno(e), None
+
+    try:
+        set_nonblocking(sock)
+        set_dscp(sock, dscp)
+        try:
+            sock.connect(address)
+        except socket.error, e:
+            if get_exception_errno(e) != errno.EINPROGRESS:
+                raise
+        return 0, sock
+    except socket.error, e:
+        sock.close()
+        return get_exception_errno(e), None
+
+
 def get_socket_error(sock):
     """Returns the errno value associated with 'socket' (0 if no error) and
     resets the socket's error status."""
@@ -150,4 +182,11 @@ def set_nonblocking(sock):
         sock.setblocking(0)
     except socket.error, e:
         vlog.err("could not set nonblocking mode on socket: %s"
-                 % os.strerror(get_socket_error(e)))
+                 % os.strerror(get_exception_errno(e)))
+
+
+def set_dscp(sock, dscp):
+    if dscp > 63:
+        raise ValueError("Invalid dscp %d" % dscp)
+    val = dscp << 2
+    sock.setsockopt(socket.IPPROTO_IP, socket.IP_TOS, val)