Implement initial Python bindings for Open vSwitch database.
[sliver-openvswitch.git] / python / ovs / socket_util.py
1 # Copyright (c) 2010 Nicira Networks
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at:
6 #
7 #     http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 import errno
16 import logging
17 import os
18 import select
19 import socket
20 import sys
21
22 import ovs.fatal_signal
23
24 def make_unix_socket(style, nonblock, bind_path, connect_path):
25     """Creates a Unix domain socket in the given 'style' (either
26     socket.SOCK_DGRAM or socket.SOCK_STREAM) that is bound to 'bind_path' (if
27     'bind_path' is not None) and connected to 'connect_path' (if 'connect_path'
28     is not None).  If 'nonblock' is true, the socket is made non-blocking.
29
30     Returns (error, socket): on success 'error' is 0 and 'socket' is a new
31     socket object, on failure 'error' is a positive errno value and 'socket' is
32     None."""
33
34     try:
35         sock = socket.socket(socket.AF_UNIX, style)
36     except socket.error, e:
37         return get_exception_errno(e), None
38
39     try:
40         if nonblock:
41             set_nonblocking(sock)
42         if bind_path is not None:
43             # Delete bind_path but ignore ENOENT.
44             try:
45                 os.unlink(bind_path)
46             except OSError, e:
47                 if e.errno != errno.ENOENT:
48                     return e.errno, None
49
50             ovs.fatal_signal.add_file_to_unlink(bind_path)
51             sock.bind(bind_path)
52
53             try:
54                 if sys.hexversion >= 0x02060000:
55                     os.fchmod(sock.fileno(), 0700)
56                 else:
57                     os.chmod("/dev/fd/%d" % sock.fileno(), 0700)
58             except OSError, e:
59                 pass
60         if connect_path is not None:
61             try:
62                 sock.connect(connect_path)
63             except socket.error, e:
64                 if get_exception_errno(e) != errno.EINPROGRESS:
65                     raise
66         return 0, sock
67     except socket.error, e:
68         sock.close()
69         try:
70             os.unlink(bind_path)
71         except OSError, e:
72             pass
73         if bind_path is not None:
74             ovs.fatal_signal.add_file_to_unlink(bind_path)
75         return get_exception_errno(e), None
76
77 def check_connection_completion(sock):
78     p = select.poll()
79     p.register(sock, select.POLLOUT)
80     if len(p.poll(0)) == 1:
81         return get_socket_error(sock)
82     else:
83         return errno.EAGAIN
84
85 def get_socket_error(sock):
86     """Returns the errno value associated with 'socket' (0 if no error) and
87     resets the socket's error status."""
88     return sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
89
90 def get_exception_errno(e):
91     """A lot of methods on Python socket objects raise socket.error, but that
92     exception is documented as having two completely different forms of
93     arguments: either a string or a (errno, string) tuple.  We only want the
94     errno."""
95     if type(e.args) == tuple:
96         return e.args[0]
97     else:
98         return errno.EPROTO
99
100 null_fd = -1
101 def get_null_fd():
102     """Returns a readable and writable fd for /dev/null, if successful,
103     otherwise a negative errno value.  The caller must not close the returned
104     fd (because the same fd will be handed out to subsequent callers)."""
105     global null_fd
106     if null_fd < 0:
107         try:
108             null_fd = os.open("/dev/null", os.O_RDWR)
109         except OSError, e:
110             logging.error("could not open /dev/null: %s"
111                           % os.strerror(e.errno))
112             return -e.errno
113     return null_fd
114
115 def write_fully(fd, buf):
116     """Returns an (error, bytes_written) tuple where 'error' is 0 on success,
117     otherwise a positive errno value, and 'bytes_written' is the number of
118     bytes that were written before the error occurred.  'error' is 0 if and
119     only if 'bytes_written' is len(buf)."""
120     bytes_written = 0
121     if len(buf) == 0:
122         return 0, 0
123     while True:
124         try:
125             retval = os.write(fd, buf)
126             assert retval >= 0
127             if retval == len(buf):
128                 return 0, bytes_written + len(buf)
129             elif retval == 0:
130                 logging.warning("write returned 0")
131                 return errno.EPROTO, bytes_written
132             else:
133                 bytes_written += retval
134                 buf = buf[:retval]
135         except OSError, e:
136             return e.errno, bytes_written
137
138 def set_nonblocking(sock):
139     try:
140         sock.setblocking(0)
141     except socket.error, e:
142         logging.error("could not set nonblocking mode on socket: %s"
143                       % os.strerror(get_socket_error(e)))