]> git.evergreen-ils.org Git - OpenSRF.git/blob - src/python/osrf/server.py
10f4d660416521002f8a4fd05e3491f5046a6634
[OpenSRF.git] / src / python / osrf / server.py
1 # -----------------------------------------------------------------------
2 # Copyright (C) 2008  Equinox Software, Inc.
3 # Bill Erickson <erickson@esilibrary.com>
4 #
5 # This program is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU General Public License
7 # as published by the Free Software Foundation; either version 2
8 # of the License, or (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program; if not, write to the Free Software
17 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  
18 # 02110-1301, USA
19 # -----------------------------------------------------------------------
20
21 import os, sys, threading, logging, fcntl, socket, errno, signal, time
22 import osrf.log, osrf.conf, osrf.net, osrf.system, osrf.stack, osrf.app
23
24
25 # used to define the size of the PID/size leader in 
26 # status and data messages passed to and from children
27 SIZE_PAD = 12
28
29 class Controller(object):
30     ''' 
31         OpenSRF forking request server.  
32     '''
33
34     def __init__(self, service):
35         self.service = service # service name
36         self.application = None # the application we're serving
37         self.max_requests = 0 # max child requests
38         self.max_children = 0 # max num of child processes
39         self.min_childen = 0 # min num of child processes
40         self.num_children = 0 # current num children
41         self.child_idx = 0 # current index into the children array
42         self.children = [] # list of children
43         self.osrf_handle = None # xmpp handle
44         self.routers = [] # list of registered routers
45
46         # Global status socketpair.  All children relay their 
47         # availability info to the parent through this socketpair. 
48         self.read_status, self.write_status = socket.socketpair()
49
50     def load_app(self):
51         settings = osrf.set.get('activeapps.%s' % self.service)
52         
53
54     def cleanup(self):
55         ''' Closes management sockets, kills children, reaps children, exits '''
56
57         osrf.log.log_info("Shutting down...")
58         self.cleanup_routers()
59
60         self.read_status.shutdown(socket.SHUT_RDWR)
61         self.write_status.shutdown(socket.SHUT_RDWR)
62         self.read_status.close()
63         self.write_status.close()
64
65         for child in self.children:
66             child.read_data.shutdown(socket.SHUT_RDWR)
67             child.write_data.shutdown(socket.SHUT_RDWR)
68             child.read_data.close()
69             child.write_data.close()
70
71         os.kill(0, signal.SIGKILL)
72         self.reap_children(True)
73         os._exit(0)
74
75
76     def handle_signals(self):
77         ''' Installs SIGINT and SIGTERM handlers '''
78         def handler(signum, frame):
79             self.cleanup()
80         signal.signal(signal.SIGINT, handler)
81         signal.signal(signal.SIGTERM, handler)
82
83
84     def run(self):
85
86         osrf.net.get_network_handle().disconnect()
87         osrf.net.clear_network_handle()
88         self.spawn_children()
89         self.handle_signals()
90
91         time.sleep(.5) # give children a chance to connect before we start taking data
92         self.osrf_handle = osrf.system.System.net_connect(resource = '%s_listener' % self.service)
93
94         # clear the recv callback so inbound messages do not filter through the opensrf stack
95         self.osrf_handle.receive_callback = None
96
97         # connect to our listening routers
98         self.register_routers()
99
100         try:
101             osrf.log.log_debug("entering main server loop...")
102             while True: # main server loop
103
104                 self.reap_children()
105                 self.check_status()
106                 data = self.osrf_handle.recv(-1).to_xml()
107
108                 if self.try_avail_child(data):
109                     continue
110
111                 if self.try_new_child(data):
112                     continue
113
114                 self.wait_for_child()
115
116         except KeyboardInterrupt:
117             self.cleanup()
118         #except Exception, e: 
119             #osrf.log.log_error("server exiting with exception: %s" % e.message)
120             #self.cleanup()
121                 
122
123     def try_avail_child(self, data):
124         ''' Trys to send current request data to an available child process '''
125         ctr = 0
126         while ctr < self.num_children:
127
128             if self.child_idx >= self.num_children:
129                 self.child_idx = 0
130             child = self.children[self.child_idx]
131
132             if child.available:
133                 osrf.log.log_internal("sending data to available child")
134                 self.write_child(child, data)
135                 return True
136
137             ctr += 1
138             self.child_idx += 1
139         return False
140
141     def try_new_child(self, data):
142         ''' Tries to spawn a new child to send request data to '''
143         if self.num_children < self.max_children:
144             osrf.log.log_internal("spawning new child to handle data")
145             child = self.spawn_child()
146             self.write_child(child, data)
147             return True
148         return False
149
150     def try_wait_child(self, data):
151         ''' Waits for a child to become available '''
152         osrf.log.log_warn("No children available, waiting...")
153         child = self.check_status(True)
154         self.write_child(child, data)
155
156
157     def write_child(self, child, data):
158         ''' Sends data to the child process '''
159         child.available = False
160         child.write_data.sendall(str(len(data)).rjust(SIZE_PAD) + data)
161         self.child_idx += 1
162
163
164     def check_status(self, block=False):
165         ''' Checks to see if any children have indicated they are done with 
166             their current request.  If block is true, this will wait 
167             indefinitely for a child to be free. '''
168
169         pid = None
170         child = None
171         if block:
172             pid = self.read_status.recv(SIZE_PAD)
173         else:
174             try:
175                 self.read_status.setblocking(0)
176                 pid = self.read_status.recv(SIZE_PAD)
177             except socket.error, e:
178                 if e.args[0] != errno.EAGAIN:
179                     raise e
180             self.read_status.setblocking(1)
181                 
182         if pid:
183             pid = int(pid)
184             child = [c for c in self.children if c.pid == pid][0]
185             child.available = True
186
187         return child
188         
189
190     def reap_children(self, done=False):
191         ''' Uses waitpid() to reap the children.  If necessary, new children are spawned '''
192         options = 0
193         if not done: 
194             options = os.WNOHANG 
195
196         while True:
197             try:
198                 (pid, status) = os.waitpid(0, options)
199                 if pid == 0:
200                     if not done:
201                         self.spawn_children()
202                     return
203                 osrf.log.log_debug("reaping child %d" % pid)
204                 self.num_children -= 1
205                 self.children = [c for c in self.children if c.pid != pid]
206             except OSError:
207                 return
208         
209     def spawn_children(self):
210         ''' Launches up to min_children child processes '''
211         while self.num_children < self.min_children:
212             self.spawn_child()
213
214     def spawn_child(self):
215         ''' Spawns a new child process '''
216
217         child = Child(self)
218         child.read_data, child.write_data = socket.socketpair()
219         child.pid = os.fork()
220
221         if child.pid:
222             self.num_children += 1
223             self.children.append(child)
224             osrf.log.log_debug("spawned child %d : %d total" % (child.pid, self.num_children))
225             return child
226         else:
227             child.pid = os.getpid()
228             child.init()
229             child.run()
230             osrf.net.get_network_handle().disconnect()
231             osrf.log.log_internal("child exiting...")
232             os._exit(0)
233
234     def register_routers(self):
235         ''' Registers this application instance with all configured routers '''
236         routers = osrf.conf.get('routers.router')
237
238         if not isinstance(routers, list):
239             routers = [routers]
240
241         for router in routers:
242             if isinstance(router, dict):
243                 if not 'services' in router or \
244                         self.service in router['services']['service']:
245                     target = "%s@%s/router" % (router['name'], router['domain'])
246                     self.register_router(target)
247             else:
248                 router_name = osrf.conf.get('router_name')
249                 target = "%s@%s/router" % (router_name, router)
250                 self.register_router(target)
251
252
253     def register_router(self, target):
254         ''' Registers with a single router '''
255         osrf.log.log_info("registering with router %s" % target)
256         self.routers.append(target)
257
258         reg_msg = osrf.net.NetworkMessage(
259             recipient = target,
260             body = 'registering...',
261             router_command = 'register',
262             router_class = self.service
263         )
264
265         self.osrf_handle.send(reg_msg)
266
267     def cleanup_routers(self):
268         ''' Un-registers with all connected routers '''
269         for target in self.routers:
270             osrf.log.log_info("un-registering with router %s" % target)
271             unreg_msg = osrf.net.NetworkMessage(
272                 recipient = target,
273                 body = 'un-registering...',
274                 router_command = 'unregister',
275                 router_class = self.service
276             )
277             self.osrf_handle.send(unreg_msg)
278         
279
280 class Child(object):
281     ''' Models a single child process '''
282
283     def __init__(self, controller):
284         self.controller = controller # our Controller object
285         self.num_requests = 0 # how many requests we've served so far
286         self.read_data = None # the child reads data from the controller on this socket
287         self.write_data = None # the controller sends data to the child on this socket 
288         self.available = True # true if this child is not currently serving a request
289         self.pid = 0 # my process id
290
291
292     def run(self):
293         ''' Loops, processing data, until max_requests is reached '''
294         while True:
295             try:
296                 size = int(self.read_data.recv(SIZE_PAD) or 0)
297                 data = self.read_data.recv(size)
298                 osrf.log.log_internal("recv'd data " + data)
299                 osrf.stack.push(osrf.net.NetworkMessage.from_xml(data))
300                 self.num_requests += 1
301                 if self.num_requests == self.controller.max_requests:
302                     break
303                 self.send_status()
304             except KeyboardInterrupt:
305                 pass
306         # run the exit handler
307         osrf.app.Application.application.child_exit()
308
309     def send_status(self):
310         ''' Informs the controller that we are done processing this request '''
311         fcntl.lockf(self.controller.write_status.fileno(), fcntl.LOCK_EX)
312         try:
313             self.controller.write_status.sendall(str(self.pid).rjust(SIZE_PAD))
314         finally:
315             fcntl.lockf(self.controller.write_status.fileno(), fcntl.LOCK_UN)
316
317     def init(self):
318         ''' Connects the opensrf xmpp handle '''
319         osrf.net.clear_network_handle()
320         osrf.system.System.net_connect(resource = '%s_drone' % self.controller.service)
321         osrf.app.Application.application.child_init()
322