Subversion Repositories SmartDukaan

Rev

Rev 30 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
30 ashish 1
#
2
# Licensed to the Apache Software Foundation (ASF) under one
3
# or more contributor license agreements. See the NOTICE file
4
# distributed with this work for additional information
5
# regarding copyright ownership. The ASF licenses this file
6
# to you under the Apache License, Version 2.0 (the
7
# "License"); you may not use this file except in compliance
8
# with the License. You may obtain a copy of the License at
9
#
10
#   http://www.apache.org/licenses/LICENSE-2.0
11
#
12
# Unless required by applicable law or agreed to in writing,
13
# software distributed under the License is distributed on an
14
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15
# KIND, either express or implied. See the License for the
16
# specific language governing permissions and limitations
17
# under the License.
18
#
19
 
20
from TTransport import *
21
import os
22
import errno
23
import socket
24
 
25
class TSocketBase(TTransportBase):
26
  def _resolveAddr(self):
27
    if self._unix_socket is not None:
28
      return [(socket.AF_UNIX, socket.SOCK_STREAM, None, None, self._unix_socket)]
29
    else:
30
      return socket.getaddrinfo(self.host, self.port, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_PASSIVE | socket.AI_ADDRCONFIG)
31
 
32
  def close(self):
33
    if self.handle:
34
      self.handle.close()
35
      self.handle = None
36
 
37
class TSocket(TSocketBase):
38
  """Socket implementation of TTransport base."""
39
 
40
  def __init__(self, host='localhost', port=9090, unix_socket=None):
41
    """Initialize a TSocket
42
 
43
    @param host(str)  The host to connect to.
44
    @param port(int)  The (TCP) port to connect to.
45
    @param unix_socket(str)  The filename of a unix socket to connect to.
46
                             (host and port will be ignored.)
47
    """
48
 
49
    self.host = host
50
    self.port = port
51
    self.handle = None
52
    self._unix_socket = unix_socket
53
    self._timeout = None
54
 
55
  def setHandle(self, h):
56
    self.handle = h
57
 
58
  def isOpen(self):
59
    return self.handle != None
60
 
61
  def setTimeout(self, ms):
62
    if ms is None:
63
      self._timeout = None
64
    else:
65
      self._timeout = ms/1000.0
66
 
67
    if (self.handle != None):
68
      self.handle.settimeout(self._timeout)
69
 
70
  def open(self):
71
    try:
72
      res0 = self._resolveAddr()
73
      for res in res0:
74
        self.handle = socket.socket(res[0], res[1])
75
        self.handle.settimeout(self._timeout)
76
        try:
77
          self.handle.connect(res[4])
78
        except socket.error, e:
79
          if res is not res0[-1]:
80
            continue
81
          else:
82
            raise e
83
        break
84
    except socket.error, e:
85
      if self._unix_socket:
86
        message = 'Could not connect to socket %s' % self._unix_socket
87
      else:
88
        message = 'Could not connect to %s:%d' % (self.host, self.port)
89
      raise TTransportException(type=TTransportException.NOT_OPEN, message=message)
90
 
91
  def read(self, sz):
92
    buff = self.handle.recv(sz)
93
    if len(buff) == 0:
94
      raise TTransportException(type=TTransportException.END_OF_FILE, message='TSocket read 0 bytes')
95
    return buff
96
 
97
  def write(self, buff):
98
    if not self.handle:
99
      raise TTransportException(type=TTransportException.NOT_OPEN, message='Transport not open')
100
    sent = 0
101
    have = len(buff)
102
    while sent < have:
103
      plus = self.handle.send(buff)
104
      if plus == 0:
105
        raise TTransportException(type=TTransportException.END_OF_FILE, message='TSocket sent 0 bytes')
106
      sent += plus
107
      buff = buff[plus:]
108
 
109
  def flush(self):
110
    pass
111
 
112
class TServerSocket(TSocketBase, TServerTransportBase):
113
  """Socket implementation of TServerTransport base."""
114
 
115
  def __init__(self, port=9090, unix_socket=None):
116
    self.host = None
117
    self.port = port
118
    self._unix_socket = unix_socket
119
    self.handle = None
120
 
121
  def listen(self):
122
    res0 = self._resolveAddr()
123
    for res in res0:
124
      if res[0] is socket.AF_INET6 or res is res0[-1]:
125
        break
126
 
127
    # We need remove the old unix socket if the file exists and
128
    # nobody is listening on it.
129
    if self._unix_socket:
130
      tmp = socket.socket(res[0], res[1])
131
      try:
132
        tmp.connect(res[4])
133
      except socket.error, err:
134
        eno, message = err.args
135
        if eno == errno.ECONNREFUSED:
136
          os.unlink(res[4])
137
 
138
    self.handle = socket.socket(res[0], res[1])
139
    self.handle.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
140
    if hasattr(self.handle, 'set_timeout'):
141
      self.handle.set_timeout(None)
142
    self.handle.bind(res[4])
143
    self.handle.listen(128)
144
 
145
  def accept(self):
146
    client, addr = self.handle.accept()
147
    result = TSocket()
148
    result.setHandle(client)
149
    return result