aboutsummaryrefslogtreecommitdiffstats
path: root/etherpad/src/etherpad/pad/dbwriter.js
blob: 233622b98b85a4466d81a4d65887fce00f4411e7 (plain) (blame)
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
/**
 * Copyright 2009 Google Inc.
 * 
 * Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS-IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import("execution");
import("profiler");

import("etherpad.pad.model");
import("etherpad.pad.model.accessPadGlobal");
import("etherpad.log");
import("etherpad.utils");

jimport("net.appjet.oui.exceptionlog");
jimport("java.util.concurrent.ConcurrentHashMap");
jimport("java.lang.System.out.println");

var MIN_WRITE_INTERVAL_MS = 2000; // 2 seconds
var MIN_WRITE_DELAY_NOTIFY_MS = 2000; // 2 seconds
var AGE_FOR_PAD_FLUSH_MS = 5*60*1000; // 5 minutes
var DBUNWRITABLE_WRITE_DELAY_MS = 30*1000; // 30 seconds

// state is { constant: true }, { constant: false }, { trueAfter: timeInMs }
function setWritableState(state) {
  _dbwriter().dbWritable = state;
}

function getWritableState() {
  return _dbwriter().dbWritable;
}

function isDBWritable() {
  return _isDBWritable();
}

function _isDBWritable() {
  var state = _dbwriter().dbWritable;
  if (typeof state != "object") {
    return true;
  }
  else if (state.constant !== undefined) {
    return !! state.constant;
  }
  else if (state.trueAfter !== undefined) {
    return (+new Date()) > state.trueAfter;
  }
  else return true;
}

function getWritableStateDescription(state) {
  var v = _isDBWritable();
  var restOfMessage = "";
  if (state.trueAfter !== undefined) {
    var now = +new Date();
    var then = state.trueAfter;
    var diffSeconds = java.lang.String.format("%.1f", Math.abs(now - then)/1000);
    if (now < then) {
      restOfMessage = " until "+diffSeconds+" seconds from now";
    }
    else {
      restOfMessage = " since "+diffSeconds+" seconds ago";
    }
  }
  return v+restOfMessage;
}

function _dbwriter() {
  return appjet.cache.dbwriter;
}

function onStartup() {
  appjet.cache.dbwriter = {};
  var dbwriter = _dbwriter();
  dbwriter.pendingWrites = new ConcurrentHashMap();
  dbwriter.scheduledFor = new ConcurrentHashMap(); // padId --> long
  dbwriter.dbWritable = { constant: true };

  execution.initTaskThreadPool("dbwriter", 4);
  // we don't wait for scheduled tasks in the infreq pool to run and complete
  execution.initTaskThreadPool("dbwriter_infreq", 1);

  _scheduleCheckForStalePads();
}

function _scheduleCheckForStalePads() {
  execution.scheduleTask("dbwriter_infreq", "checkForStalePads", AGE_FOR_PAD_FLUSH_MS, []);
}

function onShutdown() {
  log.info("Doing final DB writes before shutdown...");
  var success = execution.shutdownAndWaitOnTaskThreadPool("dbwriter", 10000);
  if (! success) {
    log.warn("ERROR! DB WRITER COULD NOT SHUTDOWN THREAD POOL!");
  }
}

function _logException(e) {
  var exc = utils.toJavaException(e);
  log.warn("writeAllToDB: Error writing to SQL!  Written to exceptions.log: "+exc);
  log.logException(exc);
  exceptionlog.apply(exc);
}

function taskFlushPad(padId, reason) {
  var dbwriter = _dbwriter();
  if (! _isDBWritable()) {
    // DB is unwritable, delay
    execution.scheduleTask("dbwriter_infreq", "flushPad", DBUNWRITABLE_WRITE_DELAY_MS, [padId, reason]);
    return;
  }

  model.accessPadGlobal(padId, function(pad) {
    writePadNow(pad, true);
  }, "r");

  log.info("taskFlushPad: flushed "+padId+(reason?(" (reason: "+reason+")"):''));
}

function taskWritePad(padId) {
  var dbwriter = _dbwriter();
  if (! _isDBWritable()) {
    // DB is unwritable, delay
    dbwriter.scheduledFor.put(padId, (+(new Date)+DBUNWRITABLE_WRITE_DELAY_MS));
    execution.scheduleTask("dbwriter", "writePad", DBUNWRITABLE_WRITE_DELAY_MS, [padId]);
    return;
  }

  profiler.reset();
  var t1 = profiler.rcb("lock wait");
  model.accessPadGlobal(padId, function(pad) {
    t1();
    _dbwriter().pendingWrites.remove(padId); // do this first

    var success = false;
    try {
      var t2 = profiler.rcb("write");
      writePadNow(pad);
      t2();

      success = true;
    }
    finally {
      if (! success) {
        log.warn("DB WRITER FAILED TO WRITE PAD: "+padId);
      }
      profiler.print();
    }
  }, "r");
}

function taskCheckForStalePads() {
  // do this first
  _scheduleCheckForStalePads();

  if (! _isDBWritable()) return;

  // get "active" pads into an array
  var padIter = appjet.cache.pads.meta.keySet().iterator();
  var padList = [];
  while (padIter.hasNext()) { padList.push(padIter.next()); }

  var numStale = 0;

  for (var i = 0; i < padList.length; i++) {
    if (! _isDBWritable()) break;
    var p = padList[i];
    if (model.isPadLockHeld(p)) {
      // skip it, don't want to lock up stale pad flusher
    }
    else {
      accessPadGlobal(p, function(pad) {
        if (pad.exists()) {
	  var padAge = (+new Date()) - pad._meta.status.lastAccess;
	  if (padAge > AGE_FOR_PAD_FLUSH_MS) {
	    writePadNow(pad, true);
	    numStale++;
	  }
        }
      }, "r");
    }
  }

  log.info("taskCheckForStalePads: flushed "+numStale+" stale pads");
}

function notifyPadDirty(padId) {
  var dbwriter = _dbwriter();
  if (! dbwriter.pendingWrites.containsKey(padId)) {
    dbwriter.pendingWrites.put(padId, "pending");
    dbwriter.scheduledFor.put(padId, (+(new Date)+MIN_WRITE_INTERVAL_MS));
    execution.scheduleTask("dbwriter", "writePad", MIN_WRITE_INTERVAL_MS, [padId]);
  }
}

function scheduleFlushPad(padId, reason) {
  execution.scheduleTask("dbwriter_infreq", "flushPad", 0, [padId, reason]);
}

/*function _dbwriterLoopBody(executor) {
  try {
    var info = writeAllToDB(executor);
    if (!info.boring) {
      log.info("DB writer: "+info.toSource());
    }
    java.lang.Thread.sleep(Math.max(0, MIN_WRITE_INTERVAL_MS - info.elapsed));
  }
  catch (e) {
    _logException(e);
    java.lang.Thread.sleep(MIN_WRITE_INTERVAL_MS);
  }
}

function _startInThread(name, func) {
  (new Thread(new Runnable({
      run: function() {
        func();
      }
  }), name)).start();
}

function killDBWriterThreadAndWait() {
  appjet.cache.abortDBWriter = true;
  while (appjet.cache.runningDBWriter) {
    java.lang.Thread.sleep(100);
  }
}*/

/*function writeAllToDB(executor, andFlush) {
  if (!executor) {
    executor = new ScheduledThreadPoolExecutor(NUM_WRITER_THREADS);
  }

  profiler.reset();
  var startWriteTime = profiler.time();
  var padCount = new AtomicInteger(0);
  var writeCount = new AtomicInteger(0);
  var removeCount = new AtomicInteger(0);

  // get pads into an array
  var padIter = appjet.cache.pads.meta.keySet().iterator();
  var padList = [];
  while (padIter.hasNext()) { padList.push(padIter.next()); }

  var latch = new CountDownLatch(padList.length);

  for (var i = 0; i < padList.length; i++) {
    _spawnCall(executor, function(p) {
      try {
        var padWriteResult = {};
        accessPadGlobal(p, function(pad) {
          if (pad.exists()) {
               padCount.getAndIncrement();
            padWriteResult = writePad(pad, andFlush);
            if (padWriteResult.didWrite) writeCount.getAndIncrement();
            if (padWriteResult.didRemove) removeCount.getAndIncrement();
          }
        }, "r");
      } catch (e) {
        _logException(e);
      } finally {
          latch.countDown();
      }
    }, padList[i]);
  }

  // wait for them all to finish
  latch.await();

  var endWriteTime = profiler.time();
  var elapsed = Math.round((endWriteTime - startWriteTime)/1000)/1000;
  var interesting = (writeCount.get() > 0 || removeCount.get() > 0);

  var obj = {padCount:padCount.get(), writeCount:writeCount.get(), elapsed:elapsed, removeCount:removeCount.get()};
  if (! interesting) obj.boring = true;
  if (interesting) {
    profiler.record("writeAll", profiler.time()-startWriteTime);
    profiler.print();
  }

  return obj;
}*/

function writePadNow(pad, andFlush) {
  var didWrite = false;
  var didRemove = false;

  if (pad.exists()) {
    var dbUpToDate = false;
    if (pad._meta.status.dirty) {
      /*log.info("Writing pad "+pad.getId());*/
      pad._meta.status.dirty = false;
      //var t1 = +new Date();
      pad.writeToDB();
      //var t2 = +new Date();
      didWrite = true;

      //log.info("Wrote pad "+pad.getId()+" in "+(t2-t1)+" ms.");

      var now = +(new Date);
      var sched = _dbwriter().scheduledFor.get(pad.getId());
      if (sched) {
        var delay = now - sched;
        if (delay > MIN_WRITE_DELAY_NOTIFY_MS) {
          log.warn("dbwriter["+pad.getId()+"] behind schedule by "+delay+"ms");
        }
        _dbwriter().scheduledFor.remove(pad.getId());
      }
    }
    if (andFlush) {
      // remove from cache
      model.removeFromMemory(pad);
      didRemove = true;
    }
  }
  return {didWrite:didWrite, didRemove:didRemove};
}

/*function _spawnCall(executor, func, varargs) {
  var args = Array.prototype.slice.call(arguments, 2);
  var that = this;
  executor.schedule(new Runnable({
    run: function() {
      func.apply(that, args);
    }
  }), 0, TimeUnit.MICROSECONDS);
}*/