summaryrefslogtreecommitdiffstats
path: root/chrome/browser/extensions/activity_database.cc
blob: 293a8375789e84d22b1b737c17fe808cd8b8cf57 (plain)
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
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <string>
#include "base/command_line.h"
#include "base/logging.h"
#include "base/string_util.h"
#include "base/stringprintf.h"
#include "base/threading/thread.h"
#include "base/threading/thread_checker.h"
#include "base/time.h"
#include "base/time/clock.h"
#include "chrome/browser/extensions/activity_database.h"
#include "chrome/common/chrome_switches.h"
#include "sql/transaction.h"

#if defined(OS_MACOSX)
#include "base/mac/mac_util.h"
#endif

using content::BrowserThread;

namespace {

bool SortActionsByTime(const scoped_refptr<extensions::Action> a,
                       const scoped_refptr<extensions::Action> b) {
  return a->time() > b->time();
}

}  // namespace

namespace extensions {

ActivityDatabase::ActivityDatabase()
    : testing_clock_(NULL),
      initialized_(false) {
  // We don't batch commits when in testing mode.
  batch_mode_ = !(CommandLine::ForCurrentProcess()->
      HasSwitch(switches::kEnableExtensionActivityLogTesting));
}

ActivityDatabase::~ActivityDatabase() {}

void ActivityDatabase::SetErrorDelegate(sql::ErrorDelegate* error_delegate) {
  db_.set_error_delegate(error_delegate);
}

void ActivityDatabase::Init(const base::FilePath& db_name) {
  if (BrowserThread::IsMessageLoopValid(BrowserThread::DB))
    DCHECK(BrowserThread::CurrentlyOn(BrowserThread::DB));
  db_.set_page_size(4096);
  db_.set_cache_size(32);

  if (!db_.Open(db_name)) {
    LOG(ERROR) << db_.GetErrorMessage();
    return LogInitFailure();
  }

  // Wrap the initialization in a transaction so that the db doesn't
  // get corrupted if init fails/crashes.
  sql::Transaction committer(&db_);
  if (!committer.Begin())
    return LogInitFailure();

#if defined(OS_MACOSX)
  // Exclude the database from backups.
  base::mac::SetFileBackupExclusion(db_name);
#endif

  db_.Preload();

  // Create the DOMAction database.
  if (!DOMAction::InitializeTable(&db_))
    return LogInitFailure();

  // Create the APIAction database.
  if (!APIAction::InitializeTable(&db_))
    return LogInitFailure();

  // Create the BlockedAction database.
  if (!BlockedAction::InitializeTable(&db_))
    return LogInitFailure();

  sql::InitStatus stat = committer.Commit() ? sql::INIT_OK : sql::INIT_FAILURE;
  if (stat != sql::INIT_OK)
    return LogInitFailure();

  initialized_ = true;
  timer_.Start(FROM_HERE,
               base::TimeDelta::FromMinutes(2),
               this,
               &ActivityDatabase::RecordBatchedActions);
}

void ActivityDatabase::LogInitFailure() {
  LOG(ERROR) << "Couldn't initialize the activity log database.";
}

void ActivityDatabase::RecordAction(scoped_refptr<Action> action) {
  if (initialized_) {
    if (batch_mode_)
      batched_actions_.push_back(action);
    else
      action->Record(&db_);
  }
}

void ActivityDatabase::RecordBatchedActions() {
  std::vector<scoped_refptr<Action> >::size_type i;
  for (i = 0; i != batched_actions_.size(); ++i) {
    batched_actions_.at(i)->Record(&db_);
  }
  batched_actions_.clear();
}

void ActivityDatabase::SetBatchModeForTesting(bool batch_mode) {
  if (batch_mode && !batch_mode_) {
    timer_.Start(FROM_HERE,
                 base::TimeDelta::FromMinutes(2),
                 this,
                 &ActivityDatabase::RecordBatchedActions);
  } else if (!batch_mode && batch_mode_) {
    timer_.Stop();
    RecordBatchedActions();
  }
  batch_mode_ = batch_mode;
}

scoped_ptr<std::vector<scoped_refptr<Action> > > ActivityDatabase::GetActions(
    const std::string& extension_id, const int days_ago) {
  if (BrowserThread::IsMessageLoopValid(BrowserThread::DB))
    DCHECK(BrowserThread::CurrentlyOn(BrowserThread::DB));
  DCHECK_GE(days_ago, 0);
  scoped_ptr<std::vector<scoped_refptr<Action> > >
      actions(new std::vector<scoped_refptr<Action> >());
  if (!initialized_)
    return actions.Pass();
  // Compute the time bounds for that day.
  base::Time morning_midnight = testing_clock_ ?
      testing_clock_->Now().LocalMidnight() :
      base::Time::Now().LocalMidnight();
  int64 early_bound = 0;
  int64 late_bound = 0;
  if (days_ago == 0) {
      early_bound = morning_midnight.ToInternalValue();
      late_bound = base::Time::Max().ToInternalValue();
  } else {
      base::Time early_time = morning_midnight -
          base::TimeDelta::FromDays(days_ago);
      base::Time late_time = morning_midnight -
          base::TimeDelta::FromDays(days_ago-1);
      early_bound = early_time.ToInternalValue();
      late_bound = late_time.ToInternalValue();
  }
  // Get the DOMActions.
  std::string dom_str = base::StringPrintf("SELECT * FROM %s "
                                           "WHERE extension_id=? AND "
                                           "time>? AND time<=?",
                                           DOMAction::kTableName);
  sql::Statement dom_statement(db_.GetCachedStatement(SQL_FROM_HERE,
                                                      dom_str.c_str()));
  dom_statement.BindString(0, extension_id);
  dom_statement.BindInt64(1, early_bound);
  dom_statement.BindInt64(2, late_bound);
  while (dom_statement.Step()) {
    scoped_refptr<DOMAction> action = new DOMAction(dom_statement);
    actions->push_back(action);
  }
  // Get the APIActions.
  std::string api_str = base::StringPrintf("SELECT * FROM %s "
                                           "WHERE extension_id=? AND "
                                           "time>? AND time<=?",
                                            APIAction::kTableName);
  sql::Statement api_statement(db_.GetCachedStatement(SQL_FROM_HERE,
                                                      api_str.c_str()));
  api_statement.BindString(0, extension_id);
  api_statement.BindInt64(1, early_bound);
  api_statement.BindInt64(2, late_bound);
  while (api_statement.Step()) {
    scoped_refptr<APIAction> action = new APIAction(api_statement);
    actions->push_back(action);
  }
  // Get the BlockedActions.
  std::string blocked_str = base::StringPrintf("SELECT * FROM %s "
                                               "WHERE extension_id=? AND "
                                               "time>? AND time<=?",
                                               BlockedAction::kTableName);
  sql::Statement blocked_statement(db_.GetCachedStatement(SQL_FROM_HERE,
                                                          blocked_str.c_str()));
  blocked_statement.BindString(0, extension_id);
  blocked_statement.BindInt64(1, early_bound);
  blocked_statement.BindInt64(2, late_bound);
  while (blocked_statement.Step()) {
    scoped_refptr<BlockedAction> action = new BlockedAction(blocked_statement);
    actions->push_back(action);
  }
  // Sort by time (from newest to oldest).
  std::sort(actions->begin(), actions->end(), SortActionsByTime);
  return actions.Pass();
}

void ActivityDatabase::BeginTransaction() {
  db_.BeginTransaction();
}

void ActivityDatabase::CommitTransaction() {
  db_.CommitTransaction();
}

void ActivityDatabase::RollbackTransaction() {
  db_.RollbackTransaction();
}

bool ActivityDatabase::Raze() {
  return db_.Raze();
}

void ActivityDatabase::Close() {
  timer_.Stop();
  RecordBatchedActions();
  db_.Close();
  delete this;
}

void ActivityDatabase::KillDatabase() {
  timer_.Stop();
  db_.RazeAndClose();
}

void ActivityDatabase::SetClockForTesting(base::Clock* clock) {
  testing_clock_ = clock;
}

void ActivityDatabase::RecordBatchedActionsWhileTesting() {
  RecordBatchedActions();
  timer_.Stop();
}

void ActivityDatabase::SetTimerForTesting(int ms) {
  timer_.Stop();
  timer_.Start(FROM_HERE,
               base::TimeDelta::FromMilliseconds(ms),
               this,
               &ActivityDatabase::RecordBatchedActionsWhileTesting);
}

}  // namespace extensions