summaryrefslogtreecommitdiffstats
path: root/node-maintainer/src/main/java/com/yahoo/vespa/hosted/node/maintainer/Maintainer.java
blob: 1e95ca15c3db9346a472b4e143564582a45e2c3c (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
// 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.maintainer;

import com.yahoo.log.LogSetup;
import com.yahoo.slime.ArrayTraverser;
import com.yahoo.slime.Inspector;
import com.yahoo.slime.Type;
import com.yahoo.system.ProcessExecuter;
import com.yahoo.vespa.config.SlimeUtils;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.HttpClientBuilder;

import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author freva
 */
public class Maintainer {

    private static final CoreCollector coreCollector = new CoreCollector(new ProcessExecuter());
    private static final HttpClient httpClient = createHttpClient(Duration.ofSeconds(5));

    public static void main(String[] args) {
        LogSetup.initVespaLogging("node-maintainer");
        if (args.length != 1) {
            throw new RuntimeException("Expected only 1 argument - a JSON list of maintainer jobs to execute");
        }

        Inspector object = SlimeUtils.jsonToSlime(args[0].getBytes()).get();
        if (object.type() != Type.ARRAY) {
            throw new IllegalArgumentException("Expected a list of maintainer jobs to execute");
        }

        // Variable must be effectively final to be used in lambda expression
        AtomicInteger numberOfJobsFailed = new AtomicInteger(0);
        object.traverse((ArrayTraverser) (int i, Inspector item) -> {
            try {
                String type = getFieldOrFail(item, "type").asString();
                Inspector arguments = getFieldOrFail(item, "arguments");
                parseMaintenanceJob(type, arguments);
            } catch (Exception e) {
                System.err.println("Failed executing job: " + item.toString());
                e.printStackTrace();
                numberOfJobsFailed.incrementAndGet();
            }
        });

        if (numberOfJobsFailed.get() > 0) {
            System.err.println(numberOfJobsFailed.get() + " of jobs has failed");
            System.exit(1);
        }
    }

    private static void parseMaintenanceJob(String type, Inspector arguments) {
        if (arguments.type() != Type.OBJECT) {
            throw new IllegalArgumentException("Expected a 'arguments' to be an object");
        }

        switch (type) {
            case "delete-files":
                parseDeleteFilesJob(arguments);
                break;

            case "delete-directories":
                parseDeleteDirectoriesJob(arguments);
                break;

            case "recursive-delete":
                parseRecursiveDelete(arguments);
                break;

            case "move-files":
                parseMoveFiles(arguments);
                break;

            case "handle-core-dumps":
                parseHandleCoreDumps(arguments);
                break;

            default:
                throw new IllegalArgumentException("Unknown job: " + type);
        }
    }

    private static void parseDeleteFilesJob(Inspector arguments) {
        Path basePath = Paths.get(getFieldOrFail(arguments, "basePath").asString());
        Duration maxAge = Duration.ofSeconds(getFieldOrFail(arguments, "maxAgeSeconds").asLong());
        Optional<String> fileNameRegex = SlimeUtils.optionalString(arguments.field("fileNameRegex"));
        boolean recursive = getFieldOrFail(arguments, "recursive").asBool();
        try {
            FileHelper.deleteFiles(basePath, maxAge, fileNameRegex, recursive);
        } catch (IOException e) {
            throw new RuntimeException("Failed deleting files under " + basePath.toAbsolutePath() +
                    fileNameRegex.map(regex -> ", matching '" + regex + "'").orElse("") +
                    ", " + (recursive ? "" : "not ") + "recursively" +
                    " and older than " + maxAge, e);
        }
    }

    private static void parseDeleteDirectoriesJob(Inspector arguments) {
        Path basePath = Paths.get(getFieldOrFail(arguments, "basePath").asString());
        Duration maxAge = Duration.ofSeconds(getFieldOrFail(arguments, "maxAgeSeconds").asLong());
        Optional<String> dirNameRegex = SlimeUtils.optionalString(arguments.field("dirNameRegex"));
        try {
            FileHelper.deleteDirectories(basePath, maxAge, dirNameRegex);
        } catch (IOException e) {
            throw new RuntimeException("Failed deleting directories under " + basePath.toAbsolutePath() +
                    dirNameRegex.map(regex -> ", matching '" + regex + "'").orElse("") +
                    " and older than " + maxAge, e);
        }
    }

    private static void parseRecursiveDelete(Inspector arguments) {
        Path basePath = Paths.get(getFieldOrFail(arguments, "path").asString());
        try {
            FileHelper.recursiveDelete(basePath);
        } catch (IOException e) {
            throw new RuntimeException("Failed deleting " + basePath.toAbsolutePath(), e);
        }
    }

    private static void parseMoveFiles(Inspector arguments) {
        Path from = Paths.get(getFieldOrFail(arguments, "from").asString());
        Path to = Paths.get(getFieldOrFail(arguments, "to").asString());

        try {
            FileHelper.moveIfExists(from, to);
        } catch (IOException e) {
            throw new RuntimeException("Failed moving from " + from.toAbsolutePath() + ", to " + to.toAbsolutePath(), e);
        }
    }

    private static void parseHandleCoreDumps(Inspector arguments) {
        Path coredumpsPath = Paths.get(getFieldOrFail(arguments, "coredumpsPath").asString());
        Path doneCoredumpsPath = Paths.get(getFieldOrFail(arguments, "doneCoredumpsPath").asString());
        Map<String, Object> attributesMap = parseMap(arguments);
        Optional<Path> installStatePath = SlimeUtils.optionalString(arguments.field("yinstStatePath")).map(Paths::get);
        String feedEndpoint = getFieldOrFail(arguments, "feedEndpoint").asString();

        try {
            CoredumpHandler coredumpHandler = new CoredumpHandler(httpClient, coreCollector, coredumpsPath,
                                                                  doneCoredumpsPath, attributesMap, installStatePath,
                                                                  feedEndpoint);
            coredumpHandler.processAll();
        } catch (IOException e) {
            throw new RuntimeException("Failed processing coredumps at " + coredumpsPath.toAbsolutePath() +
                    ", moving fished dumps to " + doneCoredumpsPath.toAbsolutePath(), e);
        }
    }

    private static Map<String, Object> parseMap(Inspector object) {
        Map<String, Object> map = new HashMap<>();
        getFieldOrFail(object, "attributes").traverse((String key, Inspector value) -> {
            switch (value.type()) {
                case BOOL:
                    map.put(key, value.asBool());
                    break;
                case LONG:
                    map.put(key, value.asLong());
                    break;
                case DOUBLE:
                    map.put(key, value.asDouble());
                    break;
                case STRING:
                    map.put(key, value.asString());
                    break;
                default:
                    throw new IllegalArgumentException("Invalid attribute for key '" + key + "', value " + value);
            }
        });
        return map;
    }

    private static Inspector getFieldOrFail(Inspector object, String key) {
        Inspector out = object.field(key);
        if (out.type() == Type.NIX) {
            throw new IllegalArgumentException("Key '" + key + "' was not found!");
        }
        return out;
    }

    private static HttpClient createHttpClient(Duration timeout) {
        int timeoutInMillis = (int) timeout.toMillis();
        return HttpClientBuilder.create()
                .setUserAgent("node-maintainer")
                .setDefaultRequestConfig(RequestConfig.custom()
                        .setConnectTimeout(timeoutInMillis)
                        .setConnectionRequestTimeout(timeoutInMillis)
                        .setSocketTimeout(timeoutInMillis)
                        .build())
                .setMaxConnTotal(100)
                .setMaxConnPerRoute(10)
                .build();
    }

}