aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/main/java/com/google/devtools/build/lib/rules/extra/ExtraAction.java
blob: d2ad58c9d9fa8b8a516eb4378a715d1c4eb1690e (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
// Copyright 2014 The Bazel Authors. All rights reserved.
//
// 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.devtools.build.lib.rules.extra;

import com.google.common.base.Preconditions;
import com.google.common.base.Predicates;
import com.google.common.collect.Collections2;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.devtools.build.lib.actions.AbstractAction;
import com.google.devtools.build.lib.actions.Action;
import com.google.devtools.build.lib.actions.ActionExecutionContext;
import com.google.devtools.build.lib.actions.ActionExecutionException;
import com.google.devtools.build.lib.actions.ActionOwner;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.actions.ArtifactResolver;
import com.google.devtools.build.lib.actions.DelegateSpawn;
import com.google.devtools.build.lib.actions.ExecException;
import com.google.devtools.build.lib.actions.Executor;
import com.google.devtools.build.lib.actions.PackageRootResolutionException;
import com.google.devtools.build.lib.actions.PackageRootResolver;
import com.google.devtools.build.lib.actions.Spawn;
import com.google.devtools.build.lib.actions.SpawnActionContext;
import com.google.devtools.build.lib.analysis.actions.CommandLine;
import com.google.devtools.build.lib.analysis.actions.SpawnAction;
import com.google.devtools.build.lib.collect.nestedset.NestedSet;
import com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder;
import com.google.devtools.build.lib.collect.nestedset.Order;
import com.google.devtools.build.lib.vfs.FileSystemUtils;
import com.google.devtools.build.lib.vfs.PathFragment;

import java.io.IOException;
import java.util.Collection;
import java.util.Map;
import java.util.Set;

import javax.annotation.Nullable;
import javax.annotation.concurrent.GuardedBy;

/**
 * Action used by extra_action rules to create an action that shadows an existing action. Runs a
 * command-line using {@link SpawnActionContext} for executions.
 */
public final class ExtraAction extends SpawnAction {
  private final Action shadowedAction;
  private final boolean createDummyOutput;
  private final ImmutableMap<PathFragment, Artifact> runfilesManifests;
  private final ImmutableSet<Artifact> extraActionInputs;
  // This can be read/written from multiple threads, and so accesses should be synchronized.
  @GuardedBy("this")
  private boolean inputsKnown;

  public ExtraAction(ActionOwner owner,
      ImmutableSet<Artifact> extraActionInputs,
      Map<PathFragment, Artifact> runfilesManifests,
      Collection<Artifact> outputs,
      Action shadowedAction,
      boolean createDummyOutput,
      CommandLine argv,
      Map<String, String> environment,
      Map<String, String> executionInfo,
      String progressMessage,
      String mnemonic) {
    super(owner,
        createInputs(shadowedAction.getInputs(), extraActionInputs),
        outputs,
        AbstractAction.DEFAULT_RESOURCE_SET,
        argv,
        ImmutableMap.copyOf(environment),
        ImmutableMap.copyOf(executionInfo),
        progressMessage,
        getManifests(shadowedAction),
        mnemonic,
        false,
        null);
    this.shadowedAction = shadowedAction;
    this.runfilesManifests = ImmutableMap.copyOf(runfilesManifests);
    this.createDummyOutput = createDummyOutput;

    this.extraActionInputs = extraActionInputs;
    inputsKnown = shadowedAction.inputsKnown();
    if (createDummyOutput) {
      // Expecting just a single dummy file in the outputs.
      Preconditions.checkArgument(outputs.size() == 1, outputs);
    }
  }

  private static ImmutableMap<PathFragment, Artifact> getManifests(Action shadowedAction) {
    // If the shadowed action is a SpawnAction, then we also add the input manifests to this
    // action's input manifests.
    // TODO(bazel-team): Also handle other action classes correctly.
    if (shadowedAction instanceof SpawnAction) {
      return ((SpawnAction) shadowedAction).getInputManifests();
    }
    return ImmutableMap.of();
  }

  @Override
  public boolean discoversInputs() {
    return shadowedAction.discoversInputs();
  }

  @Nullable
  @Override
  public Collection<Artifact> discoverInputs(ActionExecutionContext actionExecutionContext)
      throws ActionExecutionException, InterruptedException {
    Preconditions.checkState(discoversInputs(), this);
    if (getContext(actionExecutionContext.getExecutor()).isRemotable(getMnemonic(),
        isRemotable())) {
      // If we're running remotely, we need to update our inputs to take account of any additional
      // inputs the shadowed action may need to do its work.
      if (shadowedAction.discoversInputs() && shadowedAction instanceof AbstractAction) {
        Iterable<Artifact> additionalInputs =
            ((AbstractAction) shadowedAction).getInputFilesForExtraAction(actionExecutionContext);
        updateInputs(createInputs(additionalInputs, extraActionInputs));
        return ImmutableSet.copyOf(additionalInputs);
      }
    }
    return null;
  }

  @Override
  public synchronized boolean inputsKnown() {
    return inputsKnown;
  }

  private static NestedSet<Artifact> createInputs(
      Iterable<Artifact> shadowedActionInputs, ImmutableSet<Artifact> extraActionInputs) {
    NestedSetBuilder<Artifact> result = new NestedSetBuilder<>(Order.STABLE_ORDER);
    if (shadowedActionInputs instanceof NestedSet) {
      result.addTransitive((NestedSet<Artifact>) shadowedActionInputs);
    } else {
      result.addAll(shadowedActionInputs);
    }
    return result.addAll(extraActionInputs).build();
  }

  @Override
  public synchronized void updateInputs(Iterable<Artifact> discoveredInputs) {
    setInputs(discoveredInputs);
    inputsKnown = true;
  }

  @Nullable
  @Override
  public Iterable<Artifact> resolveInputsFromCache(ArtifactResolver artifactResolver,
      PackageRootResolver resolver, Collection<PathFragment> inputPaths)
          throws PackageRootResolutionException {
    // We update the inputs directly from the shadowed action.
    Set<PathFragment> extraActionPathFragments =
        ImmutableSet.copyOf(Artifact.asPathFragments(extraActionInputs));
    return shadowedAction.resolveInputsFromCache(artifactResolver, resolver,
        Collections2.filter(inputPaths, Predicates.in(extraActionPathFragments)));
  }

  /**
   * @InheritDoc
   *
   * This method calls in to {@link AbstractAction#getInputFilesForExtraAction} and
   * {@link Action#getExtraActionInfo} of the action being shadowed from the thread executing this
   * ExtraAction. It assumes these methods are safe to call from a different thread than the thread
   * responsible for the execution of the action being shadowed.
   */
  @Override
  public void execute(ActionExecutionContext actionExecutionContext)
      throws ActionExecutionException, InterruptedException {
    Executor executor = actionExecutionContext.getExecutor();

    // PHASE 2: execution of extra_action.

    if (getContext(executor).isRemotable(getMnemonic(), isRemotable())) {
      try {
        getContext(executor).exec(getExtraActionSpawn(), actionExecutionContext);
      } catch (ExecException e) {
        throw e.toActionExecutionException(this);
      }
    } else {
      super.execute(actionExecutionContext);
    }

    // PHASE 3: create dummy output.
    // If the user didn't specify output, we need to create dummy output
    // to make blaze schedule this action.
    if (createDummyOutput) {
      for (Artifact output : getOutputs()) {
        try {
          FileSystemUtils.touchFile(output.getPath());
        } catch (IOException e) {
          throw new ActionExecutionException(e.getMessage(), e, this, false);
        }
      }
    }
    synchronized (this) {
      inputsKnown = true;
    }
  }

  /**
   * The spawn command for ExtraAction needs to be slightly modified from
   * regular SpawnActions:
   * -the extraActionInfo file needs to be added to the list of inputs.
   * -the extraActionInfo file that is an output file of this task is created
   * before the SpawnAction so should not be listed as one of its outputs.
   */
  // TODO(bazel-team): Add more tests that execute this code path!
  private Spawn getExtraActionSpawn() {
    final Spawn base = super.getSpawn();
    return new DelegateSpawn(base) {
      @Override public ImmutableMap<PathFragment, Artifact> getRunfilesManifests() {
        ImmutableMap.Builder<PathFragment, Artifact> builder = ImmutableMap.builder();
        builder.putAll(super.getRunfilesManifests());
        builder.putAll(runfilesManifests);
        return builder.build();
      }

      @Override public String getMnemonic() { return ExtraAction.this.getMnemonic(); }
    };
  }

  /**
   * Returns the action this extra action is 'shadowing'.
   */
  public Action getShadowedAction() {
    return shadowedAction;
  }
}