aboutsummaryrefslogtreecommitdiffstats
path: root/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/task/util/file/UnixPath.java
blob: 94c2df1a8b869e357ace1e71e0b13ed55e6b8ecb (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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.node.admin.task.util.file;

import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.ByteBuffer;
import java.nio.channels.SeekableByteChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.NotDirectoryException;
import java.nio.file.OpenOption;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.nio.file.attribute.FileAttribute;
import java.nio.file.attribute.FileTime;
import java.nio.file.attribute.GroupPrincipal;
import java.nio.file.attribute.PosixFileAttributeView;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
import java.nio.file.attribute.UserPrincipal;
import java.nio.file.attribute.UserPrincipalLookupService;
import java.time.Instant;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Stream;

import static com.yahoo.vespa.hosted.node.admin.task.util.file.IOExceptionUtil.ifExists;
import static com.yahoo.yolean.Exceptions.uncheck;

/**
 * Thin wrapper around java.nio.file.Path, especially nice for UNIX-specific features.
 *
 * @author hakonhall
 */
// @Immutable
public class UnixPath {

    private static final Set<OpenOption> DEFAULT_OPEN_OPTIONS =
            Set.of(StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE);

    private final Path path;

    public UnixPath(Path path) { this.path = path; }
    public UnixPath(String path) { this(Path.of(path)); }

    public Path toPath() { return path; }
    public UnixPath resolve(String relativeOrAbsolutePath) { return new UnixPath(path.resolve(relativeOrAbsolutePath)); }

    public UnixPath getParent() {
        Path parentPath = path.getParent();
        if (parentPath == null) {
            throw new IllegalStateException("Path has no parent directory: '" + path + "'");
        }

        return new UnixPath(parentPath);
    }

    public String getFilename() {
        Path filename = path.getFileName();
        if (filename == null) {
            // E.g. "/".
            throw new IllegalStateException("Path has no filename: '" + path + "'");
        }

        return filename.toString();
    }

    public boolean exists() { return Files.exists(path); }

    public String readUtf8File() {
        return new String(readBytes(), StandardCharsets.UTF_8);
    }

    public Optional<String> readUtf8FileIfExists() {
        try {
            return Optional.of(Files.readString(path));
        } catch (NoSuchFileException ignored) {
            return Optional.empty();
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }

    public byte[] readBytes() {
        return uncheck(() -> Files.readAllBytes(path));
    }

    /** Reads and returns all bytes contained in this path, if any such path exists. */
    public Optional<byte[]> readBytesIfExists() {
        try {
            return Optional.of(Files.readAllBytes(path));
        } catch (NoSuchFileException ignored) {
            return Optional.empty();
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }

    public List<String> readLines() {
        return uncheck(() -> Files.readAllLines(path));
    }

    /** Create an empty file and return true, or false if the file already exists (the file may not be regular). */
    public boolean create() {
        try {
            Files.createFile(path);
            return true;
        } catch (FileAlreadyExistsException ignored) {
            return false;
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }

    public UnixPath writeUtf8File(String content, OpenOption... options) {
        return writeBytes(content.getBytes(StandardCharsets.UTF_8), options);
    }

    public UnixPath writeUtf8File(String content, String permissions, OpenOption... options) {
        return writeBytes(content.getBytes(StandardCharsets.UTF_8), permissions, options);
    }

    public UnixPath writeBytes(byte[] content, OpenOption... options) {
        return writeBytes(content, null, options);
    }

    public UnixPath writeBytes(byte[] content, String permissions, OpenOption... options) {
        FileAttribute<?>[] attributes = Optional.ofNullable(permissions)
                .map(this::permissionsAsFileAttributes)
                .orElseGet(() -> new FileAttribute<?>[0]);

        Set<OpenOption> optionsSet = options.length == 0 ? DEFAULT_OPEN_OPTIONS : Set.of(options);

        try (SeekableByteChannel channel = Files.newByteChannel(path, optionsSet, attributes)) {
            channel.write(ByteBuffer.wrap(content));
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
        return this;
    }

    /** Write a file to the same dir as this, and then atomically move it to this' path. */
    public UnixPath atomicWriteBytes(byte[] content) {
        UnixPath temporaryPath = getParent().resolve(getFilename() + ".10Ia2f4N5");
        temporaryPath.writeBytes(content);
        temporaryPath.atomicMove(path);
        return this;
    }

    public String getPermissions() {
        return getAttributes().permissions();
    }

    /**
     * @param permissions Example: "rwxr-x---" means rwx for owner, rx for group,
     *                    and no permissions for others.
     */
    public UnixPath setPermissions(String permissions) {
        Set<PosixFilePermission> permissionSet = getPosixFilePermissionsFromString(permissions);
        uncheck(() -> Files.setPosixFilePermissions(path, permissionSet));
        return this;
    }

    public int getOwnerId() {
        return getAttributes().ownerId();
    }

    public UnixPath setOwner(String user) { return setOwner(user, "user"); }
    public UnixPath setOwnerId(int uid) { return setOwner(String.valueOf(uid), "uid"); }
    private UnixPath setOwner(String owner, String type) {
        UserPrincipalLookupService service = path.getFileSystem().getUserPrincipalLookupService();
        UserPrincipal principal = uncheck(
                () -> service.lookupPrincipalByName(owner),
                "While looking up %s %s", type, owner);
        uncheck(() -> Files.setOwner(path, principal));
        return this;
    }

    public int getGroupId() {
        return getAttributes().groupId();
    }

    public UnixPath setGroup(String group) { return setGroup(group, "group"); }
    public UnixPath setGroupId(int gid) { return setGroup(String.valueOf(gid), "gid"); }
    private UnixPath setGroup(String group, String type) {
        UserPrincipalLookupService service = path.getFileSystem().getUserPrincipalLookupService();
        GroupPrincipal principal = uncheck(
                () -> service.lookupPrincipalByGroupName(group),
                "While looking up group %s %s", type, group);
        uncheck(() -> Files.getFileAttributeView(path, PosixFileAttributeView.class).setGroup(principal));
        return this;
    }

    public Instant getLastModifiedTime() {
        return getAttributes().lastModifiedTime();
    }

    public UnixPath updateLastModifiedTime() {
        return setLastModifiedTime(Instant.now());
    }

    public UnixPath setLastModifiedTime(Instant instant) {
        uncheck(() -> Files.setLastModifiedTime(path, FileTime.from(instant)));
        return this;
    }

    public FileAttributes getAttributes() {
        return uncheck(() -> FileAttributes.fromAttributes(Files.readAttributes(path, "unix:*")));
    }

    public Optional<FileAttributes> getAttributesIfExists() {
        return ifExists(this::getAttributes);
    }

    public UnixPath createNewFile(String... permissions) {
        uncheck(() -> Files.createFile(path, permissionsAsFileAttributes(permissions)));
        return this;
    }

    public UnixPath createParents(String... permissions) {
        getParent().createDirectories(permissions);
        return this;
    }

    /** Create directory with given permissions and return true, or false if it already exists. */
    public boolean createDirectory(String... permissions) {
        try {
            Files.createDirectory(path, permissionsAsFileAttributes(permissions));
        } catch (FileAlreadyExistsException ignore) {
            return false;
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
        return true;
    }

    public UnixPath createDirectories(String... permissions) {
        uncheck(() -> Files.createDirectories(path, permissionsAsFileAttributes(permissions)));
        return this;
    }

    /**
     * Returns whether this path is a directory. Symlinks are followed, so this returns true for symlinks pointing to a
     * directory.
     */
    public boolean isDirectory() {
        return uncheck(() -> Files.isDirectory(path));
    }

    /** Returns whether this is a symlink */
    public boolean isSymbolicLink() {
        return Files.isSymbolicLink(path);
    }

    /**
     * Similar to rm -rf file:
     * - It's not an error if file doesn't exist
     * - If file is a directory, it and all content is removed
     * - For symlinks: Only the symlink is removed, not what the symlink points to
     */
    public boolean deleteRecursively() {
        if (!isSymbolicLink() && isDirectory()) {
            try (Stream<UnixPath> paths = listContentsOfDirectory()) {
                paths.forEach(UnixPath::deleteRecursively);
            }
        }
        return uncheck(() -> Files.deleteIfExists(path));
    }

    public boolean deleteIfExists() {
        return uncheck(() -> Files.deleteIfExists(path));
    }

    /** @return false path does not exist, is not a directory, or has at least one entry. */
    public boolean isEmptyDirectory() {
        try (var entryStream = Files.list(path)) {
            return entryStream.findAny().isEmpty();
        } catch (NotDirectoryException | NoSuchFileException e) {
            return false;
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }

    /** Lists the contents of this as a stream. Callers should use try-with to ensure that the stream is closed */
    public Stream<UnixPath> listContentsOfDirectory() {
        try {
            // Avoid the temptation to collect the stream here as collecting a directory with a high number of entries
            // can quickly lead to out of memory conditions
            return Files.list(path).map(UnixPath::new);
        } catch (NoSuchFileException ignored) {
            return Stream.empty();
        } catch (IOException e) {
            throw new UncheckedIOException("Failed to list contents of directory " + path.toAbsolutePath(), e);
        }
    }

    /** This path must be on the same file system as the to-path. Returns UnixPath of 'to'. */
    public UnixPath atomicMove(Path to) {
        uncheck(() -> Files.move(path, to, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING));
        return new UnixPath(to);
    }

    public boolean moveIfExists(Path to) {
        try {
            Files.move(path, to);
            return true;
        } catch (NoSuchFileException ignored) {
            return false;
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }

    /**
     * Creates a symbolic link from {@code link} to {@code this} (the target)
     * @param link the path for the symbolic link
     * @return the path to the symbolic link
     */
    public UnixPath createSymbolicLink(Path link) {
        uncheck(() -> Files.createSymbolicLink(link, path));
        return new UnixPath(link);
    }

    @Override
    public String toString() {
        return path.toString();
    }

    private FileAttribute<?>[] permissionsAsFileAttributes(String... permissions) {
        if (permissions.length == 0) return new FileAttribute<?>[0];
        if (permissions.length > 1)
            throw new IllegalArgumentException("Expected permissions to not be set or be a single string");

       return new FileAttribute<?>[]{PosixFilePermissions.asFileAttribute(getPosixFilePermissionsFromString(permissions[0]))};
    }

    private Set<PosixFilePermission> getPosixFilePermissionsFromString(String permissions) {
        try {
            return PosixFilePermissions.fromString(permissions);
        } catch (IllegalArgumentException e) {
            throw new IllegalArgumentException("Failed to set permissions '" +
                    permissions + "' on path " + path, e);
        }
    }
}