mirror of https://github.com/micromata/borgbackup-butler.git

Kai Reinhard
24.52.2019 c50335dff01dffab42f4f25639eb14c11d80a70c
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
package de.micromata.borgbutler.demo;
 
import de.micromata.borgbutler.BorgCommand;
import de.micromata.borgbutler.BorgJob;
import de.micromata.borgbutler.config.BorgRepoConfig;
import de.micromata.borgbutler.config.ConfigurationHandler;
import de.micromata.borgbutler.config.Definitions;
import de.micromata.borgbutler.data.Repository;
import de.micromata.borgbutler.jobs.JobResult;
import de.micromata.borgbutler.json.JsonUtils;
import de.micromata.borgbutler.json.borg.ProgressInfo;
import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.*;
 
public class DemoRepos {
    private enum Type {FAST, SLOW, VERY_SLOW}
 
    private static Logger log = LoggerFactory.getLogger(DemoRepos.class);
    private static final String DEMO_IDENTIFIER = "borgbutler-demo";
 
    private static final String[] REPOS = {"fast", "slow", "very-slow"};
    private static List<BorgRepoConfig> demoRepos;
 
    /**
     * If configured by the user, demo repositories are added to the given list. If not configured this method does nothing.
     *
     * @param repositoryList
     */
    public static void handleDemoRepos(List<BorgRepoConfig> repositoryList) {
        if (!ConfigurationHandler.getConfiguration().isShowDemoRepos()) {
            // Remove any demo repository if exist due to former settings:
            Iterator<BorgRepoConfig> it = repositoryList.iterator();
            while (it.hasNext()) {
                BorgRepoConfig repoConfig = it.next();
                if (!StringUtils.startsWith(repoConfig.getRepo(), DEMO_IDENTIFIER)) {
                    continue;
                }
                it.remove();
            }
            return;
        }
        init();
        for (BorgRepoConfig repo : demoRepos) {
            if (!repositoryList.contains(repo))
                repositoryList.add(repo);
        }
        // Remove duplicate entries (produced by former versions of BorgButler:
        Set<String> set = new HashSet<>();
        Iterator<BorgRepoConfig> it = repositoryList.iterator();
        try {
            while (it.hasNext()) {
                BorgRepoConfig repoConfig = it.next();
                if (!StringUtils.startsWith(repoConfig.getRepo(), DEMO_IDENTIFIER)) {
                    continue;
                }
                if (set.contains(repoConfig.getRepo())) {
                    it.remove();
                } else {
                    set.add(repoConfig.getRepo());
                }
            }
        } catch (Exception ex) {
            // ConcurrentException, ignore it, it's only for demo purposes.
        }
    }
 
    public static boolean isDemo(String name) {
        return StringUtils.startsWith(name, DEMO_IDENTIFIER);
    }
 
    public static void repoWasRead(BorgRepoConfig repoConfig, Repository repository) {
        if (!isDemo(repository.getName())) {
            return;
        }
        repository.setId(repository.getId() + "-" + REPOS[getType(repoConfig).ordinal()]);
    }
 
    public static JobResult<String> execute(BorgJob job) {
        BorgCommand command = job.getCommand();
        if (!StringUtils.equalsAny(command.getCommand(), "list", "info")) {
            log.info("Commmand '" + command.getCommand() + "' not supported for demo repositories.");
            return new JobResult<String>().setStatus(JobResult.Status.ERROR);
        }
        StringBuilder sb = new StringBuilder();
        boolean archive = command.getArchive() != null;
        if (archive) {
            sb.append("archive-");
        } else {
            sb.append("repo-");
        }
        sb.append(command.getCommand());
        if (archive) {
            sb.append("-").append(command.getArchive());
        }
        sb.append(".json.gz");
        int wait = 0;
        Type type = getType(command.getRepoConfig());
        if (type == Type.VERY_SLOW) {
            wait = 10;
        } else if (type == Type.SLOW) {
            wait = 1;
        }
        String file = sb.toString();
        log.info("Loading demo archive from '" + file + "'...");
        try (InputStream inputStream = new GzipCompressorInputStream(DemoRepos.class.getResourceAsStream("/demodata/" + file))) {
            if (wait > 0) {
                ProgressInfo progress = new ProgressInfo()
                        .setMessage("Faked demo progress")
                        .setTotal(10 * wait);
                for (int i = 0; i < 10 * wait; i++) {
                    if (job.isCancellationRequested()) {
                        break;
                    }
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException ex) {
                        // Do nothing.
                    }
                    job.processStdErrLine(JsonUtils.toJson(progress.setCurrent(i)), 0);
                }
            }
            if (archive && "list".equals(command.getCommand())) {
                try (Scanner scanner = new Scanner(inputStream)) {
                    while (scanner.hasNextLine()) {
                        String line = scanner.nextLine();
                        job.processStdOutLine(line, 0);
                    }
                    return new JobResult<String>().setStatus(JobResult.Status.OK);
                }
            } else {
                StringWriter writer = new StringWriter();
                IOUtils.copy(inputStream, writer, Definitions.STD_CHARSET);
                return new JobResult<String>().setResultObject(writer.toString()).setStatus(JobResult.Status.OK);
            }
        } catch (IOException ex) {
            log.error("Error while reading demo file '" + file + "': " + ex.getMessage() + ".");
            return null;
        }
    }
 
    private static Type getType(BorgRepoConfig repoConfig) {
        if (repoConfig.getRepo().endsWith("very-slow")) {
            return Type.VERY_SLOW;
        } else if (repoConfig.getRepo().endsWith("slow")) {
            return Type.SLOW;
        }
        return Type.FAST;
    }
 
    private static void init() {
        synchronized (DEMO_IDENTIFIER) {
            if (demoRepos != null) {
                return;
            }
            demoRepos = new ArrayList<>();
            demoRepos.add(new BorgRepoConfig()
                    .setRepo(DEMO_IDENTIFIER + "-fast")
                    .setDisplayName("Demo repository fast"));
            demoRepos.add(new BorgRepoConfig()
                    .setRepo(DEMO_IDENTIFIER + "-slow")
                    .setDisplayName("Demo repository slow"));
            demoRepos.add(new BorgRepoConfig()
                    .setRepo(DEMO_IDENTIFIER + "-very-slow")
                    .setDisplayName("Demo repository very-slow"));
        }
    }
}