python: Break unixctl implementation into registry, client, and server.
[sliver-openvswitch.git] / python / ovs / unixctl / client.py
1 # Copyright (c) 2011, 2012 Nicira, Inc.
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 copy
16 import errno
17 import os
18 import types
19
20 import ovs.jsonrpc
21 import ovs.stream
22 import ovs.util
23
24
25 vlog = ovs.vlog.Vlog("unixctl_client")
26 strtypes = types.StringTypes
27
28
29 class UnixctlClient(object):
30     def __init__(self, conn):
31         assert isinstance(conn, ovs.jsonrpc.Connection)
32         self._conn = conn
33
34     def transact(self, command, argv):
35         assert isinstance(command, strtypes)
36         assert isinstance(argv, list)
37         for arg in argv:
38             assert isinstance(arg, strtypes)
39
40         request = ovs.jsonrpc.Message.create_request(command, argv)
41         error, reply = self._conn.transact_block(request)
42
43         if error:
44             vlog.warn("error communicating with %s: %s"
45                       % (self._conn.name, os.strerror(error)))
46             return error, None, None
47
48         if reply.error is not None:
49             return 0, str(reply.error), None
50         else:
51             assert reply.result is not None
52             return 0, None, str(reply.result)
53
54     def close(self):
55         self._conn.close()
56         self.conn = None
57
58     @staticmethod
59     def create(path):
60         assert isinstance(path, str)
61
62         unix = "unix:%s" % ovs.util.abs_file_name(ovs.dirs.RUNDIR, path)
63         error, stream = ovs.stream.Stream.open_block(
64             ovs.stream.Stream.open(unix))
65
66         if error:
67             vlog.warn("failed to connect to %s" % path)
68             return error, None
69
70         return 0, UnixctlClient(ovs.jsonrpc.Connection(stream))