aboutsummaryrefslogtreecommitdiff
path: root/central/src/main/java/moe/yuuta/dn42peering/admin/nodes/NodeHandler.java
blob: 1450cff9648cbee88c8c660ac6066f2ab8025b4e (plain)
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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
package moe.yuuta.dn42peering.admin.nodes;

import io.vertx.core.Future;
import io.vertx.core.Vertx;
import io.vertx.core.impl.logging.Logger;
import io.vertx.core.impl.logging.LoggerFactory;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.common.template.TemplateEngine;
import io.vertx.ext.web.handler.BodyHandler;
import io.vertx.ext.web.templ.freemarker.FreeMarkerTemplateEngine;
import io.vertx.ext.web.validation.RequestParameters;
import io.vertx.ext.web.validation.RequestPredicate;
import io.vertx.ext.web.validation.ValidationHandler;
import io.vertx.ext.web.validation.builder.Bodies;
import io.vertx.json.schema.SchemaParser;
import io.vertx.json.schema.SchemaRouter;
import io.vertx.json.schema.SchemaRouterOptions;
import io.vertx.json.schema.common.dsl.ObjectSchemaBuilder;
import io.vertx.serviceproxy.ServiceException;
import moe.yuuta.dn42peering.asn.IASNService;
import moe.yuuta.dn42peering.jaba.Pair;
import moe.yuuta.dn42peering.node.DuplicateNodeException;
import moe.yuuta.dn42peering.node.INodeService;
import moe.yuuta.dn42peering.node.Node;
import moe.yuuta.dn42peering.peer.IPeerService;
import moe.yuuta.dn42peering.portal.FormException;
import moe.yuuta.dn42peering.portal.HTTPException;
import moe.yuuta.dn42peering.portal.ISubRouter;
import moe.yuuta.dn42peering.provision.IProvisionRemoteService;

import javax.annotation.Nonnull;
import java.util.Arrays;

import static io.vertx.ext.web.validation.builder.Parameters.param;
import static io.vertx.json.schema.common.dsl.Schemas.objectSchema;
import static io.vertx.json.schema.common.dsl.Schemas.stringSchema;

public class NodeHandler implements ISubRouter {
    private final Logger logger = LoggerFactory.getLogger(getClass().getSimpleName());

    @Nonnull
    @Override
    public Router mount(@Nonnull Vertx vertx) {
        final IASNService asnService = IASNService.createProxy(vertx, IASNService.ADDRESS);
        final INodeService nodeService = INodeService.createProxy(vertx);
        final IPeerService peerService = IPeerService.createProxy(vertx);
        final IProvisionRemoteService provisionRemoteService = IProvisionRemoteService.create(vertx);
        final TemplateEngine engine = FreeMarkerTemplateEngine.create(vertx, "ftlh");
        final SchemaParser parser = SchemaParser.createDraft7SchemaParser(
                SchemaRouter.create(vertx, new SchemaRouterOptions()));

        final ObjectSchemaBuilder nodeSchema = objectSchema()
                .allowAdditionalProperties(false)
                .property("asn", stringSchema())
                .property("name", stringSchema())
                .property("notice", stringSchema())
                .property("ipv4", stringSchema())
                .property("ipv6", stringSchema())
                .property("ipv6_non_ll", stringSchema())
                .property("public_ip", stringSchema())
                .property("internal_ip", stringSchema())
                .property("internal_port", stringSchema())
                .property("tunneling_method_wireguard", stringSchema());

        final Router router = Router.router(vertx);
        router.post().handler(BodyHandler.create().setBodyLimit(100 * 1024));

        router.get("/new")
                .produces("text/html")
                .handler(ctx -> NodeAdminUI.renderForm(engine,
                        nodeService,
                        ctx.user().principal().getString("username"),
                        true,
                        null,
                        null,
                        ctx));

        router.post("/new")
                .handler(BodyHandler.create().setBodyLimit(100 * 1024))
                .handler(ValidationHandler
                        .builder(parser)
                        .body(Bodies.formUrlEncoded(nodeSchema))
                        .predicate(RequestPredicate.BODY_REQUIRED)
                        .build())
                .handler(ctx -> {
                    final String asn = ctx.user().principal().getString("username");
                    final JsonObject parameters = ctx.<RequestParameters>get(ValidationHandler.REQUEST_CONTEXT_KEY)
                            .body().getJsonObject();
                    NodeAdminUI.parseForm(nodeService, asn, parameters)
                            .<Node>compose(node -> Future.future(f -> nodeService.addNew(node, ar -> {
                                if (ar.succeeded()) {
                                    node.setId((int) (long) ar.result());
                                    f.complete(node);
                                } else {
                                    if(((ServiceException)ar.cause()).getDebugInfo().getString("causeName")
                                    .equals(DuplicateNodeException.class.getName())) {
                                        f.fail(new FormException(node, "A node with your given public IP already exists."));
                                        return;
                                    }
                                    f.fail(ar.cause());
                                }
                            })))
                            .onSuccess(peer -> {
                                ctx.response()
                                        .setStatusCode(303)
                                        .putHeader("Location", "/admin")
                                        .end();
                            })
                            .onFailure(err -> {
                                if (err instanceof FormException) {
                                    NodeAdminUI.renderForm(engine, nodeService,
                                            asn,
                                            true,
                                            ((Node) ((FormException) err).data),
                                            Arrays.asList(((FormException) err).errors),
                                            ctx);
                                } else {
                                    if (!(err instanceof HTTPException)) logger.error("Cannot add node.", err);
                                    ctx.fail(err);
                                }
                            });
                });

        router.get("/edit")
                .produces("text/html")
                .handler(ValidationHandler
                        .builder(parser)
                        .queryParameter(param("id", stringSchema()))
                        .build())
                .handler(ctx -> {
                    final String asn = ctx.user().principal().getString("username");
                    final String id = ctx.<RequestParameters>get(ValidationHandler.REQUEST_CONTEXT_KEY)
                            .queryParameter("id").getString();
                    int intId;
                    try {
                        intId = Integer.parseInt(id);
                    } catch (NumberFormatException ignored) {
                        ctx.fail(new HTTPException(400));
                        return;
                    }
                    Future.<Node>future(f -> nodeService.getNode(intId, f))
                            .compose(node -> {
                                if (node == null) {
                                    return Future.failedFuture(new HTTPException(400));
                                } else {
                                    return Future.succeededFuture(node);
                                }
                            })
                            .onSuccess(node ->
                                    NodeAdminUI.renderForm(
                                            engine,
                                            nodeService,
                                            asn,
                                            false,
                                            node,
                                            null,
                                            ctx))
                            .onFailure(ctx::fail);
                });

        router.post("/edit")
                .handler(BodyHandler.create().setBodyLimit(100 * 1024))
                .handler(ValidationHandler
                        .builder(parser)
                        .body(Bodies.formUrlEncoded(nodeSchema))
                        .queryParameter(param("id", stringSchema()))
                        .predicate(RequestPredicate.BODY_REQUIRED)
                        .build())
                .handler(ctx -> {
                    final String asn = ctx.user().principal().getString("username");
                    final JsonObject parameters = ctx.<RequestParameters>get(ValidationHandler.REQUEST_CONTEXT_KEY)
                            .body().getJsonObject();
                    final String id = ctx.<RequestParameters>get(ValidationHandler.REQUEST_CONTEXT_KEY)
                            .queryParameter("id").getString();
                    int intId;
                    try {
                        intId = Integer.parseInt(id);
                    } catch (NumberFormatException ignored) {
                        ctx.response().setStatusCode(400).end();
                        return;
                    }
                    Future.<Node>future(f -> nodeService.getNode(intId, f))
                            .compose(node -> {
                                if(node == null) {
                                    return Future.failedFuture(new HTTPException(404));
                                }
                                return Future.succeededFuture(node);
                            })
                            .compose(existingNode -> {
                                return NodeAdminUI.parseForm(nodeService, asn, parameters)
                                        .compose(newNode -> {
                                            newNode.setId(existingNode.getId());
                                            return Future.succeededFuture(new Pair<>(existingNode, newNode));
                                        });
                            })
                            .<Node>compose(node -> Future.future(f -> nodeService.updateTo(node.b, ar -> {
                                if (ar.succeeded()) {
                                    f.complete(node.b);
                                } else {
                                    if(((ServiceException)ar.cause()).getDebugInfo().getString("causeName")
                                            .equals(DuplicateNodeException.class.getName())) {
                                        f.fail(new FormException(node.b, "A node with your given public IP already exists."));
                                        return;
                                    }
                                    f.fail(ar.cause());
                                }
                            })))
                            .onSuccess(node -> {
                                ctx.response()
                                        .setStatusCode(303)
                                        .putHeader("Location", "/admin")
                                        .end();
                                provisionRemoteService.deploy(node.getId(), ar -> {});
                            })
                            .onFailure(err -> {
                                if (err instanceof FormException) {
                                    final Node node = (Node) ((FormException) err).data;
                                    if(node != null) {
                                        // The exception may be generated from parseForm.
                                        node.setId(Integer.parseInt(id)); // It must work.
                                    }
                                    NodeAdminUI.renderForm(engine, nodeService,
                                            asn,
                                            false,
                                            node,
                                            Arrays.asList(((FormException) err).errors),
                                            ctx);
                                } else {
                                    if (!(err instanceof HTTPException)) logger.error("Cannot add node.", err);
                                    ctx.fail(err);
                                }
                            });
                });

        router.get("/delete")
                .handler(BodyHandler.create().setBodyLimit(100 * 1024))
                .handler(ValidationHandler
                        .builder(parser)
                        .queryParameter(param("id", stringSchema()))
                        .build())
                .handler(ctx -> {
                    final String id = ctx.<RequestParameters>get(ValidationHandler.REQUEST_CONTEXT_KEY)
                            .queryParameter("id").getString();
                    int intId;
                    try {
                        intId = Integer.parseInt(id);
                    } catch (NumberFormatException ignored) {
                        ctx.response().setStatusCode(400).end();
                        return;
                    }
                    nodeService.delete(intId, ar -> {
                        if(ar.succeeded()) {
                            ctx.response()
                                    .setStatusCode(303)
                                    .putHeader("Location", "/admin")
                                    .end();
                        } else {
                            logger.error("Cannot delete node " + intId, ar.cause());
                            ctx.fail(ar.cause());
                        }
                    });
                });

        router.get("/redeploy")
                .handler(ValidationHandler
                        .builder(parser)
                        .queryParameter(param("id", stringSchema()))
                        .build())
                .handler(ctx -> {
                    final String id = ctx.<RequestParameters>get(ValidationHandler.REQUEST_CONTEXT_KEY)
                            .queryParameter("id").getString();
                    int intId;
                    try {
                        intId = Integer.parseInt(id);
                    } catch (NumberFormatException ignored) {
                        ctx.response().setStatusCode(400).end();
                        return;
                    }
                    provisionRemoteService.deploy(intId, ar -> {
                        ctx.response()
                                .setStatusCode(303)
                                .putHeader("Location", "/admin")
                                .end();
                    });
                });

        return router;
    }
}