aboutsummaryrefslogtreecommitdiffstats
path: root/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/StorageMaintainerTest.java
blob: b5640ddb996fd72a6f6493ac8096d8b956a465fa (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
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
// Copyright 2017 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;

import com.google.common.collect.ImmutableSet;
import com.yahoo.component.Version;
import com.yahoo.config.provision.CloudName;
import com.yahoo.config.provision.Environment;
import com.yahoo.config.provision.NodeType;
import com.yahoo.config.provision.RegionName;
import com.yahoo.config.provision.SystemName;
import com.yahoo.config.provision.zone.ZoneId;
import com.yahoo.vespa.hosted.node.admin.configserver.noderepository.NodeMembership;
import com.yahoo.vespa.hosted.node.admin.configserver.noderepository.NodeOwner;
import com.yahoo.vespa.hosted.node.admin.configserver.noderepository.NodeSpec;
import com.yahoo.vespa.hosted.node.admin.configserver.noderepository.NodeState;
import com.yahoo.vespa.hosted.node.admin.docker.DockerOperations;
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.FileFinder;
import com.yahoo.vespa.hosted.node.admin.task.util.file.UnixPath;
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.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;

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.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static com.yahoo.yolean.Exceptions.uncheck;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;

/**
 * @author dybis
 */
@RunWith(Enclosed.class)
public class StorageMaintainerTest {
    private static final DockerOperations docker = mock(DockerOperations.class);

    public static class SecretAgentCheckTests {
        private final StorageMaintainer storageMaintainer = new StorageMaintainer(null, docker, null, null);

        @Test
        public void tenant() {
            Path path = executeAs(NodeType.tenant);

            assertChecks(path, "athenz-certificate-expiry", "host-life",
                    "system-coredumps-processing", "vespa", "vespa-health");

            // All dimensions for vespa metrics should be set by metricsproxy
            assertCheckEnds(path.resolve("vespa.yaml"),
                    "  args:\n" +
                    "    - all\n");

            // For non vespa metrics, we need to set all the dimensions ourselves
            assertCheckEnds(path.resolve("host-life.yaml"),
                    "tags:\n" +
                    "    namespace: Vespa\n" +
                    "    role: tenants\n" +
                    "    zone: prod.us-north-1\n" +
                    "    vespaVersion: 6.305.12\n" +
                    "    state: active\n" +
                    "    parentHostname: host123.test.domain.tld\n" +
                    "    tenantName: tenant\n" +
                    "    app: application.instance\n" +
                    "    applicationName: application\n" +
                    "    instanceName: instance\n" +
                    "    applicationId: tenant.application.instance\n" +
                    "    clustertype: clusterType\n" +
                    "    clusterid: clusterId\n");
        }

        @Test
        public void proxy() {
            Path path = executeAs(NodeType.proxy);

            assertChecks(path, "athenz-certificate-expiry", "host-life", "routing-configage",
                    "ssl-status", "system-coredumps-processing", "vespa", "vespa-health");

            // All dimensions for vespa metrics should be set by the source
            assertCheckEnds(path.resolve("vespa.yaml"),
                    "  args:\n" +
                    "    - all\n");

            // For non vespa metrics, we need to set all the dimensions ourselves
            assertCheckEnds(path.resolve("host-life.yaml"),
                    "tags:\n" +
                    "    namespace: Vespa\n" +
                    "    role: routing\n" +
                    "    zone: prod.us-north-1\n" +
                    "    vespaVersion: 6.305.12\n" +
                    "    state: active\n" +
                    "    parentHostname: host123.test.domain.tld\n" +
                    "    tenantName: tenant\n" +
                    "    app: application.instance\n" +
                    "    applicationName: application\n" +
                    "    instanceName: instance\n" +
                    "    applicationId: tenant.application.instance\n" +
                    "    clustertype: clusterType\n" +
                    "    clusterid: clusterId\n");
        }

        @Test
        public void configserver() {
            Path path = executeAs(NodeType.config);

            assertChecks(path, "athenz-certificate-expiry", "configserver", "configserver-logd", "host-life",
                         "system-coredumps-processing", "zkbackupage");

            assertCheckEnds(path.resolve("configserver.yaml"),
                    "  tags:\n" +
                    "    namespace: Vespa\n" +
                    "    role: configserver\n" +
                    "    zone: prod.us-north-1\n" +
                    "    vespaVersion: 6.305.12\n");
        }

        @Test
        public void controller() {
            Path path = executeAs(NodeType.controller);

            assertChecks(path, "athenz-certificate-expiry", "controller", "controller-logd", "host-life",
                         "system-coredumps-processing", "vespa", "vespa-health", "zkbackupage");


            // Do not set namespace for vespa metrics. WHY?
            assertCheckEnds(path.resolve("vespa.yaml"),
                    "  tags:\n" +
                    "    role: controller\n" +
                    "    zone: prod.us-north-1\n" +
                    "    vespaVersion: 6.305.12\n");

            assertCheckEnds(path.resolve("controller.yaml"),
                    "  tags:\n" +
                    "    namespace: Vespa\n" +
                    "    role: controller\n" +
                    "    zone: prod.us-north-1\n" +
                    "    vespaVersion: 6.305.12\n");
        }

        private Path executeAs(NodeType nodeType) {
            NodeSpec nodeSpec = new NodeSpec.Builder()
                    .hostname("host123-5.test.domain.tld")
                    .nodeType(nodeType)
                    .state(NodeState.active)
                    .parentHostname("host123.test.domain.tld")
                    .owner(new NodeOwner("tenant", "application", "instance"))
                    .membership(new NodeMembership("clusterType", "clusterId", null, 0, false))
                    .vespaVersion(Version.fromString("6.305.12"))
                    .flavor("d-2-8-50")
                    .canonicalFlavor("d-2-8-50")
                    .build();
            NodeAgentContext context = new NodeAgentContextImpl.Builder(nodeSpec)
                    .fileSystem(TestFileSystem.create())
                    .zoneId(ZoneId.from(Environment.prod, RegionName.from("us-north-1"), CloudName.defaultName(), SystemName.defaultSystem())).build();
            Path path = context.pathOnHostFromPathInNode("/etc/yamas-agent");
            uncheck(() -> Files.createDirectories(path));
            storageMaintainer.writeMetricsConfig(context);
            return path;
        }

        private void assertCheckEnds(Path checkPath, String contentsEnd) {
            String contents = new UnixPath(checkPath).readUtf8File();
            assertTrue(contents, contents.endsWith(contentsEnd));
        }

        private void assertChecks(Path checksPath, String... checkNames) {
            List<String> expectedChecks = Stream.of(checkNames).sorted().collect(Collectors.toList());
            List<String> actualChecks = FileFinder.files(checksPath).stream()
                    .map(FileFinder.FileAttributes::filename)
                    .map(filename -> filename.replaceAll("\\.yaml$", ""))
                    .sorted()
                    .collect(Collectors.toList());
            assertEquals(expectedChecks, actualChecks);
        }
    }

    public static class DiskUsageTests {

        private final TestTerminal terminal = new TestTerminal();

        @Test
        public void testDiskUsed() throws IOException {
            StorageMaintainer storageMaintainer = new StorageMaintainer(terminal, docker, null, null);
            FileSystem fileSystem = TestFileSystem.create();
            NodeAgentContext context = new NodeAgentContextImpl.Builder("host-1.domain.tld").fileSystem(fileSystem).build();
            Files.createDirectories(context.pathOnHostFromPathInNode("/"));

            terminal.expectCommand("du -xsk /home/docker/host-1 2>&1", 0, "321\t/home/docker/host-1/");
            assertEquals(Optional.of(328_704L), storageMaintainer.getDiskUsageFor(context));

            // Value should still be cached, no new execution against the terminal
            assertEquals(Optional.of(328_704L), storageMaintainer.getDiskUsageFor(context));
        }

        @Test
        public void testNonExistingDiskUsed() {
            StorageMaintainer storageMaintainer = new StorageMaintainer(terminal, docker, null, null);
            long usedBytes = storageMaintainer.getDiskUsedInBytes(null, Paths.get("/fake/path"));
            assertEquals(0L, usedBytes);
        }

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

    public static class ArchiveContainerDataTests {
        @Test
        public void archive_container_data_test() throws IOException {
            // Create some files in containers
            FileSystem fileSystem = TestFileSystem.create();
            NodeAgentContext context1 = createNodeAgentContextAndContainerStorage(fileSystem, "container-1");
            createNodeAgentContextAndContainerStorage(fileSystem, "container-2");

            Path pathToArchiveDir = fileSystem.getPath("/home/docker/container-archive");
            Files.createDirectories(pathToArchiveDir);

            Path containerStorageRoot = context1.pathOnHostFromPathInNode("/").getParent();
            Set<String> containerStorageRootContentsBeforeArchive = FileFinder.from(containerStorageRoot)
                    .maxDepth(1)
                    .stream()
                    .map(FileFinder.FileAttributes::filename)
                    .collect(Collectors.toSet());
            assertEquals(ImmutableSet.of("container-archive", "container-1", "container-2"), containerStorageRootContentsBeforeArchive);


            // Archive container-1
            StorageMaintainer storageMaintainer = new StorageMaintainer(null, docker, null, pathToArchiveDir);
            storageMaintainer.archiveNodeStorage(context1);

            // container-1 should be gone from container-storage
            Set<String> containerStorageRootContentsAfterArchive = FileFinder.from(containerStorageRoot)
                    .maxDepth(1)
                    .stream()
                    .map(FileFinder.FileAttributes::filename)
                    .collect(Collectors.toSet());
            assertEquals(ImmutableSet.of("container-archive", "container-2"), containerStorageRootContentsAfterArchive);

            // container archive directory should contain exactly 1 directory - the one we just archived
            List<FileFinder.FileAttributes> containerArchiveContentsAfterArchive = FileFinder.from(pathToArchiveDir).maxDepth(1).list();
            assertEquals(1, containerArchiveContentsAfterArchive.size());
            Path archivedContainerStoragePath = containerArchiveContentsAfterArchive.get(0).path();
            assertTrue(archivedContainerStoragePath.getFileName().toString().matches("container-1_[0-9]{14}"));
            Set<String> archivedContainerStorageContents = FileFinder.files(archivedContainerStoragePath)
                    .stream()
                    .map(fileAttributes -> archivedContainerStoragePath.relativize(fileAttributes.path()).toString())
                    .collect(Collectors.toSet());
            assertEquals(ImmutableSet.of("opt/vespa/logs/vespa/vespa.log", "opt/vespa/logs/vespa/zookeeper.log"), archivedContainerStorageContents);
        }

        private NodeAgentContext createNodeAgentContextAndContainerStorage(FileSystem fileSystem, String containerName) throws IOException {
            NodeAgentContext context = new NodeAgentContextImpl.Builder(containerName + ".domain.tld")
                    .fileSystem(fileSystem).build();

            Path containerVespaHomeOnHost = context.pathOnHostFromPathInNode(context.pathInNodeUnderVespaHome(""));
            Files.createDirectories(context.pathOnHostFromPathInNode("/etc/something"));
            Files.createFile(context.pathOnHostFromPathInNode("/etc/something/conf"));

            Files.createDirectories(containerVespaHomeOnHost.resolve("logs/vespa"));
            Files.createFile(containerVespaHomeOnHost.resolve("logs/vespa/vespa.log"));
            Files.createFile(containerVespaHomeOnHost.resolve("logs/vespa/zookeeper.log"));

            Files.createDirectories(containerVespaHomeOnHost.resolve("var/db"));
            Files.createFile(containerVespaHomeOnHost.resolve("var/db/some-file"));

            Path containerRootOnHost = context.pathOnHostFromPathInNode("/");
            Set<String> actualContents = FileFinder.files(containerRootOnHost)
                    .stream()
                    .map(fileAttributes -> containerRootOnHost.relativize(fileAttributes.path()).toString())
                    .collect(Collectors.toSet());
            Set<String> expectedContents = new HashSet<>(Arrays.asList(
                    "etc/something/conf",
                    "opt/vespa/logs/vespa/vespa.log",
                    "opt/vespa/logs/vespa/zookeeper.log",
                    "opt/vespa/var/db/some-file"));
            assertEquals(expectedContents, actualContents);
            return context;
        }
    }
}