-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathManagementVerticle.java
More file actions
228 lines (199 loc) · 7.96 KB
/
ManagementVerticle.java
File metadata and controls
228 lines (199 loc) · 7.96 KB
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
package com.example;
import io.vertx.core.CompositeFuture;
import io.vertx.core.VerticleBase;
import io.vertx.core.Future;
import io.vertx.core.DeploymentOptions;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.file.FileSystem;
import io.vertx.core.json.JsonObject;
import io.vertx.core.json.JsonArray;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.handler.BodyHandler;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
public class ManagementVerticle extends VerticleBase {
private static final String DEPLOYMENTS_DIR = "./deployments/";
private final Map<String, String> deployments = new ConcurrentHashMap<>();
private FileSystem fs;
@Override
public Future<?> start() {
fs = vertx.fileSystem();
Path dirPath = Paths.get(DEPLOYMENTS_DIR);
return fs.mkdirs(dirPath.toString())
.compose(v -> restoreDeployments())
.compose(v -> setupRouter())
.compose(v -> deployExampleApi());
}
private Future<?> restoreDeployments() {
return fs.readDir(DEPLOYMENTS_DIR, ".*\\.json")
.flatMap(files -> {
List<Future<JsonObject>> reads = files.stream()
.map(this::readDeploymentConfig)
.toList();
return Future.join(reads)
.map(CompositeFuture::list)
.map(results -> results.stream()
.map(obj -> (JsonObject) obj)
.filter(Objects::nonNull)
.toList());
})
.compose(validConfigs -> {
List<Future<String>> deploys = validConfigs.stream()
.map(this::deployFromConfig)
.toList();
return Future.join(deploys)
.map(cf -> cf.list())
.mapEmpty()
.onSuccess(v -> System.out.println("Restored " + validConfigs.size() + " deployments"));
});
}
private Future<JsonObject> readDeploymentConfig(String filePath) {
return fs.readFile(filePath)
.map(Buffer::toJsonObject)
.compose(config -> {
String name = config.getString("name");
String fname = filePath.replaceFirst("^.*?(([^/\\\\\\.]+))\\.[^\\.]+$", "$1");
if (name == null) {
System.err.println("Skipping " + filePath + ": no 'name'");
return Future.succeededFuture(null); // null = пропустить
} else if (!name.equals(fname)) {
System.err.println("Skipping " + filePath + ": filename is not equals to 'name' -> " + fname + " != "+name);
return Future.succeededFuture(null); // null = пропустить
}
return Future.succeededFuture(config
.put("deploymentFile", filePath)
.put("name", name));
})
.recover(err -> {
System.err.println("Failed to load " + filePath + ": " + err.getMessage());
return Future.succeededFuture(null); // null = пропустить
});
}
private Future<String> deployFromConfig(JsonObject config) {
String name = config.getString("name");
DeploymentOptions options = new DeploymentOptions().setConfig(config);
return vertx.deployVerticle(ApiVerticle.class.getName(), options)
.map(deploymentID -> {
deployments.put(name, deploymentID);
System.out.println("Restored deployment '" + name + "': " + deploymentID);
return deploymentID;
});
}
private Future<?> setupRouter() {
Router router = Router.router(vertx);
router.route().handler(BodyHandler.create());
router.get("/verticles").handler(this::listVerticles);
router.post("/verticles/:name/deploy").handler(this::deployVerticle);
router.delete("/verticles/:name").handler(this::undeployVerticle);
router.put("/verticles/:name/config").handler(this::updateConfig);
return vertx.createHttpServer()
.requestHandler(router)
.listen(8080)
.map(v -> {
System.out.println("Management UI на http://localhost:8080");
return v;
});
}
private Future<?> deployExampleApi() {
// Если api0 уже восстановлен — пропускаем
if (deployments.containsKey("api0")) {
return Future.succeededFuture();
}
JsonObject config = new JsonObject()
.put("name", "api0")
.put("httpPort", 8081)
.put("endpoints", new JsonArray()
.add(new JsonObject()
.put("path", "/api/hello")
.put("method", "GET")
.put("response", new JsonObject()
.put("status", 200)
.put("headers", new JsonObject().put("Content-Type", "application/json"))
.put("body", "{\"msg\":\"hello from example\"}")))
.add(new JsonObject()
.put("path", "/api/status")
.put("method", "GET")
.put("response", new JsonObject()
.put("status", 200)
.put("headers", new JsonObject().put("Content-Type", "application/json"))
.put("body", "{\"status\":\"ok\"}"))));
DeploymentOptions options = new DeploymentOptions().setConfig(config);
return vertx.deployVerticle(ApiVerticle.class.getName(), options)
.map(deploymentID -> {
deployments.put("api0", deploymentID);
return saveDeploymentConfig("api0", config).map(deploymentID);
});
}
private void deployVerticle(RoutingContext ctx) {
String name = ctx.pathParam("name");
JsonObject config = ctx.body().asJsonObject();
DeploymentOptions options = new DeploymentOptions().setConfig(config);
vertx.deployVerticle(ApiVerticle.class.getName(), options)
.onSuccess(deploymentID -> {
deployments.put(name, deploymentID);
saveDeploymentConfig(name, config)
.onFailure(err -> System.err.println("Failed to save " + name + ": " + err));
ctx.response()
.putHeader("Content-Type", "application/json")
.end(new JsonObject().put("deploymentID", deploymentID).put("name", name).encode());
})
.onFailure(err -> ctx.fail(500, err));
}
private void undeployVerticle(RoutingContext ctx) {
String name = ctx.pathParam("name");
String depId = deployments.remove(name);
if (depId != null) {
vertx.undeploy(depId)
.onSuccess(v -> {
fs.delete(DEPLOYMENTS_DIR + name + ".json")
.onFailure(err -> System.err.println("Failed to delete " + name + ": " + err));
ctx.response().end("Undeployed " + name);
})
.onFailure(err -> ctx.fail(500, err));
} else {
ctx.response().setStatusCode(404).end("Not found");
}
}
private Future<?> updateConfig(RoutingContext ctx) {
String name = ctx.pathParam("name");
String depId = deployments.get(name);
if (depId == null) {
return ctx.response().setStatusCode(404).end("Not found");
}
JsonObject newConfig = ctx.body().asJsonObject();
return vertx.undeploy(depId)
.compose(v -> {
deployments.remove(name);
fs.delete(DEPLOYMENTS_DIR + name + ".json");
return vertx.deployVerticle(ApiVerticle.class.getName(),
new DeploymentOptions().setConfig(newConfig));
})
.map(newDepId -> {
deployments.put(name, newDepId);
return saveDeploymentConfig(name, newConfig).map(newDepId);
})
.onSuccess(id -> ctx.response().end("Updated"))
.onFailure(err -> ctx.fail(500, err));
}
private Future<?> saveDeploymentConfig(String name, JsonObject config) {
return fs.writeFile(DEPLOYMENTS_DIR + name + ".json",
Buffer.buffer(config.encode()));
}
private void listVerticles(RoutingContext ctx) {
JsonArray names = new JsonArray(new ArrayList<>(deployments.keySet()));
JsonObject list = new JsonObject().put("deployed", new JsonObject().put("names", names));
ctx.response().putHeader("Content-Type", "application/json").end(list.encode());
}
@Override
public Future<?> stop() {
if (deployments.isEmpty()) return Future.succeededFuture();
return Future.join(deployments.values().stream()
.map(vertx::undeploy)
.toList())
.mapEmpty();
}
}