]> git.phdru.name Git - bookmarks_db.git/blob - Robots/bkmk_rforking.py
e1b4ee24a74d3717317855e8cb9eede270f9f423
[bookmarks_db.git] / Robots / bkmk_rforking.py
1 """Forking robot
2
3 This file is a part of Bookmarks database and Internet robot.
4 """
5
6 __author__ = "Oleg Broytman <phd@phdru.name>"
7 __copyright__ = "Copyright (C) 2000-2012 PhiloSoft Design"
8 __license__ = "GNU GPL"
9
10 __all__ = ['robot_forking']
11
12
13 import sys, os
14
15 try:
16    import cPickle as pickle
17 except ImportError:
18    import pickle
19
20 from subproc import Subprocess, RecordFile
21 from bkmk_objects import Robot
22
23
24 # This is to catch 'close failed: [Errno 9] Bad file descriptor' message
25 # from os.close() in Subprocess.die() and errors from the subprocess.
26 sys.stderr = open("err.log", 'a')
27
28 check_subp = None
29 subp_pipe = None
30
31 def stop_subp(log):
32    global check_subp, subp_pipe
33    if check_subp:
34       if log: log("   restarting hanging subprocess")
35       del check_subp
36    del subp_pipe
37
38 def restart_subp(log):
39    global check_subp, subp_pipe
40    stop_subp(log)
41
42    check_subp = Subprocess("%s/Robots/bkmk_rforking_sub.py" % os.path.dirname(sys.argv[0]),
43       control_stderr=True)
44    subp_pipe = RecordFile(check_subp)
45
46
47 _set_subproc = True
48
49 class robot_forking(Robot):
50    subproc = 'urllib' # Default subprocess
51
52    def check_url(self, bookmark):
53       global _set_subproc
54       if _set_subproc:
55          _set_subproc = False
56          os.environ['BKMK_ROBOT'] = self.subproc
57
58       if not check_subp:
59          restart_subp(self.log) # Not restart, just start afresh
60
61       try:
62          save_parent = bookmark.parent
63          bookmark.parent = None
64          subp_pipe.write_record(pickle.dumps(bookmark))
65
66          if check_subp.waitForPendingChar(60): # wait a minute
67             new_b = pickle.loads(subp_pipe.read_record())
68             for attr in ("error", "no_error",
69                   "moved", "size", "md5", "real_title",
70                   "last_tested", "last_modified", "test_time",
71                   "icon", "icon_href"):
72                if hasattr(new_b, attr):
73                   setattr(bookmark, attr, getattr(new_b, attr))
74          else:
75             bookmark.error = "Subprocess connection timed out"
76             restart_subp(self.log)
77
78          bookmark.parent = save_parent
79
80          while True:
81             error = check_subp.readPendingErrLine()
82             if not error:
83                break
84             sys.stderr.write("(subp) " + error)
85          sys.stderr.flush()
86
87       except KeyboardInterrupt:
88          return 0
89
90       # Tested
91       return 1
92
93    def stop(self):
94       stop_subp(None) # Stop subprocess; do not log restarting