summaryrefslogtreecommitdiffstats
path: root/gerrit-server/src/main/java/com/google/gerrit/server/account/AccountsUpdate.java
blob: 6f11015c6b938ebb316fac6b2578b8ae846477e5 (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
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
// Copyright (C) 2017 The Android Open Source Project
//
// 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.

package com.google.gerrit.server.account;

import static com.google.common.base.Preconditions.checkNotNull;

import com.google.common.collect.ImmutableList;
import com.google.gerrit.common.Nullable;
import com.google.gerrit.reviewdb.client.Account;
import com.google.gerrit.reviewdb.client.Project;
import com.google.gerrit.reviewdb.client.RefNames;
import com.google.gerrit.server.GerritPersonIdent;
import com.google.gerrit.server.IdentifiedUser;
import com.google.gerrit.server.config.AllUsersName;
import com.google.gerrit.server.extensions.events.GitReferenceUpdated;
import com.google.gerrit.server.git.GitRepositoryManager;
import com.google.gerrit.server.git.MetaDataUpdate;
import com.google.gerrit.server.index.change.ReindexAfterRefUpdate;
import com.google.gerrit.server.mail.send.OutgoingEmailValidator;
import com.google.gwtorm.server.OrmDuplicateKeyException;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
import java.io.IOException;
import java.util.List;
import java.util.function.Consumer;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.PersonIdent;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.RefUpdate;
import org.eclipse.jgit.lib.RefUpdate.Result;
import org.eclipse.jgit.lib.Repository;

/**
 * Updates accounts.
 *
 * <p>The account updates are written to NoteDb.
 *
 * <p>In NoteDb accounts are represented as user branches in the All-Users repository. Optionally a
 * user branch can contain a 'account.config' file that stores account properties, such as full
 * name, preferred email, status and the active flag. The timestamp of the first commit on a user
 * branch denotes the registration date. The initial commit on the user branch may be empty (since
 * having an 'account.config' is optional). See {@link AccountConfig} for details of the
 * 'account.config' file format.
 *
 * <p>On updating accounts the accounts are evicted from the account cache and thus reindexed. The
 * eviction from the account cache is done by the {@link ReindexAfterRefUpdate} class which receives
 * the event about updating the user branch that is triggered by this class.
 */
@Singleton
public class AccountsUpdate {
  /**
   * Factory to create an AccountsUpdate instance for updating accounts by the Gerrit server.
   *
   * <p>The Gerrit server identity will be used as author and committer for all commits that update
   * the accounts.
   */
  @Singleton
  public static class Server {
    private final GitRepositoryManager repoManager;
    private final GitReferenceUpdated gitRefUpdated;
    private final AllUsersName allUsersName;
    private final OutgoingEmailValidator emailValidator;
    private final Provider<PersonIdent> serverIdent;
    private final Provider<MetaDataUpdate.Server> metaDataUpdateServerFactory;

    @Inject
    public Server(
        GitRepositoryManager repoManager,
        GitReferenceUpdated gitRefUpdated,
        AllUsersName allUsersName,
        OutgoingEmailValidator emailValidator,
        @GerritPersonIdent Provider<PersonIdent> serverIdent,
        Provider<MetaDataUpdate.Server> metaDataUpdateServerFactory) {
      this.repoManager = repoManager;
      this.gitRefUpdated = gitRefUpdated;
      this.allUsersName = allUsersName;
      this.emailValidator = emailValidator;
      this.serverIdent = serverIdent;
      this.metaDataUpdateServerFactory = metaDataUpdateServerFactory;
    }

    public AccountsUpdate create() {
      PersonIdent i = serverIdent.get();
      return new AccountsUpdate(
          repoManager,
          gitRefUpdated,
          null,
          allUsersName,
          emailValidator,
          i,
          () -> metaDataUpdateServerFactory.get().create(allUsersName));
    }
  }

  /**
   * Factory to create an AccountsUpdate instance for updating accounts by the current user.
   *
   * <p>The identity of the current user will be used as author for all commits that update the
   * accounts. The Gerrit server identity will be used as committer.
   */
  @Singleton
  public static class User {
    private final GitRepositoryManager repoManager;
    private final GitReferenceUpdated gitRefUpdated;
    private final AllUsersName allUsersName;
    private final OutgoingEmailValidator emailValidator;
    private final Provider<PersonIdent> serverIdent;
    private final Provider<IdentifiedUser> identifiedUser;
    private final Provider<MetaDataUpdate.User> metaDataUpdateUserFactory;

    @Inject
    public User(
        GitRepositoryManager repoManager,
        GitReferenceUpdated gitRefUpdated,
        AllUsersName allUsersName,
        OutgoingEmailValidator emailValidator,
        @GerritPersonIdent Provider<PersonIdent> serverIdent,
        Provider<IdentifiedUser> identifiedUser,
        Provider<MetaDataUpdate.User> metaDataUpdateUserFactory) {
      this.repoManager = repoManager;
      this.gitRefUpdated = gitRefUpdated;
      this.allUsersName = allUsersName;
      this.serverIdent = serverIdent;
      this.emailValidator = emailValidator;
      this.identifiedUser = identifiedUser;
      this.metaDataUpdateUserFactory = metaDataUpdateUserFactory;
    }

    public AccountsUpdate create() {
      IdentifiedUser user = identifiedUser.get();
      PersonIdent i = serverIdent.get();
      return new AccountsUpdate(
          repoManager,
          gitRefUpdated,
          user,
          allUsersName,
          emailValidator,
          createPersonIdent(i, user),
          () -> metaDataUpdateUserFactory.get().create(allUsersName));
    }

    private PersonIdent createPersonIdent(PersonIdent ident, IdentifiedUser user) {
      return user.newCommitterIdent(ident.getWhen(), ident.getTimeZone());
    }
  }

  private final GitRepositoryManager repoManager;
  private final GitReferenceUpdated gitRefUpdated;
  @Nullable private final IdentifiedUser currentUser;
  private final AllUsersName allUsersName;
  private final OutgoingEmailValidator emailValidator;
  private final PersonIdent committerIdent;
  private final MetaDataUpdateFactory metaDataUpdateFactory;

  private AccountsUpdate(
      GitRepositoryManager repoManager,
      GitReferenceUpdated gitRefUpdated,
      @Nullable IdentifiedUser currentUser,
      AllUsersName allUsersName,
      OutgoingEmailValidator emailValidator,
      PersonIdent committerIdent,
      MetaDataUpdateFactory metaDataUpdateFactory) {
    this.repoManager = checkNotNull(repoManager, "repoManager");
    this.gitRefUpdated = checkNotNull(gitRefUpdated, "gitRefUpdated");
    this.currentUser = currentUser;
    this.allUsersName = checkNotNull(allUsersName, "allUsersName");
    this.emailValidator = checkNotNull(emailValidator, "emailValidator");
    this.committerIdent = checkNotNull(committerIdent, "committerIdent");
    this.metaDataUpdateFactory = checkNotNull(metaDataUpdateFactory, "metaDataUpdateFactory");
  }

  /**
   * Inserts a new account.
   *
   * @param accountId ID of the new account
   * @param init consumer to populate the new account
   * @return the newly created account
   * @throws OrmDuplicateKeyException if the account already exists
   * @throws IOException if updating the user branch fails
   * @throws ConfigInvalidException if any of the account fields has an invalid value
   */
  public Account insert(Account.Id accountId, Consumer<Account> init)
      throws OrmDuplicateKeyException, IOException, ConfigInvalidException {
    AccountConfig accountConfig = read(accountId);
    Account account = accountConfig.getNewAccount();
    init.accept(account);

    // Create in NoteDb
    commitNew(accountConfig);
    return account;
  }

  /**
   * Gets the account and updates it atomically.
   *
   * <p>Changing the registration date of an account is not supported.
   *
   * @param accountId ID of the account
   * @param consumer consumer to update the account, only invoked if the account exists
   * @return the updated account, {@code null} if the account doesn't exist
   * @throws IOException if updating the user branch fails
   * @throws ConfigInvalidException if any of the account fields has an invalid value
   */
  public Account update(Account.Id accountId, Consumer<Account> consumer)
      throws IOException, ConfigInvalidException {
    return update(accountId, ImmutableList.of(consumer));
  }

  /**
   * Gets the account and updates it atomically.
   *
   * <p>Changing the registration date of an account is not supported.
   *
   * @param accountId ID of the account
   * @param consumers consumers to update the account, only invoked if the account exists
   * @return the updated account, {@code null} if the account doesn't exist
   * @throws IOException if updating the user branch fails
   * @throws ConfigInvalidException if any of the account fields has an invalid value
   */
  public Account update(Account.Id accountId, List<Consumer<Account>> consumers)
      throws IOException, ConfigInvalidException {
    if (consumers.isEmpty()) {
      return null;
    }

    AccountConfig accountConfig = read(accountId);
    Account account = accountConfig.getAccount();
    if (account != null) {
      consumers.stream().forEach(c -> c.accept(account));
      commit(accountConfig);
    }

    return account;
  }

  /**
   * Replaces the account.
   *
   * <p>The existing account with the same account ID is overwritten by the given account. Choosing
   * to overwrite an account means that any updates that were done to the account by a racing
   * request after the account was read are lost. Updates are also lost if the account was read from
   * a stale account index. This is why using {@link
   * #update(com.google.gerrit.reviewdb.client.Account.Id, Consumer)} to do an atomic update is
   * always preferred.
   *
   * <p>Changing the registration date of an account is not supported.
   *
   * @param account the new account
   * @throws IOException if updating the user branch fails
   * @throws ConfigInvalidException if any of the account fields has an invalid value
   * @see #update(com.google.gerrit.reviewdb.client.Account.Id, Consumer)
   */
  public void replace(Account account) throws IOException, ConfigInvalidException {
    AccountConfig accountConfig = read(account.getId());
    accountConfig.setAccount(account);
    commit(accountConfig);
  }

  /**
   * Deletes the account.
   *
   * @param account the account that should be deleted
   * @throws IOException if updating the user branch fails
   */
  public void delete(Account account) throws IOException {
    deleteByKey(account.getId());
  }

  /**
   * Deletes the account.
   *
   * @param accountId the ID of the account that should be deleted
   * @throws IOException if updating the user branch fails
   */
  public void deleteByKey(Account.Id accountId) throws IOException {
    deleteUserBranch(accountId);
  }

  private void deleteUserBranch(Account.Id accountId) throws IOException {
    try (Repository repo = repoManager.openRepository(allUsersName)) {
      deleteUserBranch(repo, allUsersName, gitRefUpdated, currentUser, committerIdent, accountId);
    }
  }

  public static void deleteUserBranch(
      Repository repo,
      Project.NameKey project,
      GitReferenceUpdated gitRefUpdated,
      @Nullable IdentifiedUser user,
      PersonIdent refLogIdent,
      Account.Id accountId)
      throws IOException {
    String refName = RefNames.refsUsers(accountId);
    Ref ref = repo.exactRef(refName);
    if (ref == null) {
      return;
    }

    RefUpdate ru = repo.updateRef(refName);
    ru.setExpectedOldObjectId(ref.getObjectId());
    ru.setNewObjectId(ObjectId.zeroId());
    ru.setForceUpdate(true);
    ru.setRefLogIdent(refLogIdent);
    ru.setRefLogMessage("Delete Account", true);
    Result result = ru.delete();
    if (result != Result.FORCED) {
      throw new IOException(String.format("Failed to delete ref %s: %s", refName, result.name()));
    }
    gitRefUpdated.fire(project, ru, user != null ? user.getAccount() : null);
  }

  private AccountConfig read(Account.Id accountId) throws IOException, ConfigInvalidException {
    try (Repository repo = repoManager.openRepository(allUsersName)) {
      AccountConfig accountConfig = new AccountConfig(emailValidator, accountId);
      accountConfig.load(repo);
      return accountConfig;
    }
  }

  private void commitNew(AccountConfig accountConfig) throws IOException {
    // When creating a new account we must allow empty commits so that the user branch gets created
    // with an empty commit when no account properties are set and hence no 'account.config' file
    // will be created.
    commit(accountConfig, true);
  }

  private void commit(AccountConfig accountConfig) throws IOException {
    commit(accountConfig, false);
  }

  private void commit(AccountConfig accountConfig, boolean allowEmptyCommit) throws IOException {
    try (MetaDataUpdate md = metaDataUpdateFactory.create()) {
      md.setAllowEmpty(allowEmptyCommit);
      accountConfig.commit(md);
    }
  }

  @FunctionalInterface
  private static interface MetaDataUpdateFactory {
    MetaDataUpdate create() throws IOException;
  }
}