source: proiecte/HadoopJUnit/hadoop-0.20.1/contrib/hod/hodlib/Common/tcp.py @ 120

Last change on this file since 120 was 120, checked in by (none), 14 years ago

Added the mail files for the Hadoop JUNit Project

  • Property svn:executable set to *
File size: 5.2 KB
Line 
1#Licensed to the Apache Software Foundation (ASF) under one
2#or more contributor license agreements.  See the NOTICE file
3#distributed with this work for additional information
4#regarding copyright ownership.  The ASF licenses this file
5#to you under the Apache License, Version 2.0 (the
6#"License"); you may not use this file except in compliance
7#with the License.  You may obtain a copy of the License at
8
9#     http://www.apache.org/licenses/LICENSE-2.0
10
11#Unless required by applicable law or agreed to in writing, software
12#distributed under the License is distributed on an "AS IS" BASIS,
13#WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14#See the License for the specific language governing permissions and
15#limitations under the License.
16# $Id:tcp.py 6172 2007-05-22 20:26:54Z zim $
17#
18#------------------------------------------------------------------------------
19
20""" TCP related classes. """
21
22import socket, re, string
23reAddress    = re.compile(":")
24reMayBeIp = re.compile("^\d+\.\d+\.\d+\.\d+$")
25reValidPort = re.compile("^\d+$")
26
27class Error(Exception):
28    def __init__(self, msg=''):
29        self.message = msg
30        Exception.__init__(self, msg)
31
32    def __repr__(self):
33        return self.message
34
35class tcpError(Error):
36    def __init__(self, message):
37        Error.__init__(self, message)
38
39class tcpSocket:
40    def __init__(self, address, timeout=30, autoflush=0):
41        """Constructs a tcpSocket object.
42
43           address - standard tcp address (HOST:PORT)
44           timeout - socket timeout"""
45
46        self.address = address
47        self.__autoFlush = autoflush
48        self.__remoteSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
49        self.__remoteSock.settimeout(timeout)
50        self.host = None
51        self.port = None
52        splitAddress = address
53        if isinstance(address, (tuple, list)):
54            self.host = address[0]
55            self.port = int(address[1])
56        else:
57            splitAddress = get_address_tuple(address)
58            if not splitAddress[0]:
59                self.host = 'localhost'
60            else:
61                self.host = splitAddress[0]
62
63            self.port = int(splitAddress[1])
64
65        self.__fileObjectOut = ''
66        self.__fileObjectIn = ''
67
68    def __repr__(self):
69        return self.address
70
71    def __iter__(self):
72        return self
73
74    def next(self):
75        sockLine = self.read()
76        if not sockLine:
77            raise StopIteration
78
79        return sockLine
80
81    def open(self):
82        """Attempts to open a socket to the specified address."""
83
84        socketAddress = (self.host, self.port)
85
86        try:
87            self.__remoteSock.connect(socketAddress)
88            if self.__autoFlush:
89                self.__fileObjectOut = self.__remoteSock.makefile('wb', 0)
90            else:
91                self.__fileObjectOut = self.__remoteSock.makefile('wb')
92
93            self.__fileObjectIn  = self.__remoteSock.makefile('rb', 0)
94        except:
95            raise tcpError, "connection failure: %s" % self.address
96
97    def flush(self):
98        """Flushes write buffer."""
99        self.__fileObjectOut.flush()
100
101    def close(self):
102        """Attempts to close and open socket connection"""
103
104        try:
105            self.__remoteSock.close()
106            self.__fileObjectOut.close()
107            self.__fileObjectIn.close()
108        except socket.error, exceptionObject:
109            exceptionMessage = "close failure %s %s" % (self.address,
110                exceptionObject.__str__())
111            raise tcpError, exceptionMessage
112
113    def verify(self):
114        """Verifies that a given IP address/host and port are valid. This
115           method will not attempt to open a socket to the specified address.
116        """
117
118        isValidAddress = False
119        if reMayBeIp.match(self.host):
120            if check_ip_address(self.host):
121                if reValidPort.match(str(self.port)):
122                    isValidAddress = True
123        else:
124            if reValidPort.match(str(self.port)):
125                isValidAddress = True
126
127        return(isValidAddress)
128
129    def read(self):
130        """Reads a line off of the active socket."""
131
132        return self.__fileObjectIn.readline()
133
134    def write(self, string):
135        """Writes a string to the active socket."""
136
137        print >> self.__fileObjectOut, string
138
139def check_net_address(address):
140    valid = True
141    pieces = string.split(address, '.')
142    if len(pieces) != 4:
143        valid = False
144    else:
145        for piece in pieces:
146            if int(piece) < 0 or int(piece) > 255:
147                valid = False
148
149    return valid
150
151def check_ip_address(address):
152    valid = True
153    pieces = string.split(address, '.')
154    if len(pieces) != 4:
155        valid = False
156    else:
157        if int(pieces[0]) < 1 or int(pieces[0]) > 254:
158            valid = False
159        for i in range(1,4):
160            if int(pieces[i]) < 0 or int(pieces[i]) > 255:
161                valid = False
162
163    return valid
164
165def get_address_tuple(address):
166    """ Returns an address tuple for TCP address.
167
168        address - TCP address of the form host:port
169
170        returns address tuple (host, port)
171    """
172
173    addressList = reAddress.split(address)
174    addressTuple = (addressList[0], int(addressList[1]))
175
176    return addressTuple
Note: See TracBrowser for help on using the repository browser.