aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/test/java/com/google/devtools/build/lib/skyframe/ArtifactFunctionTest.java
blob: 789e2b1e1d530aff48950f94302d4ee6ffd23040 (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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
// Copyright 2015 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.skyframe;
import static com.google.common.truth.Truth.assertThat;
import static com.google.devtools.build.lib.skyframe.FileArtifactValue.create;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.fail;

import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.testing.EqualsTester;
import com.google.devtools.build.lib.actions.Action;
import com.google.devtools.build.lib.actions.ActionAnalysisMetadata;
import com.google.devtools.build.lib.actions.ActionAnalysisMetadata.MiddlemanType;
import com.google.devtools.build.lib.actions.ActionInputHelper;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.actions.Artifact.SpecialArtifact;
import com.google.devtools.build.lib.actions.Artifact.SpecialArtifactType;
import com.google.devtools.build.lib.actions.Artifact.TreeFileArtifact;
import com.google.devtools.build.lib.actions.MissingInputFileException;
import com.google.devtools.build.lib.actions.Root;
import com.google.devtools.build.lib.actions.util.ActionsTestUtil;
import com.google.devtools.build.lib.actions.util.TestAction.DummyAction;
import com.google.devtools.build.lib.events.NullEventHandler;
import com.google.devtools.build.lib.util.Pair;
import com.google.devtools.build.lib.vfs.FileStatus;
import com.google.devtools.build.lib.vfs.FileSystemUtils;
import com.google.devtools.build.lib.vfs.Path;
import com.google.devtools.build.lib.vfs.PathFragment;
import com.google.devtools.build.skyframe.EvaluationResult;
import com.google.devtools.build.skyframe.SkyFunction;
import com.google.devtools.build.skyframe.SkyKey;
import com.google.devtools.build.skyframe.SkyValue;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Tests for {@link ArtifactFunction}.
 */
// Doesn't actually need any particular Skyframe, but is only relevant to Skyframe full mode.
@RunWith(JUnit4.class)
public class ArtifactFunctionTest extends ArtifactFunctionTestCase {

  private PathFragment allowedMissingInput = null;

  @Before
  public final void setUp() throws Exception  {
    delegateActionExecutionFunction = new SimpleActionExecutionFunction();
    allowedMissingInputsPredicate = new Predicate<PathFragment>() {
      @Override
      public boolean apply(PathFragment input) {
        return input.equals(allowedMissingInput);
      }
    };
  }

  private void assertFileArtifactValueMatches(boolean expectDigest) throws Throwable {
    Artifact output = createDerivedArtifact("output");
    Path path = output.getPath();
    file(path, "contents");
    assertValueMatches(path.stat(), expectDigest ? path.getMD5Digest() : null, evaluateFAN(output));
  }

  @Test
  public void testBasicArtifact() throws Throwable {
    fastDigest = false;
    assertFileArtifactValueMatches(/*expectDigest=*/ true);
  }

  @Test
  public void testBasicArtifactWithXattr() throws Throwable {
    fastDigest = true;
    assertFileArtifactValueMatches(/*expectDigest=*/ true);
  }

  @Test
  public void testMissingNonMandatoryArtifact() throws Throwable {
    Artifact input = createSourceArtifact("input1");
    assertNotNull(evaluateArtifactValue(input, /*mandatory=*/ false));
  }

  @Test
  public void testMissingMandatoryAllowedMissingArtifact() throws Throwable {
    Artifact input = createSourceArtifact("allowedMissing");
    allowedMissingInput = input.getRootRelativePath();
    assertThat(evaluateArtifactValue(input, /*mandatory=*/ true))
        .isEqualTo(FileArtifactValue.MISSING_FILE_MARKER);
  }

  @Test
  public void testUnreadableMandatoryAllowedMissingArtifact() throws Throwable {
    Artifact input = createSourceArtifact("allowedMissing");
    file(input.getPath(), "allowedMissing");
    input.getPath().chmod(0);

    allowedMissingInput = input.getRootRelativePath();
    assertThat(evaluateArtifactValue(input, /*mandatory=*/ true))
        .isEqualTo(FileArtifactValue.MISSING_FILE_MARKER);
  }

  @Test
  public void testUnreadableInputWithFsWithAvailableDigest() throws Throwable {
    final byte[] expectedDigest = MessageDigest.getInstance("md5").digest(
        "someunreadablecontent".getBytes(StandardCharsets.UTF_8));
    setupRoot(
        new CustomInMemoryFs() {
          @Override
          public byte[] getMD5Digest(Path path) throws IOException {
            return path.getBaseName().equals("unreadable")
                ? expectedDigest
                : super.getMD5Digest(path);
          }
        });

    Artifact input = createSourceArtifact("unreadable");
    Path inputPath = input.getPath();
    file(inputPath, "dummynotused");
    inputPath.chmod(0);

    FileArtifactValue value =
        (FileArtifactValue) evaluateArtifactValue(input, /*mandatory=*/ true);

    FileStatus stat = inputPath.stat();
    assertThat(value.getSize()).isEqualTo(stat.getSize());
    assertThat(value.getDigest()).isEqualTo(expectedDigest);
  }

  @Test
  public void testMissingMandatoryArtifact() throws Throwable {
    Artifact input = createSourceArtifact("input1");
    try {
      evaluateArtifactValue(input, /*mandatory=*/ true);
      fail();
    } catch (MissingInputFileException ex) {
      // Expected.
    }
  }

  @Test
  public void testMiddlemanArtifact() throws Throwable {
    Artifact output = createDerivedArtifact("output");
    Artifact input1 = createSourceArtifact("input1");
    Artifact input2 = createDerivedArtifact("input2");
    Action action =
        new DummyAction(
            ImmutableList.of(input1, input2), output, MiddlemanType.AGGREGATING_MIDDLEMAN);
    // Overwrite default generating action with this one.
    for (Iterator<ActionAnalysisMetadata> it = actions.iterator(); it.hasNext(); ) {
      if (it.next().getOutputs().contains(output)) {
        it.remove();
        break;
      }
    }
    actions.add(action);
    file(input2.getPath(), "contents");
    file(input1.getPath(), "source contents");
    evaluate(
        Iterables.toArray(
            ArtifactValue.mandatoryKeys(ImmutableSet.of(input2, input1, input2)), SkyKey.class));
    ArtifactValue value = evaluateArtifactValue(output);
    assertThat(((AggregatingArtifactValue) value).getInputs())
        .containsExactly(Pair.of(input1, create(input1)), Pair.of(input2, create(input2)));
  }

  @Test
  public void testIOException() throws Exception {
    fastDigest = false;
    final IOException exception = new IOException("beep");
    setupRoot(
        new CustomInMemoryFs() {
          @Override
          public byte[] getMD5Digest(Path path) throws IOException {
            throw exception;
          }
        });
    Artifact artifact = createDerivedArtifact("no-read");
    writeFile(artifact.getPath(), "content");
    try {
      create(createDerivedArtifact("no-read"));
      fail();
    } catch (IOException e) {
      assertSame(exception, e);
    }
  }

  /**
   * Tests that ArtifactFunction rethrows transitive {@link IOException}s as
   * {@link MissingInputFileException}s.
   */
  @Test
  public void testIOException_EndToEnd() throws Throwable {
    final IOException exception = new IOException("beep");
    setupRoot(
        new CustomInMemoryFs() {
          @Override
          public FileStatus stat(Path path, boolean followSymlinks) throws IOException {
            if (path.getBaseName().equals("bad")) {
              throw exception;
            }
            return super.stat(path, followSymlinks);
          }
        });
    try {
      evaluateArtifactValue(createSourceArtifact("bad"));
      fail();
    } catch (MissingInputFileException e) {
      assertThat(e.getMessage()).contains(exception.getMessage());
    }
  }

  @Test
  public void testNoMtimeIfNonemptyFile() throws Exception {
    Artifact artifact = createDerivedArtifact("no-digest");
    Path path = artifact.getPath();
    writeFile(path, "hello"); //Non-empty file.
    FileArtifactValue value = create(artifact);
    assertArrayEquals(path.getMD5Digest(), value.getDigest());
    try {
      value.getModifiedTime();
      fail("mtime for non-empty file should not be stored.");
    } catch (IllegalStateException e) {
      // Expected.
    }
  }

  @Test
  public void testDirectory() throws Exception {
    Artifact artifact = createDerivedArtifact("dir");
    Path path = artifact.getPath();
    FileSystemUtils.createDirectoryAndParents(path);
    path.setLastModifiedTime(1L);
    FileArtifactValue value = create(artifact);
    assertNull(value.getDigest());
    assertEquals(1L, value.getModifiedTime());
  }

  // Empty files need to store their mtimes, so touching an empty file
  // can be used to trigger rebuilds.
  @Test
  public void testEmptyFile() throws Exception {
    Artifact artifact = createDerivedArtifact("empty");
    Path path = artifact.getPath();
    writeFile(path, "");
    path.setLastModifiedTime(1L);
    FileArtifactValue value = create(artifact);
    assertArrayEquals(path.getMD5Digest(), value.getDigest());
    assertEquals(1L, value.getModifiedTime());
    assertEquals(0L, value.getSize());
  }

  @Test
  public void testEquality() throws Exception {
    Artifact artifact1 = createDerivedArtifact("artifact1");
    Artifact artifact2 = createDerivedArtifact("artifact2");
    Artifact diffDigest = createDerivedArtifact("diffDigest");
    Artifact diffMtime = createDerivedArtifact("diffMtime");
    Artifact empty1 = createDerivedArtifact("empty1");
    Artifact empty2 = createDerivedArtifact("empty2");
    Artifact empty3 = createDerivedArtifact("empty3");
    Artifact dir1 = createDerivedArtifact("dir1");
    Artifact dir2 = createDerivedArtifact("dir2");
    Artifact dir3 = createDerivedArtifact("dir3");
    Path path1 = artifact1.getPath();
    Path path2 = artifact2.getPath();
    Path digestPath = diffDigest.getPath();
    Path mtimePath = diffMtime.getPath();
    writeFile(artifact1.getPath(), "content");
    writeFile(artifact2.getPath(), "content");
    path1.setLastModifiedTime(0);
    path2.setLastModifiedTime(0);
    writeFile(diffDigest.getPath(), "1234567"); // Same size as artifact1.
    digestPath.setLastModifiedTime(0);
    writeFile(mtimePath, "content");
    mtimePath.setLastModifiedTime(1);
    Path emptyPath1 = empty1.getPath();
    Path emptyPath2 = empty2.getPath();
    Path emptyPath3 = empty3.getPath();
    writeFile(emptyPath1, "");
    writeFile(emptyPath2, "");
    writeFile(emptyPath3, "");
    emptyPath1.setLastModifiedTime(0L);
    emptyPath2.setLastModifiedTime(1L);
    emptyPath3.setLastModifiedTime(1L);
    Path dirPath1 = dir1.getPath();
    Path dirPath2 = dir2.getPath();
    Path dirPath3 = dir3.getPath();
    FileSystemUtils.createDirectoryAndParents(dirPath1);
    FileSystemUtils.createDirectoryAndParents(dirPath2);
    FileSystemUtils.createDirectoryAndParents(dirPath3);
    dirPath1.setLastModifiedTime(0L);
    dirPath2.setLastModifiedTime(1L);
    dirPath3.setLastModifiedTime(1L);
    EqualsTester equalsTester = new EqualsTester();
    equalsTester
        .addEqualityGroup(create(artifact1), create(artifact2), create(diffMtime))
        .addEqualityGroup(create(empty1))
        .addEqualityGroup(create(empty2), create(empty3))
        .addEqualityGroup(create(dir1))
        .addEqualityGroup(create(dir2), create(dir3))
        .testEquals();
  }

  @Test
  public void testActionTreeArtifactOutput() throws Throwable {
    Artifact artifact = createDerivedTreeArtifactWithAction("treeArtifact");
    TreeFileArtifact treeFileArtifact1 = createFakeTreeFileArtifact(artifact, "child1", "hello1");
    TreeFileArtifact treeFileArtifact2 = createFakeTreeFileArtifact(artifact, "child2", "hello2");

    TreeArtifactValue value = (TreeArtifactValue) evaluateArtifactValue(artifact);
    assertNotNull(value.getChildValue(treeFileArtifact1));
    assertNotNull(value.getChildValue(treeFileArtifact2));
    assertNotNull(value.getChildValue(treeFileArtifact1).getDigest());
    assertNotNull(value.getChildValue(treeFileArtifact2).getDigest());
  }

  @Test
  public void testSpawnActionTemplate() throws Throwable {
    // artifact1 is a tree artifact generated by normal action.
    Artifact artifact1 = createDerivedTreeArtifactWithAction("treeArtifact1");
    createFakeTreeFileArtifact(artifact1, "child1", "hello1");
    createFakeTreeFileArtifact(artifact1, "child2", "hello2");


    // artifact2 is a tree artifact generated by action template.
    Artifact artifact2 = createDerivedTreeArtifactOnly("treeArtifact2");
    TreeFileArtifact treeFileArtifact1 = createFakeTreeFileArtifact(artifact2, "child1", "hello1");
    TreeFileArtifact treeFileArtifact2 = createFakeTreeFileArtifact(artifact2, "child2", "hello2");

    actions.add(
        ActionsTestUtil.createDummySpawnActionTemplate(artifact1, artifact2));

    TreeArtifactValue value = (TreeArtifactValue) evaluateArtifactValue(artifact2);
    assertNotNull(value.getChildValue(treeFileArtifact1));
    assertNotNull(value.getChildValue(treeFileArtifact2));
    assertNotNull(value.getChildValue(treeFileArtifact1).getDigest());
    assertNotNull(value.getChildValue(treeFileArtifact2).getDigest());
  }

  @Test
  public void testConsecutiveSpawnActionTemplates() throws Throwable {
    // artifact1 is a tree artifact generated by normal action.
    Artifact artifact1 = createDerivedTreeArtifactWithAction("treeArtifact1");
    createFakeTreeFileArtifact(artifact1, "child1", "hello1");
    createFakeTreeFileArtifact(artifact1, "child2", "hello2");

    // artifact2 is a tree artifact generated by action template.
    Artifact artifact2 = createDerivedTreeArtifactOnly("treeArtifact2");
    createFakeTreeFileArtifact(artifact2, "child1", "hello1");
    createFakeTreeFileArtifact(artifact2, "child2", "hello2");
    actions.add(
        ActionsTestUtil.createDummySpawnActionTemplate(artifact1, artifact2));

    // artifact3 is a tree artifact generated by action template.
    Artifact artifact3 = createDerivedTreeArtifactOnly("treeArtifact3");
    TreeFileArtifact treeFileArtifact1 = createFakeTreeFileArtifact(artifact3, "child1", "hello1");
    TreeFileArtifact treeFileArtifact2 = createFakeTreeFileArtifact(artifact3, "child2", "hello2");
    actions.add(
        ActionsTestUtil.createDummySpawnActionTemplate(artifact2, artifact3));

    TreeArtifactValue value = (TreeArtifactValue) evaluateArtifactValue(artifact3);
    assertNotNull(value.getChildValue(treeFileArtifact1));
    assertNotNull(value.getChildValue(treeFileArtifact2));
    assertNotNull(value.getChildValue(treeFileArtifact1).getDigest());
    assertNotNull(value.getChildValue(treeFileArtifact2).getDigest());
  }

  private void file(Path path, String contents) throws Exception {
    FileSystemUtils.createDirectoryAndParents(path.getParentDirectory());
    writeFile(path, contents);
  }

  private Artifact createSourceArtifact(String path) {
    return new Artifact(new PathFragment(path), Root.asSourceRoot(root));
  }

  private Artifact createDerivedArtifact(String path) {
    PathFragment execPath = new PathFragment("out").getRelative(path);
    Path fullPath = root.getRelative(execPath);
    Artifact output =
        new Artifact(
            fullPath, Root.asDerivedRoot(root, root.getRelative("out")), execPath, ALL_OWNER);
    actions.add(new DummyAction(ImmutableList.<Artifact>of(), output));
    return output;
  }

  private Artifact createDerivedTreeArtifactWithAction(String path) {
    Artifact treeArtifact = createDerivedTreeArtifactOnly(path);
    actions.add(new DummyAction(ImmutableList.<Artifact>of(), treeArtifact));
    return treeArtifact;
  }

  private Artifact createDerivedTreeArtifactOnly(String path) {
    PathFragment execPath = new PathFragment("out").getRelative(path);
    Path fullPath = root.getRelative(execPath);
    return new SpecialArtifact(
        fullPath,
        Root.asDerivedRoot(root, root.getRelative("out")),
        execPath,
        ALL_OWNER,
        SpecialArtifactType.TREE);
  }

  private TreeFileArtifact createFakeTreeFileArtifact(Artifact treeArtifact,
      String parentRelativePath, String content) throws Exception {
    TreeFileArtifact treeFileArtifact = ActionInputHelper.treeFileArtifact(
        treeArtifact, new PathFragment(parentRelativePath));
    Path path = treeFileArtifact.getPath();
    FileSystemUtils.createDirectoryAndParents(path.getParentDirectory());
    writeFile(path, content);
    return treeFileArtifact;
  }

  private void assertValueMatches(FileStatus file, byte[] digest, FileArtifactValue value)
      throws IOException {
    assertEquals(file.getSize(), value.getSize());
    if (digest == null) {
      assertNull(value.getDigest());
      assertEquals(file.getLastModifiedTime(), value.getModifiedTime());
    } else {
      assertArrayEquals(digest, value.getDigest());
    }
  }

  private FileArtifactValue evaluateFAN(Artifact artifact) throws Throwable {
    return ((FileArtifactValue) evaluateArtifactValue(artifact));
  }

  private ArtifactValue evaluateArtifactValue(Artifact artifact) throws Throwable {
    return evaluateArtifactValue(artifact, /*isMandatory=*/ true);
  }

  private ArtifactValue evaluateArtifactValue(Artifact artifact, boolean mandatory)
      throws Throwable {
    SkyKey key = ArtifactValue.key(artifact, mandatory);
    EvaluationResult<ArtifactValue> result = evaluate(ImmutableList.of(key).toArray(new SkyKey[0]));
    if (result.hasError()) {
      throw result.getError().getException();
    }
    return result.get(key);
  }

  private void setGeneratingActions() {
    if (evaluator.getExistingValueForTesting(OWNER_KEY) == null) {
      differencer.inject(ImmutableMap.of(
          OWNER_KEY,
          new ActionLookupValue(ImmutableList.<ActionAnalysisMetadata>copyOf(actions))));
    }
  }

  private <E extends SkyValue> EvaluationResult<E> evaluate(SkyKey... keys)
      throws InterruptedException {
    setGeneratingActions();
    return driver.evaluate(
        Arrays.asList(keys),
        /*keepGoing=*/false,
        SkyframeExecutor.DEFAULT_THREAD_COUNT,
        NullEventHandler.INSTANCE);
  }

  /** Value Builder for actions that just stats and stores the output file (which must exist). */
  private static class SimpleActionExecutionFunction implements SkyFunction {
    @Override
    public SkyValue compute(SkyKey skyKey, Environment env) {
      Map<Artifact, FileValue> artifactData = new HashMap<>();
      Map<Artifact, TreeArtifactValue> treeArtifactData = new HashMap<>();
      Map<Artifact, FileArtifactValue> additionalOutputData = new HashMap<>();
      Action action = (Action) skyKey.argument();
      Artifact output = Iterables.getOnlyElement(action.getOutputs());

      try {
        if (output.isTreeArtifact()) {
          TreeFileArtifact treeFileArtifact1 = ActionInputHelper.treeFileArtifact(
              output, new PathFragment("child1"));
          TreeFileArtifact treeFileArtifact2 = ActionInputHelper.treeFileArtifact(
              output, new PathFragment("child2"));
          TreeArtifactValue treeArtifactValue = TreeArtifactValue.create(ImmutableMap.of(
              treeFileArtifact1, FileArtifactValue.create(treeFileArtifact1),
              treeFileArtifact2, FileArtifactValue.create(treeFileArtifact2)));
          treeArtifactData.put(output, treeArtifactValue);
        } else if (action.getActionType() == MiddlemanType.NORMAL) {
          FileValue fileValue = ActionMetadataHandler.fileValueFromArtifact(output, null, null);
          artifactData.put(output, fileValue);
          additionalOutputData.put(output, FileArtifactValue.create(output, fileValue));
       } else {
          additionalOutputData.put(output, FileArtifactValue.DEFAULT_MIDDLEMAN);
        }
      } catch (IOException e) {
        throw new IllegalStateException(e);
      }
      return new ActionExecutionValue(
          artifactData,
          treeArtifactData,
          additionalOutputData);
    }

    @Override
    public String extractTag(SkyKey skyKey) {
      return null;
    }
  }
}