forked from SublimeCodeIntel/SublimeCodeIntel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindexer.py
999 lines (875 loc) · 38.1 KB
/
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
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
#!python
# ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1/GPL 2.0/LGPL 2.1
#
# The contents of this file are subject to the Mozilla Public License
# Version 1.1 (the "License"); you may not use this file except in
# compliance with the License. You may obtain a copy of the License at
# http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS IS"
# basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
# License for the specific language governing rights and limitations
# under the License.
#
# The Original Code is Komodo code.
#
# The Initial Developer of the Original Code is ActiveState Software Inc.
# Portions created by ActiveState Software Inc are Copyright (C) 2000-2007
# ActiveState Software Inc. All Rights Reserved.
#
# Contributor(s):
# ActiveState Software Inc
#
# Alternatively, the contents of this file may be used under the terms of
# either the GNU General Public License Version 2 or later (the "GPL"), or
# the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
# in which case the provisions of the GPL or the LGPL are applicable instead
# of those above. If you wish to allow use of your version of this file only
# under the terms of either the GPL or the LGPL, and not to allow others to
# use your version of this file under the terms of the MPL, indicate your
# decision by deleting the provisions above and replace them with the notice
# and other provisions required by the GPL or the LGPL. If you do not delete
# the provisions above, a recipient may use your version of this file under
# the terms of any one of the MPL, the GPL or the LGPL.
#
# ***** END LICENSE BLOCK *****
"""The codeintel indexer is a thread that handles scanning files and
loading them into the database. There is generally one indexer on the
Manager instance.
mgr.idxr = Indexer(mgr)
XXX A separate indexer instance may be used for batch updates of the db.
"""
# TODO:
# - How are scan errors handled? do we try to keep from re-scanning over
# and over? Perhaps still use mtime to only try again on new content.
# Could still have a "N strikes in the last 1 minute" rule or
# something.
# - batch updating (still wanted? probably)
import os, sys
import threading
import time
import bisect
import Queue
from hashlib import md5
import traceback
import logging
from codeintel2.common import *
from codeintel2.buffer import Buffer
from codeintel2.database.langlib import LangDirsLib
from codeintel2.database.multilanglib import MultiLangDirsLib
if _xpcom_:
from xpcom.server import UnwrapObject
#---- globals
log = logging.getLogger("codeintel.indexer")
#log.setLevel(logging.DEBUG)
#---- internal support
class _PriorityQueue(Queue.Queue):
"""A thread-safe priority queue.
In order to use this the inserted items should be tuples with the
priority first. Note that subsequent elements of the item tuples will
be used for secondary sorting. As a result, it is often desirable to
make the second tuple index be a timestamp so that the queue is a
FIFO for elements with the same priority, e.g.:
item = (PRIORITY, time.time(), element)
Usage:
q = _PriorityQueue(0) # unbounded queue
q.put( (2, time.time(), "second") )
q.put( (1, time.time(), "first") )
q.put( (3, time.time(), "third") )
priority, timestamp, value = q.get()
"""
def _put(self, item):
bisect.insort(self.queue, item)
# The following are to ensure a *list* is being used as the internal
# Queue data structure. Python 2.4 switched to using a deque
# internally which doesn't have the insert() method that
# bisect.insort() uses.
def _init(self, maxsize):
self.maxsize = maxsize
self.queue = []
def _get(self):
return self.queue.pop(0)
class _Request(object):
"""Base class for a queue-able thing.
A request object must have an 'id'. This is used for "staging"
requests on the queue. A staged request will sit around for 'delay'
amount of time before actually being put on the processing queue.
During that wait, a subsequent stage request with the same 'id' will
replace the first one -- including resetting the delay. This is
useful for staging relatively expensive processing in the background
for content that is under ongoing changes (e.g. for processing an
editor buffer while it is being editted).
"""
#XXX PERF: use a slot?
id = None
def __init__(self, id=None):
if id is not None:
self.id = id
class _UniqueRequestPriorityQueue(_PriorityQueue):
"""A thread-safe priority queue for '_Request' objects.
This queue class extends _PriorityQueue with the condition that:
When adding a _Request to the queue, if a _Request with the same id
already exists in the queue, then the new _Request inherits the
higher priority and the earlier timestamp of the two and _replaces_
the older _Request.
This condition is added because there is no point in scanning file
contents from time T1 when a scan of the file contents at time T2
(more recent) is being requested. It is important to adopt the
higher priority (and earlier timestamp) to ensure the requestor does
not starve.
Note: This presumes that an "item" is this 3-tuple:
(<priority-number>, <timestamp>, <_Request instance>)
"""
def __init__(self, maxsize=0):
_PriorityQueue.__init__(self, maxsize)
self._item_from_id = {}
def _put(self, item):
# Remove a possible existing request for the same file (there can
# be only one).
priority, timestamp, request = item
id = request.id
if id in self._item_from_id:
i = self._item_from_id[id]
self.queue.remove(i)
p, t, r = i
item = (min(priority, p), t, request)
# Add the (possibly updated) item to the queue.
self._item_from_id[id] = item
_PriorityQueue._put(self, item)
def _get(self):
item = _PriorityQueue._get(self)
del self._item_from_id[item[-1].id]
return item
class _StagingRequestQueue(_UniqueRequestPriorityQueue):
"""A thread-safe priority queue for '_Request' objects with delayed
staging support.
This queue class extends _UniqueRequestPriorityQueue by adding the
.stage() method. This method is like the regular .put() method
except that staged requests are only actually placed on the queue if
a certain period of inactivity passes without subsequent stage
requests for the same request id.
This is to support reasonable performance for live updating while a
document is being edited. Rather than executing a scan for every
intermediate edited state, scanning is only after a period of
relative inactivity.
One additional burden is that a "staging thread" is involved so one must
call this queue's .finalize() method to properly shut it down.
As with the _ScanRequestQueue this queue presumes that and item is this
3-tuple:
(<priority-number>, <timestamp>, <ScanRequest instance>)
"""
DEFAULT_STAGING_DELAY = 1.5 # default delay from on deck -> on queue (s)
def __init__(self, maxsize=0, stagingDelay=None):
"""Create a staging scan request queue.
"maxsize" (optional) is an upperbound limit on the number of
items in the queue (<= 0 means the queue is unbounded).
"stagingDelay" (optional) is a number of seconds to use as a
delay from being staged to being placed on the queue.
"""
_UniqueRequestPriorityQueue.__init__(self, maxsize)
if stagingDelay is None:
self._stagingDelay = self.DEFAULT_STAGING_DELAY
else:
self._stagingDelay = stagingDelay
self._onDeck = {
# <request-id> : (<time when due>, <priority>, <queue item>)
}
self._nothingOnDeck = threading.Lock()
self._nothingOnDeck.acquire()
self._terminate = 0 # boolean telling "staging thread" to terminate
self._stager = threading.Thread(target=self._stagingThread,
name="request staging thread")
self._stager.setDaemon(True)
self._stager.start()
def finalize(self):
if self._stager:
self._terminate = 1
# Make sure staging thread isn't blocked so it can terminate.
self.mutex.acquire()
try:
if not self._onDeck:
self._nothingOnDeck.release()
finally:
self.mutex.release()
# Don't bother join'ing because there is no point waiting for
# up to self._stagingDelay while the staging thread shuts down.
#self._stager.join()
def stage(self, item, delay=None):
if delay is None:
delay = self._stagingDelay
self.mutex.acquire()
try:
priority, timestamp, request = item
wasEmpty = not self._onDeck
if request.id not in self._onDeck \
or self._onDeck[request.id][1] != PRIORITY_IMMEDIATE:
self._onDeck[request.id] = (timestamp + delay, priority, item)
if wasEmpty:
self._nothingOnDeck.release()
finally:
self.mutex.release()
def _stagingThread(self):
"""Thread that handles moving requests on-deck to the queue."""
log.debug("staging thread: start")
while 1:
# If nothing is on-deck, wait until there is.
#log.debug("staging thread: acquire self._nothingOnDeck")
self._nothingOnDeck.acquire()
#log.debug("staging thread: acquired self._nothingOnDeck")
if self._terminate:
break
# Place any "due" items on the queue.
self.mutex.acquire()
somethingStillOnDeck = 1
currTime = time.time()
toQueue = []
try:
for id, (timeDue, priority, item) in self._onDeck.items():
if currTime >= timeDue:
toQueue.append(item)
del self._onDeck[id]
if not self._onDeck:
somethingStillOnDeck = 0
finally:
if somethingStillOnDeck:
self._nothingOnDeck.release()
self.mutex.release()
if toQueue:
log.debug("staging thread: queuing %r", toQueue)
for item in toQueue:
self.put(item)
# Sleep for a bit.
#XXX If the latency it too large we may want to sleep for some
# fraction of the staging delay.
log.debug("staging thread: sleep for %.3fs", self._stagingDelay)
time.sleep(self._stagingDelay)
log.debug("staging thread: end")
#---- public classes
class XMLParseRequest(_Request):
"""A request to re-parse and XML-y/HTML-y file
(For XML completion and Komodo's DOMViewer.)
"""
def __init__(self, buf, priority, force=False):
if _xpcom_:
buf = UnwrapObject(buf)
self.buf = buf
self.id = buf.path + "#xml-parse"
self.priority = priority
self.force = force
def __repr__(self):
return "<XMLParseRequest %r>" % self.id
def __str__(self):
return "xml parse '%s' (prio %s)" % (self.buf.path, self.priority)
class ScanRequest(_Request):
"""A request to scan a file for codeintel.
A ScanRequest has the following properties:
"buf" is the CitadelBuffer instance.
"priority" must be one of the PRIORITY_* priorities.
"force" is a boolean indicating if a scan should be run even if
the database is already up-to-date for this content.
"mtime" is the modified time of the file/content. If not given
it defaults to the current time.
"on_complete" (optional) is a callable to call when the scan
and load is complete. (XXX: Is this being used by anyone?)
"status" is set on completion. See .complete() docstring for details.
"""
status = None
def __init__(self, buf, priority, force=False, mtime=None, on_complete=None):
if _xpcom_:
buf = UnwrapObject(buf)
self.buf = buf
self.id = buf.path
self.priority = priority
self.force = force
if mtime is None:
self.mtime = time.time()
else:
self.mtime = mtime
self.on_complete = on_complete
self.complete_event = threading.Event() #XXX use a pool
def __repr__(self):
return "<ScanRequest %r>" % self.id
def __str__(self):
return "scan request '%s' (prio %s)" % (self.buf.path, self.priority)
def complete(self, status):
"""Called by scheduler when this scan is complete (whether or
not it was successful/skipped/whatever).
"status" is one of the following:
changed The scan was done and (presumably) something
changed. PERF: Eventually want to be able to
detect when an actual change is made to be
used elsewhere to know not to update.
skipped The scan was skipped.
"""
log.debug("complete %s", self)
self.status = status
self.complete_event.set()
if self.on_complete:
try:
self.on_complete()
except:
log.exception("ignoring exception in ScanRequest "
"on_complete callback")
def wait(self, timeout=None):
"""Can be called by code requesting a scan to wait for completion
of this particular scan.
"""
self.complete_event.wait(timeout)
class PreloadBufLibsRequest(_Request):
priority = PRIORITY_BACKGROUND
def __init__(self, buf):
if _xpcom_:
buf = UnwrapObject(buf)
self.buf = buf
self.id = buf.path + "#preload-libs"
def __repr__(self):
return "<PreloadBufLibsRequest %r>" % self.id
def __str__(self):
return "pre-load libs for '%s'" % self.buf.path
class PreloadLibRequest(_Request):
priority = PRIORITY_BACKGROUND
def __init__(self, lib):
self.lib = lib
self.id = "%s %s with %s dirs#preload-lib" \
% (lib.lang, lib.name, len(lib.dirs))
def __repr__(self):
return "<PreloadLibRequest %r>" % self.id
def __str__(self):
return "pre-load %s %s (%d dirs)" \
% (self.lib.lang, self.lib.name, len(self.lib.dirs))
class IndexerStopRequest(_Request):
id = "indexer stop request"
priority = PRIORITY_CONTROL
def __repr__(self):
return '<'+self.id+'>'
class IndexerPauseRequest(_Request):
id = "indexer pause request"
priority = PRIORITY_CONTROL
def __repr__(self):
return '<'+self.id+'>'
class Indexer(threading.Thread):
"""A codeintel indexer thread.
An indexer is mainly responsible for taking requests to scan
(Citadel) buffers and load the data into the appropriate LangZone of
the database.
#XXX Only needed when/if batch updating is redone.
## This thread manages a queue of ScanRequest's, scheduling the scans in
## priority order. It has two modes of usage:
## MODE_DAEMON
## The scheduler remains running until it is explicitly stopped with
## the .stop() method.
## MODE_ONE_SHOT
## All added requests are processed and then the scheduler
## terminates. Note that the .stageRequest() method is not
## allowed in this mode.
Usage:
from codeintel.indexer import Indexer
idxr = Indexer(mgr)
idxr.start()
try:
# idxr.stage_request(<request>)
# idxr.add_request(<request>)
finally:
idxr.finalize()
Dev Notes:
- The intention is the indexer will grow to handle other requests as
well (saving and culling cached parts of the database).
- There is a potential race condition on request id generation
if addRequest/stageRequest calls are made from multiple threads.
"""
MODE_DAEMON, MODE_ONE_SHOT = range(2)
mode = MODE_DAEMON
class StopIndexing(Exception):
"""Used to signal that indexer iteration should stop.
Dev Note: I *could* use StopIteration here, but I don't want to
possibly misinterpret a real StopIteration.
"""
pass
def __init__(self, mgr, on_scan_complete=None):
"""
"on_scan_complete" (optional), if specified, is called when
a ScanRequest is completed.
TODO: add back the requestStartCB and completedCB (for batch updates)
"""
threading.Thread.__init__(self, name="codeintel indexer")
self.setDaemon(True)
self.mgr = mgr
self.on_scan_complete = on_scan_complete
if self.mode == self.MODE_DAEMON:
self._requests = _StagingRequestQueue()
else:
self._requests = _UniqueRequestPriorityQueue()
self._stopping = False
self._resumeEvent = None
def finalize(self):
"""Shutdown the indexer.
This must be done even if the the indexer thread was never
.start()'ed -- because of the thread used for the
_StagingRequestQueue.
"""
self._stopping = True
if isinstance(self._requests, _StagingRequestQueue):
self._requests.finalize()
if self.isAlive():
self.add_request(IndexerStopRequest())
try:
self.join(5) # see bug 77284
except AssertionError:
pass # thread was not started
def pause(self):
self._resumeEvent = threading.Event()
self._pauseEvent = threading.Event()
#TODO: shouldn't this be `self.add_request`?
self.addRequest(IndexerPauseRequest())
self._pauseEvent.wait() # wait until the Scheduler is actually paused
log.debug("indexer: paused")
def resume(self):
if self._resumeEvent:
self._resumeEvent.set()
self._resumeEvent = None
log.debug("indexer: resumed")
def stage_request(self, request, delay=None):
log.debug("stage %r", request)
if self.mode == self.MODE_ONE_SHOT:
raise CodeIntelError("cannot call stage requests on a "
"MODE_ONE_SHOT indexer")
#self._abortMatchingRunner(request.buf.path, request.buf.lang)
self._requests.stage( (request.priority, time.time(), request), delay )
def add_request(self, request):
log.debug("add %r", request)
#self._abortMatchingRunner(request.buf.path, request.buf.lang)
self._requests.put( (request.priority, time.time(), request) )
#XXX re-instate for batch updating (was getNumRequests)
## def num_requests(self):
## return self._requests.qsize()
def run(self): # the scheduler thread run-time
log.debug("indexer: start")
## reason = "failed"
try:
while 1:
try:
self._iteration()
except Queue.Empty: # for mode=MODE_ONE_SHOT only
## reason = "completed"
break
except self.StopIndexing:
## reason = "stopped"
break
except:
# Because we aren't fully waiting for indexer
# termination in `self.finalize` it is possible that
# an ongoing request fails (Manager finalization
# destroys the `mgr.db` instance). Don't bother
# logging an error if we are stopping.
#
# Note: The typical culprit is a *long*
# <PreloadBufLibsRequest> for a PHP or JS library
# dir. Ideally this would be split into a number of
# lower-prio indexer requests.
if not self._stopping:
log.exception("unexpected internal error in indexer: "
"ignoring and continuing")
finally:
## try:
## if self._completedCB:
## self._completedCB(reason)
## except:
## log.exception("unexpected error in completion callback")
log.debug("indexer thread: stopped")
def _iteration(self):
"""Handle one request on the queue.
Raises StopIndexing exception if iteration should stop.
"""
#log.debug("indexer: get request")
if self.mode == self.MODE_DAEMON:
priority, timestamp, request = self._requests.get()
else: # mode == self.MODE_ONE_SHOT
priority, timestamp, request = self._requests.get_nowait()
#log.debug("indexer: GOT request")
try:
if request.priority == PRIORITY_CONTROL: # sentinel
if isinstance(request, IndexerStopRequest):
raise self.StopIndexing()
elif isinstance(request, IndexerPauseRequest):
self._pauseEvent.set() # tell .pause() that Indexer has paused
self._resumeEvent.wait()
return
else:
raise CodeIntelError("unexpected indexer control "
"request: %r" % request)
if isinstance(request, ScanRequest):
# Drop this request if the database is already up-to-date.
db = self.mgr.db
buf = request.buf
status = "changed"
if not request.force:
scan_time_in_db = db.get_buf_scan_time(buf)
if scan_time_in_db is not None \
and scan_time_in_db > request.mtime:
log.debug("indexer: drop %s: have up-to-date data for "
"%s in the db", request, buf)
status = "skipped"
return
buf.scan(mtime=request.mtime)
elif isinstance(request, XMLParseRequest):
request.buf.xml_parse()
# Currently these two are somewhat of a DB zone-specific hack.
#TODO: The standard DB "lib" iface should grow a
# .preload() (and perhaps .can_preload()) with a
# ctlr arg. This should be unified with the current
# StdLib.preload().
elif isinstance(request, PreloadBufLibsRequest):
for lib in request.buf.libs:
if isinstance(lib, (LangDirsLib, MultiLangDirsLib)):
for dir in lib.dirs:
lib.ensure_dir_scanned(dir)
elif isinstance(request, PreloadLibRequest):
lib = request.lib
assert isinstance(lib, (LangDirsLib, MultiLangDirsLib))
for dir in lib.dirs:
lib.ensure_dir_scanned(dir)
finally:
if isinstance(request, ScanRequest):
request.complete(status)
if self.on_scan_complete:
try:
self.on_scan_complete(request)
except:
log.exception("ignoring exception in Indexer "
"on_scan_complete callback")
#TODO: I believe this is unused. Drop it.
class BatchUpdater(threading.Thread):
"""A scheduler thread for batch updates to the CIDB.
Usage:
# May want to have a subclass of BatchUpdater for fine control.
updater = BatchUpdater()
updater.add_request(...) # Make one or more requests.
mgr.batch_update(updater=updater) # This will start the updater.
# Optionally use/override methods on the updater to control/monitor
# the update.
# Control methods:
# abort() Abort the update.
# join(timeout=None) Wait for the update to complete.
#
# Query methods:
# num_files_to_process()
# is_aborted()
#
# Monitoring methods (need to override these in subclass to catch):
# debug(msg, *args)
# info(msg, *args)
# warn(msg, *args)
# error(msg, *args)
# progress(stage, obj)
# done(reason) Called when complete.
Dev Notes:
- Yes, there are two ways to get code run on completion:
.start(..., on_complete=None) intended for the controlling Citadel
.done() intended for the sub-classing user
"""
citadel = None
on_complete = None
_aborted = None
def __init__(self):
XXX
threading.Thread.__init__(self, name="CodeIntel Batch Scheduler")
self.setDaemon(True)
self._requests = Queue.Queue()
self.mode = None # "upgrade", "non-upgrade" or None
self._scheduler = None # lazily created (if necessary) Scheduler
#XXX Need these two anymore?
self._completion_reason = None
self._had_errors = False
def start(self, citadel, on_complete=None):
self.citadel = citadel
self.on_complete = on_complete
threading.Thread.start(self)
def abort(self):
"""Abort the batch update.
XXX The scheduler.stop() call will *block* until the scheduler is
done. Don't want that, but need to rationalize with other
calls to Scheduler.stop().
"""
self._aborted = True
if self._scheduler:
self._scheduler.stop()
def is_aborted(self):
return self._aborted
def done(self, reason):
"""Called when the update is complete.
"reason" is a short string indicating how the batch update
completed. Currently expected values are (though this
may not be rigorous):
aborted
error
success
failed (from Scheduler)
completed (from Scheduler)
stopped (from Scheduler)
XXX Might be helpful to rationalize these.
"""
self.info("done: %s", reason)
def add_request(self, type, path, language=None, extra=None):
"""Add a batch request
"type" is one of:
language scan a language installation
cix import a CIX file
directory scan a source directory
upgrade upgrade a CIDB file to the current version
"path", depending on "type" is the full path to:
language a language installation
cix a CIX file
directory a source directory
upgrade a CIDB file
"language", depending on "type" is:
language the language of the language installation
cix (not relevant, should be None)
directory the language of the source directory
upgrade (not relevant, should be None)
"extra" is an optional (null if not used) extra value depending
on the type, path and/or language of the request that may be
request for processing it. For example, a PHP language batch
update request uses the "extra" field to specify the
"php.ini"-config-file path.
"""
if self.isAlive():
raise CodeIntelError("cannot add a batch update request while "
"the batch scheduler is alive")
if type in ("language", "cix", "directory", "upgrade"):
if type in ("language", "cix", "directory"):
if self.mode == "upgrade":
raise CodeIntelError("cannot mix 'upgrade' batch requests "
"with other types: (%s, %s, %s, %s)"
% (type, path, language, extra))
self.mode = "non-upgrade"
elif type == "upgrade":
if self.mode == "non-upgrade":
raise CodeIntelError("cannot mix 'upgrade' batch requests "
"with other types: (%s, %s, %s, %s)"
% (type, path, language, extra))
self.mode = "upgrade"
self._requests.put( (type, path, language, extra) )
else:
raise CodeIntelError("unknown batch update request type: '%s'"
% type)
def num_files_to_process(self):
"""Return the number of files remaining to process."""
#XXX Might want to do something for "upgrade" mode here.
if self._scheduler:
return self._scheduler.getNumRequests()
else:
return 0
def progress(self, msg, data):
"""Report progress.
"msg" is some string, generally used to indicate a stage of
processing
"data" is some object dependent on the value of "msg".
"""
self.info("progress: %s %r", msg, data)
def debug(self, msg, *args):
log.debug(msg, *args)
def info(self, msg, *args):
log.info(msg, *args)
def warn(self, msg, *args):
log.warn(msg, *args)
def error(self, msg, *args):
log.error(msg, *args)
def _subscheduler_request_started(self, request):
"""Callback from sub-Scheduler thread."""
self.progress("scanning", request)
def _subscheduler_completed(self, reason):
"""Callback from sub-Scheduler thread."""
self._completion_reason = reason
def _get_scheduler(self):
if not self._scheduler:
self._scheduler = Scheduler(Scheduler.MODE_ONE_SHOT,
self.citadel,
None,
self._subscheduler_request_started,
self._subscheduler_completed)
return self._scheduler
def run(self):
log.debug("batch scheduler thread: start")
self.errors = []
try:
while 1:
if self._aborted:
self._completion_reason = "aborted"
break
try:
type_, path, lang, extra = self._requests.get_nowait()
self.debug("handle %r batch update request: "
"path=%r, language=%r, extra=%r",
type_, path, lang, extra)
if type_ == "upgrade":
self._handle_upgrade_request(path)
elif type_ == "language":
self._handle_lang_request(path, lang, extra)
elif type_ == "cix":
self._handle_cix_request(path)
elif type_ == "directory":
self._handle_directory_request(path, lang)
else:
raise CitadelError(
"unexpected batch request type: '%s'" % type_)
except Queue.Empty:
break
except Exception, ex:
self._had_errors = True
self.error("unexpected error handling batch update:\n%s",
_indent(traceback.format_exc()))
break
if self._had_errors:
log.debug("batch scheduler thread: error out")
self._completion_reason = "error"
elif self.mode == "upgrade":
self._completion_reason = "success"
elif self._scheduler: # No Scheduler for "upgrade" batch mode.
# Phase 2: start the scheduler and wait for it to complete.
self._scheduler.start()
self._scheduler.join()
if self._had_errors:
self._completion_reason = "error"
else:
self._completion_reason = "success"
finally:
log.debug("batch scheduler thread: stop scheduler")
if self._scheduler:
self._scheduler.stop()
log.debug("batch scheduler thread: scheduler stopped, call on_complete")
if self.on_complete:
try:
self.on_complete()
except:
log.exception("error in batch scheduler on_complete "
"(ignoring)")
log.debug("batch scheduler thread: on_complete called, call done")
self.done(self._completion_reason)
log.debug("batch scheduler thread: done called")
log.debug("batch scheduler thread: end")
def _cidb_upgrade_progress_callback(self, stage, percent):
self.progress("upgrade", (stage, percent))
def _handle_upgrade_request(self, dbPath):
db = Database(self.citadel)
starttime = time.time()
try:
currVer = db.upgrade(dbPath, self._cidb_upgrade_progress_callback)
except CodeIntelError, ex:
self._had_errors = True
self.error("Error upgrading CIDB: %s\n%s",
ex, _indent(traceback.format_exc()))
return
#XXX Re-evaluate this. Might make more sense in the Komodo-specific
# batch update controller now.
# Komodo-specific HACK: Allow for a more pleasing user experience
# by making sure the "Upgrading Database" dialog is up for at
# least 2 seconds, rather than flashing for a quick upgrade.
endtime = time.time()
elapsed = endtime - starttime
if elapsed < 2.0:
time.sleep(2.0-elapsed)
def _handle_cix_request(self, path):
self.progress("importing", path)
#XXX Consider not bothering if MD5 of file is already in DB.
# md5sum = md5(cix).hexdigest()
# c.f. "Can an MD5 for a CIX file be added?" in my notes.
try:
fin = open(path, 'r')
try:
cix = fin.read()
finally:
fin.close()
except EnvironmentError, ex:
self._had_errors = True
self.error("Error importing CIX file '%s': %s\n%s",
path, ex, _indent(traceback.format_exc()))
return
db = Database(self.citadel)
try:
db.update(cix, recover=0, scan_imports=False)
except CodeIntelError, ex:
self._had_errors = True
self.error("Error importing CIX file '%s': %s\n%s",
path, ex, _indent(traceback.format_exc()))
return
def _handle_lang_request(self, path, lang, extra):
if lang == "*":
langs = self.citadel.get_supported_langs()
else:
langs = [lang]
for lang in langs:
# See if have any pre-created CIX files for this language to use
# instead of or in addition to actually scanning the core
# library.
stdcix = os.path.join(os.path.dirname(__file__),
lang.lower()+".cix")
if os.path.exists(stdcix):
self._handle_cix_request(stdcix)
try:
importer = self.citadel.import_handler_from_lang(lang)
except CodeIntelError, ex:
if lang != "*":
self._had_errors = True
self.error("cannot handle 'language' batch update "
"request for %s: %s", lang, ex)
continue
try:
importer.setCorePath(path, extra)
UPDATE_EVERY = 50
n = 0
scheduler = self._get_scheduler()
for file in importer.genScannableFiles(skipRareImports=True,
importableOnly=True):
if n % UPDATE_EVERY == 0:
self.progress("gathering files", n)
if self._aborted:
break
r = ScanRequest(file, lang, PRIORITY_IMMEDIATE,
scan_imports=False)
scheduler.addRequest(r)
n += 1
except CodeIntelError, ex:
self._had_errors = True
self.error("error handling %s request: %s\n%s",
lang, ex, _indent(traceback.format_exc()))
def _handle_directory_request(self, path, lang):
if lang == "*":
langs = self.citadel.mgr.get_citadel_langs()
else:
langs = [lang]
for lang in langs:
try:
importer = self.citadel.import_handler_from_lang(lang)
except CodeIntelError, ex:
if lang == "*":
continue
else:
raise CodeIntelError("cannot handle 'directory' batch "
"update request for '%s': %s"
% (lang, ex))
UPDATE_EVERY = 10
n = 0
scheduler = self._get_scheduler()
for file in importer.genScannableFiles([path]):
if n % UPDATE_EVERY == 0:
self.progress("gathering files", n)
if self._aborted:
break
r = ScanRequest(file, lang, PRIORITY_IMMEDIATE,
scan_imports=False)
scheduler.addRequest(r)
n += 1
#---- internal support stuff
# Recipe: indent (0.2.1) in C:\trentm\tm\recipes\cookbook
def _indent(s, width=4, skip_first_line=False):
"""_indent(s, [width=4]) -> 's' indented by 'width' spaces
The optional "skip_first_line" argument is a boolean (default False)
indicating if the first line should NOT be indented.
"""
lines = s.splitlines(1)
indentstr = ' '*width
if skip_first_line:
return indentstr.join(lines)
else:
return indentstr + indentstr.join(lines)