/
CmdFunctions.java
1294 lines (1160 loc) · 61.9 KB
/
CmdFunctions.java
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
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.pulsar.admin.cli;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Objects.isNull;
import static org.apache.bookkeeper.common.concurrent.FutureUtils.result;
import static org.apache.commons.lang.StringUtils.isBlank;
import static org.apache.commons.lang.StringUtils.isNotBlank;
import static org.apache.commons.lang3.StringUtils.isNotBlank;
import static org.apache.pulsar.common.naming.TopicName.DEFAULT_NAMESPACE;
import static org.apache.pulsar.common.naming.TopicName.PUBLIC_TENANT;
import static org.apache.pulsar.functions.utils.Utils.fileExists;
import static org.apache.pulsar.functions.worker.Utils.downloadFromHttpUrl;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.ParameterException;
import com.beust.jcommander.Parameters;
import com.beust.jcommander.converters.StringConverter;
import com.google.common.annotations.VisibleForTesting;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Type;
import java.net.MalformedURLException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.bookkeeper.api.StorageClient;
import org.apache.bookkeeper.api.kv.Table;
import org.apache.bookkeeper.api.kv.result.KeyValue;
import org.apache.bookkeeper.clients.StorageClientBuilder;
import org.apache.bookkeeper.clients.config.StorageClientSettings;
import org.apache.commons.lang.StringUtils;
import org.apache.pulsar.admin.cli.utils.CmdUtils;
import org.apache.pulsar.client.admin.PulsarAdmin;
import org.apache.pulsar.client.admin.internal.FunctionsImpl;
import org.apache.pulsar.client.api.PulsarClientException;
import org.apache.pulsar.functions.api.Function;
import org.apache.pulsar.functions.instance.AuthenticationConfig;
import org.apache.pulsar.functions.instance.InstanceConfig;
import org.apache.pulsar.functions.proto.Function.ConsumerSpec;
import org.apache.pulsar.functions.proto.Function.FunctionDetails;
import org.apache.pulsar.functions.proto.Function.Resources;
import org.apache.pulsar.functions.proto.Function.SinkSpec;
import org.apache.pulsar.functions.proto.Function.SourceSpec;
import org.apache.pulsar.functions.proto.Function.SubscriptionType;
import org.apache.pulsar.functions.runtime.ProcessRuntimeFactory;
import org.apache.pulsar.functions.runtime.RuntimeSpawner;
import org.apache.pulsar.functions.utils.ConsumerConfig;
import org.apache.pulsar.functions.utils.FunctionConfig;
import org.apache.pulsar.functions.utils.Reflections;
import org.apache.pulsar.functions.utils.Utils;
import org.apache.pulsar.functions.utils.WindowConfig;
import org.apache.pulsar.functions.utils.FunctionConfig.ProcessingGuarantees;
import org.apache.pulsar.functions.utils.validation.ConfigValidation;
import org.apache.pulsar.functions.utils.validation.ValidatorImpls.ImplementsClassesValidator;
import org.apache.pulsar.functions.windowing.WindowFunctionExecutor;
import org.apache.pulsar.functions.windowing.WindowUtils;
@Slf4j
@Parameters(commandDescription = "Interface for managing Pulsar Functions (lightweight, Lambda-style compute processes that work with Pulsar)")
public class CmdFunctions extends CmdBase {
private static final String DEFAULT_SERVICE_URL = "pulsar://localhost:6650";
private final LocalRunner localRunner;
private final CreateFunction creater;
private final DeleteFunction deleter;
private final UpdateFunction updater;
private final GetFunction getter;
private final GetFunctionStatus functionStatus;
private final RestartFunction restart;
private final StopFunction stop;
private final ListFunctions lister;
private final StateGetter stateGetter;
private final TriggerFunction triggerer;
private final UploadFunction uploader;
private final DownloadFunction downloader;
/**
* Base command
*/
@Getter
abstract class BaseCommand extends CliCommand {
@Override
void run() throws Exception {
processArguments();
runCmd();
}
void processArguments() throws Exception {}
abstract void runCmd() throws Exception;
}
/**
* Namespace level command
*/
@Getter
abstract class NamespaceCommand extends BaseCommand {
@Parameter(names = "--tenant", description = "The function's tenant")
protected String tenant;
@Parameter(names = "--namespace", description = "The function's namespace")
protected String namespace;
@Override
public void processArguments() {
if (tenant == null) {
tenant = PUBLIC_TENANT;
}
if (namespace == null) {
namespace = DEFAULT_NAMESPACE;
}
}
}
/**
* Function level command
*/
@Getter
abstract class FunctionCommand extends BaseCommand {
@Parameter(names = "--fqfn", description = "The Fully Qualified Function Name (FQFN) for the function")
protected String fqfn;
@Parameter(names = "--tenant", description = "The function's tenant")
protected String tenant;
@Parameter(names = "--namespace", description = "The function's namespace")
protected String namespace;
@Parameter(names = "--name", description = "The function's name")
protected String functionName;
@Override
void processArguments() throws Exception {
super.processArguments();
boolean usesSetters = (null != tenant || null != namespace || null != functionName);
boolean usesFqfn = (null != fqfn);
// Throw an exception if --fqfn is set alongside any combination of --tenant, --namespace, and --name
if (usesFqfn && usesSetters) {
throw new RuntimeException(
"You must specify either a Fully Qualified Function Name (FQFN) or tenant, namespace, and function name");
} else if (usesFqfn) {
// If the --fqfn flag is used, parse tenant, namespace, and name using that flag
String[] fqfnParts = fqfn.split("/");
if (fqfnParts.length != 3) {
throw new RuntimeException(
"Fully qualified function names (FQFNs) must be of the form tenant/namespace/name");
}
tenant = fqfnParts[0];
namespace = fqfnParts[1];
functionName = fqfnParts[2];
} else {
if (tenant == null) {
tenant = PUBLIC_TENANT;
}
if (namespace == null) {
namespace = DEFAULT_NAMESPACE;
}
if (null == functionName) {
throw new RuntimeException(
"You must specify a name for the function or a Fully Qualified Function Name (FQFN)");
}
}
}
}
/**
* Commands that require a function config
*/
@Getter
abstract class FunctionDetailsCommand extends BaseCommand {
@Parameter(names = "--fqfn", description = "The Fully Qualified Function Name (FQFN) for the function")
protected String fqfn;
@Parameter(names = "--tenant", description = "The function's tenant")
protected String tenant;
@Parameter(names = "--namespace", description = "The function's namespace")
protected String namespace;
@Parameter(names = "--name", description = "The function's name")
protected String functionName;
// for backwards compatibility purposes
@Parameter(names = "--className", description = "The function's class name", hidden = true)
protected String DEPRECATED_className;
@Parameter(names = "--classname", description = "The function's class name")
protected String className;
@Parameter(names = "--jar", description = "Path to the jar file for the function (if the function is written in Java). It also supports url-path [http/https/file (file protocol assumes that file already exists on worker host)] from which worker can download the package.", listConverter = StringConverter.class)
protected String jarFile;
@Parameter(
names = "--py",
description = "Path to the main Python file for the function (if the function is written in Python)",
listConverter = StringConverter.class)
protected String pyFile;
@Parameter(names = { "-i",
"--inputs" }, description = "The function's input topic or topics (multiple topics can be specified as a comma-separated list)")
protected String inputs;
// for backwards compatibility purposes
@Parameter(names = "--topicsPattern", description = "TopicsPattern to consume from list of topics under a namespace that match the pattern. [--input] and [--topic-pattern] are mutually exclusive. Add SerDe class name for a pattern in --custom-serde-inputs (supported for java fun only)", hidden = true)
protected String DEPRECATED_topicsPattern;
@Parameter(names = "--topics-pattern", description = "The topic pattern to consume from list of topics under a namespace that match the pattern. [--input] and [--topic-pattern] are mutually exclusive. Add SerDe class name for a pattern in --custom-serde-inputs (supported for java fun only)")
protected String topicsPattern;
@Parameter(names = {"-o", "--output"}, description = "The function's output topic (If none is specified, no output is written)")
protected String output;
// for backwards compatibility purposes
@Parameter(names = "--logTopic", description = "The topic to which the function's logs are produced", hidden = true)
protected String DEPRECATED_logTopic;
@Parameter(names = "--log-topic", description = "The topic to which the function's logs are produced")
protected String logTopic;
@Parameter(names = {"-st", "--schema-type"}, description = "The builtin schema type or custom schema class name to be used for messages output by the function")
protected String schemaType = "";
// for backwards compatibility purposes
@Parameter(names = "--customSerdeInputs", description = "The map of input topics to SerDe class names (as a JSON string)", hidden = true)
protected String DEPRECATED_customSerdeInputString;
@Parameter(names = "--custom-serde-inputs", description = "The map of input topics to SerDe class names (as a JSON string)")
protected String customSerdeInputString;
@Parameter(names = "--custom-schema-inputs", description = "The map of input topics to Schema class names (as a JSON string)")
protected String customSchemaInputString;
// for backwards compatibility purposes
@Parameter(names = "--outputSerdeClassName", description = "The SerDe class to be used for messages output by the function", hidden = true)
protected String DEPRECATED_outputSerdeClassName;
@Parameter(names = "--output-serde-classname", description = "The SerDe class to be used for messages output by the function")
protected String outputSerdeClassName;
// for backwards compatibility purposes
@Parameter(names = "--functionConfigFile", description = "The path to a YAML config file specifying the function's configuration", hidden = true)
protected String DEPRECATED_fnConfigFile;
@Parameter(names = "--function-config-file", description = "The path to a YAML config file specifying the function's configuration")
protected String fnConfigFile;
// for backwards compatibility purposes
@Parameter(names = "--processingGuarantees", description = "The processing guarantees (aka delivery semantics) applied to the function", hidden = true)
protected FunctionConfig.ProcessingGuarantees DEPRECATED_processingGuarantees;
@Parameter(names = "--processing-guarantees", description = "The processing guarantees (aka delivery semantics) applied to the function")
protected FunctionConfig.ProcessingGuarantees processingGuarantees;
// for backwards compatibility purposes
@Parameter(names = "--userConfig", description = "User-defined config key/values", hidden = true)
protected String DEPRECATED_userConfigString;
@Parameter(names = "--user-config", description = "User-defined config key/values")
protected String userConfigString;
@Parameter(names = "--retainOrdering", description = "Function consumes and processes messages in order", hidden = true)
protected Boolean DEPRECATED_retainOrdering;
@Parameter(names = "--retain-ordering", description = "Function consumes and processes messages in order")
protected boolean retainOrdering;
@Parameter(names = "--subs-name", description = "Pulsar source subscription name if user wants a specific subscription-name for input-topic consumer")
protected String subsName;
@Parameter(names = "--parallelism", description = "The function's parallelism factor (i.e. the number of function instances to run)")
protected Integer parallelism;
@Parameter(names = "--cpu", description = "The cpu in cores that need to be allocated per function instance(applicable only to docker runtime)")
protected Double cpu;
@Parameter(names = "--ram", description = "The ram in bytes that need to be allocated per function instance(applicable only to process/docker runtime)")
protected Long ram;
@Parameter(names = "--disk", description = "The disk in bytes that need to be allocated per function instance(applicable only to docker runtime)")
protected Long disk;
// for backwards compatibility purposes
@Parameter(names = "--windowLengthCount", description = "The number of messages per window", hidden = true)
protected Integer DEPRECATED_windowLengthCount;
@Parameter(names = "--window-length-count", description = "The number of messages per window")
protected Integer windowLengthCount;
// for backwards compatibility purposes
@Parameter(names = "--windowLengthDurationMs", description = "The time duration of the window in milliseconds", hidden = true)
protected Long DEPRECATED_windowLengthDurationMs;
@Parameter(names = "--window-length-duration-ms", description = "The time duration of the window in milliseconds")
protected Long windowLengthDurationMs;
// for backwards compatibility purposes
@Parameter(names = "--slidingIntervalCount", description = "The number of messages after which the window slides", hidden = true)
protected Integer DEPRECATED_slidingIntervalCount;
@Parameter(names = "--sliding-interval-count", description = "The number of messages after which the window slides")
protected Integer slidingIntervalCount;
// for backwards compatibility purposes
@Parameter(names = "--slidingIntervalDurationMs", description = "The time duration after which the window slides", hidden = true)
protected Long DEPRECATED_slidingIntervalDurationMs;
@Parameter(names = "--sliding-interval-duration-ms", description = "The time duration after which the window slides")
protected Long slidingIntervalDurationMs;
// for backwards compatibility purposes
@Parameter(names = "--autoAck", description = "Whether or not the framework will automatically acknowleges messages", hidden = true)
protected Boolean DEPRECATED_autoAck = null;
@Parameter(names = "--auto-ack", description = "Whether or not the framework will automatically acknowleges messages", arity = 1)
protected boolean autoAck = true;
// for backwards compatibility purposes
@Parameter(names = "--timeoutMs", description = "The message timeout in milliseconds", hidden = true)
protected Long DEPRECATED_timeoutMs;
@Parameter(names = "--timeout-ms", description = "The message timeout in milliseconds")
protected Long timeoutMs;
protected FunctionConfig functionConfig;
protected String userCodeFile;
private void mergeArgs() {
if (!StringUtils.isBlank(DEPRECATED_className)) className = DEPRECATED_className;
if (!StringUtils.isBlank(DEPRECATED_topicsPattern)) topicsPattern = DEPRECATED_topicsPattern;
if (!StringUtils.isBlank(DEPRECATED_logTopic)) logTopic = DEPRECATED_logTopic;
if (!StringUtils.isBlank(DEPRECATED_outputSerdeClassName)) outputSerdeClassName = DEPRECATED_outputSerdeClassName;
if (!StringUtils.isBlank(DEPRECATED_customSerdeInputString)) customSerdeInputString = DEPRECATED_customSerdeInputString;
if (!StringUtils.isBlank(DEPRECATED_fnConfigFile)) fnConfigFile = DEPRECATED_fnConfigFile;
if (DEPRECATED_processingGuarantees != null) processingGuarantees = DEPRECATED_processingGuarantees;
if (!StringUtils.isBlank(DEPRECATED_userConfigString)) userConfigString = DEPRECATED_userConfigString;
if (DEPRECATED_retainOrdering != null) retainOrdering = DEPRECATED_retainOrdering;
if (DEPRECATED_windowLengthCount != null) windowLengthCount = DEPRECATED_windowLengthCount;
if (DEPRECATED_windowLengthDurationMs != null) windowLengthDurationMs = DEPRECATED_windowLengthDurationMs;
if (DEPRECATED_slidingIntervalCount != null) slidingIntervalCount = DEPRECATED_slidingIntervalCount;
if (DEPRECATED_slidingIntervalDurationMs != null) slidingIntervalDurationMs = DEPRECATED_slidingIntervalDurationMs;
if (DEPRECATED_autoAck != null) autoAck = DEPRECATED_autoAck;
if (DEPRECATED_timeoutMs != null) timeoutMs = DEPRECATED_timeoutMs;
}
@Override
void processArguments() throws Exception {
super.processArguments();
// merge deprecated args with new args
mergeArgs();
// Initialize config builder either from a supplied YAML config file or from scratch
if (null != fnConfigFile) {
functionConfig = CmdUtils.loadConfig(fnConfigFile, FunctionConfig.class);
} else {
functionConfig = new FunctionConfig();
}
if (null != fqfn) {
parseFullyQualifiedFunctionName(fqfn, functionConfig);
} else {
if (null != tenant) {
functionConfig.setTenant(tenant);
}
if (null != namespace) {
functionConfig.setNamespace(namespace);
}
if (null != functionName) {
functionConfig.setName(functionName);
}
}
if (null != inputs) {
List<String> inputTopics = Arrays.asList(inputs.split(","));
functionConfig.setInputs(inputTopics);
}
if (null != customSerdeInputString) {
Type type = new TypeToken<Map<String, String>>(){}.getType();
Map<String, String> customSerdeInputMap = new Gson().fromJson(customSerdeInputString, type);
functionConfig.setCustomSerdeInputs(customSerdeInputMap);
}
if (null != customSchemaInputString) {
Type type = new TypeToken<Map<String, String>>(){}.getType();
Map<String, String> customschemaInputMap = new Gson().fromJson(customSchemaInputString, type);
functionConfig.setCustomSchemaInputs(customschemaInputMap);
}
if (null != topicsPattern) {
functionConfig.setTopicsPattern(topicsPattern);
}
if (null != output) {
functionConfig.setOutput(output);
}
if (null != logTopic) {
functionConfig.setLogTopic(logTopic);
}
if (null != className) {
functionConfig.setClassName(className);
}
if (null != outputSerdeClassName) {
functionConfig.setOutputSerdeClassName(outputSerdeClassName);
}
if (null != schemaType) {
functionConfig.setOutputSchemaType(schemaType);
}
if (null != processingGuarantees) {
functionConfig.setProcessingGuarantees(processingGuarantees);
}
functionConfig.setRetainOrdering(retainOrdering);
if (isNotBlank(subsName)) {
functionConfig.setSubName(subsName);
}
if (null != userConfigString) {
Type type = new TypeToken<Map<String, String>>(){}.getType();
Map<String, Object> userConfigMap = new Gson().fromJson(userConfigString, type);
functionConfig.setUserConfig(userConfigMap);
}
if (functionConfig.getUserConfig() == null) {
functionConfig.setUserConfig(new HashMap<>());
}
if (parallelism != null) {
functionConfig.setParallelism(parallelism);
}
functionConfig.setResources(new org.apache.pulsar.functions.utils.Resources(cpu, ram, disk));
if (timeoutMs != null) {
functionConfig.setTimeoutMs(timeoutMs);
}
// window configs
WindowConfig windowConfig = functionConfig.getWindowConfig();
if (null != windowLengthCount) {
if (windowConfig == null) {
windowConfig = new WindowConfig();
}
windowConfig.setWindowLengthCount(windowLengthCount);
}
if (null != windowLengthDurationMs) {
if (windowConfig == null) {
windowConfig = new WindowConfig();
}
windowConfig.setWindowLengthDurationMs(windowLengthDurationMs);
}
if (null != slidingIntervalCount) {
if (windowConfig == null) {
windowConfig = new WindowConfig();
}
windowConfig.setSlidingIntervalCount(slidingIntervalCount);
}
if (null != slidingIntervalDurationMs) {
if (windowConfig == null) {
windowConfig = new WindowConfig();
}
windowConfig.setSlidingIntervalDurationMs(slidingIntervalDurationMs);
}
functionConfig.setWindowConfig(windowConfig);
functionConfig.setAutoAck(autoAck);
if (null != jarFile) {
functionConfig.setJar(jarFile);
}
if (null != pyFile) {
functionConfig.setPy(pyFile);
}
if (functionConfig.getJar() != null) {
userCodeFile = functionConfig.getJar();
} else if (functionConfig.getPy() != null) {
userCodeFile = functionConfig.getPy();
}
// infer default vaues
inferMissingArguments(functionConfig);
}
protected void validateFunctionConfigs(FunctionConfig functionConfig) {
if (isNotBlank(functionConfig.getJar()) && isNotBlank(functionConfig.getPy())) {
throw new ParameterException("Either a Java jar or a Python file needs to"
+ " be specified for the function. Cannot specify both.");
}
if (isBlank(functionConfig.getJar()) && isBlank(functionConfig.getPy())) {
throw new ParameterException("Either a Java jar or a Python file needs to"
+ " be specified for the function. Please specify one.");
}
boolean isJarPathUrl = isNotBlank(functionConfig.getJar()) && Utils.isFunctionPackageUrlSupported(functionConfig.getJar());
String jarFilePath = null;
if (isJarPathUrl) {
if (functionConfig.getJar().startsWith(Utils.HTTP)) {
// download jar file if url is http or file is downloadable
File tempPkgFile = null;
try {
tempPkgFile = downloadFromHttpUrl(functionConfig.getJar(), functionConfig.getName());
jarFilePath = tempPkgFile.getAbsolutePath();
} catch (Exception e) {
if (tempPkgFile != null) {
tempPkgFile.deleteOnExit();
}
throw new ParameterException("Failed to download jar from " + functionConfig.getJar()
+ ", due to =" + e.getMessage());
}
}
} else {
if (!fileExists(userCodeFile)) {
throw new ParameterException("File " + userCodeFile + " does not exist");
}
jarFilePath = userCodeFile;
}
if (functionConfig.getRuntime() == FunctionConfig.Runtime.JAVA) {
if (jarFilePath != null) {
File file = new File(jarFilePath);
ClassLoader userJarLoader;
try {
userJarLoader = Reflections.loadJar(file);
} catch (MalformedURLException e) {
throw new ParameterException(
"Failed to load user jar " + file + " with error " + e.getMessage());
}
// make sure the function class loader is accessible thread-locally
Thread.currentThread().setContextClassLoader(userJarLoader);
(new ImplementsClassesValidator(Function.class, java.util.function.Function.class))
.validateField("className", functionConfig.getClassName());
}
}
try {
// Need to load jar and set context class loader before calling
ConfigValidation.validateConfig(functionConfig, functionConfig.getRuntime().name());
} catch (Exception e) {
throw new ParameterException(e.getMessage());
}
}
private void inferMissingArguments(FunctionConfig functionConfig) {
if (StringUtils.isEmpty(functionConfig.getName())) {
inferMissingFunctionName(functionConfig);
}
if (StringUtils.isEmpty(functionConfig.getTenant())) {
inferMissingTenant(functionConfig);
}
if (StringUtils.isEmpty(functionConfig.getNamespace())) {
inferMissingNamespace(functionConfig);
}
if (functionConfig.getParallelism() == 0) {
functionConfig.setParallelism(1);
}
if (functionConfig.getJar() != null) {
functionConfig.setRuntime(FunctionConfig.Runtime.JAVA);
} else if (functionConfig.getPy() != null) {
functionConfig.setRuntime(FunctionConfig.Runtime.PYTHON);
}
WindowConfig windowConfig = functionConfig.getWindowConfig();
if (windowConfig != null) {
WindowUtils.inferDefaultConfigs(windowConfig);
functionConfig.setAutoAck(false);
}
}
private void inferMissingFunctionName(FunctionConfig functionConfig) {
if (isNull(functionConfig.getClassName())) {
throw new ParameterException("You must specify a class name for the function");
}
String [] domains = functionConfig.getClassName().split("\\.");
if (domains.length == 0) {
functionConfig.setName(functionConfig.getClassName());
} else {
functionConfig.setName(domains[domains.length - 1]);
}
}
private void inferMissingTenant(FunctionConfig functionConfig) {
functionConfig.setTenant(PUBLIC_TENANT);
}
private void inferMissingNamespace(FunctionConfig functionConfig) {
functionConfig.setNamespace(DEFAULT_NAMESPACE);
}
protected FunctionDetails convert(FunctionConfig functionConfig)
throws IOException {
// check if configs are valid
validateFunctionConfigs(functionConfig);
Class<?>[] typeArgs = null;
if (functionConfig.getRuntime() == FunctionConfig.Runtime.JAVA) {
if (functionConfig.getJar().startsWith(Utils.FILE)) {
// server derives the arg-type by loading a class
if (isBlank(functionConfig.getClassName())) {
throw new ParameterException("Class-name must be present for jar with file-url");
}
} else {
typeArgs = Utils.getFunctionTypes(functionConfig);
}
}
FunctionDetails.Builder functionDetailsBuilder = FunctionDetails.newBuilder();
// Setup source
SourceSpec.Builder sourceSpecBuilder = SourceSpec.newBuilder();
if (functionConfig.getInputs() != null) {
functionConfig.getInputs().forEach((topicName -> {
sourceSpecBuilder.putInputSpecs(topicName,
ConsumerSpec.newBuilder()
.setIsRegexPattern(false)
.build());
}));
}
if (functionConfig.getTopicsPattern() != null && !functionConfig.getTopicsPattern().isEmpty()) {
sourceSpecBuilder.putInputSpecs(functionConfig.getTopicsPattern(),
ConsumerSpec.newBuilder()
.setIsRegexPattern(true)
.build());
}
if (functionConfig.getCustomSerdeInputs() != null) {
functionConfig.getCustomSerdeInputs().forEach((topicName, serdeClassName) -> {
sourceSpecBuilder.putInputSpecs(topicName,
ConsumerSpec.newBuilder()
.setSerdeClassName(serdeClassName)
.setIsRegexPattern(false)
.build());
});
}
if (functionConfig.getCustomSchemaInputs() != null) {
functionConfig.getCustomSchemaInputs().forEach((topicName, schemaType) -> {
sourceSpecBuilder.putInputSpecs(topicName,
ConsumerSpec.newBuilder()
.setSchemaType(schemaType)
.setIsRegexPattern(false)
.build());
});
}
if (functionConfig.getInputSpecs() != null) {
functionConfig.getInputSpecs().forEach((topicName, consumerConf) -> {
ConsumerSpec.Builder bldr = ConsumerSpec.newBuilder()
.setIsRegexPattern(consumerConf.isRegexPattern());
if (!StringUtils.isBlank(consumerConf.getSchemaType())) {
bldr.setSchemaType(consumerConf.getSchemaType());
} else if (!StringUtils.isBlank(consumerConf.getSerdeClassName())) {
bldr.setSerdeClassName(consumerConf.getSerdeClassName());
}
sourceSpecBuilder.putInputSpecs(topicName, bldr.build());
});
}
// Set subscription type based on ordering and EFFECTIVELY_ONCE semantics
SubscriptionType subType = (functionConfig.isRetainOrdering()
|| ProcessingGuarantees.EFFECTIVELY_ONCE.equals(functionConfig.getProcessingGuarantees()))
? SubscriptionType.FAILOVER
: SubscriptionType.SHARED;
sourceSpecBuilder.setSubscriptionType(subType);
if (isNotBlank(functionConfig.getSubName())) {
sourceSpecBuilder.setSubscriptionName(functionConfig.getSubName());
}
if (typeArgs != null) {
sourceSpecBuilder.setTypeClassName(typeArgs[0].getName());
}
if (functionConfig.getTimeoutMs() != null) {
sourceSpecBuilder.setTimeoutMs(functionConfig.getTimeoutMs());
}
functionDetailsBuilder.setSource(sourceSpecBuilder);
// Setup sink
SinkSpec.Builder sinkSpecBuilder = SinkSpec.newBuilder();
if (functionConfig.getOutput() != null) {
sinkSpecBuilder.setTopic(functionConfig.getOutput());
}
if (!StringUtils.isBlank(functionConfig.getOutputSerdeClassName())) {
sinkSpecBuilder.setSerDeClassName(functionConfig.getOutputSerdeClassName());
}
if (!StringUtils.isBlank(functionConfig.getOutputSchemaType())) {
sinkSpecBuilder.setSchemaType(functionConfig.getOutputSchemaType());
}
if (typeArgs != null) {
sinkSpecBuilder.setTypeClassName(typeArgs[1].getName());
}
functionDetailsBuilder.setSink(sinkSpecBuilder);
if (functionConfig.getTenant() != null) {
functionDetailsBuilder.setTenant(functionConfig.getTenant());
}
if (functionConfig.getNamespace() != null) {
functionDetailsBuilder.setNamespace(functionConfig.getNamespace());
}
if (functionConfig.getName() != null) {
functionDetailsBuilder.setName(functionConfig.getName());
}
if (functionConfig.getLogTopic() != null) {
functionDetailsBuilder.setLogTopic(functionConfig.getLogTopic());
}
if (functionConfig.getRuntime() != null) {
functionDetailsBuilder.setRuntime(Utils.convertRuntime(functionConfig.getRuntime()));
}
if (functionConfig.getProcessingGuarantees() != null) {
functionDetailsBuilder.setProcessingGuarantees(
Utils.convertProcessingGuarantee(functionConfig.getProcessingGuarantees()));
}
Map<String, Object> configs = new HashMap<>();
configs.putAll(functionConfig.getUserConfig());
// windowing related
WindowConfig windowConfig = functionConfig.getWindowConfig();
if (windowConfig != null) {
windowConfig.setActualWindowFunctionClassName(functionConfig.getClassName());
configs.put(WindowConfig.WINDOW_CONFIG_KEY, windowConfig);
// set class name to window function executor
functionDetailsBuilder.setClassName(WindowFunctionExecutor.class.getName());
} else {
if (functionConfig.getClassName() != null) {
functionDetailsBuilder.setClassName(functionConfig.getClassName());
}
}
if (!configs.isEmpty()) {
functionDetailsBuilder.setUserConfig(new Gson().toJson(configs));
}
functionDetailsBuilder.setAutoAck(functionConfig.isAutoAck());
functionDetailsBuilder.setParallelism(functionConfig.getParallelism());
if (functionConfig.getResources() != null) {
Resources.Builder bldr = Resources.newBuilder();
if (functionConfig.getResources().getCpu() != null) {
bldr.setCpu(functionConfig.getResources().getCpu());
}
if (functionConfig.getResources().getRam() != null) {
bldr.setRam(functionConfig.getResources().getRam());
}
if (functionConfig.getResources().getDisk() != null) {
bldr.setDisk(functionConfig.getResources().getDisk());
}
functionDetailsBuilder.setResources(bldr.build());
}
return functionDetailsBuilder.build();
}
protected org.apache.pulsar.functions.proto.Function.FunctionDetails convertProto2(FunctionConfig functionConfig)
throws IOException {
org.apache.pulsar.functions.proto.Function.FunctionDetails.Builder functionDetailsBuilder = org.apache.pulsar.functions.proto.Function.FunctionDetails.newBuilder();
Utils.mergeJson(FunctionsImpl.printJson(convert(functionConfig)), functionDetailsBuilder);
return functionDetailsBuilder.build();
}
}
@Parameters(commandDescription = "Run the Pulsar Function locally (rather than deploying it to the Pulsar cluster)")
class LocalRunner extends FunctionDetailsCommand {
// TODO: this should become bookkeeper url and it should be fetched from pulsar client.
// for backwards compatibility purposes
@Parameter(names = "--stateStorageServiceUrl", description = "The URL for the state storage service (by default Apache BookKeeper)", hidden = true)
protected String DEPRECATED_stateStorageServiceUrl;
@Parameter(names = "--state-storage-service-url", description = "The URL for the state storage service (by default Apache BookKeeper)")
protected String stateStorageServiceUrl;
// for backwards compatibility purposes
@Parameter(names = "--brokerServiceUrl", description = "The URL for the Pulsar broker", hidden = true)
protected String DEPRECATED_brokerServiceUrl;
@Parameter(names = "--broker-service-url", description = "The URL for the Pulsar broker")
protected String brokerServiceUrl;
// for backwards compatibility purposes
@Parameter(names = "--clientAuthPlugin", description = "Client authentication plugin using which function-process can connect to broker", hidden = true)
protected String DEPRECATED_clientAuthPlugin;
@Parameter(names = "--client-auth-plugin", description = "Client authentication plugin using which function-process can connect to broker")
protected String clientAuthPlugin;
// for backwards compatibility purposes
@Parameter(names = "--clientAuthParams", description = "Client authentication param", hidden = true)
protected String DEPRECATED_clientAuthParams;
@Parameter(names = "--client-auth-params", description = "Client authentication param")
protected String clientAuthParams;
// for backwards compatibility purposes
@Parameter(names = "--use_tls", description = "Use tls connection\n", hidden = true)
protected Boolean DEPRECATED_useTls = null;
@Parameter(names = "--use-tls", description = "Use tls connection\n")
protected boolean useTls;
// for backwards compatibility purposes
@Parameter(names = "--tls_allow_insecure", description = "Allow insecure tls connection\n", hidden = true)
protected Boolean DEPRECATED_tlsAllowInsecureConnection = null;
@Parameter(names = "--tls-allow-insecure", description = "Allow insecure tls connection\n")
protected boolean tlsAllowInsecureConnection;
// for backwards compatibility purposes
@Parameter(names = "--hostname_verification_enabled", description = "Enable hostname verification", hidden = true)
protected Boolean DEPRECATED_tlsHostNameVerificationEnabled = null;
@Parameter(names = "--hostname-verification-enabled", description = "Enable hostname verification")
protected boolean tlsHostNameVerificationEnabled;
// for backwards compatibility purposes
@Parameter(names = "--tls_trust_cert_path", description = "tls trust cert file path", hidden = true)
protected String DEPRECATED_tlsTrustCertFilePath;
@Parameter(names = "--tls-trust-cert-path", description = "tls trust cert file path")
protected String tlsTrustCertFilePath;
// for backwards compatibility purposes
@Parameter(names = "--instanceIdOffset", description = "Start the instanceIds from this offset", hidden = true)
protected Integer DEPRECATED_instanceIdOffset = null;
@Parameter(names = "--instance-id-offset", description = "Start the instanceIds from this offset")
protected Integer instanceIdOffset = 0;
private void mergeArgs() {
if (!StringUtils.isBlank(DEPRECATED_stateStorageServiceUrl)) stateStorageServiceUrl = DEPRECATED_stateStorageServiceUrl;
if (!StringUtils.isBlank(DEPRECATED_brokerServiceUrl)) brokerServiceUrl = DEPRECATED_brokerServiceUrl;
if (!StringUtils.isBlank(DEPRECATED_clientAuthPlugin)) clientAuthPlugin = DEPRECATED_clientAuthPlugin;
if (!StringUtils.isBlank(DEPRECATED_clientAuthParams)) clientAuthParams = DEPRECATED_clientAuthParams;
if (DEPRECATED_useTls != null) useTls = DEPRECATED_useTls;
if (DEPRECATED_tlsAllowInsecureConnection != null) tlsAllowInsecureConnection = DEPRECATED_tlsAllowInsecureConnection;
if (DEPRECATED_tlsHostNameVerificationEnabled != null) tlsHostNameVerificationEnabled = DEPRECATED_tlsHostNameVerificationEnabled;
if (!StringUtils.isBlank(DEPRECATED_tlsTrustCertFilePath)) tlsTrustCertFilePath = DEPRECATED_tlsTrustCertFilePath;
if (DEPRECATED_instanceIdOffset != null) instanceIdOffset = DEPRECATED_instanceIdOffset;
}
@Override
void runCmd() throws Exception {
// merge deprecated args with new args
mergeArgs();
CmdFunctions.startLocalRun(convertProto2(functionConfig), functionConfig.getParallelism(),
instanceIdOffset, brokerServiceUrl, stateStorageServiceUrl,
AuthenticationConfig.builder().clientAuthenticationPlugin(clientAuthPlugin)
.clientAuthenticationParameters(clientAuthParams).useTls(useTls)
.tlsAllowInsecureConnection(tlsAllowInsecureConnection)
.tlsHostnameVerificationEnable(tlsHostNameVerificationEnabled)
.tlsTrustCertsFilePath(tlsTrustCertFilePath).build(),
userCodeFile, admin);
}
}
@Parameters(commandDescription = "Create a Pulsar Function in cluster mode (i.e. deploy it on a Pulsar cluster)")
class CreateFunction extends FunctionDetailsCommand {
@Override
void runCmd() throws Exception {
if (Utils.isFunctionPackageUrlSupported(functionConfig.getJar())) {
admin.functions().createFunctionWithUrl(convert(functionConfig), functionConfig.getJar());
} else {
admin.functions().createFunction(convert(functionConfig), userCodeFile);
}
print("Created successfully");
}
}
@Parameters(commandDescription = "Fetch information about a Pulsar Function")
class GetFunction extends FunctionCommand {
@Override
void runCmd() throws Exception {
String json = Utils.printJson(admin.functions().getFunction(tenant, namespace, functionName));
Gson gson = new GsonBuilder().setPrettyPrinting().create();
System.out.println(gson.toJson(new JsonParser().parse(json)));
}
}
@Parameters(commandDescription = "Check the current status of a Pulsar Function")
class GetFunctionStatus extends FunctionCommand {
@Parameter(names = "--instance-id", description = "The function instanceId (Get-status of all instances if instance-id is not provided")
protected String instanceId;
@Override
void runCmd() throws Exception {
String json = Utils.printJson(
isBlank(instanceId) ? admin.functions().getFunctionStatus(tenant, namespace, functionName)
: admin.functions().getFunctionStatus(tenant, namespace, functionName,
Integer.parseInt(instanceId)));
Gson gson = new GsonBuilder().setPrettyPrinting().create();
System.out.println(gson.toJson(new JsonParser().parse(json)));
}
}
@Parameters(commandDescription = "Restart function instance")
class RestartFunction extends FunctionCommand {
@Parameter(names = "--instance-id", description = "The function instanceId (restart all instances if instance-id is not provided")
protected String instanceId;
@Override
void runCmd() throws Exception {
if (isNotBlank(instanceId)) {
try {
admin.functions().restartFunction(tenant, namespace, functionName, Integer.parseInt(instanceId));
} catch (NumberFormatException e) {
System.err.println("instance-id must be a number");
}
} else {
admin.functions().restartFunction(tenant, namespace, functionName);
}
System.out.println("Restarted successfully");
}
}
@Parameters(commandDescription = "Temporary stops function instance. (If worker restarts then it reassigns and starts functiona again")
class StopFunction extends FunctionCommand {
@Parameter(names = "--instance-id", description = "The function instanceId (stop all instances if instance-id is not provided")
protected String instanceId;
@Override
void runCmd() throws Exception {
if (isNotBlank(instanceId)) {
try {
admin.functions().stopFunction(tenant, namespace, functionName, Integer.parseInt(instanceId));
} catch (NumberFormatException e) {
System.err.println("instance-id must be a number");
}
} else {
admin.functions().stopFunction(tenant, namespace, functionName);
}
System.out.println("Restarted successfully");
}
}
@Parameters(commandDescription = "Delete a Pulsar Function that's running on a Pulsar cluster")
class DeleteFunction extends FunctionCommand {
@Override
void runCmd() throws Exception {
admin.functions().deleteFunction(tenant, namespace, functionName);
print("Deleted successfully");
}
}
@Parameters(commandDescription = "Update a Pulsar Function that's been deployed to a Pulsar cluster")
class UpdateFunction extends FunctionDetailsCommand {
@Override
void runCmd() throws Exception {
if (Utils.isFunctionPackageUrlSupported(functionConfig.getJar())) {
admin.functions().updateFunctionWithUrl(convert(functionConfig), functionConfig.getJar());
} else {
admin.functions().updateFunction(convert(functionConfig), userCodeFile);
}
print("Updated successfully");
}
}
@Parameters(commandDescription = "List all of the Pulsar Functions running under a specific tenant and namespace")
class ListFunctions extends NamespaceCommand {
@Override
void runCmd() throws Exception {
print(admin.functions().getFunctions(tenant, namespace));
}
}
@Parameters(commandDescription = "Fetch the current state associated with a Pulsar Function running in cluster mode")
class StateGetter extends FunctionCommand {
@Parameter(names = { "-k", "--key" }, description = "key")
private String key = null;
// TODO: this url should be fetched along with bookkeeper location from pulsar admin
@Parameter(names = { "-u", "--storage-service-url" }, description = "The URL for the storage service used by the function")
private String stateStorageServiceUrl = null;
@Parameter(names = { "-w", "--watch" }, description = "Watch for changes in the value associated with a key for a Pulsar Function")
private boolean watch = false;
@Override
void runCmd() throws Exception {
checkNotNull(stateStorageServiceUrl, "The state storage service URL is missing");
String tableNs = String.format(
"%s_%s",
tenant,
namespace).replace('-', '_');
String tableName = getFunctionName();
try (StorageClient client = StorageClientBuilder.newBuilder()
.withSettings(StorageClientSettings.newBuilder()
.serviceUri(stateStorageServiceUrl)
.clientName("functions-admin")
.build())
.withNamespace(tableNs)
.build()) {
try (Table<ByteBuf, ByteBuf> table = result(client.openTable(tableName))) {
long lastVersion = -1L;
do {
try (KeyValue<ByteBuf, ByteBuf> kv = result(table.getKv(Unpooled.wrappedBuffer(key.getBytes(UTF_8))))) {
if (null == kv) {
System.out.println("key '" + key + "' doesn't exist.");
} else {
if (kv.version() > lastVersion) {
if (kv.isNumber()) {
System.out.println("value = " + kv.numberValue());
} else {
System.out.println("value = " + new String(ByteBufUtil.getBytes(kv.value()), UTF_8));
}
lastVersion = kv.version();