-
Notifications
You must be signed in to change notification settings - Fork 3
/
fast_indexer.py
216 lines (184 loc) · 7.14 KB
/
fast_indexer.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
""" Fast indexer
Supports fast query of posts from a certain thread.
"""
import threading
import os
import time
import sqlite3
import BoardManager
import PostEntry
import Config
from Log import Log
from Util import Util
INDEX_INTERVAL = 15
INDEX_DB = "index.db"
class State(object):
""" FastIndexer's shared state """
def __init__(self):
self.locks = {}
class IndexBoardInfo(object):
""" Indexing status of one board """
def __init__(self, board, last_idx):
self.board = board
self.last_idx = last_idx
class FastIndexer(threading.Thread):
""" The Fast Indexer """
def __init__(self, state):
threading.Thread.__init__(self)
self.stopped = False
self.board_info = {}
self.conn = None
self.init_conn()
self.load_idx_status()
self.state = state
Log.info("FastIndexer init...")
try:
self.index_boards()
except Exception as exc:
Log.error("Exception caught initializing FastIndexer: %r" % exc)
raise exc
Log.info("FastIndexer inited")
self.close_conn()
def init_conn(self):
""" Initialize database connection """
self.conn = sqlite3.connect(os.path.join(Config.BBS_ROOT, INDEX_DB),
detect_types=sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES)
self.conn.row_factory = sqlite3.Row
def close_conn(self):
""" Close database connection """
self.conn.close()
def run(self):
Log.info("FastIndexer start")
self.init_conn()
while True:
if self.stopped:
break
try:
self.index_boards()
except Exception as exc:
Log.error("Exception caught in FastIndexer: %r" % exc)
time.sleep(INDEX_INTERVAL)
self.close_conn()
def init_buf(self, board):
""" Initialize buffer table. """
self.conn.execute("drop table if exists %s"
% buf_table_name(board))
self.conn.execute("create table %s("\
"id int, xid int, tid int, rid int, time int"\
")" % buf_table_name(board))
self.conn.commit()
def load_idx_status(self):
""" Load latest indexing status. """
self.conn.execute("create table if not exists status("\
"board text, last_idx int)")
self.conn.commit()
try:
for row in self.conn.execute("select * from status"):
idx_info = IndexBoardInfo(**row)
self.board_info[idx_info.board] = idx_info
except:
Log.info("Index info not present")
def insert_idx_status(self, idx_obj):
""" Insert new indexing status for 'idx_obj'. """
self.conn.execute("insert into status values (?, ?)",
(idx_obj.board, idx_obj.last_idx))
self.conn.commit()
def remove_idx_status(self, idx_obj):
""" Remove indexing status for 'idx_obj'. """
self.conn.execute("delete from status where board=?",
(idx_obj.board, ))
self.conn.commit()
def index_boards(self):
""" Index all the boards. """
boards = BoardManager.BoardManager.boards.keys()
for board in boards:
try:
self.index_board(board)
except Exception as exc:
Log.error("Exception caught when indexing %s: %r"
% (board, exc))
def index_board(self, board):
""" Index one board (name: board)"""
boardobj = BoardManager.BoardManager.GetBoard(board)
if not boardobj:
Log.error("Error loading board %s" % board)
return
if board in self.board_info:
idx_obj = self.board_info[board]
else:
idx_obj = IndexBoardInfo(board, 0)
self.board_info[board] = idx_obj
bdir_path = boardobj.GetDirPath()
with open(bdir_path, 'rb') as bdir:
Util.FLock(bdir, shared=True)
try:
if not board in self.state.locks:
self.state.locks[board] = threading.Lock()
status = os.stat(bdir_path)
if status.st_mtime <= idx_obj.last_idx:
# why <? anyway...
return
Log.debug("Board %s updated. Indexing..." % board)
# index into buffer table
self.init_buf(board)
for idx in xrange(status.st_size / PostEntry.PostEntry.size):
post_entry = PostEntry.PostEntry(
bdir.read(PostEntry.PostEntry.size))
self.insert_entry(board, post_entry, idx)
self.conn.commit()
# commit buffer table
self.state.locks[board].acquire()
try:
self.remove_idx_status(idx_obj)
self.commit_buf(board)
self.create_db_index(board)
idx_obj.last_idx = status.st_mtime
self.insert_idx_status(idx_obj)
finally:
self.state.locks[board].release()
Log.debug("Board %s indexed." % board)
finally:
Util.FUnlock(bdir)
def insert_entry(self, board, post_entry, idx):
""" Insert into the buffer board """
self.conn.execute("insert into %s values (?, ?, ?, ?, ?)"
% buf_table_name(board),
(idx, post_entry.id, post_entry.groupid,
post_entry.reid, post_entry.GetPostTime()))
# batch commit later
def commit_buf(self, board):
""" Rename the temporary table to final table """
self.conn.execute("drop table if exists %s" % table_name(board))
self.conn.execute("alter table %s rename to %s" %
(buf_table_name(board), table_name(board)))
self.conn.commit()
def create_db_index(self, board):
""" Create database index for faster query. """
idx_name = "idx_tid_%s" % board
self.conn.execute("drop index if exists %s" % idx_name)
self.conn.execute("create index %s on %s ( tid )" %
(idx_name, table_name(board)))
self.conn.commit()
def query_by_tid(state, board, tid, start, count):
""" Query in the index of board 'board' for all threads with tid 'tid'
starting from 'start', return 'count' results """
conn = sqlite3.connect(os.path.join(Config.BBS_ROOT, INDEX_DB),
detect_types=sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES)
conn.row_factory = sqlite3.Row
state.locks[board].acquire()
try:
result = []
for row in conn.execute(
"select id, xid from %s where tid=? order by id limit %d offset %d"
% (table_name(board), count, start), (tid, )):
result.append((row['id'] + 1, row['xid']))
finally:
state.locks[board].release()
conn.close()
return result
def table_name(board):
""" Table name for board 'board' """
return "idx_" + board
def buf_table_name(board):
""" Temporary table name for board 'board' """
return "tmp_idx_" + board