summaryrefslogtreecommitdiffstats
path: root/gerrit-sshd/src/main/java/com/google/gerrit/sshd/commands/KillCommand.java
blob: 69018afbb1f3dce7ed05dc58c959ddd38d788c67 (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
// Copyright (C) 2009 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.sshd.commands;

import com.google.gerrit.server.IdentifiedUser;
import com.google.gerrit.server.git.WorkQueue;
import com.google.gerrit.server.git.WorkQueue.Task;
import com.google.gerrit.server.util.IdGenerator;
import com.google.gerrit.sshd.BaseCommand;
import com.google.inject.Inject;

import org.apache.sshd.server.Environment;
import org.kohsuke.args4j.Argument;

import java.io.PrintWriter;
import java.util.HashSet;
import java.util.Set;

/** Kill a task in the work queue. */
final class KillCommand extends BaseCommand {
  @Inject
  private IdentifiedUser currentUser;

  @Inject
  private WorkQueue workQueue;

  private final Set<Integer> taskIds = new HashSet<Integer>();

  @Argument(index = 0, multiValued = true, required = true, metaVar = "ID")
  void addTaskId(final String taskId) {
    int p = 0;
    while (p < taskId.length() - 1 && taskId.charAt(p) == '0') {
      p++;
    }
    taskIds.add((int) Long.parseLong(taskId.substring(p), 16));
  }

  @Override
  public void start(final Environment env) {
    startThread(new CommandRunnable() {
      @Override
      public void run() throws Exception {
        if (!currentUser.getCapabilities().canKillTask()) {
          String msg = String.format(
            "fatal: %s does not have \"Kill Task\" capability.",
            currentUser.getUserName());
          throw new UnloggedFailure(BaseCommand.STATUS_NOT_ADMIN, msg);
        }

        parseCommandLine();
        KillCommand.this.commitMurder();
      }
    });
  }

  private void commitMurder() {
    final PrintWriter p = toPrintWriter(err);
    for (final Integer id : taskIds) {
      final Task<?> task = workQueue.getTask(id);
      if (task != null) {
        task.cancel(true);
      } else {
        p.print("kill: " + IdGenerator.format(id) + ": No such task\n");
      }
    }
    p.flush();
  }
}