use of com.google.gerrit.exceptions.StorageException in project gerrit by GerritCodeReview.
the class ReceiveCommits method parseCreate.
private void parseCreate(ReceiveCommand cmd) throws PermissionBackendException, NoSuchProjectException, IOException {
try (TraceTimer traceTimer = newTimer("parseCreate")) {
if (repo.resolve(cmd.getRefName()) != null) {
reject(cmd, String.format("Cannot create ref '%s' because it already exists.", cmd.getRefName()));
return;
}
RevObject obj;
try {
obj = receivePack.getRevWalk().parseAny(cmd.getNewId());
} catch (IOException e) {
throw new StorageException(String.format("Invalid object %s for %s creation", cmd.getNewId().name(), cmd.getRefName()), e);
}
logger.atFine().log("Creating %s", cmd);
if (isHead(cmd) && !isCommit(cmd)) {
return;
}
BranchNameKey branch = BranchNameKey.create(project.getName(), cmd.getRefName());
try {
// Must pass explicit user instead of injecting a provider into CreateRefControl, since
// Provider<CurrentUser> within ReceiveCommits will always return anonymous.
createRefControl.checkCreateRef(Providers.of(user), receivePack.getRepository(), branch, obj);
} catch (AuthException denied) {
rejectProhibited(cmd, denied);
return;
} catch (ResourceConflictException denied) {
reject(cmd, "prohibited by Gerrit: " + denied.getMessage());
return;
}
if (validRefOperation(cmd)) {
validateRegularPushCommits(BranchNameKey.create(project.getNameKey(), cmd.getRefName()), cmd);
}
}
}
use of com.google.gerrit.exceptions.StorageException in project gerrit by GerritCodeReview.
the class ReceiveCommits method processCommandsUnsafe.
// Process as many commands as possible, but may leave some commands in state NOT_ATTEMPTED.
private void processCommandsUnsafe(Collection<ReceiveCommand> commands, MultiProgressMonitor progress) {
logger.atFine().log("Calling user: %s, commands: %d", user.getLoggableName(), commands.size());
// If the list of groups is large, the log entry may get dropped, so separate out.
logger.atFine().log("Groups: %s", lazy(() -> user.getEffectiveGroups().getKnownGroups()));
if (!projectState.getProject().getState().permitsWrite()) {
for (ReceiveCommand cmd : commands) {
reject(cmd, "prohibited by Gerrit: project state does not permit write");
}
return;
}
List<ReceiveCommand> magicCommands = new ArrayList<>();
List<ReceiveCommand> regularCommands = new ArrayList<>();
for (ReceiveCommand cmd : commands) {
if (MagicBranch.isMagicBranch(cmd.getRefName())) {
magicCommands.add(cmd);
} else {
regularCommands.add(cmd);
}
}
if (!magicCommands.isEmpty() && !regularCommands.isEmpty()) {
rejectRemaining(commands, "cannot combine normal pushes and magic pushes");
return;
}
try {
if (!magicCommands.isEmpty()) {
parseMagicBranch(Iterables.getLast(magicCommands));
// Using the submit option submits the created change(s) immediately without checking labels
// nor submit rules. Hence we shouldn't record such pushes as "magic" which implies that
// code review is being done.
String pushKind = magicBranch != null && magicBranch.submit ? "direct_submit" : "magic";
metrics.pushCount.increment(pushKind, project.getName(), getUpdateType(magicCommands));
}
if (!regularCommands.isEmpty()) {
metrics.pushCount.increment("direct", project.getName(), getUpdateType(regularCommands));
}
if (!regularCommands.isEmpty()) {
handleRegularCommands(regularCommands, progress);
return;
}
boolean first = true;
for (ReceiveCommand cmd : magicCommands) {
if (first) {
first = false;
} else {
reject(cmd, "duplicate request");
}
}
} catch (PermissionBackendException | NoSuchProjectException | IOException err) {
logger.atSevere().withCause(err).log("Failed to process refs in %s", project.getName());
return;
}
Task newProgress = progress.beginSubTask("new", UNKNOWN);
Task replaceProgress = progress.beginSubTask("updated", UNKNOWN);
ImmutableList<CreateRequest> newChanges = ImmutableList.of();
try {
if (magicBranch != null && magicBranch.cmd.getResult() == NOT_ATTEMPTED) {
try {
newChanges = selectNewAndReplacedChangesFromMagicBranch(newProgress);
} catch (IOException e) {
throw new StorageException("Failed to select new changes in " + project.getName(), e);
}
}
// Commit validation has already happened, so any changes without Change-Id are for the
// deprecated feature.
warnAboutMissingChangeId(newChanges);
preparePatchSetsForReplace(newChanges);
insertChangesAndPatchSets(newChanges, replaceProgress);
} finally {
newProgress.end();
replaceProgress.end();
}
queueSuccessMessages(newChanges);
logger.atFine().log("Command results: %s", lazy(() -> commands.stream().map(ReceiveCommits::commandToString).collect(joining(","))));
}
use of com.google.gerrit.exceptions.StorageException in project gerrit by GerritCodeReview.
the class DeleteGpgKey method apply.
@Override
public Response<?> apply(GpgKey rsrc, Input input) throws RestApiException, PGPException, IOException, ConfigInvalidException {
PGPPublicKey key = rsrc.getKeyRing().getPublicKey();
String fingerprint = BaseEncoding.base16().encode(key.getFingerprint());
Optional<ExternalId> extId = externalIds.get(externalIdKeyFactory.create(SCHEME_GPGKEY, fingerprint));
if (!extId.isPresent()) {
throw new ResourceNotFoundException(fingerprint);
}
accountsUpdateProvider.get().update("Delete GPG Key via API", rsrc.getUser().getAccountId(), u -> u.deleteExternalId(extId.get()));
try (PublicKeyStore store = storeProvider.get()) {
store.remove(rsrc.getKeyRing().getPublicKey().getFingerprint());
CommitBuilder cb = new CommitBuilder();
PersonIdent committer = serverIdent.get();
cb.setAuthor(rsrc.getUser().newCommitterIdent(committer));
cb.setCommitter(committer);
cb.setMessage("Delete public key " + keyIdToString(key.getKeyID()));
RefUpdate.Result saveResult = store.save(cb);
switch(saveResult) {
case NO_CHANGE:
case FAST_FORWARD:
try {
deleteKeySenderFactory.create(rsrc.getUser(), ImmutableList.of(PublicKeyStore.keyToString(key))).send();
} catch (EmailException e) {
logger.atSevere().withCause(e).log("Cannot send GPG key deletion message to %s", rsrc.getUser().getAccount().preferredEmail());
}
break;
case LOCK_FAILURE:
case FORCED:
case IO_FAILURE:
case NEW:
case NOT_ATTEMPTED:
case REJECTED:
case REJECTED_CURRENT_BRANCH:
case RENAMED:
case REJECTED_MISSING_OBJECT:
case REJECTED_OTHER_REASON:
default:
throw new StorageException(String.format("Failed to delete public key: %s", saveResult));
}
}
return Response.none();
}
use of com.google.gerrit.exceptions.StorageException in project gerrit by GerritCodeReview.
the class AccountCacheImpl method get.
@Override
public Map<Account.Id, AccountState> get(Set<Account.Id> accountIds) {
try {
try (Repository allUsers = repoManager.openRepository(allUsersName)) {
// Get the default preferences for this Gerrit host
Ref ref = allUsers.exactRef(RefNames.REFS_USERS_DEFAULT);
CachedPreferences defaultPreferences = ref != null ? defaultPreferenceCache.get(ref.getObjectId()) : DefaultPreferencesCache.EMPTY;
Set<CachedAccountDetails.Key> keys = Sets.newLinkedHashSetWithExpectedSize(accountIds.size());
for (Account.Id id : accountIds) {
Ref userRef = allUsers.exactRef(RefNames.refsUsers(id));
if (userRef == null) {
continue;
}
keys.add(CachedAccountDetails.Key.create(id, userRef.getObjectId()));
}
ImmutableMap.Builder<Account.Id, AccountState> result = ImmutableMap.builder();
for (Map.Entry<CachedAccountDetails.Key, CachedAccountDetails> account : accountDetailsCache.getAll(keys).entrySet()) {
result.put(account.getKey().accountId(), AccountState.forCachedAccount(account.getValue(), defaultPreferences, externalIds));
}
return result.build();
}
} catch (IOException | ExecutionException e) {
throw new StorageException(e);
}
}
use of com.google.gerrit.exceptions.StorageException in project gerrit by GerritCodeReview.
the class StarredChangesUtil method updateLabels.
private void updateLabels(Repository repo, String refName, ObjectId oldObjectId, Collection<String> labels) throws IOException, InvalidLabelsException {
try (TraceTimer traceTimer = TraceContext.newTimer("Update star labels", Metadata.builder().noteDbRefName(refName).resourceCount(labels.size()).build());
RevWalk rw = new RevWalk(repo)) {
RefUpdate u = repo.updateRef(refName);
u.setExpectedOldObjectId(oldObjectId);
u.setForceUpdate(true);
u.setNewObjectId(writeLabels(repo, labels));
u.setRefLogIdent(serverIdent.get());
u.setRefLogMessage("Update star labels", true);
RefUpdate.Result result = u.update(rw);
switch(result) {
case NEW:
case FORCED:
case NO_CHANGE:
case FAST_FORWARD:
gitRefUpdated.fire(allUsers, u, null);
return;
case LOCK_FAILURE:
throw new LockFailureException(String.format("Update star labels on ref %s failed", refName), u);
case IO_FAILURE:
case NOT_ATTEMPTED:
case REJECTED:
case REJECTED_CURRENT_BRANCH:
case RENAMED:
case REJECTED_MISSING_OBJECT:
case REJECTED_OTHER_REASON:
default:
throw new StorageException(String.format("Update star labels on ref %s failed: %s", refName, result.name()));
}
}
}
Aggregations