blob: 72c65dd97ed65c2d66c4636e0122cbba3fe39c52 [file] [log] [blame]
Steve McIntyreb1cbad32014-12-12 21:40:25 +00001# Copyright 2014 Linaro Limited
2#
3# This program is free software; you can redistribute it and/or modify
4# it under the terms of the GNU General Public License as published by
5# the Free Software Foundation; either version 2 of the License, or
6# (at your option) any later version.
7#
8# This program is distributed in the hope that it will be useful,
9# but WITHOUT ANY WARRANTY; without even the implied warranty of
10# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11# GNU General Public License for more details.
12#
13# You should have received a copy of the GNU General Public License
14# along with this program; if not, write to the Free Software
15# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
16# MA 02110-1301, USA.
17#
18# Simple VLANd IPC module
19
Steve McIntyreb8832e02014-12-18 16:16:49 +000020import socket, json, time, os, sys, datetime
Steve McIntyrea3c87672014-12-15 17:59:48 +000021
22vlandpath = os.path.abspath(os.path.normpath(os.path.dirname(sys.argv[0])))
23sys.path.insert(0, vlandpath)
24from errors import CriticalError, InputError, ConfigError, SocketError
Steve McIntyreb1cbad32014-12-12 21:40:25 +000025
26class VlanIpc:
27 """VLANd IPC class"""
28
29 def server_init(self, host, port):
30 self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
31
32 while True:
33 try:
34 self.socket.bind((host, port))
35 break
Steve McIntyredfa1e2c2014-12-23 13:24:33 +000036 except socket.error as e:
37 print "Can't bind to port %d: %s" % (port, e)
Steve McIntyreb1cbad32014-12-12 21:40:25 +000038 time.sleep(1)
39
40 def server_listen(self):
41 if self.socket is None:
42 raise SocketError("Server can't receive data: no socket")
43 self.socket.listen(1)
44
45 def server_recv(self):
46 if self.socket is None:
47 raise SocketError("Server can't receive data: no socket")
48
49 self.conn, addr = self.socket.accept()
50 data = self.conn.recv(8) # 32bit limit
51 count = int(data, 16)
52 c = 0
53 data = ''
54 while c < count:
55 data += self.conn.recv(1)
56 c += 1
57 try:
58 json_data = json.loads(data)
59 except ValueError:
60 self.conn.close()
61 self.conn = None
62 raise SocketError("Server unable to decode receieved data: corrupt?")
63
64 if 'client_name' not in json_data:
65 self.conn.close()
66 self.conn = None
67 raise SocketError("Server unable to detect client name: corrupt packet?")
68
69 return json_data
70
71 def server_reply(self, json_data):
72 if self.conn is None:
73 raise SocketError("Server can't send data: no connection")
74
75 data = self._format_message(json_data)
76 if not data:
77 self.conn.close()
78 self.conn = None
79 raise SocketError("Server unable to format reply data")
80
81 # send the actual number of bytes to read.
82 self.conn.send(data[0])
83 # now send the bytes.
84 self.conn.send(data[1])
85
86 def server_close(self):
87 if self.conn is not None:
88 self.conn.close()
89
90 def client_connect(self, host, port):
91 self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
92 while True:
93 try:
94 ret = self.socket.connect_ex((host, port))
95 if ret:
96 self.socket.close()
97 self.socket = None
98 raise SocketError("Client can't send connect: %s" % ret)
99 else:
100 break
101 except socket.error:
102 time.sleep(1)
103 return True
104
105 def client_send(self, json_data):
106 if self.socket is None:
107 raise SocketError("Client can't send data: no socket")
108
109 data = self._format_message(json_data)
110 if not data:
111 self.socket.shutdown(socket.SHUT_RDWR)
112 self.socket.close()
113 self.socket = None
114 raise SocketError("Client unable to send data")
115
116 # send the actual number of bytes to read.
117 self.socket.send(data[0])
118 # now send the bytes.
119 self.socket.send(data[1])
120
121 def client_recv_and_close(self):
122 if self.socket is None:
123 raise SocketError("Client can't receieve data: no socket")
124
125 data = self.socket.recv(8) # 32bit limit
126 count = int(data, 16)
127 c = 0
128 data = ''
129 while c < count:
130 data += self.socket.recv(1)
131 c += 1
132 try:
133 json_data = json.loads(data)
134 except ValueError:
135 self.socket.close()
136 self.socket = None
137 raise SocketError("Client unable to decode receieved data: corrupt?")
138
139 self.socket.shutdown(socket.SHUT_RDWR)
140 self.socket.close()
141
142 return json_data
Steve McIntyreb8832e02014-12-18 16:16:49 +0000143
144 # The default JSON serialiser code can't deal with datetime
145 # objects by default, so let's tell it how to.
146 def _json_serial(self, obj):
147 """JSON serializer for objects not serialisable by default json code"""
148 if isinstance(obj, datetime.datetime):
149 serial = obj.isoformat()
150 return serial
Steve McIntyreb1cbad32014-12-12 21:40:25 +0000151
152 def _format_message(self, json_data):
153 try:
Steve McIntyreb8832e02014-12-18 16:16:49 +0000154 msgstr = json.dumps(json_data, default=self._json_serial)
Steve McIntyreb1cbad32014-12-12 21:40:25 +0000155 except ValueError:
156 return None
157 # "header" calculation
158 msglen = "%08X" % len(msgstr)
159 return (msglen, msgstr)