]> git.cworth.org Git - sup/blob - lib/sup/index.rb
9c985d98588739d2ecc5b1856cdfc5389df39f9c
[sup] / lib / sup / index.rb
1 ## the index structure for redwood. interacts with ferret.
2
3 require 'fileutils'
4 require 'ferret'
5
6 begin
7   require 'chronic'
8   $have_chronic = true
9 rescue LoadError => e
10   Redwood::log "optional 'chronic' library not found (run 'gem install chronic' to install)"
11   $have_chronic = false
12 end
13
14 module Redwood
15
16 class Index
17   class LockError < StandardError
18     def initialize h
19       @h = h
20     end
21
22     def method_missing m; @h[m.to_s] end
23   end
24
25   include Singleton
26
27   HookManager.register "custom-search", <<EOS
28 Executes before a string search is applied to the index,
29 returning a new search string.
30 Variables:
31   subs: The string being searched. Be careful about shadowing:
32     this variable is actually a method, so use a temporary variable
33     or explicitly call self.subs; the substitutions in index.rb
34     don't actually work.
35 EOS
36
37   ## these two accessors should ONLY be used by single-threaded programs.
38   ## otherwise you will have a naughty ferret on your hands.
39   attr_reader :index
40   alias ferret index
41
42   def initialize dir=BASE_DIR
43     @index_mutex = Monitor.new
44
45     @dir = dir
46     @sources = {}
47     @sources_dirty = false
48     @source_mutex = Monitor.new
49
50     wsa = Ferret::Analysis::WhiteSpaceAnalyzer.new false
51     sa = Ferret::Analysis::StandardAnalyzer.new [], true
52     @analyzer = Ferret::Analysis::PerFieldAnalyzer.new wsa
53     @analyzer[:body] = sa
54     @analyzer[:subject] = sa
55     @qparser ||= Ferret::QueryParser.new :default_field => :body, :analyzer => @analyzer, :or_default => false
56     @lock = Lockfile.new lockfile, :retries => 0, :max_age => nil
57
58     self.class.i_am_the_instance self
59   end
60
61   def lockfile; File.join @dir, "lock" end
62
63   def lock
64     Redwood::log "locking #{lockfile}..."
65     begin
66       @lock.lock
67     rescue Lockfile::MaxTriesLockError
68       raise LockError, @lock.lockinfo_on_disk
69     end
70   end
71
72   def start_lock_update_thread
73     @lock_update_thread = Redwood::reporting_thread("lock update") do
74       while true
75         sleep 30
76         @lock.touch_yourself
77       end
78     end
79   end
80
81   def stop_lock_update_thread
82     @lock_update_thread.kill if @lock_update_thread
83     @lock_update_thread = nil
84   end
85
86   def possibly_pluralize number_of, kind
87     "#{number_of} #{kind}" +
88         if number_of == 1 then "" else "s" end
89   end
90
91   def fancy_lock_error_message_for e
92     secs = (Time.now - e.mtime).to_i
93     mins = secs / 60
94     time =
95       if mins == 0
96         possibly_pluralize secs , "second"
97       else
98         possibly_pluralize mins, "minute"
99       end
100
101     <<EOS
102 Error: the sup index is locked by another process! User '#{e.user}' on
103 host '#{e.host}' is running #{e.pname} with pid #{e.pid}. The process was alive
104 as of #{time} ago.
105 EOS
106   end
107
108   def lock_or_die
109     begin
110       lock
111     rescue LockError => e
112       $stderr.puts fancy_lock_error_message_for(e)
113       $stderr.puts <<EOS
114
115 You can wait for the process to finish, or, if it crashed and left a
116 stale lock file behind, you can manually delete #{@lock.path}.
117 EOS
118       exit
119     end
120   end
121
122   def unlock
123     if @lock && @lock.locked?
124       Redwood::log "unlocking #{lockfile}..."
125       @lock.unlock
126     end
127   end
128
129   def load
130     load_sources
131     load_index
132   end
133
134   def save
135     Redwood::log "saving index and sources..."
136     FileUtils.mkdir_p @dir unless File.exists? @dir
137     save_sources
138     save_index
139   end
140
141   def add_source source
142     @source_mutex.synchronize do
143       raise "duplicate source!" if @sources.include? source
144       @sources_dirty = true
145       max = @sources.max_of { |id, s| s.is_a?(DraftLoader) || s.is_a?(SentLoader) ? 0 : id }
146       source.id ||= (max || 0) + 1
147       ##source.id += 1 while @sources.member? source.id
148       @sources[source.id] = source
149     end
150   end
151
152   def sources
153     ## favour the inbox by listing non-archived sources first
154     @source_mutex.synchronize { @sources.values }.sort_by { |s| s.id }.partition { |s| !s.archived? }.flatten
155   end
156
157   def source_for uri; sources.find { |s| s.is_source_for? uri }; end
158   def usual_sources; sources.find_all { |s| s.usual? }; end
159
160   def load_index dir=File.join(@dir, "ferret")
161     if File.exists? dir
162       Redwood::log "loading index..."
163       @index_mutex.synchronize do
164         @index = Ferret::Index::Index.new(:path => dir, :analyzer => @analyzer)
165         Redwood::log "loaded index of #{@index.size} messages"
166       end
167     else
168       Redwood::log "creating index..."
169       @index_mutex.synchronize do
170         field_infos = Ferret::Index::FieldInfos.new :store => :yes
171         field_infos.add_field :message_id, :index => :untokenized
172         field_infos.add_field :source_id
173         field_infos.add_field :source_info
174         field_infos.add_field :date, :index => :untokenized
175         field_infos.add_field :body
176         field_infos.add_field :label
177         field_infos.add_field :attachments
178         field_infos.add_field :subject
179         field_infos.add_field :from
180         field_infos.add_field :to
181         field_infos.add_field :refs
182         field_infos.add_field :snippet, :index => :no, :term_vector => :no
183         field_infos.create_index dir
184         @index = Ferret::Index::Index.new(:path => dir, :analyzer => @analyzer)
185       end
186     end
187   end
188
189   ## Syncs the message to the index, replacing any previous version.  adding
190   ## either way. Index state will be determined by the message's #labels
191   ## accessor.
192   ##
193   ## if need_load is false, docid and entry are assumed to be set to the
194   ## result of load_entry_for_id (which can be nil).
195   def sync_message m, need_load=true, docid=nil, entry=nil, opts={}
196     docid, entry = load_entry_for_id m.id if need_load
197
198     raise "no source info for message #{m.id}" unless m.source && m.source_info
199     @index_mutex.synchronize do
200       raise "trying to delete non-corresponding entry #{docid} with index message-id #{@index[docid][:message_id].inspect} and parameter message id #{m.id.inspect}" if docid && @index[docid][:message_id] != m.id
201     end
202
203     source_id = if m.source.is_a? Integer
204       m.source
205     else
206       m.source.id or raise "unregistered source #{m.source} (id #{m.source.id.inspect})"
207     end
208
209     snippet = if m.snippet_contains_encrypted_content? && $config[:discard_snippets_from_encrypted_messages]
210       ""
211     else
212       m.snippet
213     end
214
215     ## write the new document to the index. if the entry already exists in the
216     ## index, reuse it (which avoids having to reload the entry from the source,
217     ## which can be quite expensive for e.g. large threads of IMAP actions.)
218     ##
219     ## exception: if the index entry belongs to an earlier version of the
220     ## message, use everything from the new message instead, but union the
221     ## flags. this allows messages sent to mailing lists to have their header
222     ## updated and to have flags set properly.
223     ##
224     ## minor hack: messages in sources with lower ids have priority over
225     ## messages in sources with higher ids. so messages in the inbox will
226     ## override everyone, and messages in the sent box will be overridden
227     ## by everyone else.
228     ##
229     ## written in this manner to support previous versions of the index which
230     ## did not keep around the entry body. upgrading is thus seamless.
231     entry ||= {}
232     labels = m.labels.uniq # override because this is the new state, unless...
233
234     ## if we are a later version of a message, ignore what's in the index,
235     ## but merge in the labels.
236     if entry[:source_id] && entry[:source_info] && entry[:label] &&
237       ((entry[:source_id].to_i > source_id) || (entry[:source_info].to_i < m.source_info))
238       labels = (entry[:label].symbolistize + m.labels).uniq
239       #Redwood::log "found updated version of message #{m.id}: #{m.subj}"
240       #Redwood::log "previous version was at #{entry[:source_id].inspect}:#{entry[:source_info].inspect}, this version at #{source_id.inspect}:#{m.source_info.inspect}"
241       #Redwood::log "merged labels are #{labels.inspect} (index #{entry[:label].inspect}, message #{m.labels.inspect})"
242       entry = {}
243     end
244
245     ## if force_overwite is true, ignore what's in the index. this is used
246     ## primarily by sup-sync to force index updates.
247     entry = {} if opts[:force_overwrite]
248
249     d = {
250       :message_id => m.id,
251       :source_id => source_id,
252       :source_info => m.source_info,
253       :date => (entry[:date] || m.date.to_indexable_s),
254       :body => (entry[:body] || m.indexable_content),
255       :snippet => snippet, # always override
256       :label => labels.uniq.join(" "),
257       :attachments => (entry[:attachments] || m.attachments.uniq.join(" ")),
258
259       ## always override :from and :to.
260       ## older versions of Sup would often store the wrong thing in the index
261       ## (because they were canonicalizing email addresses, resulting in the
262       ## wrong name associated with each.) the correct address is read from
263       ## the original header when these messages are opened in thread-view-mode,
264       ## so this allows people to forcibly update the address in the index by
265       ## marking those threads for saving.
266       :from => (m.from ? m.from.indexable_content : ""),
267       :to => (m.to + m.cc + m.bcc).map { |x| x.indexable_content }.join(" "),
268
269       :subject => (entry[:subject] || wrap_subj(Message.normalize_subj(m.subj))),
270       :refs => (entry[:refs] || (m.refs + m.replytos).uniq.join(" ")),
271     }
272
273     @index_mutex.synchronize do
274       @index.delete docid if docid
275       @index.add_document d
276     end
277
278     ## this hasn't been triggered in a long time.
279     ## docid, entry = load_entry_for_id m.id
280     ## raise "just added message #{m.id.inspect} but couldn't find it in a search" unless docid
281   end
282
283   def save_index fn=File.join(@dir, "ferret")
284     # don't have to do anything, apparently
285   end
286
287   def contains_id? id
288     @index_mutex.synchronize { @index.search(Ferret::Search::TermQuery.new(:message_id, id)).total_hits > 0 }
289   end
290   def contains? m; contains_id? m.id end
291   def size; @index_mutex.synchronize { @index.size } end
292   def empty?; size == 0 end
293
294   ## you should probably not call this on a block that doesn't break
295   ## rather quickly because the results can be very large.
296   EACH_BY_DATE_NUM = 100
297   def each_id_by_date opts={}
298     return if empty? # otherwise ferret barfs ###TODO: remove this once my ferret patch is accepted
299     query = build_query opts
300     offset = 0
301     while true
302       limit = (opts[:limit])? [EACH_BY_DATE_NUM, opts[:limit] - offset].min : EACH_BY_DATE_NUM
303       results = @index_mutex.synchronize { @index.search query, :sort => "date DESC", :limit => limit, :offset => offset }
304       Redwood::log "got #{results.total_hits} results for query (offset #{offset}) #{query.inspect}"
305       results.hits.each do |hit|
306         yield @index_mutex.synchronize { @index[hit.doc][:message_id] }, lambda { build_message hit.doc }
307       end
308       break if opts[:limit] and offset >= opts[:limit] - limit
309       break if offset >= results.total_hits - limit
310       offset += limit
311     end
312   end
313
314   def num_results_for opts={}
315     return 0 if empty? # otherwise ferret barfs ###TODO: remove this once my ferret patch is accepted
316
317     q = build_query opts
318     @index_mutex.synchronize { @index.search(q, :limit => 1).total_hits }
319   end
320
321   ## yield all messages in the thread containing 'm' by repeatedly
322   ## querying the index. yields pairs of message ids and
323   ## message-building lambdas, so that building an unwanted message
324   ## can be skipped in the block if desired.
325   ##
326   ## only two options, :limit and :skip_killed. if :skip_killed is
327   ## true, stops loading any thread if a message with a :killed flag
328   ## is found.
329   SAME_SUBJECT_DATE_LIMIT = 7
330   MAX_CLAUSES = 1000
331   def each_message_in_thread_for m, opts={}
332     #Redwood::log "Building thread for #{m.id}: #{m.subj}"
333     messages = {}
334     searched = {}
335     num_queries = 0
336
337     pending = [m.id]
338     if $config[:thread_by_subject] # do subject queries
339       date_min = m.date - (SAME_SUBJECT_DATE_LIMIT * 12 * 3600)
340       date_max = m.date + (SAME_SUBJECT_DATE_LIMIT * 12 * 3600)
341
342       q = Ferret::Search::BooleanQuery.new true
343       sq = Ferret::Search::PhraseQuery.new(:subject)
344       wrap_subj(Message.normalize_subj(m.subj)).split.each do |t|
345         sq.add_term t
346       end
347       q.add_query sq, :must
348       q.add_query Ferret::Search::RangeQuery.new(:date, :>= => date_min.to_indexable_s, :<= => date_max.to_indexable_s), :must
349
350       q = build_query :qobj => q
351
352       p1 = @index_mutex.synchronize { @index.search(q).hits.map { |hit| @index[hit.doc][:message_id] } }
353       Redwood::log "found #{p1.size} results for subject query #{q}"
354
355       p2 = @index_mutex.synchronize { @index.search(q.to_s, :limit => :all).hits.map { |hit| @index[hit.doc][:message_id] } }
356       Redwood::log "found #{p2.size} results in string form"
357
358       pending = (pending + p1 + p2).uniq
359     end
360
361     until pending.empty? || (opts[:limit] && messages.size >= opts[:limit])
362       q = Ferret::Search::BooleanQuery.new true
363       # this disappeared in newer ferrets... wtf.
364       # q.max_clause_count = 2048
365
366       lim = [MAX_CLAUSES / 2, pending.length].min
367       pending[0 ... lim].each do |id|
368         searched[id] = true
369         q.add_query Ferret::Search::TermQuery.new(:message_id, id), :should
370         q.add_query Ferret::Search::TermQuery.new(:refs, id), :should
371       end
372       pending = pending[lim .. -1]
373
374       q = build_query :qobj => q
375
376       num_queries += 1
377       killed = false
378       @index_mutex.synchronize do
379         @index.search_each(q, :limit => :all) do |docid, score|
380           break if opts[:limit] && messages.size >= opts[:limit]
381           if @index[docid][:label].split(/\s+/).include?("killed") && opts[:skip_killed]
382             killed = true
383             break
384           end
385           mid = @index[docid][:message_id]
386           unless messages.member?(mid)
387             #Redwood::log "got #{mid} as a child of #{id}"
388             messages[mid] ||= lambda { build_message docid }
389             refs = @index[docid][:refs].split
390             pending += refs.select { |id| !searched[id] }
391           end
392         end
393       end
394     end
395
396     if killed
397       Redwood::log "thread for #{m.id} is killed, ignoring"
398       false
399     else
400       Redwood::log "ran #{num_queries} queries to build thread of #{messages.size} messages for #{m.id}: #{m.subj}" if num_queries > 0
401       messages.each { |mid, builder| yield mid, builder }
402       true
403     end
404   end
405
406   ## builds a message object from a ferret result
407   def build_message docid
408     @index_mutex.synchronize do
409       doc = @index[docid]
410
411       source = @source_mutex.synchronize { @sources[doc[:source_id].to_i] }
412       raise "invalid source #{doc[:source_id]}" unless source
413
414       #puts "building message #{doc[:message_id]} (#{source}##{doc[:source_info]})"
415
416       fake_header = {
417         "date" => Time.at(doc[:date].to_i),
418         "subject" => unwrap_subj(doc[:subject]),
419         "from" => doc[:from],
420         "to" => doc[:to].split.join(", "), # reformat
421         "message-id" => doc[:message_id],
422         "references" => doc[:refs].split.map { |x| "<#{x}>" }.join(" "),
423       }
424
425       m = Message.new :source => source, :source_info => doc[:source_info].to_i,
426                   :labels => doc[:label].symbolistize,
427                   :snippet => doc[:snippet]
428       m.parse_header fake_header
429       m
430     end
431   end
432
433   def fresh_thread_id; @next_thread_id += 1; end
434   def wrap_subj subj; "__START_SUBJECT__ #{subj} __END_SUBJECT__"; end
435   def unwrap_subj subj; subj =~ /__START_SUBJECT__ (.*?) __END_SUBJECT__/ && $1; end
436
437   def drop_entry docno; @index_mutex.synchronize { @index.delete docno } end
438
439   def load_entry_for_id mid
440     @index_mutex.synchronize do
441       results = @index.search Ferret::Search::TermQuery.new(:message_id, mid)
442       return if results.total_hits == 0
443       docid = results.hits[0].doc
444       entry = @index[docid]
445       entry_dup = entry.fields.inject({}) { |h, f| h[f] = entry[f]; h }
446       [docid, entry_dup]
447     end
448   end
449
450   def load_contacts emails, h={}
451     q = Ferret::Search::BooleanQuery.new true
452     emails.each do |e|
453       qq = Ferret::Search::BooleanQuery.new true
454       qq.add_query Ferret::Search::TermQuery.new(:from, e), :should
455       qq.add_query Ferret::Search::TermQuery.new(:to, e), :should
456       q.add_query qq
457     end
458     q.add_query Ferret::Search::TermQuery.new(:label, "spam"), :must_not
459     
460     Redwood::log "contact search: #{q}"
461     contacts = {}
462     num = h[:num] || 20
463     @index_mutex.synchronize do
464       @index.search_each q, :sort => "date DESC", :limit => :all do |docid, score|
465         break if contacts.size >= num
466         #Redwood::log "got message #{docid} to: #{@index[docid][:to].inspect} and from: #{@index[docid][:from].inspect}"
467         f = @index[docid][:from]
468         t = @index[docid][:to]
469
470         if AccountManager.is_account_email? f
471           t.split(" ").each { |e| contacts[Person.from_address(e)] = true }
472         else
473           contacts[Person.from_address(f)] = true
474         end
475       end
476     end
477
478     contacts.keys.compact
479   end
480
481   def load_sources fn=Redwood::SOURCE_FN
482     source_array = (Redwood::load_yaml_obj(fn) || []).map { |o| Recoverable.new o }
483     @source_mutex.synchronize do
484       @sources = Hash[*(source_array).map { |s| [s.id, s] }.flatten]
485       @sources_dirty = false
486     end
487   end
488
489   def has_any_from_source_with_label? source, label
490     q = Ferret::Search::BooleanQuery.new
491     q.add_query Ferret::Search::TermQuery.new("source_id", source.id.to_s), :must
492     q.add_query Ferret::Search::TermQuery.new("label", label.to_s), :must
493     @index_mutex.synchronize { @index.search(q, :limit => 1).total_hits > 0 }
494   end
495
496   ## takes a user query string and returns the list of docids for messages
497   ## that match the query.
498   ##
499   ## messages can then be loaded from the index with #build_message.
500   ##
501   ## raises a ParseError if the parsing failed.
502   def run_query query
503     qobj, opts = Redwood::Index.parse_user_query_string query
504     query = Redwood::Index.build_query opts.merge(:qobj => qobj)
505     results = @index.search query, :limit => (opts[:limit] || :all)
506     results.hits.map { |hit| hit.doc }
507   end
508
509 protected
510
511   class ParseError < StandardError; end
512
513   ## parse a query string from the user. returns a query object and a set of
514   ## extra flags; both of these are meant to be passed to #build_query.
515   ##
516   ## raises a ParseError if something went wrong.
517   def parse_user_query_string s
518     extraopts = {}
519
520     subs = HookManager.run("custom-search", :subs => s) || s
521
522     subs = subs.gsub(/\b(to|from):(\S+)\b/) do
523       field, name = $1, $2
524       if(p = ContactManager.contact_for(name))
525         [field, p.email]
526       elsif name == "me"
527         [field, "(" + AccountManager.user_emails.join("||") + ")"]
528       else
529         [field, name]
530       end.join(":")
531     end
532
533     ## if we see a label:deleted or a label:spam term anywhere in the query
534     ## string, we set the extra load_spam or load_deleted options to true.
535     ## bizarre? well, because the query allows arbitrary parenthesized boolean
536     ## expressions, without fully parsing the query, we can't tell whether
537     ## the user is explicitly directing us to search spam messages or not.
538     ## e.g. if the string is -(-(-(-(-label:spam)))), does the user want to
539     ## search spam messages or not?
540     ##
541     ## so, we rely on the fact that turning these extra options ON turns OFF
542     ## the adding of "-label:deleted" or "-label:spam" terms at the very
543     ## final stage of query processing. if the user wants to search spam
544     ## messages, not adding that is the right thing; if he doesn't want to
545     ## search spam messages, then not adding it won't have any effect.
546     extraopts[:load_spam] = true if subs =~ /\blabel:spam\b/
547     extraopts[:load_deleted] = true if subs =~ /\blabel:deleted\b/
548
549     ## gmail style "is" operator
550     subs = subs.gsub(/\b(is|has):(\S+)\b/) do
551       field, label = $1, $2
552       case label
553       when "read"
554         "-label:unread"
555       when "spam"
556         extraopts[:load_spam] = true
557         "label:spam"
558       when "deleted"
559         extraopts[:load_deleted] = true
560         "label:deleted"
561       else
562         "label:#{$2}"
563       end
564     end
565
566     ## gmail style attachments "filename" and "filetype" searches
567     subs = subs.gsub(/\b(filename|filetype):(\((.+?)\)\B|(\S+)\b)/) do
568       field, name = $1, ($3 || $4)
569       case field
570       when "filename"
571         Redwood::log "filename - translated #{field}:#{name} to attachments:(#{name.downcase})"
572         "attachments:(#{name.downcase})"
573       when "filetype"
574         Redwood::log "filetype - translated #{field}:#{name} to attachments:(*.#{name.downcase})"
575         "attachments:(*.#{name.downcase})"
576       end
577     end
578
579     if $have_chronic
580       subs = subs.gsub(/\b(before|on|in|during|after):(\((.+?)\)\B|(\S+)\b)/) do
581         field, datestr = $1, ($3 || $4)
582         realdate = Chronic.parse datestr, :guess => false, :context => :past
583         if realdate
584           case field
585           when "after"
586             Redwood::log "chronic: translated #{field}:#{datestr} to #{realdate.end}"
587             "date:(>= #{sprintf "%012d", realdate.end.to_i})"
588           when "before"
589             Redwood::log "chronic: translated #{field}:#{datestr} to #{realdate.begin}"
590             "date:(<= #{sprintf "%012d", realdate.begin.to_i})"
591           else
592             Redwood::log "chronic: translated #{field}:#{datestr} to #{realdate}"
593             "date:(<= #{sprintf "%012d", realdate.end.to_i}) date:(>= #{sprintf "%012d", realdate.begin.to_i})"
594           end
595         else
596           raise ParseError, "can't understand date #{datestr.inspect}"
597         end
598       end
599     end
600
601     ## limit:42 restrict the search to 42 results
602     subs = subs.gsub(/\blimit:(\S+)\b/) do
603       lim = $1
604       if lim =~ /^\d+$/
605         extraopts[:limit] = lim.to_i
606         ''
607       else
608         raise ParseError, "non-numeric limit #{lim.inspect}"
609       end
610     end
611     
612     begin
613       [@qparser.parse(subs), extraopts]
614     rescue Ferret::QueryParser::QueryParseException => e
615       raise ParseError, e.message
616     end
617   end
618
619   def build_query opts
620     query = Ferret::Search::BooleanQuery.new
621     query.add_query opts[:qobj], :must if opts[:qobj]
622     labels = ([opts[:label]] + (opts[:labels] || [])).compact
623     labels.each { |t| query.add_query Ferret::Search::TermQuery.new("label", t.to_s), :must }
624     if opts[:participants]
625       q2 = Ferret::Search::BooleanQuery.new
626       opts[:participants].each do |p|
627         q2.add_query Ferret::Search::TermQuery.new("from", p.email), :should
628         q2.add_query Ferret::Search::TermQuery.new("to", p.email), :should
629       end
630       query.add_query q2, :must
631     end
632         
633     query.add_query Ferret::Search::TermQuery.new("label", "spam"), :must_not unless opts[:load_spam] || labels.include?(:spam)
634     query.add_query Ferret::Search::TermQuery.new("label", "deleted"), :must_not unless opts[:load_deleted] || labels.include?(:deleted)
635     query.add_query Ferret::Search::TermQuery.new("label", "killed"), :must_not if opts[:skip_killed]
636     query
637   end
638
639   def save_sources fn=Redwood::SOURCE_FN
640     @source_mutex.synchronize do
641       if @sources_dirty || @sources.any? { |id, s| s.dirty? }
642         bakfn = fn + ".bak"
643         if File.exists? fn
644           File.chmod 0600, fn
645           FileUtils.mv fn, bakfn, :force => true unless File.exists?(bakfn) && File.size(fn) == 0
646         end
647         Redwood::save_yaml_obj sources.sort_by { |s| s.id.to_i }, fn, true
648         File.chmod 0600, fn
649       end
650       @sources_dirty = false
651     end
652   end
653 end
654
655 end