1 package org.simantics.district.maps.server;
3 import java.io.ByteArrayOutputStream;
4 import java.io.IOException;
5 import java.io.InputStream;
6 import java.nio.charset.StandardCharsets;
7 import java.nio.file.DirectoryStream;
8 import java.nio.file.Files;
9 import java.nio.file.Path;
10 import java.nio.file.StandardOpenOption;
11 import java.util.ArrayList;
12 import java.util.HashMap;
13 import java.util.List;
15 import java.util.concurrent.TimeUnit;
16 import java.util.concurrent.atomic.AtomicBoolean;
17 import java.util.stream.Stream;
19 import org.simantics.district.maps.server.prefs.MapsServerPreferences;
20 import org.slf4j.Logger;
21 import org.slf4j.LoggerFactory;
22 import org.yaml.snakeyaml.Yaml;
23 import org.zeroturnaround.exec.ProcessExecutor;
24 import org.zeroturnaround.exec.StartedProcess;
25 import org.zeroturnaround.exec.stream.slf4j.Slf4jStream;
26 import org.zeroturnaround.process.PidProcess;
27 import org.zeroturnaround.process.PidUtil;
28 import org.zeroturnaround.process.Processes;
29 import org.zeroturnaround.process.SystemProcess;
31 import com.fasterxml.jackson.core.JsonParseException;
32 import com.fasterxml.jackson.databind.JsonMappingException;
33 import com.fasterxml.jackson.databind.ObjectMapper;
35 public class TileserverMapnik {
37 private static final Logger LOGGER = LoggerFactory.getLogger(TileserverMapnik.class);
38 private static final String[] ADDITIONAL_DEPENDENCIES = new String[] { "tilelive-vector@3.9.4", "tilelive-tmstyle@0.6.0" };
40 private SystemProcess process;
41 private Path serverRoot;
43 private AtomicBoolean running = new AtomicBoolean(false);
45 TileserverMapnik(Path serverRoot) {
46 this.serverRoot = serverRoot.normalize();
49 public boolean isRunning() throws IOException, InterruptedException {
50 return process == null ? false : process.isAlive() && isReady();
53 public boolean isReady() {
57 public void start() throws Exception {
58 // check if existing server is left hanging
59 if (Files.exists(getPid())) {
60 String pid = new String(Files.readAllBytes(getPid()));
61 PidProcess pr = Processes.newPidProcess(Integer.parseInt(pid));
62 pr.destroyForcefully();
65 // check that npm dependencies are satisfied
66 if (checkAndInstall(null)) {
67 checkAndInstall(ADDITIONAL_DEPENDENCIES[0]);
68 checkAndInstall(ADDITIONAL_DEPENDENCIES[1]);
74 if (process != null && process.isAlive())
77 StartedProcess startedProcess = new ProcessExecutor().directory(serverRoot.resolve("tileserver-mapnik").toFile()).destroyOnExit().environment(getEnv())
78 .command(NodeJS.executable().toString(), getTessera().toString(), "-c", getConfigJson().toString(), "-p", Integer.toString(MapsServerPreferences.defaultPort()))
79 .redirectOutput(Slf4jStream.ofCaller().asDebug()).start();
81 Process nativeProcess = startedProcess.getProcess();
82 process = Processes.newStandardProcess(nativeProcess);
83 int pid = PidUtil.getPid(nativeProcess);
84 Files.write(getPid(), (pid + "").getBytes(), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
88 private Map<String, String> getEnv() {
89 Map<String, String> env = new HashMap<>();
90 env.put("MAPNIK_FONT_PATH", getFonts().toString());
91 env.put("ICU_DATA", getICU().toString());
95 public void stop() throws IOException, InterruptedException {
96 if (process != null && process.isAlive()) {
97 // gracefully not supported on windows
98 process.destroyForcefully();
99 if (!process.waitFor(2000, TimeUnit.MILLISECONDS)) {
100 process.destroyForcefully();
101 if (process.isAlive())
102 LOGGER.error("Could not shutdown TileserverMapnik!");
105 Files.delete(getPid());
110 private Path getPid() {
111 return serverRoot.resolve("pid");
114 public void restart() throws Exception {
119 private boolean checkIfInstalled(String module) throws Exception {
120 String tileserverMapnik = tileserverMapnikRoot().toString();
122 try (ByteArrayOutputStream output = new ByteArrayOutputStream()) {
123 if (module == null) {
124 retVal = NodeJS.npm(output, "--prefix", tileserverMapnik, "list");
126 retVal = NodeJS.npm(output, "--prefix", tileserverMapnik, "list", module);
128 String outputString = new String(output.toByteArray(), StandardCharsets.UTF_8);
133 private boolean install(String module) throws Exception {
134 String tileserverMapnik = tileserverMapnikRoot().toString();
137 retVal = NodeJS.npm(null, "--prefix", tileserverMapnik, "install", "--save");
139 retVal = NodeJS.npm(null, "--prefix", tileserverMapnik, "install", module, "--save");
141 LOGGER.warn("Could not install module " + module == null ? "package.json" : module + "! " + retVal);
145 private boolean checkAndInstall(String module) throws Exception {
146 boolean installed = checkIfInstalled(module);
153 private Path tileserverMapnikRoot() {
154 return serverRoot.resolve("tileserver-mapnik").toAbsolutePath();
157 private Path getFonts() {
158 return serverRoot.resolve("fonts").toAbsolutePath();
161 private Path getICU() {
162 return serverRoot.resolve("tileserver-mapnik/node_modules/tilelive-vector/node_modules/mapnik/lib/binding/node-v46-win32-x64/share/icu").toAbsolutePath();
165 private Path getTessera() {
166 return serverRoot.resolve("tileserver-mapnik/bin/tessera.js").toAbsolutePath();
169 private Path getConfigJson() {
170 return serverRoot.resolve("config.json").toAbsolutePath();
173 public List<String> availableMBTiles() throws IOException {
174 Path data = getDataDirectory();
175 List<String> result = new ArrayList<>();
176 try (Stream<Path> paths = Files.walk(data)) {
178 if (!p.equals(data)) {
179 String tiles = p.getFileName().toString();
187 private void checkConfigJson() throws JsonParseException, JsonMappingException, IOException {
188 Path configJson = getConfigJson();
189 Map<String, Object> config = new HashMap<>();
190 Path tm2 = getStyleDirectory();
191 try (DirectoryStream<Path> stream = Files.newDirectoryStream(tm2)) {
192 stream.forEach(p -> {
193 Path projectYaml = p.resolve("project.yml");
194 if (Files.exists(projectYaml)) {
197 Map<String, String> source = new HashMap<>();
199 Path tm2style = serverRoot.relativize(projectYaml.getParent());
201 String prefix = "tmstyle://../";
202 String tmStyle = prefix + tm2style.toString();
203 source.put("source", tmStyle);
204 config.put("/" + projectYaml.getParent().getFileName().toString(), source);
208 ObjectMapper mapper = new ObjectMapper();
209 mapper.writerWithDefaultPrettyPrinter().writeValue(Files.newOutputStream(configJson, StandardOpenOption.TRUNCATE_EXISTING), config);
212 public Path getStyleDirectory() {
213 return serverRoot.resolve("tm2");
216 public Path getDataDirectory() {
217 return serverRoot.resolve("data");
220 public Path getCurrentTiles() {
221 return getDataDirectory().resolve(MapsServerPreferences.currentMBTiles());
224 public void checkTm2Styles() {
225 Path tm2 = getStyleDirectory();
226 try (DirectoryStream<Path> stream = Files.newDirectoryStream(tm2)) {
227 stream.forEach(p -> {
228 Path projectYaml = p.resolve("project.yml");
229 Yaml yaml = new Yaml();
230 Map<String, String> data = null;
231 try (InputStream input = Files.newInputStream(projectYaml, StandardOpenOption.READ)) {
232 data = yaml.loadAs(input, Map.class);
234 Path tiles = serverRoot.relativize(getCurrentTiles());
236 String tmStyle = "mbtiles://../" + tiles.toString();
237 data.put("source", tmStyle);
239 } catch (IOException e) {
240 LOGGER.error("Could not read yaml", e);
243 Files.write(projectYaml, yaml.dump(data).getBytes(), StandardOpenOption.TRUNCATE_EXISTING);
244 } catch (IOException e) {
245 LOGGER.error("Could not write yaml", e);
248 } catch (IOException e) {
249 LOGGER.error("Could not browse tm2 styles", e);
253 public List<String> listStyles() throws IOException {
254 List<String> results = new ArrayList<>();
255 Path tm2 = getStyleDirectory();
256 try (DirectoryStream<Path> stream = Files.newDirectoryStream(tm2)) {
257 stream.forEach(p -> {
258 results.add(p.getFileName().toString());