-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathioman.py
2712 lines (2423 loc) · 87.5 KB
/
ioman.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) 2005-2009 by Kenjiro Taura. All rights reserved.
# Copyright (c) 2005-2009 by Yoshikazu Kamoshida. All rights reserved.
#
# THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY
# EXPRESSED OR IMPLIED. ANY USE IS AT YOUR OWN RISK.
#
# Permission is hereby granted to use or copy this program
# for any purpose, provided the above notices are retained on all
# copies. Permission to modify the code and to distribute modified
# code is granted, provided the above notices are retained, and
# a notice that the code was modified is included with the above
# copyright notice.
#
# $Header: /cvsroot/gxp/gxp3/ioman.py,v 1.18 2013/10/25 12:00:54 ttaauu Exp $
# $Name: $
#
import errno,fcntl,os,random,re,resource,select,signal,socket,string,sys
import time,types
# import profile,pstats
# -------------------------------------------------------------------
# debug flag
# -------------------------------------------------------------------
dbg=0
# -------------------------------------------------------------------
# constants
# -------------------------------------------------------------------
INF = "" # infty
#
#
#
class logger:
def __init__(self, filename=None):
self.fd = None
if filename is None:
self.filename = self.default_log_filename()
else:
self.filename = filename
self.set_log_filename(self.filename)
self.set_log_header(None)
self.set_log_base_time()
self.set_show_time()
def default_log_filename(self):
return "log_%s" % socket.gethostname()
def set_log_filename(self, filename):
self.requested_file = filename
def delete_log_file(self):
if self.filename is not None:
try:
os.remove(self.filename)
self.filename = None
except EnvironmentError,e:
pass
def set_log_header(self, header):
self.header = header
def set_show_time(self):
self.show_time = 1
def set_log_base_time(self):
self.base_time = time.time()
def log(self, msg):
if self.requested_file != self.filename:
if self.fd is not None:
os.close(self.fd)
self.fd = None
self.filename = self.requested_file
assert self.filename == self.requested_file, \
(self.filename, self.requested_file)
if self.fd is None:
self.fd = os.open(self.filename,
os.O_CREAT|os.O_WRONLY|os.O_TRUNC,
0644)
portability.set_close_on_exec_fd(self.fd, 1)
assert self.fd is not None
if self.header is not None:
os.write(self.fd, ("%s : " % self.header))
if self.show_time:
os.write(self.fd,
("%.6f : " % (time.time() - self.base_time)))
os.write(self.fd, msg)
the_logger = logger()
def LOG(msg):
the_logger.log(msg)
def set_log_header():
the_logger.set_log_header()
def set_log_base_time():
the_logger.set_log_base_time()
def set_log_filename(filename):
the_logger.set_log_filename(filename)
def delete_log_file():
the_logger.delete_log_file()
# -------------------------------------------------------------------
# infrastructure for IO that does not return with signals or
# keyboard interrupt
# -------------------------------------------------------------------
def apply_no_intr(f, args):
keyboard = 0
for i in range(0, 500):
try:
return apply(f, args)
except EnvironmentError,e:
pass
except socket.error,e:
pass
except select.error,e:
pass
except KeyboardInterrupt,e:
keyboard = 1
pass
if keyboard == 0 and e.args[0] != errno.EINTR: raise
raise
class non_interruptible_os_io:
def write(self, fd, s):
return apply_no_intr(os.write, (fd, s))
def read(self, fd, sz):
return apply_no_intr(os.read, (fd, sz))
def close(self, fd):
return apply_no_intr(os.close, (fd, ))
nointr_os = non_interruptible_os_io()
class non_interruptible_socket:
def __init__(self, so):
self.so = so
def nointr_send(self, s, flags=0):
return apply_no_intr(self.so.send, (s, flags))
def nointr_recv(self, sz, flags=0):
return apply_no_intr(self.so.recv, (sz, flags))
def nointr_connect(self, name):
return apply_no_intr(self.so.connect, (name, ))
def nointr_accept(self):
conn,addr = apply_no_intr(self.so.accept, ())
return non_interruptible_socket(conn),addr
def nointr_close(self):
# return apply_no_intr(self.so.close, ())
return self.so.close()
def fileno(self):
return self.so.fileno()
def setblocking(self, x):
return self.so.setblocking(x)
def setsockopt(self, level, opt, val):
return self.so.setsockopt(level, opt, val)
def getsockopt(self, level, opt):
return self.so.getsockopt(level, opt)
def bind(self, name):
return self.so.bind(name)
def listen(self, qlen):
return self.so.listen(qlen)
def getsockname(self):
return self.so.getsockname()
def getpeername(self):
return self.so.getpeername()
def mk_non_interruptible_socket(af, type):
return non_interruptible_socket(socket.socket(af, type))
class non_interruptible_select:
def select(self, R, W, E, T=None):
if T is None:
return apply_no_intr(select.select, (R, W, E))
else:
return apply_no_intr(select.select, (R, W, E, T))
class non_interruptible_select_by_poll:
def select(self, R, W, E, T=None):
d = {}
for f in R:
fd = f.fileno()
d[fd] = select.POLLIN
for f in W:
fd = f.fileno()
d[fd] = d.get(fd, 0) | select.POLLOUT
for f in E:
fd = f.fileno()
d[fd] = d.get(fd, 0) | select.POLLIN | select.POLLOUT
p = select.poll()
for (fd, mask) in d.items():
p.register(fd, mask)
if T is None:
list = apply_no_intr(p.poll, ())
else:
list = apply_no_intr(p.poll, (T*1000,))
R0 = []
W0 = []
E0 = []
d = dict(list)
for f in R:
if (d.get(f.fileno(), 0) & (select.POLLIN|select.POLLHUP)) != 0:
R0.append(f)
for f in W:
if (d.get(f.fileno(), 0) & (select.POLLOUT)) != 0:
W0.append(f)
for f in E:
if (d.get(f.fileno(), 0) & select.POLLERR) != 0:
E0.append(f)
return R0,W0,E0
if hasattr(select, "poll"):
nointr_select = non_interruptible_select_by_poll()
else:
nointr_select = non_interruptible_select()
# -------------------------------------------------------------------
# a simple layer hiding some of the platform/python version
# dependences
# -------------------------------------------------------------------
class portability_class:
"""
1. Some versions of Python define F_SETFL and F_GETFL in FCNTL,
while others in fcntl.
"""
def __init__(self):
self.set_fcntl_constants()
def set_fcntl_constants(self):
self.F_GETFL = fcntl.F_GETFL
self.F_SETFL = fcntl.F_SETFL
self.F_GETFD = fcntl.F_GETFD
self.F_SETFD = fcntl.F_SETFD
ok = 0
if fcntl.__dict__.has_key("FD_CLOEXEC"):
self.FD_CLOEXEC = fcntl.FD_CLOEXEC
ok = 1
if ok == 0:
try:
FCNTL_ok = 0
import warnings
warnings.filterwarnings("ignore", "", DeprecationWarning)
import FCNTL
FCNTL_ok = 1
warnings.resetwarnings()
except ImportError:
pass
if FCNTL_ok and FCNTL.__dict__.has_key("FD_CLOEXEC"):
self.FD_CLOEXEC = FCNTL.FD_CLOEXEC
ok = 1
if ok == 0:
# assume FD_CLOEXEC = 1. see
# http://mail.python.org/pipermail/python-bugs-list/2001-December/009360.html
self.FD_CLOEXEC = 1
ok = 1
if ok == 0:
LOG("This platform provides no ways to set "
"close-on-exec flag. abort\n")
os._exit(1)
def set_blocking_fd(self, fd, blocking):
"""
make fd non blocking
"""
flag = fcntl.fcntl(fd, self.F_GETFL)
if blocking:
new_flag = flag & ~os.O_NONBLOCK
else:
new_flag = flag | os.O_NONBLOCK
fcntl.fcntl(fd, self.F_SETFL, new_flag)
def set_close_on_exec_fd(self, fd, close_on_exec):
"""
make fd non blocking
"""
if close_on_exec:
fcntl.fcntl(fd, self.F_SETFD, self.FD_CLOEXEC)
else:
fcntl.fcntl(fd, self.F_SETFD, 0)
portability = portability_class()
# -------------------------------------------------------------------
# abstract primitive asynchronous channel classes
# -------------------------------------------------------------------
class primitive_channel:
def fileno(self):
"""
the number passed to select syscall
"""
should_be_implemented_in_subclasses()
def read(self, sz):
"""
Try to read <= sz bytes asynchronously and return whatever
is read. Return (-1,error_msg) or (n,data), where n is
the size of data read.
"""
should_be_implemented_in_subclasses()
def write(self, data):
"""
Try to write data asynchronously and return the number of
bytes written. Return (-1,error_msg) or (n,"") where n is
the size of data written.
"""
should_be_implemented_in_subclasses()
def close(self):
"""
close the underlying descriptor or socket
"""
should_be_implemented_in_subclasses()
def is_closed(self):
"""
1 if this channel has been closed
"""
should_be_implemented_in_subclasses()
# -------------------------------------------------------------------
# primitive asynchronous channel
# -------------------------------------------------------------------
class primitive_channel_fd:
"""
Primitive channels based on file descriptors (integer).
"""
def __init__(self, fd, blocking):
portability.set_blocking_fd(fd, blocking)
portability.set_close_on_exec_fd(fd, 1)
self.fd = fd
self.closed = 0
def fileno(self):
return self.fd
def read(self, sz):
"""
Asynchronously read at most sz bytes.
When successful, return len(whatever_is_read),
whatever_is_read.
'whatever_is_read' should not be an empty string.
Otherwise return -1,error_msg.
"""
try:
frag = nointr_os.read(self.fd, sz)
return len(frag),0,frag
except EnvironmentError,e:
return -1,e.args[0],e.args[1]
def write(self, frag):
"""
Try to write a string FRAG. The entire msg may not be
written. When successful, return number_of_bytes_written,"".
Otherwise, return -1,error_msg.
"""
try:
return nointr_os.write(self.fd, frag),0,""
except EnvironmentError,e:
return -1,e.args[0],e.args[1]
def close(self):
if self.closed == 0:
self.closed = 1
nointr_os.close(self.fd)
def is_closed(self):
return self.closed
class primitive_channel_socket:
"""
Primitive channels based on sockets (socket objects).
"""
def __init__(self, so, blocking):
so.setblocking(blocking)
portability.set_close_on_exec_fd(so.fileno(), 1)
self.so = so
self.closed = 0
def fileno(self):
return self.so.fileno()
def read(self, sz):
"""
Asynchronously read at most sz bytes.
When successful, return len(whatever_is_read),
whatever_is_read.
'whatever_is_read' should not be an empty string.
Otherwise return -1,error_msg.
"""
try:
frag = self.so.nointr_recv(sz)
return len(frag),0,frag
except socket.error,e:
return -1,e.args[0],e.args[1]
except EnvironmentError,e:
return -1,e.args[0],e.args[1]
def write(self, frag):
"""
Try to write a string FRAG. The entire msg may not be
written. When successful, return number_of_bytes_written,"".
Otherwise, return -1,error_msg.
"""
try:
return self.so.nointr_send(frag),0,""
except socket.error,e:
return -1,e.args[0],e.args[1]
except EnvironmentError,e:
return -1,e.args[0],e.args[1]
def accept(self):
try:
conn,addr = self.so.nointr_accept()
except socket.error,e:
return -1,e.args[0],e.args[1]
except EnvironmentError,e:
return -1,e.args[0],e.args[1]
portability.set_close_on_exec_fd(conn.fileno(), 1)
return 0,0,(conn,addr)
def connect(self, name):
try:
self.so.nointr_connect(name)
except socket.error,e:
return -1,e
except EnvironmentError,e:
return -1,e
return 0,None
def getsockname(self):
return self.so.getsockname()
def close(self):
if self.closed == 0:
self.closed = 1
self.so.nointr_close()
def is_closed(self):
return self.closed
# -------------------------------------------------------------------
# priority queue to make high level channel interface
# -------------------------------------------------------------------
class prio_queue:
"""
Dumb implementation of heapq.
FIXME: use heap
priority : 0 is lowest
"""
def __init__(self):
self.data = [] # list of (prio,val)
def try_get(self, default):
"""
Try to get an (element,priority) from the list. If the
list is empty return (default,None)
"""
if len(self.data) > 0:
prio,datum = self.data.pop(0)
return datum,prio
else:
return default,None
def get(self):
"""
Get (element,priority). Raise an error if the queue is empty
"""
datum,prio = self.try_get(None)
assert prio is not None
return datum,prio
def put(self, val, prio):
"""
put a value VAL to the queue for priority PRIO
"""
if prio == 0:
self.data.append((prio, val))
else:
idx = 0
for _,p in self.data:
if prio > p: break
idx = idx + 1
self.data.insert(idx, (prio, val))
def push_back(self, val, prio):
"""
put a value VAL to the queue for priority PRIO.
"""
idx = 0
for _,p in self.data:
if prio >= p: break
idx = idx + 1
self.data.insert(idx, (prio, val))
def put_low(self, val):
"""
put a value VAL to the queue for priority PRIO
"""
self.data.append((0, val))
def empty(self):
"""
1 if empty
"""
if len(self.data) == 0:
return 1
else:
return 0
# -------------------------------------------------------------------
# string buffer
# -------------------------------------------------------------------
class string_buffer:
"""
Java-like string buffer object.
s = string_buffer()
s.extend('abc')
Also support:
len(s), s[i], s[i:j], s[i] = 'a', s[i:j] = 'abc',
del s[i], del s[i:j]
"""
def __init__(self):
self.S = [] # list of strings
self.l = 0 # total length
def extend(self, a):
self.S.append(a)
self.l = self.l + len(a)
def __len__(self): # len(S)
return self.l
def __getitem__(self, idx): # S[i] or S[i:j]
return self.aux__(idx, None)
def __setitem__(self, i, val): # S[i] = val or S[i:j] = val
self.aux__(i, val)
def __delitem__(self, i): # del S[i] or del S[i:j]
self.aux__(i, "")
def delete(self, i, j):
# like del self[i:j] but return the deleted item
return self.aux__(slice(i,j), "")
def aux__(self, idx, val):
"""
access idx-th element of th string buffer.
it is used to implement all of buf[i], buf[i:j],
buf[i] = x, buf[i:j] = X, del buf[i], and and buf[i:j]
if val is not None, set (replace) the value.
"""
if type(idx) is types.SliceType:
start,stop,step = idx.start,idx.stop,idx.step
if stop > self.l: stop = self.l
if start < 0: start = 0
else:
start,stop,step = idx,idx+1,None
if not (0 <= idx < self.l):
raise IndexError("string buffer index out of range")
assert step is None,(start,stop,step)
if 1 and (start == 0 and stop == self.l):
X = string.join(self.S, "")
if val is not None:
self.S[:] = []
self.l = 0
return X
x = 0
A = []
B = []
C = []
len_A = 0
len_B = 0
len_C = 0
for s in self.S:
y = x + len(s)
# intersect [x,y] with [0,start]
a = x
b = min(y, start)
if a < b:
A.append(s[a-x:b-x])
len_A = len_A + b - a
# intersect [x,y] with [start,stop]
a = max(x, start)
b = min(y, stop)
if a < b:
B.append(s[a-x:b-x])
len_B = len_B + b - a
# intersect [x,y] with [stop,n]
a = max(x, stop)
b = y
if a < b:
C.append(s[a-x:b-x])
len_C = len_C + b - a
x = x + len(s)
assert len_A + len_B + len_C == self.l
X = string.join(B, "")
assert len(X) == stop - start, (start, stop)
if val is not None:
self.S[:] = []
self.S.extend(A)
if val != "": self.S.append(val)
self.S.extend(C)
self.l = len_A + len(val) + len_C
return X
if sys.hexversion < 0x02000000:
# version_info < (2,0)
def __getslice__(self, i, j):
return self[max(0, i):max(0, j):]
def __setslice__(self, i, j, seq):
self[max(0, i):max(0, j):] = seq
def __delslice__(self, i, j):
del self[max(0, i):max(0, j):]
# -------------------------------------------------------------------
# stream searcher to find matching msgs in the pending queue
# -------------------------------------------------------------------
class pattern_searcher:
def search(self, frag):
"""
search(frag) should search a prescribed pattern in frag,
and return a,b,prio
"""
should_be_implemented_in_subclasses()
def get_overlap(self):
return INF
def get_payload(self, s):
return s
class pattern_searcher_any(pattern_searcher):
def search(self, frag):
if dbg>=2:
LOG("pattern_searcher_any : "
"search any in %d bytes [%s ...]\n" % \
(len(frag), frag[0:30]))
LOG("pattern_searcher_any : "
"found %d bytes [%s ...]\n" % \
(len(frag), frag[0:30]))
return None,len(frag),0
def get_overlap(self):
return 0
class pattern_searcher_sz(pattern_searcher):
def __init__(self, sz):
self.sz = sz
def search(self, frag):
if dbg>=2:
LOG("pattern_searcher_sz : "
"search %d bytes in %d bytes [%s ...]\n" % \
(self.sz, len(frag), frag[0:30]))
if len(frag) >= self.sz:
if dbg>=2:
LOG("pattern_searcher_sz : "
"found %d bytes [%s ...]\n" % \
(self.sz, frag[0:30]))
return None,self.sz,0
else:
if dbg>=2:
LOG("pattern_searcher_sz : not enough data\n")
return None
def get_overlap(self):
return self.sz - 1
class pattern_searcher_exact(pattern_searcher):
def __init__(self, needle):
self.needle = needle
self.overlap = len(needle) - 1
def search(self, frag):
if dbg>=2:
LOG("pattern_searcher_exact : "
"search [%s] in %d bytes [%s ...]\n" % \
(self.needle, len(frag), frag[0:30]))
# idx = string.find(frag, self.needle)
idx = string.rfind(frag, self.needle)
if idx != -1:
if dbg>=2:
LOG("pattern_searcher_exact : "
"found %d bytes [%s ...]\n" % \
(idx+len(self.needle), frag[0:30]))
return None,idx+len(self.needle),0
else:
if dbg>=2:
LOG("pattern_searcher_exact : pattern not found\n")
return None
def get_overlap(self):
return self.overlap
class pattern_searcher_regexp(pattern_searcher):
def __init__(self, regexp, overlap):
self.regexp_str = regexp
self.regexp = re.compile(self.regexp_str)
self.overlap = overlap
def search(self, frag):
if dbg>=2:
LOG("pattern_searcher_regexp : "
"search [%s] in %d bytes [%s ...]\n" % \
(self.regexp_str, len(frag), frag[0:30]))
m = self.regexp.search(frag)
if m:
# lowest priority = 0, highest size = INF
a,b = m.span(0)
if dbg>=2:
LOG("pattern_searcher_regexp : "
"found %d bytes [%s ...]\n" % (b, frag[0:30]))
return None,b,0
else:
if dbg>=2:
LOG("pattern_searcher_regexp : pattern not found\n")
return None
def get_overlap(self):
return self.overlap
class pattern_searcher_msg(pattern_searcher):
h_temp = "HEADER len %20d prio %20d HEADER_END"
h_pat = "HEADER len +(\d+) prio +(\d+) HEADER_END"
t_temp = "TRAIL len %20d prio %20d sum %20d TRAIL_END"
t_pat = "TRAIL len +(\d+) prio +(\d+) sum +(\d+) TRAIL_END"
header_temp = h_temp
header_len = len(h_temp % (0, 0))
header_pat = re.compile(h_pat)
trailer_temp = t_temp
trailer_len = len(t_temp % (0, 0, 0))
trailer_pat = re.compile(t_pat)
def get_payload(self, s):
a = pattern_searcher_msg.header_len
b = pattern_searcher_msg.trailer_len
return s[a:-b]
def search(self, frag):
if dbg>=2:
LOG("pattern_searcher_msg : "
"search msg in %d bytes [%s ...]\n" % \
(len(frag), frag[0:30]))
m = pattern_searcher_msg.trailer_pat.search(frag)
if m:
b = m.end(0)
sz = string.atoi(m.group(1))
prio = string.atoi(m.group(2))
total_sz = pattern_searcher_msg.header_len + sz \
+ pattern_searcher_msg.trailer_len
a = b - total_sz
if dbg>=2:
LOG("pattern_searcher_msg : "
"found %d bytes [%s ...]\n" % \
(total_sz, frag[a:a + 30]))
return a,b,prio
else:
return None
def get_overlap(self):
return pattern_searcher_msg.trailer_len - 1
# -------------------------------------------------------------------
# events for high level channels
# -------------------------------------------------------------------
class ch_event:
OK = 0 # got OK data
IO_ERROR = -1 # got IO error
TIMEOUT = -2 # got timeout
EOF = -3 # got EOF
kind_to_str = {
OK : "OK",
IO_ERROR : "IO_ERROR",
TIMEOUT : "TIMEOUT",
EOF : "EOF"
}
def __init__(self, kind):
self.kind = kind
def kind_str(self):
return ch_event.kind_to_str[self.kind]
class revent(ch_event):
"""
a read event represents an event in which an amount of data
has been received
"""
def __init__(self, kind, data):
ch_event.__init__(self, kind)
self.data = data
self.err_msg = ""
class wevent(ch_event):
pass
class aevent(ch_event):
pass
class revent_OK(revent):
def __init__(self, data):
revent.__init__(self, ch_event.OK, data)
class revent_IO_ERROR(revent):
def __init__(self, data, err_msg):
revent.__init__(self, ch_event.IO_ERROR, data)
self.err_msg = err_msg
class revent_EOF(revent):
def __init__(self, data):
revent.__init__(self, ch_event.EOF, data)
class revent_TIMEOUT(revent):
def __init__(self, data):
revent.__init__(self, ch_event.TIMEOUT, data)
class wevent_OK(wevent):
def __init__(self, tag, written):
wevent.__init__(self, ch_event.OK)
self.tag = tag
self.written = written
class wevent_IO_ERROR(wevent):
def __init__(self, err_msg):
wevent.__init__(self, ch_event.IO_ERROR)
self.err_msg = err_msg
class wevent_TIMEOUT(wevent):
def __init__(self):
wevent.__init__(self, ch_event.TIMEOUT)
self.err_msg = "timeout"
class aevent_OK(aevent):
def __init__(self, new_so, addr):
aevent.__init__(self, ch_event.OK)
self.new_so = new_so
self.addr = addr
class aevent_IO_ERROR(aevent):
def __init__(self, err_msg):
aevent.__init__(self, ch_event.IO_ERROR)
self.err_msg = err_msg
class aevent_TIMEOUT(aevent):
def __init__(self):
aevent.__init__(self, ch_event.TIMEOUT)
# -------------------------------------------------------------------
# high level channel interface
# -------------------------------------------------------------------
class channel:
def __init__(self, pch):
# pch : underlying primitive channel
self.pch = pch
# timelimit
self.x_timelimit = INF
# deamon managing this channel
self.iom = None
# self.preference = 0
def set_ioman(self, iom):
self.iom = iom
def close(self):
"""
Close the underlying primitive fd/socket.
This may double-close because a primitive channel may
be shared by multiple (high-level) channels.
primitive_channel.close prevents double close of fd/socket
"""
self.pch.close()
def is_closed(self):
return self.pch.is_closed()
def fileno(self):
"""
Called by select. we must ensure closed channels are
never passed to select, so we never pass -1 to select.
Just for the sake of logging purposes, we gently return
-1 when called on closed channels
"""
if self.is_closed():
return -1
else:
return self.pch.fileno()
def set_timeout(self, timeout):
if timeout == INF: # infinite
self.x_timelimit = INF
else:
self.x_timelimit = time.time() + timeout
def is_garbage(self):
"""
1 if this channel will never generate further events,
so it does not have to be checked by IO manager.
Basically, a closed channel is usually a garbage, but even
if it is closed, it is not a garbage if there are some
pending events (buffered items previously read).
"""
if self.is_closed() and self.has_pending_events() == 0:
return 1
else:
return 0
# --------- abstract stuff to be implemented in subclass
def discard(self):
"""
make this channel garbage.
"""
should_be_implemented_in_subclasses()
def has_pending_events(self):
"""
1 if there are some pending events that can be generated
without performing any IO. For read channels, it is true
when there are some buffered iterms previously read.
If there are some channels who have pending events,
the IO manager should not block waiting for IO.
"""
should_be_implemented_in_subclasses()
def want_io(self):
should_be_implemented_in_subclasses()
def do_io(self):
should_be_implemented_in_subclasses()
def do_timeout(self):
should_be_implemented_in_subclasses()
def process_event(self, ev):
should_be_implemented_in_subclasses()
# -------------------------------------------------------------------
# read channel
# -------------------------------------------------------------------
class rchannel(channel):
"""
abstract base class for high-level channels to read
"""
# default_read_gran = 150000
default_read_gran = 10000
def __init__(self, pch):
channel.__init__(self, pch)
# receiver's expectation
self.expected = []
# we know pending[:cursor] does not match any expected msg
self.cursor = 0
# msgs received, but does not match receiver's expectation
self.pending = string_buffer()
# set to an appropriate status when got EOF/IO_ERROR/TIMEOUT
self.pending_close = []
# msgs received and match
# self.deliver_q = prio_queue()
# read granularity (approx. 10K)
self.set_read_gran(rchannel.default_read_gran)
def set_read_gran(self, g):
if g < 1: g = 1
self.read_gran = g
def discard(self):
self.close()
del self.pending[:]
del self.pending_close[:]
self.cursor = 0
assert self.is_garbage()
def has_pending_events(self):
if self.cursor < len(self.pending):
return 1
else:
return 0