summaryrefslogtreecommitdiffstats
path: root/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/task/WriteFileTask.java
blob: 308a7470d2438d051cff05dca669df9d2af02a3d (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
// 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 com.yahoo.vespa.hosted.node.admin.io.FileSystemPath;
import org.glassfish.jersey.internal.util.Producer;

import java.nio.file.Path;
import java.util.Optional;

public class WriteFileTask implements Task {
    private final Path path;
    private final Producer<String> contentProducer;

    private Optional<String> owner = Optional.empty();
    private Optional<String> group = Optional.empty();
    private Optional<String> permissions = Optional.empty();

    public WriteFileTask(Path path, Producer<String> contentProducer) {
        this.path = path;
        this.contentProducer = contentProducer;
    }

    public WriteFileTask withOwner(String owner) {
        this.owner = Optional.of(owner);
        return this;
    }

    public WriteFileTask withGroup(String group) {
        this.group = Optional.of(group);
        return this;
    }

    /**
     * @param permissions of the form "rwxr-x---".
     */
    public WriteFileTask withPermissions(String permissions) {
        this.permissions = Optional.of(permissions);
        return this;
    }

    @Override
    public boolean execute(TaskContext context) {
        final FileSystemPath fileSystemPath = context.getFileSystem().withPath(path);

        // TODO: Only return false if content, permission, etc would be unchanged.
        if (fileSystemPath.isRegularFile()) {
            return false;
        }

        context.executeSubtask(new MakeDirectoryTask(path.getParent()).withParents());

        String content = contentProducer.call();
        fileSystemPath.writeUtf8File(content);
        permissions.ifPresent(fileSystemPath::setPermissions);
        owner.ifPresent(fileSystemPath::setOwner);
        group.ifPresent(fileSystemPath::setGroup);

        return true;
    }

    public Path getPath() {
        return path;
    }

    public Producer<String> getContentProducer() {
        return contentProducer;
    }

    public Optional<String> getOwner() {
        return owner;
    }

    public Optional<String> getGroup() {
        return group;
    }

    public Optional<String> getPermissions() {
        return permissions;
    }
}