aboutsummaryrefslogtreecommitdiffstats
path: root/config/src/main/java/com/yahoo/config/subscription/impl/FileConfigSubscription.java
blob: 5311b91c31f43cc999427188ce1be4df01b0e6b0 (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
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.config.subscription.impl;

import com.yahoo.config.ConfigInstance;
import com.yahoo.config.ConfigurationRuntimeException;
import com.yahoo.config.subscription.CfgConfigPayloadBuilder;
import com.yahoo.config.subscription.ConfigInterruptedException;
import com.yahoo.io.IOUtils;
import com.yahoo.vespa.config.ConfigKey;
import com.yahoo.vespa.config.ConfigPayload;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;

import static java.util.logging.Level.FINE;

/**
 * Subscription used when config id is file:...
 *
 * @author Vegard Havdal
 */
public class FileConfigSubscription<T extends ConfigInstance> extends ConfigSubscription<T> {

    final File file;
    long ts;

    FileConfigSubscription(ConfigKey<T> key, File f) {
        super(key);
        setGeneration(0L);
        file = f;
        if (!file.exists() && !file.isFile())
            throw new IllegalArgumentException("Not a file: " + file);
    }

    @Override
    public boolean nextConfig(long timeout) {
        if (!file.exists() && !file.isFile()) throw new IllegalArgumentException("Not a file: " + file);
        if (checkReloaded()) {
            log.log(FINE, () -> "User forced config reload at " + System.currentTimeMillis());
            // User forced reload
            setConfigIfChanged(updateConfig());
            ConfigState<T> configState = getConfigState();
            log.log(FINE, () -> "Config updated at " + System.currentTimeMillis() + ", changed: " + configState.isConfigChanged());
            log.log(FINE, () -> "Config: " + configState.getConfig().toString());
            return true;
        }
        if (file.lastModified() != ts) {
            setConfigIncGen(updateConfig());
            return true;
        }
        try {
            Thread.sleep(timeout);
        } catch (InterruptedException e) {
            throw new ConfigInterruptedException(e);
        }

        return false;
    }

    private T updateConfig() {
        ts = file.lastModified();
        try {
            ConfigPayload payload = new CfgConfigPayloadBuilder().deserialize(Arrays.asList(IOUtils.readFile(file).split("\n")));
            return payload.toInstance(configClass, key.getConfigId());
        } catch (IOException e) {
            throw new ConfigurationRuntimeException(e);
        }
    }

    @Override
    public boolean subscribe(long timeout) {
        return true;
    }

}