summaryrefslogtreecommitdiffstats
path: root/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/task/AddYumRepoTask.java
blob: a2ed6a800842e8c745d4812744d4fbbf79fd59e3 (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
// 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.task;

import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.regex.Pattern;

public class AddYumRepoTask implements Task {
    private static final Pattern REPOSITORY_ID_PATTERN = Pattern.compile("^[a-zA-Z_-]+$");

    private final String repositoryId; // e.g. "platform_rpms-latest"
    private final String name; // e.g. "Platform RPM Latest Repo"
    private final String baseurl;
    private final boolean enabled;

    public AddYumRepoTask(String repositoryId,
                          String name,
                          String baseurl,
                          boolean enabled) {
        this.repositoryId = repositoryId;
        this.name = name;
        this.baseurl = baseurl;
        this.enabled = enabled;
        validateRepositoryId(repositoryId);
    }

    @Override
    public boolean execute(TaskContext context) {
        Path path = Paths.get("/etc/yum.repos.d",repositoryId + ".repo");

        if (context.getFileSystem().isRegularFile(path)) {
            return false;
        }

        WriteFileTask writeFileTask = new WriteFileTask(path, this::getRepoFileContent)
                .withOwner("root")
                .withGroup("root")
                .withPermissions("rw-r--r--");

        return context.executeSubtask(writeFileTask);
    }

    String getRepoFileContent() {
        return String.join("\n",
                "# This file was generated by node admin",
                "# Do NOT modify this file by hand",
                "",
                "[" + repositoryId + "]",
                "name=" + name,
                "baseurl=" + baseurl,
                "enabled=" + (enabled ? 1 : 0),
                "gpgcheck=0"
        ) + "\n";
    }

    static void validateRepositoryId(String repositoryId) {
        if (!REPOSITORY_ID_PATTERN.matcher(repositoryId).matches()) {
            throw new IllegalArgumentException("Invalid repository ID '" + repositoryId + "'");
        }
    }
}