forked from roastedroot/proxy-wasm-java-host
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPlugin.java
More file actions
570 lines (494 loc) · 20.6 KB
/
Plugin.java
File metadata and controls
570 lines (494 loc) · 20.6 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
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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
package io.roastedroot.proxywasm.internal;
import static io.roastedroot.proxywasm.internal.Helpers.bytes;
import static io.roastedroot.proxywasm.internal.WellKnownHeaders.AUTHORITY;
import static io.roastedroot.proxywasm.internal.WellKnownHeaders.METHOD;
import static io.roastedroot.proxywasm.internal.WellKnownHeaders.PATH;
import static io.roastedroot.proxywasm.internal.WellKnownHeaders.SCHEME;
import static io.roastedroot.proxywasm.internal.WellKnownProperties.PLUGIN_NAME;
import static io.roastedroot.proxywasm.internal.WellKnownProperties.PLUGIN_VM_ID;
import io.roastedroot.proxywasm.ForeignFunction;
import io.roastedroot.proxywasm.LogHandler;
import io.roastedroot.proxywasm.LogLevel;
import io.roastedroot.proxywasm.MetricType;
import io.roastedroot.proxywasm.MetricsHandler;
import io.roastedroot.proxywasm.QueueName;
import io.roastedroot.proxywasm.SharedData;
import io.roastedroot.proxywasm.SharedDataHandler;
import io.roastedroot.proxywasm.SharedQueueHandler;
import io.roastedroot.proxywasm.StartException;
import io.roastedroot.proxywasm.WasmException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;
public final class Plugin implements io.roastedroot.proxywasm.Plugin {
private final ReentrantLock lock = new ReentrantLock();
final ProxyWasm wasm;
ServerAdaptor serverAdaptor;
private final boolean shared;
private final String name;
private final MetricsHandler metricsHandler;
private final SharedQueueHandler sharedQueueHandler;
private final SharedDataHandler sharedDataHandler;
public Plugin(
ProxyWasm proxyWasm,
boolean shared,
String name,
HashMap<String, ForeignFunction> foreignFunctions,
HashMap<String, URI> upstreams,
boolean strictUpstreams,
int minTickPeriodMilliseconds,
LogHandler logger,
byte[] vmConfig,
byte[] pluginConfig,
MetricsHandler metricsHandler,
SharedQueueHandler sharedQueueHandler,
SharedDataHandler sharedDataHandler)
throws StartException {
Objects.requireNonNull(proxyWasm);
this.name = Objects.requireNonNullElse(name, "default");
this.shared = shared;
this.foreignFunctions = Objects.requireNonNullElseGet(foreignFunctions, HashMap::new);
this.upstreams = Objects.requireNonNullElseGet(upstreams, HashMap::new);
this.strictUpstreams = strictUpstreams;
this.minTickPeriodMilliseconds = minTickPeriodMilliseconds;
this.vmConfig = vmConfig;
this.pluginConfig = pluginConfig;
this.logger = Objects.requireNonNullElse(logger, LogHandler.DEFAULT);
;
this.metricsHandler = Objects.requireNonNullElse(metricsHandler, MetricsHandler.DEFAULT);
this.sharedQueueHandler =
Objects.requireNonNullElse(sharedQueueHandler, SharedQueueHandler.DEFAULT);
this.sharedDataHandler =
Objects.requireNonNullElse(sharedDataHandler, SharedDataHandler.DEFAULT);
this.wasm = proxyWasm;
this.wasm.setPluginHandler(new HandlerImpl());
this.wasm.start();
}
@Override
public String name() {
return name;
}
public void lock() {
lock.lock();
}
public void unlock() {
lock.unlock();
}
public boolean isShared() {
return shared;
}
public ServerAdaptor getServerAdaptor() {
return serverAdaptor;
}
public void setServerAdaptor(ServerAdaptor serverAdaptor) {
this.serverAdaptor = serverAdaptor;
}
public LogHandler logger() {
return logger;
}
public PluginHttpContext createHttpContext(HttpRequestAdaptor requestAdaptor) {
return new PluginHttpContext(this, requestAdaptor);
}
public void close() {
lock();
try {
wasm.close();
if (cancelTick != null) {
cancelTick.run();
cancelTick = null;
}
for (var cancel : httpCalls.values()) {
cancel.run();
}
httpCalls.clear();
for (var cancel : grpcCalls.values()) {
cancel.run();
}
grpcCalls.clear();
} finally {
unlock();
}
}
public LogHandler logger;
static final boolean DEBUG = "true".equals(System.getenv("DEBUG"));
byte[] vmConfig;
byte[] pluginConfig;
private final AtomicInteger lastCallId = new AtomicInteger(0);
private final HashMap<Integer, Runnable> httpCalls = new HashMap<>();
private final HashMap<Integer, Runnable> grpcCalls = new HashMap<>();
private final HashMap<String, URI> upstreams;
boolean strictUpstreams;
int minTickPeriodMilliseconds;
private int tickPeriodMilliseconds;
private Runnable cancelTick;
private final HashMap<String, ForeignFunction> foreignFunctions;
private byte[] funcCallData = new byte[0];
private final HashMap<List<String>, byte[]> properties = new HashMap<>();
class HandlerImpl extends ChainedHandler {
@Override
protected Handler next() {
return Handler.DEFAULT;
}
// //////////////////////////////////////////////////////////////////////
// Plugin config
// //////////////////////////////////////////////////////////////////////
@Override
public byte[] getVmConfig() {
return vmConfig;
}
@Override
public byte[] getPluginConfig() {
return pluginConfig;
}
// //////////////////////////////////////////////////////////////////////
// Properties
// //////////////////////////////////////////////////////////////////////
@Override
public byte[] getProperty(List<String> path) throws WasmException {
// TODO: do we need field for vm_id and root_id?
if (PLUGIN_VM_ID.equals(path)) {
return bytes(name);
}
if (PLUGIN_NAME.equals(path)) {
return bytes(name);
}
return properties.get(path);
}
@Override
public WasmResult setProperty(List<String> path, byte[] value) {
properties.put(path, value);
return WasmResult.OK;
}
// //////////////////////////////////////////////////////////////////////
// Logging
// //////////////////////////////////////////////////////////////////////
@Override
public void log(LogLevel level, String message) throws WasmException {
logger.log(level, message);
}
@Override
public LogLevel getLogLevel() throws WasmException {
return logger.getLogLevel();
}
// //////////////////////////////////////////////////////////////////////
// Timers
// //////////////////////////////////////////////////////////////////////
@Override
public WasmResult setTickPeriodMilliseconds(int tickMs) {
// check for no change
if (tickMs == tickPeriodMilliseconds) {
return WasmResult.OK;
}
// cancel the current tick, if any
if (cancelTick != null) {
cancelTick.run();
cancelTick = null;
}
// set the new tick period, if any
tickPeriodMilliseconds = tickMs;
if (tickPeriodMilliseconds == 0) {
return WasmResult.OK;
}
// schedule the new tick
cancelTick =
serverAdaptor.scheduleTick(
Math.max(minTickPeriodMilliseconds, tickPeriodMilliseconds),
() -> {
lock();
try {
wasm.tick();
} finally {
unlock();
}
});
return WasmResult.OK;
}
// //////////////////////////////////////////////////////////////////////
// Foreign function interface (FFI)
// //////////////////////////////////////////////////////////////////////
@Override
public byte[] getFuncCallData() {
return funcCallData;
}
@Override
public WasmResult setFuncCallData(byte[] data) {
funcCallData = data;
return WasmResult.OK;
}
// //////////////////////////////////////////////////////////////////////
// HTTP calls
// //////////////////////////////////////////////////////////////////////
@Override
public int httpCall(
String upstreamName,
ProxyMap headers,
byte[] body,
ProxyMap trailers,
int timeoutMilliseconds)
throws WasmException {
var method = headers.get(METHOD);
if (method == null) {
throw new WasmException(WasmResult.BAD_ARGUMENT);
}
var scheme = headers.get(SCHEME);
if (scheme == null) {
scheme = "http";
}
var authority = headers.get(AUTHORITY);
if (authority == null) {
throw new WasmException(WasmResult.BAD_ARGUMENT);
}
headers.put("Host", authority);
var connectUri = upstreams.get(upstreamName);
if (connectUri == null && strictUpstreams) {
throw new WasmException(WasmResult.BAD_ARGUMENT);
}
if (connectUri == null) {
try {
connectUri = new URI(upstreamName);
} catch (URISyntaxException e) {
throw new WasmException(WasmResult.BAD_ARGUMENT);
}
}
var connectHost = connectUri.getHost();
var connectPort = connectUri.getPort();
if (connectPort == -1) {
connectPort = "https".equals(scheme) ? 443 : 80;
}
var path = headers.get(PATH);
if (path == null) {
throw new WasmException(WasmResult.BAD_ARGUMENT);
}
if (!path.isEmpty() && !path.startsWith("/")) {
path = "/" + path;
}
URI uri = null;
try {
uri = URI.create(scheme + "://" + authority + path);
} catch (IllegalArgumentException e) {
throw new WasmException(WasmResult.BAD_ARGUMENT);
}
// Remove all the pseudo headers
for (var r : new ArrayProxyMap(headers).entries()) {
if (r.getKey().startsWith(":")) {
headers.remove(r.getKey());
}
}
try {
var id = lastCallId.incrementAndGet();
var future =
serverAdaptor.scheduleHttpCall(
method,
connectHost,
connectPort,
uri,
headers,
body,
trailers,
timeoutMilliseconds,
(statusCode, respHeaders, respBody) -> {
// todo: add the status
// respHeaders.put(STATUS, "" + statusCode);
lock();
try {
if (httpCalls.remove(id) == null) {
return; // the call could have already been cancelled
}
wasm.sendHttpCallResponse(
id, respHeaders, new ArrayProxyMap(), respBody);
} finally {
unlock();
}
});
httpCalls.put(id, future);
return id;
} catch (InterruptedException e) {
throw new WasmException(WasmResult.INTERNAL_FAILURE);
} catch (UnsupportedOperationException e) {
throw new WasmException(WasmResult.UNIMPLEMENTED);
}
}
@Override
public int dispatchHttpCall(
String upstreamName,
ProxyMap headers,
byte[] body,
ProxyMap trailers,
int timeoutMilliseconds)
throws WasmException {
return httpCall(upstreamName, headers, body, trailers, timeoutMilliseconds);
}
// //////////////////////////////////////////////////////////////////////
// GRPC calls
// //////////////////////////////////////////////////////////////////////
@Override
public int grpcCall(
String upstreamName,
String serviceName,
String methodName,
ProxyMap headers,
byte[] body,
int timeoutMilliseconds)
throws WasmException {
var connectUri = upstreams.get(upstreamName);
if (connectUri == null && strictUpstreams) {
throw new WasmException(WasmResult.BAD_ARGUMENT);
}
if (connectUri == null) {
try {
connectUri = new URI(upstreamName);
} catch (URISyntaxException e) {
throw new WasmException(WasmResult.BAD_ARGUMENT);
}
}
if (!("http".equals(connectUri.getScheme())
|| "https".equals(connectUri.getScheme()))) {
logger.log(
LogLevel.ERROR,
"grpc call upstream not mapped to URL with a http/https scheme: "
+ upstreamName);
throw new WasmException(WasmResult.BAD_ARGUMENT);
}
var connectHost = connectUri.getHost();
var connectPort = connectUri.getPort();
if (connectPort == -1) {
connectPort = "https".equals(connectUri.getScheme()) ? 443 : 80;
}
try {
var id = lastCallId.incrementAndGet();
var callHandler =
new GrpcCallResponseHandler() {
@Override
public void onHeaders(ArrayBytesProxyMap headers) {
lock();
try {
if (grpcCalls.get(id) == null) {
return; // the call could have already been cancelled
}
wasm.sendGrpcReceiveInitialMetadata(id, headers);
} finally {
unlock();
}
}
@Override
public void onMessage(byte[] data) {
lock();
try {
if (grpcCalls.get(id) == null) {
return; // the call could have already been cancelled
}
wasm.sendGrpcReceive(id, data);
} finally {
unlock();
}
}
@Override
public void onTrailers(ArrayBytesProxyMap trailers) {
lock();
try {
if (grpcCalls.get(id) == null) {
return; // the call could have already been cancelled
}
wasm.sendGrpcReceiveTrailingMetadata(id, trailers);
} finally {
unlock();
}
}
@Override
public void onClose(int status) {
lock();
try {
if (grpcCalls.get(id) == null) {
return; // the call could have already been cancelled
}
wasm.sendGrpcClose(id, status);
} finally {
unlock();
}
}
};
var future =
serverAdaptor.scheduleGrpcCall(
connectHost,
connectPort,
"http".equals(connectUri.getScheme()),
serviceName,
methodName,
headers,
body,
timeoutMilliseconds,
callHandler);
grpcCalls.put(id, future);
return id;
} catch (InterruptedException e) {
throw new WasmException(WasmResult.INTERNAL_FAILURE);
} catch (UnsupportedOperationException e) {
throw new WasmException(WasmResult.UNIMPLEMENTED);
}
}
// //////////////////////////////////////////////////////////////////////
// Metrics
// //////////////////////////////////////////////////////////////////////
@Override
public int defineMetric(MetricType type, String name) throws WasmException {
return metricsHandler.defineMetric(type, name);
}
@Override
public long getMetric(int metricId) throws WasmException {
return metricsHandler.getMetric(metricId);
}
@Override
public WasmResult incrementMetric(int metricId, long value) {
return metricsHandler.incrementMetric(metricId, value);
}
@Override
public WasmResult recordMetric(int metricId, long value) {
return metricsHandler.recordMetric(metricId, value);
}
@Override
public WasmResult removeMetric(int metricId) {
return metricsHandler.removeMetric(metricId);
}
// //////////////////////////////////////////////////////////////////////
// FFI
// //////////////////////////////////////////////////////////////////////
@Override
public ForeignFunction getForeignFunction(String name) {
return foreignFunctions.get(name);
}
// //////////////////////////////////////////////////////////////////////
// Shared Data
// //////////////////////////////////////////////////////////////////////
@Override
public SharedData getSharedData(String key) throws WasmException {
return sharedDataHandler.getSharedData(key);
}
@Override
public WasmResult setSharedData(String key, byte[] value, int cas) {
return sharedDataHandler.setSharedData(key, value, cas);
}
// //////////////////////////////////////////////////////////////////////
// Shared Queue
// //////////////////////////////////////////////////////////////////////
@Override
public int registerSharedQueue(QueueName queueName) throws WasmException {
return sharedQueueHandler.registerSharedQueue(queueName);
}
@Override
public int resolveSharedQueue(QueueName queueName) throws WasmException {
return sharedQueueHandler.resolveSharedQueue(queueName);
}
@Override
public byte[] dequeueSharedQueue(int queueId) throws WasmException {
return sharedQueueHandler.dequeueSharedQueue(queueId);
}
@Override
public WasmResult enqueueSharedQueue(int queueId, byte[] value) {
return sharedQueueHandler.enqueueSharedQueue(queueId, value);
}
}
}