summaryrefslogtreecommitdiffstats
path: root/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/coredump/CoredumpHandlerTest.java
blob: fa5ed169fbc279a2dcb722dbbe571979cd73cf76 (plain) (blame)
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
// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.node.admin.maintenance.coredump;

import com.yahoo.vespa.hosted.node.admin.nodeagent.NodeAgentContext;
import com.yahoo.vespa.hosted.node.admin.nodeagent.NodeAgentContextImpl;
import com.yahoo.vespa.hosted.node.admin.task.util.file.UnixPath;
import com.yahoo.vespa.hosted.node.admin.task.util.process.TestChildProcess2;
import com.yahoo.vespa.hosted.node.admin.task.util.process.TestTerminal;
import com.yahoo.vespa.test.file.TestFileSystem;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.FileTime;
import java.time.Duration;
import java.time.Instant;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;

import static com.yahoo.yolean.Exceptions.uncheck;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

/**
 * @author freva
 */
public class CoredumpHandlerTest {
    private final FileSystem fileSystem = TestFileSystem.create();
    private final Path donePath = fileSystem.getPath("/home/docker/dumps");
    private final NodeAgentContext context = new NodeAgentContextImpl.Builder("container-123.domain.tld")
            .fileSystem(fileSystem).build();
    private final Path crashPathInContainer = Paths.get("/var/crash");
    private final Path doneCoredumpsPath = fileSystem.getPath("/home/docker/dumps");

    private final TestTerminal terminal = new TestTerminal();
    private final CoreCollector coreCollector = mock(CoreCollector.class);
    private final CoredumpReporter coredumpReporter = mock(CoredumpReporter.class);
    @SuppressWarnings("unchecked")
    private final CoredumpHandler coredumpHandler = new CoredumpHandler(terminal, coreCollector, coredumpReporter,
            crashPathInContainer, doneCoredumpsPath);


    @Test
    public void coredump_enqueue_test() throws IOException {
        final Path crashPathOnHost = fileSystem.getPath("/home/docker/container-1/some/crash/path");
        final Path processingDir = fileSystem.getPath("/home/docker/container-1/some/other/processing");

        Files.createDirectories(crashPathOnHost);
        Files.setLastModifiedTime(Files.createFile(crashPathOnHost.resolve(".bash.core.431")), FileTime.from(Instant.now()));

        assertFolderContents(crashPathOnHost, ".bash.core.431");
        UUID coredumpId = UUID.randomUUID();

        Optional<Path> enqueuedPath = coredumpHandler.enqueueCoredump(coredumpId, crashPathOnHost, processingDir);
        assertEquals(Optional.empty(), enqueuedPath);

        // bash.core.431 finished writing... and 2 more have since been written
        Files.move(crashPathOnHost.resolve(".bash.core.431"), crashPathOnHost.resolve("bash.core.431"));
        Files.setLastModifiedTime(Files.createFile(crashPathOnHost.resolve("vespa-proton.core.119")), FileTime.from(Instant.now().minus(Duration.ofMinutes(10))));
        Files.setLastModifiedTime(Files.createFile(crashPathOnHost.resolve("vespa-slobrok.core.673")), FileTime.from(Instant.now().minus(Duration.ofMinutes(5))));

        enqueuedPath = coredumpHandler.enqueueCoredump(coredumpId, crashPathOnHost, processingDir);
        assertEquals(Optional.of(processingDir.resolve(coredumpId.toString())), enqueuedPath);
        assertFolderContents(crashPathOnHost, "bash.core.431", "vespa-slobrok.core.673");
        assertFolderContents(processingDir, coredumpId.toString());
        assertFolderContents(processingDir.resolve(coredumpId.toString()), "dump_vespa-proton.core.119");

        // Enqueue another
        enqueuedPath = coredumpHandler.enqueueCoredump(coredumpId, crashPathOnHost, processingDir);
        assertEquals(Optional.of(processingDir.resolve(coredumpId.toString())), enqueuedPath);
        assertFolderContents(crashPathOnHost, "bash.core.431");
        assertFolderContents(processingDir, coredumpId.toString());
        assertFolderContents(processingDir.resolve(coredumpId.toString()), "dump_vespa-proton.core.119", "dump_vespa-slobrok.core.673");
    }

    @Test
    public void coredump_to_process_test() throws IOException {
        final Path crashPathOnHost = fileSystem.getPath("/home/docker/container-1/some/crash/path");
        final Path processingDir = fileSystem.getPath("/home/docker/container-1/some/other/processing");
        UUID coredumpId = UUID.randomUUID();
        // Initially there are no core dumps
        Optional<Path> enqueuedPath = coredumpHandler.enqueueCoredump(coredumpId, crashPathOnHost, processingDir);
        assertEquals(Optional.empty(), enqueuedPath);

        // 3 core dumps occur
        Files.createDirectories(crashPathOnHost);
        Files.setLastModifiedTime(Files.createFile(crashPathOnHost.resolve("bash.core.431")), FileTime.from(Instant.now()));
        Files.setLastModifiedTime(Files.createFile(crashPathOnHost.resolve("vespa-proton.core.119")), FileTime.from(Instant.now().minus(Duration.ofMinutes(10))));
        Files.setLastModifiedTime(Files.createFile(crashPathOnHost.resolve("vespa-slobrok.core.673")), FileTime.from(Instant.now().minus(Duration.ofMinutes(5))));

        enqueuedPath = coredumpHandler.getCoredumpToProcess(coredumpId, crashPathOnHost, processingDir);
        assertEquals(Optional.of(processingDir.resolve(coredumpId.toString())), enqueuedPath);

        // Running this again wont enqueue new core dumps as we are still processing the one enqueued previously
        enqueuedPath = coredumpHandler.getCoredumpToProcess(coredumpId, crashPathOnHost, processingDir);
        assertEquals(Optional.of(processingDir.resolve(coredumpId.toString())), enqueuedPath);
    }

    @Test
    public void get_metadata_test() throws IOException {
        Map<String, Object> metadata = new HashMap<>();
        metadata.put("bin_path", "/bin/bash");
        metadata.put("backtrace", List.of("call 1", "function 2", "something something"));

        Map<String, Object> attributes = Map.of(
                "hostname", "host123.yahoo.com",
                "vespa_version", "6.48.4",
                "kernel_version", "3.10.0-862.9.1.el7.x86_64",
                "docker_image", "vespa/ci:6.48.4");

        String expectedMetadataStr = "{\"fields\":{" +
                "\"hostname\":\"host123.yahoo.com\"," +
                "\"kernel_version\":\"3.10.0-862.9.1.el7.x86_64\"," +
                "\"backtrace\":[\"call 1\",\"function 2\",\"something something\"]," +
                "\"vespa_version\":\"6.48.4\"," +
                "\"bin_path\":\"/bin/bash\"," +
                "\"docker_image\":\"vespa/ci:6.48.4\"" +
                "}}";


        Path coredumpDirectoryInContainer = Paths.get("/var/crash/id-123");
        Path coredumpDirectory = context.pathOnHostFromPathInNode(coredumpDirectoryInContainer);
        Files.createDirectories(coredumpDirectory);
        Files.createFile(coredumpDirectory.resolve("dump_core.456"));
        when(coreCollector.collect(eq(context), eq(coredumpDirectoryInContainer.resolve("dump_core.456"))))
                .thenReturn(metadata);

        assertEquals(expectedMetadataStr, coredumpHandler.getMetadata(context, coredumpDirectory, () -> attributes));
        verify(coreCollector, times(1)).collect(any(), any());

        // Calling it again will simply read the previously generated metadata from disk
        assertEquals(expectedMetadataStr, coredumpHandler.getMetadata(context, coredumpDirectory, () -> attributes));
        verify(coreCollector, times(1)).collect(any(), any());
    }

    @Test(expected = IllegalStateException.class)
    public void cant_get_metadata_if_no_core_file() throws IOException {
        coredumpHandler.getMetadata(context, fileSystem.getPath("/fake/path"), Map::of);
    }

    @Test(expected = IllegalStateException.class)
    public void fails_to_get_core_file_if_only_compressed() throws IOException {
        Path coredumpDirectory = fileSystem.getPath("/path/to/coredump/proccessing/id-123");
        Files.createDirectories(coredumpDirectory);
        Files.createFile(coredumpDirectory.resolve("dump_bash.core.431.lz4"));
        coredumpHandler.findCoredumpFileInProcessingDirectory(coredumpDirectory);
    }

    @Test
    public void process_single_coredump_test() throws IOException {
        Path coredumpDirectory = fileSystem.getPath("/path/to/coredump/proccessing/id-123");
        Files.createDirectories(coredumpDirectory);
        Files.write(coredumpDirectory.resolve("metadata.json"), "metadata".getBytes());
        Files.createFile(coredumpDirectory.resolve("dump_bash.core.431"));
        assertFolderContents(coredumpDirectory, "metadata.json", "dump_bash.core.431");

        terminal.interceptCommand("/usr/bin/lz4 -f /path/to/coredump/proccessing/id-123/dump_bash.core.431 " +
                "/path/to/coredump/proccessing/id-123/dump_bash.core.431.lz4 2>&1",
                commandLine -> {
                    uncheck(() -> Files.createFile(fileSystem.getPath(commandLine.getArguments().get(3))));
                    return new TestChildProcess2(0, "");
                });
        coredumpHandler.processAndReportSingleCoredump(context, coredumpDirectory, Map::of);
        verify(coreCollector, never()).collect(any(), any());
        verify(coredumpReporter, times(1)).reportCoredump(eq("id-123"), eq("metadata"));
        assertFalse(Files.exists(coredumpDirectory));
        assertFolderContents(doneCoredumpsPath, "id-123");
        assertFolderContents(doneCoredumpsPath.resolve("id-123"), "metadata.json", "dump_bash.core.431.lz4");
    }

    @Before
    public void setup() throws IOException {
        Files.createDirectories(donePath);
    }

    @After
    public void teardown() {
        terminal.verifyAllCommandsExecuted();
    }

    private static void assertFolderContents(Path pathToFolder, String... filenames) {
        Set<String> expectedContentsOfFolder = Set.of(filenames);
        Set<String> actualContentsOfFolder = new UnixPath(pathToFolder)
                .listContentsOfDirectory().stream()
                .map(unixPath -> unixPath.toPath().getFileName().toString())
                .collect(Collectors.toSet());
        assertEquals(expectedContentsOfFolder, actualContentsOfFolder);
    }
}