# ex:ts=4
#
# LikoRPC Client
#   -- just a simple client-side library for testing
#
# $LinuxKorea: likorpclib.py,v 2.0 2001/08/29 08:12:19 perky Exp $
#
# Copyright 2001 Hye-Shik Chang. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without 
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the distribution.
# 3. Neither the name of author nor the names of its contributors
#    may be used to endorse or promote products derived from this software
#    without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
# ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE. 
#
# code by Hye-Shik Chang <perky@linuxkorea.co.kr>
#

import socket
import string

try:
	from cPickle import dumps, loads
except:
	from pickle import dumps, loads

MTYPE_CALL   = 0
MTYPE_RETURN = 1

class LikoRPCError(Exception):
	
	def __init__(self, descr):
		Exception.__init__(self, descr)
		self.descr = descr

class LikoRPCFault(Exception):

	def __init__(self, descr):
		Exception.__init__(self, descr)
		self.descr = descr

	def __repr__(self):
		return self.descr
	
	__str__ = __repr__

class RPCMethod:
	
	def __init__(self, server, name):
		self.server = server
		self.path = string.split(name, '.')
	
	def send(self, str):
		try:
			return self.server._conn.send(str)
		except:
			self.server._close()
			raise LikoRPCError("rpc channel send error")
	
	def recv(self, limit=8192):
		try:
			return self.server._conn.recv(limit)
		except:
			self.server._close()
			raise LikoRPCError("rpc channel read error")
	
	def __call__(self, *args):
		try:
			self.send(dumps((MTYPE_CALL, self.path, args)) + '\000')
		except:
			self.server._connect()
			return apply(self, args)
		resp = ''
		while 1:
			while 1:
				data = self.recv()
				if not data:
					self.server._close()
					self.server._connect()
					continue
				resp = resp + data
				if string.find(data, '\000') >= 0:
					break
			resdata = string.split(resp, '\000')
			for i in resdata[:-1]:
				packet = loads(i)
				if packet[0] == MTYPE_RETURN:
					if packet[1]:
						raise LikoRPCFault(packet[1])
					else:
						return packet[2]   # likorpc returns (TYPE, ERROR, RETURN)

			resp = resdata[-1]

class Server:
	
	def __init__(self, addr):
		if type(addr) is type(''):
			self._family = socket.AF_UNIX
		else:   
			self._family = socket.AF_INET

		self._addr = addr
		self._connected = 0
		self._connect()
	
	def _connect(self):
		if not self._connected:
			self._conn = socket.socket(self._family, socket.SOCK_STREAM)
			self._conn.setblocking(1)
			self._conn.connect(self._addr)
			self._connected = 1
	
	def _close(self):
		try:
			if self._connected:
				self._conn.shutdown(1)
		except:
			import traceback, sys
			traceback.print_exc(file=sys.stdout)
			sys.exit()
		self._connected = 0
	
	def __getattr__(self, name):
		if name[0] == '_':
			return self.__dict__[name]
		else:
			return RPCMethod(self, name)
	
	def __del__(self):
		if self._connected:
			self._conn.close()


if __name__ == "__main__":
	c = Server("/tmp/dyna-index.sock")

	print c.hello()
