]> gerrit.simantics Code Review - simantics/district.git/blob - org.simantics.maps.server/src/org/simantics/district/maps/server/TileserverMapnik.java
5b1e735c2ee0f60345cd0e6bcde0c1b709b35b49
[simantics/district.git] / org.simantics.maps.server / src / org / simantics / district / maps / server / TileserverMapnik.java
1 package org.simantics.district.maps.server;
2
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;
14 import java.util.Map;
15 import java.util.concurrent.TimeUnit;
16 import java.util.concurrent.atomic.AtomicBoolean;
17 import java.util.stream.Stream;
18
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;
30
31 import com.fasterxml.jackson.core.JsonParseException;
32 import com.fasterxml.jackson.databind.JsonMappingException;
33 import com.fasterxml.jackson.databind.ObjectMapper;
34
35 public class TileserverMapnik {
36
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" };
39     
40     private SystemProcess process;
41     private Path serverRoot;
42     
43     private AtomicBoolean running = new AtomicBoolean(false);
44     
45     TileserverMapnik(Path serverRoot) {
46         this.serverRoot = serverRoot.normalize();
47     }
48
49     public boolean isRunning() throws IOException, InterruptedException {
50         return process == null ? false : process.isAlive() && isReady();
51     }
52     
53     public boolean isReady() {
54         return running.get();
55     }
56     
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();
63         }
64         
65         // check that npm dependencies are satisfied
66         if (checkAndInstall(null)) {
67             checkAndInstall(ADDITIONAL_DEPENDENCIES[0]);
68             checkAndInstall(ADDITIONAL_DEPENDENCIES[1]);
69         }
70         
71         checkConfigJson();
72         checkTm2Styles();
73         
74         if (process != null && process.isAlive())
75             return;
76         
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();
80         
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);
85         running.set(true);
86     }
87
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());
92         return env;
93     }
94
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!");
103             }
104             process = null;
105             Files.delete(getPid());
106             running.set(false);
107         }
108     }
109
110     private Path getPid() {
111         return serverRoot.resolve("pid");
112     }
113
114     public void restart() throws Exception {
115         stop();
116         start();
117     }
118     
119     private boolean checkIfInstalled(String module) throws Exception {
120         String tileserverMapnik = tileserverMapnikRoot().toString();
121         int retVal;
122         try (ByteArrayOutputStream output = new ByteArrayOutputStream()) {
123             if (module == null) {
124                 retVal = NodeJS.npm(output, "--prefix", tileserverMapnik, "list");
125             } else {
126                 retVal = NodeJS.npm(output, "--prefix", tileserverMapnik, "list", module);
127             }
128             String outputString = new String(output.toByteArray(), StandardCharsets.UTF_8);
129         }
130         return retVal == 0;
131     }
132     
133     private boolean install(String module) throws Exception {
134         String tileserverMapnik = tileserverMapnikRoot().toString();
135         int retVal;
136         if (module == null)
137             retVal = NodeJS.npm(null, "--prefix", tileserverMapnik, "install", "--save");
138         else 
139             retVal = NodeJS.npm(null, "--prefix", tileserverMapnik, "install", module, "--save");
140         if (retVal != 0)
141             LOGGER.warn("Could not install module " + module == null ? "package.json" : module + "! " + retVal);
142         return retVal == 0;
143     }
144     
145     private boolean checkAndInstall(String module) throws Exception {
146         boolean installed = checkIfInstalled(module); 
147         if (!installed)
148             install(module);
149         return !installed;
150     }
151
152     
153     private Path tileserverMapnikRoot() {
154         return serverRoot.resolve("tileserver-mapnik").toAbsolutePath();
155     }
156     
157     private Path getFonts() {
158         return serverRoot.resolve("fonts").toAbsolutePath();
159     }
160     
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();
163     }
164     
165     private Path getTessera() {
166         return serverRoot.resolve("tileserver-mapnik/bin/tessera.js").toAbsolutePath();
167     }
168     
169     private Path getConfigJson() {
170         return serverRoot.resolve("config.json").toAbsolutePath();
171     }
172     
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)) {
177             paths.forEach(p -> {
178                 if (!p.equals(data)) {
179                     String tiles = p.getFileName().toString();
180                     result.add(tiles);
181                 }
182             });
183         }
184         return result;
185     }
186     
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)) {
195                     // Good
196                     
197                     Map<String, String> source = new HashMap<>();
198                     
199                     Path tm2style = serverRoot.relativize(projectYaml.getParent());
200                     
201                     String prefix = "tmstyle://../";
202                     String tmStyle = prefix + tm2style.toString(); 
203                     source.put("source", tmStyle);
204                     config.put("/" + projectYaml.getParent().getFileName().toString(), source);
205                 }
206             });
207         }
208         ObjectMapper mapper = new ObjectMapper();
209         mapper.writerWithDefaultPrettyPrinter().writeValue(Files.newOutputStream(configJson, StandardOpenOption.TRUNCATE_EXISTING), config);
210     }
211     
212     public Path getStyleDirectory() {
213         return serverRoot.resolve("tm2");
214     }
215     
216     public Path getDataDirectory() {
217         return serverRoot.resolve("data");
218     }
219     
220     public Path getCurrentTiles() {
221         return getDataDirectory().resolve(MapsServerPreferences.currentMBTiles());
222     }
223     
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);
233                     
234                     Path tiles = serverRoot.relativize(getCurrentTiles());
235                     
236                     String tmStyle = "mbtiles://../" + tiles.toString();
237                     data.put("source", tmStyle);
238                     
239                 } catch (IOException e) {
240                     LOGGER.error("Could not read yaml", e);
241                 }
242                 try {
243                     Files.write(projectYaml, yaml.dump(data).getBytes(), StandardOpenOption.TRUNCATE_EXISTING);
244                 } catch (IOException e) {
245                     LOGGER.error("Could not write yaml", e);
246                 }
247             });
248         } catch (IOException e) {
249             LOGGER.error("Could not browse tm2 styles", e);
250         }
251     }
252
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());
259             });
260         }
261         return results;
262     }
263
264 }