-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathstream-producer.py
executable file
·2996 lines (2366 loc) · 103 KB
/
stream-producer.py
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
#! /usr/bin/env python3
# -----------------------------------------------------------------------------
# stream-producer.py Create a stream.
# - Uses a "pipes and filters" design pattern
# -----------------------------------------------------------------------------
# Import from standard library. https://docs.python.org/3/library/
import argparse
import gzip
import io
import json
import linecache
import logging
import multiprocessing
import os
import random
import re
import signal
import string
import sys
import threading
import time
import urllib.parse
import urllib.request
from pathlib import Path
# Import from https://pypi.org/
import boto3
import confluent_kafka
import fastavro
import pandas
import pika
import pyarrow.parquet as pq
import s3fs
from azure.servicebus import ServiceBusClient, ServiceBusMessage
# Metadata.
__all__ = []
__version__ = "1.8.9" # See https://www.python.org/dev/peps/pep-0396/
__date__ = '2020-07-07'
__updated__ = '2023-11-15'
# See https://github.com/Senzing/knowledge-base/blob/main/lists/senzing-product-ids.md
SENZING_PRODUCT_ID = "5014"
log_format = '%(asctime)s %(message)s'
# Working with bytes.
KILOBYTES = 1024
MEGABYTES = 1024 * KILOBYTES
GIGABYTES = 1024 * MEGABYTES
# Random sentinel to indicate end of service
QUEUE_SENTINEL = ".{0}.".format(''.join(
[random.choice(string.ascii_letters + string.digits) for n in range(32)]))
# The "configuration_locator" describes where configuration variables are in:
# 1) Command line options, 2) Environment variables, 3) Configuration files, 4) Default values
configuration_locator = {
"azure_queue_connection_string": {
"default": None,
"env": "SENZING_AZURE_QUEUE_CONNECTION_STRING",
"cli": "azure-queue-connection-string",
},
"azure_queue_name": {
"default": None,
"env": "SENZING_AZURE_QUEUE_NAME",
"cli": "azure-queue-name",
},
"csv_rows_in_chunk": {
"default": 10000,
"env": "SENZING_CSV_ROWS_IN_CHUNK",
"cli": "csv-rows-in-chunk"
},
"csv_delimiter": {
"default": ",",
"env": "SENZING_CSV_DELIMITER",
"cli": "csv-delimiter"
},
"debug": {
"default": False,
"env": "SENZING_DEBUG",
"cli": "debug"
},
"default_data_source": {
"default": None,
"env": "SENZING_DEFAULT_DATA_SOURCE",
"cli": "default-data-source",
},
"delay_in_seconds": {
"default": 0,
"env": "SENZING_DELAY_IN_SECONDS",
"cli": "delay-in-seconds"
},
"input_url": {
"default": "file:///data",
"env": "SENZING_INPUT_URL",
"cli": "input-url",
},
"kafka_bootstrap_server": {
"default": "localhost:9092",
"env": "SENZING_KAFKA_BOOTSTRAP_SERVER",
"cli": "kafka-bootstrap-server",
},
"kafka_configuration": {
"default": "{}",
"env": "SENZING_KAFKA_CONFIGURATION",
"cli": "kafka-configuration",
},
"kafka_group": {
"default": "senzing-kafka-group",
"env": "SENZING_KAFKA_GROUP",
"cli": "kafka-group"
},
"kafka_poll_interval": {
"default": 100,
"env": "SENZING_KAFKA_POLL_INTERVAL",
"cli": "kafka-poll-interval",
},
"kafka_topic": {
"default": "senzing-kafka-topic",
"env": "SENZING_KAFKA_TOPIC",
"cli": "kafka-topic",
},
"monitoring_period_in_seconds": {
"default": 60 * 10,
"env": "SENZING_MONITORING_PERIOD_IN_SECONDS",
"cli": "monitoring-period-in-seconds",
},
"password": {
"default": None,
"env": "SENZING_PASSWORD",
"cli": "password"
},
"rabbitmq_exchange": {
"default": "senzing-rabbitmq-exchange",
"env": "SENZING_RABBITMQ_EXCHANGE",
"cli": "rabbitmq-exchange",
},
"rabbitmq_host": {
"default": "localhost",
"env": "SENZING_RABBITMQ_HOST",
"cli": "rabbitmq-host",
},
"rabbitmq_password": {
"default": "bitnami",
"env": "SENZING_RABBITMQ_PASSWORD",
"cli": "rabbitmq-password",
},
"rabbitmq_port": {
"default": "5672",
"env": "SENZING_RABBITMQ_PORT",
"cli": "rabbitmq-port",
},
"rabbitmq_queue": {
"default": "senzing-rabbitmq-queue",
"env": "SENZING_RABBITMQ_QUEUE",
"cli": "rabbitmq-queue",
},
"rabbitmq_routing_key": {
"default": "senzing.records",
"env": "SENZING_RABBITMQ_ROUTING_KEY",
"cli": "rabbitmq-routing-key",
},
"rabbitmq_use_existing_entities": {
"default": False,
"env": "SENZING_RABBITMQ_USE_EXISTING_ENTITIES",
"cli": "rabbitmq-use-existing-entities",
},
"rabbitmq_username": {
"default": "user",
"env": "SENZING_RABBITMQ_USERNAME",
"cli": "rabbitmq-username",
},
"rabbitmq_virtual_host": {
"default": pika.ConnectionParameters.DEFAULT_VIRTUAL_HOST,
"env": "SENZING_RABBITMQ_VIRTUAL_HOST",
"cli": "rabbitmq-virtual-host",
},
"read_queue_maxsize": {
"default": 50,
"env": "SENZING_READ_QUEUE_MAXSIZE",
"cli": "read-queue-maxsize"
},
"record_identifier": {
"default": "RECORD_ID",
"env": "SENZING_RECORD_IDENTIFIER",
"cli": "record-identifier",
},
"record_max": {
"default": None,
"env": "SENZING_RECORD_MAX",
"cli": "record-max",
},
"record_min": {
"default": None,
"env": "SENZING_RECORD_MIN",
"cli": "record-min",
},
"record_monitor": {
"default": "10000",
"env": "SENZING_RECORD_MONITOR",
"cli": "record-monitor",
},
"records_per_message": {
"default": 1,
"env": "SENZING_RECORDS_PER_MESSAGE",
"cli": "records-per-message"
},
"record_size_max": {
"default": 0,
"env": "SENZING_RECORD_SIZE_MAX",
"cli": "record-size-max"
},
"sleep_time_in_seconds": {
"default": 0,
"env": "SENZING_SLEEP_TIME_IN_SECONDS",
"cli": "sleep-time-in-seconds"
},
"stream_loader_directive_action": {
"default": "addRecord",
"env": "SENZING_STREAM_LOADER_DIRECTIVE_ACTION",
"cli": "stream-loader-directive-action"
},
"stream_loader_directive_name": {
"default": None,
"env": "SENZING_STREAM_LOADER_DIRECTIVE_NAME",
"cli": "stream-loader-directive-name"
},
"sqs_delay_seconds": {
"default": 0,
"env": "SENZING_SQS_DELAY_SECONDS",
"cli": "sqs-delay-seconds"
},
"sqs_queue_url": {
"default": None,
"env": "SENZING_SQS_QUEUE_URL",
"cli": "sqs-queue-url"
},
"subcommand": {
"default": None,
"env": "SENZING_SUBCOMMAND",
},
"threads_per_print": {
"default": 4,
"env": "SENZING_THREADS_PER_PRINT",
"cli": "threads-per-print"
},
}
# Enumerate keys in 'configuration_locator' that should not be printed to the log.
keys_to_redact = [
"password",
]
# -----------------------------------------------------------------------------
# Define argument parser
# -----------------------------------------------------------------------------
def get_parser():
''' Parse commandline arguments. '''
subcommands = {
'avro-to-azure-queue': {
"help": 'Read Avro file and send to Azure Queue.',
"argument_aspects": ["input-url", "avro", "azure", "transform"]
},
'avro-to-kafka': {
"help": 'Read Avro file and send to Kafka.',
"argument_aspects": ["input-url", "avro", "kafka", "transform"]
},
'avro-to-rabbitmq': {
"help": 'Read Avro file and send to RabbitMQ.',
"argument_aspects": ["input-url", "avro", "rabbitmq", "transform"]
},
'avro-to-sqs': {
"help": 'Read Avro file and print to AWS SQS.',
"argument_aspects": ["input-url", "avro", "sqs", "transform"]
},
'avro-to-sqs-batch': {
"help": 'Read Avro file and print to AWS SQS using batch. DEPRECATED: Use avro-to-sqs and set SENZING_RECORDS_PER_MESSAGE',
"argument_aspects": ["input-url", "avro", "sqs", "transform"]
},
'avro-to-stdout': {
"help": 'Read Avro file and print to STDOUT.',
"argument_aspects": ["input-url", "avro", "stdout", "transform"]
},
'csv-to-azure-queue': {
"help": 'Read CSV file and send to Azure Queue.',
"argument_aspects": ["input-url", "csv", "azure", "transform"]
},
'csv-to-kafka': {
"help": 'Read CSV file and send to Kafka.',
"argument_aspects": ["input-url", "csv", "kafka", "transform"]
},
'csv-to-rabbitmq': {
"help": 'Read CSV file and send to RabbitMQ.',
"argument_aspects": ["input-url", "csv", "rabbitmq", "transform"]
},
'csv-to-sqs': {
"help": 'Read CSV file and print to SQS.',
"argument_aspects": ["input-url", "csv", "sqs", "transform"]
},
'csv-to-sqs-batch': {
"help": 'Read CSV file and print to SQS using batch. DEPRECATED: Use csv-to-sqs and set SENZING_RECORDS_PER_MESSAGE',
"argument_aspects": ["input-url", "csv", "sqs", "transform"]
},
'csv-to-stdout': {
"help": 'Read CSV file and print to STDOUT.',
"argument_aspects": ["input-url", "csv", "stdout", "transform"]
},
'gzipped-json-to-azure-queue': {
"help": 'Read gzipped JSON file and send to Azure Queue.',
"argument_aspects": ["input-url", "json", "azure", "transform"]
},
'gzipped-json-to-kafka': {
"help": 'Read gzipped JSON file and send to Kafka.',
"argument_aspects": ["input-url", "json", "kafka", "transform"]
},
'gzipped-json-to-rabbitmq': {
"help": 'Read gzipped JSON file and send to RabbitMQ.',
"argument_aspects": ["input-url", "json", "rabbitmq", "transform"]
},
'gzipped-json-to-sqs': {
"help": 'Read gzipped JSON file and send to AWS SQS.',
"argument_aspects": ["input-url", "json", "sqs", "transform"]
},
'gzipped-json-to-sqs-batch': {
"help": 'Read gzipped JSON file and send to AWS SQS using batch. DEPRECATED: Use gzipped-json-to-sqs and set SENZING_RECORDS_PER_MESSAGE',
"argument_aspects": ["input-url", "json", "sqs", "transform"]
},
'gzipped-json-to-stdout': {
"help": 'Read gzipped JSON file and print to STDOUT.',
"argument_aspects": ["input-url", "json", "stdout", "transform"]
},
'json-to-azure-queue': {
"help": 'Read JSON file and send to Azure Queue.',
"argument_aspects": ["input-url", "json", "azure", "transform"]
},
'json-to-kafka': {
"help": 'Read JSON file and send to Kafka.',
"argument_aspects": ["input-url", "json", "kafka", "transform"]
},
'json-to-rabbitmq': {
"help": 'Read JSON file and send to RabbitMQ.',
"argument_aspects": ["input-url", "json", "rabbitmq", "transform"]
},
'json-to-sqs': {
"help": 'Read JSON file and send to AWS SQS.',
"argument_aspects": ["input-url", "json", "sqs", "transform"]
},
'json-to-sqs-batch': {
"help": 'Read JSON file and send to AWS SQS using batch. DEPRECATED: Use json-to-sqs and set SENZING_RECORDS_PER_MESSAGE',
"argument_aspects": ["input-url", "json", "sqs", "transform"]
},
'json-to-stdout': {
"help": 'Read JSON file and print to STDOUT.',
"argument_aspects": ["input-url", "json", "stdout", "transform"]
},
'parquet-to-azure-queue': {
"help": 'Read Parquet file and send to Azure Queue.',
"argument_aspects": ["input-url", "parquet", "azure", "transform"]
},
'parquet-to-kafka': {
"help": 'Read Parquet file and send to Kafka.',
"argument_aspects": ["input-url", "parquet", "kafka", "transform"]
},
'parquet-to-rabbitmq': {
"help": 'Read Parquet file and send to RabbitMQ.',
"argument_aspects": ["input-url", "parquet", "rabbitmq", "transform"]
},
'parquet-to-sqs': {
"help": 'Read Parquet file and print to AWS SQS.',
"argument_aspects": ["input-url", "parquet", "sqs", "transform"]
},
'parquet-to-sqs-batch': {
"help": 'Read Parquet file and print to AWS SQS using batch. DEPRECATED: Use parquet-to-sqs and set SENZING_RECORDS_PER_MESSAGE',
"argument_aspects": ["input-url", "parquet", "sqs", "transform"]
},
'parquet-to-stdout': {
"help": 'Read Parquet file and print to STDOUT.',
"argument_aspects": ["input-url", "parquet", "stdout", "transform"]
},
'sleep': {
"help": 'Do nothing but sleep. For Docker testing.',
"arguments": {
"--sleep-time-in-seconds": {
"dest": "sleep_time_in_seconds",
"metavar": "SENZING_SLEEP_TIME_IN_SECONDS",
"help": "Sleep time in seconds. DEFAULT: 0 (infinite)"
},
},
},
'version': {
"help": 'Print version of program.',
},
'docker-acceptance-test': {
"help": 'For Docker acceptance testing.',
},
}
# Define argument_aspects.
argument_aspects = {
"azure": {
"--azure-queue-connection-string": {
"dest": "azure_queue_connection_string",
"metavar": "SENZING_AZURE_QUEUE_CONNECTION_STRING",
"help": "Azure Service Bus Queue connection string. Default: none"
},
"--azure-queue-name": {
"dest": "azure_queue_name",
"metavar": "SENZING_AZURE_QUEUE_NAME",
"help": "Azure Service Bus Queue name. Default: none"
}
},
"csv": {
"--csv-rows-in-chunk": {
"dest": "csv_rows_in_chunk",
"metavar": "SENZING_CSV_ROWS_IN_CHUNK",
"help": "The number of csv lines to read into memory and process at one time. Default: 10000"
},
"--csv-delimiter": {
"dest": "csv_delimiter",
"metavar": "SENZING_CSV_DELIMITER",
"help": "The character used to separate column values in a csv row. Default: ,"
}
},
"input-url": {
"--default-data-source": {
"dest": "default_data_source",
"metavar": "SENZING_DEFAULT_DATA_SOURCE",
"help": "Used when record does not have a `DATA_SOURCE` key. Default: None"
},
"--input-url": {
"dest": "input_url",
"metavar": "SENZING_INPUT_URL",
"help": "File/URL of input file. Default: None"
},
"--record-identifier": {
"dest": "record_identifier",
"metavar": "SENZING_RECORD_IDENTIFIER",
"help": "Field that identifies record. Default: RECORD_ID"
},
"--record-max": {
"dest": "record_max",
"metavar": "SENZING_RECORD_MAX",
"help": "Highest record id. Default: None."
},
"--record-min": {
"dest": "record_min",
"metavar": "SENZING_RECORD_MIN",
"help": "Lowest record id. Default: None"
},
"--record-size-max": {
"dest": "record_size_max",
"metavar": "SENZING_RECORD_SIZE_MAX",
"help": "Maximum record size (in bytes) to accept. Default: None"
},
"--records-per-message": {
"dest": "records_per_message",
"metavar": "SENZING_RECORDS_PER_MESSAGE",
"help": "The number of records to include per message to the queue. Default: 1"
},
"--threads-per-print": {
"dest": "threads_per_print",
"metavar": "SENZING_THREADS_PER_PRINT",
"help": "Threads for print phase. Default: 4"
},
},
"kafka": {
"--kafka-bootstrap-server": {
"dest": "kafka_bootstrap_server",
"metavar": "SENZING_KAFKA_BOOTSTRAP_SERVER",
"help": "Kafka bootstrap server. Default: localhost:9092"
},
"--kafka-configuration": {
"dest": "kafka_configuration",
"metavar": "SENZING_KAFKA_CONFIGURATION",
"help": "A JSON string with extra configuration parameters. Default: none"
},
"--kafka-group": {
"dest": "kafka_group",
"metavar": "SENZING_KAFKA_GROUP",
"help": "Kafka group. Default: senzing-kafka-group"
},
"--kafka-topic": {
"dest": "kafka_topic",
"metavar": "SENZING_KAFKA_TOPIC",
"help": "Kafka topic. Default: senzing-kafka-topic"
},
},
"rabbitmq": {
"--rabbitmq-host": {
"dest": "rabbitmq_host",
"metavar": "SENZING_RABBITMQ_HOST",
"help": "RabbitMQ host. Default: localhost"
},
"--rabbitmq-port": {
"dest": "rabbitmq_port",
"metavar": "SENZING_RABBITMQ_PORT",
"help": "RabbitMQ port. Default: 5672"
},
"--rabbitmq-queue": {
"dest": "rabbitmq_queue",
"metavar": "SENZING_RABBITMQ_QUEUE",
"help": "RabbitMQ queue. Default: senzing-rabbitmq-queue"
},
"--rabbitmq-routing-key": {
"dest": "rabbitmq_routing_key",
"metavar": "SENZING_RABBITMQ_ROUTING_KEY",
"help": "RabbitMQ routing key. Default: senzing.records"
},
"--rabbitmq-username": {
"dest": "rabbitmq_username",
"metavar": "SENZING_RABBITMQ_USERNAME",
"help": "RabbitMQ username. Default: user"
},
"--rabbitmq-password": {
"dest": "rabbitmq_password",
"metavar": "SENZING_RABBITMQ_PASSWORD",
"help": "RabbitMQ password. Default: bitnami"
},
"--rabbitmq-exchange": {
"dest": "rabbitmq_exchange",
"metavar": "SENZING_RABBITMQ_EXCHANGE",
"help": "RabbitMQ exchange name. Default: empty string"
},
"--rabbitmq-use-existing-entities": {
"dest": "rabbitmq_use_existing_entities",
"metavar": "SENZING_RABBITMQ_USE_EXISTING_ENTITIES",
"help": "Connect to an existing exchange and queue using their settings. An error is thrown if the exchange or queue does not exist. If False, it will create the exchange and queue if they do not exist. If they exist, then it will attempt to connect, checking the settings match. Default: False"
},
"--rabbitmq-virtual-host": {
"dest": "rabbitmq_virtual_host",
"metavar": "SENZING_RABBITMQ_VIRTUAL_HOST",
"help": "RabbitMQ virtual host. Default: None, which will use the RabbitMQ defined default virtual host"
},
},
"transform": {
"--stream-loader-directive-action": {
"dest": "stream_loader_directive_action",
"metavar": "SENZING_STREAM_LOADER_DIRECTIVE_ACTION",
"help": "Directive value used in Senzing Stream-loader. Default: none"
},
"--stream-loader-directive-name": {
"dest": "stream_loader_directive_name",
"metavar": "SENZING_STREAM_LOADER_DIRECTIVE_NAME",
"help": "Directive key used in Senzing Stream-loader. Default: none"
},
},
"sqs": {
"--sqs-queue-url": {
"dest": "sqs_queue_url",
"metavar": "SENZING_SQS_QUEUE_URL",
"help": "AWS SQS URL. Default: none"
},
}
}
# Augment "subcommands" variable with arguments specified by aspects.
for subcommand, subcommand_value in subcommands.items():
if 'argument_aspects' in subcommand_value:
for aspect in subcommand_value['argument_aspects']:
if 'arguments' not in subcommands[subcommand]:
subcommands[subcommand]['arguments'] = {}
arguments = argument_aspects.get(aspect, {})
for argument, argument_value in arguments.items():
subcommands[subcommand]['arguments'][argument] = argument_value
# Parse command line arguments.
parser = argparse.ArgumentParser(
prog="stream-producer.py", description="Queue messages. For more information, see https://github.com/Senzing/stream-producer")
subparsers = parser.add_subparsers(
dest='subcommand', help='Subcommands (SENZING_SUBCOMMAND):')
for subcommand_key, subcommand_values in subcommands.items():
subcommand_help = subcommand_values.get('help', "")
subcommand_arguments = subcommand_values.get('arguments', {})
subparser = subparsers.add_parser(subcommand_key, help=subcommand_help)
for argument_key, argument_values in subcommand_arguments.items():
subparser.add_argument(argument_key, **argument_values)
return parser
# -----------------------------------------------------------------------------
# Message handling
# -----------------------------------------------------------------------------
# 1xx Informational (i.e. logging.info())
# 3xx Warning (i.e. logging.warning())
# 5xx User configuration issues (either logging.warning() or logging.err() for Client errors)
# 7xx Internal error (i.e. logging.error for Server errors)
# 9xx Debugging (i.e. logging.debug())
MESSAGE_INFO = 100
MESSAGE_WARN = 300
MESSAGE_ERROR = 700
MESSAGE_DEBUG = 900
message_dictionary = {
"100": "senzing-" + SENZING_PRODUCT_ID + "{0:04d}I",
"103": "Kafka topic: {0}; message: {1}; error: {2}; error: {3}",
"104": "Thread: {0} Records sent to queue: {1}",
"120": "Sleeping for requested delay of {0} seconds.",
"125": "Processing file: {0}.",
"127": "Monitor: {0}",
"129": "{0} is running.",
"130": "{0} has exited.",
"180": "User-supplied Governor loaded from {0}.",
"181": "Monitoring halted. No active workers.",
"292": "Configuration change detected. Old: {0} New: {1}",
"293": "For information on warnings and errors, see https://github.com/Senzing/stream-loader#errors",
"294": "Version: {0} Updated: {1}",
"295": "Sleeping infinitely.",
"296": "Sleeping {0} seconds.",
"297": "Enter {0}",
"298": "Exit {0}",
"299": "{0}",
"300": "senzing-" + SENZING_PRODUCT_ID + "{0:04d}W",
"310": "Did not send record identified by {0}: {1}. Exceeds SENZING_RECORD_SIZE_MAX by {2} bytes.",
"311": "Did not send record identified by {0}: {1}. Exceeds queue message size limit by {2} bytes.",
"312": "Did not send record because it exceeds queue message size limit of {2} by {1} bytes. It does not have a {0} identifier",
"404": "Buffer error: {0} for line #{1} '{2}'.",
"405": "Kafka error: {0} for line #{1} '{2}'.",
"406": "Not implemented error: {0} for line #{1} '{2}'.",
"407": "Unknown kafka error: {0} for line #{1} '{2}'.",
"408": "Kafka topic: {0}; message: {1}; error: {2}; error: {3}",
"410": "Unknown RabbitMQ error when connecting: {0}.",
"411": "Unknown RabbitMQ error when adding record to queue: {0} for line {1}.",
"412": "Could not connect to RabbitMQ host at {1}. The host name maybe wrong, it may not be ready, or your credentials are incorrect. See the RabbitMQ log for more details.",
"413": "The exchange {0} and/or the queue {1} do not exist. Create them, or set rabbitmq-use-existing-entities to False to have stream-producer create them.",
"414": "The exchange {0} and/or the queue {1} exist but are configured with unexpected parameters. Set rabbitmq-use-existing-entities to True to connect to the preconfigured exchange and queue, or delete the existing exchange and queue and try again.",
"499": "{0}",
"500": "senzing-" + SENZING_PRODUCT_ID + "{0:04d}E",
"695": "Unknown database scheme '{0}' in database url '{1}'",
"696": "Bad SENZING_SUBCOMMAND: {0}.",
"697": "No processing done.",
"698": "Program terminated with error.",
"699": "{0}",
"700": "senzing-" + SENZING_PRODUCT_ID + "{0:04d}E",
"721": "Running low on workers. May need to restart",
"750": "Invalid SQS URL config for {0}",
"885": "License has expired.",
"886": "G2Engine.addRecord() bad return code: {0}; JSON: {1}",
"888": "G2Engine.addRecord() G2ModuleNotInitialized: {0}; JSON: {1}",
"889": "G2Engine.addRecord() G2ModuleGenericException: {0}; JSON: {1}",
"890": "G2Engine.addRecord() Exception: {0}; JSON: {1}",
"891": "Original and new database URLs do not match. Original URL: {0}; Reconstructed URL: {1}",
"892": "Could not initialize G2Product with '{0}'. Error: {1}",
"893": "Could not initialize G2Hasher with '{0}'. Error: {1}",
"894": "Could not initialize G2Diagnostic with '{0}'. Error: {1}",
"895": "Could not initialize G2Audit with '{0}'. Error: {1}",
"896": "Could not initialize G2ConfigMgr with '{0}'. Error: {1}",
"897": "Could not initialize G2Config with '{0}'. Error: {1}",
"898": "Could not initialize G2Engine with '{0}'. Error: {1}",
"899": "{0}",
"900": "senzing-" + SENZING_PRODUCT_ID + "{0:04d}D",
"902": "Thread: {0} Added message to internal queue: {1}",
"995": "Thread: {0} Using Class: {1}",
"996": "Thread: {0} Using Mixin: {1}",
"997": "Thread: {0} Using Thread: {1}",
"998": "Debugging enabled.",
"999": "{0}",
}
def message(index, *args):
index_string = str(index)
template = message_dictionary.get(
index_string, "No message for index {0}.".format(index_string))
return template.format(*args)
def message_generic(generic_index, index, *args):
return "{0} {1}".format(message(generic_index, index), message(index, *args))
def message_info(index, *args):
return message_generic(MESSAGE_INFO, index, *args)
def message_warning(index, *args):
return message_generic(MESSAGE_WARN, index, *args)
def message_error(index, *args):
return message_generic(MESSAGE_ERROR, index, *args)
def message_debug(index, *args):
return message_generic(MESSAGE_DEBUG, index, *args)
def get_exception():
''' Get details about an exception. '''
exception_type, exception_object, traceback = sys.exc_info()
frame = traceback.tb_frame
line_number = traceback.tb_lineno
filename = frame.f_code.co_filename
linecache.checkcache(filename)
line = linecache.getline(filename, line_number, frame.f_globals)
return {
"filename": filename,
"line_number": line_number,
"line": line.strip(),
"exception": exception_object,
"type": exception_type,
"traceback": traceback,
}
# -----------------------------------------------------------------------------
# Configuration
# -----------------------------------------------------------------------------
def get_configuration(args):
''' Order of precedence: CLI, OS environment variables, INI file, default. '''
result = {}
# Copy default values into configuration dictionary.
for key, value in list(configuration_locator.items()):
result[key] = value.get('default', None)
# "Prime the pump" with command line args. This will be done again as the last step.
for key, value in list(args.__dict__.items()):
new_key = key.format(subcommand.replace('-', '_'))
if value:
result[new_key] = value
# Copy OS environment variables into configuration dictionary.
for key, value in list(configuration_locator.items()):
os_env_var = value.get('env', None)
if os_env_var:
os_env_value = os.getenv(os_env_var, None)
if os_env_value:
result[key] = os_env_value
# Copy 'args' into configuration dictionary.
for key, value in list(args.__dict__.items()):
new_key = key.format(subcommand.replace('-', '_'))
if value:
result[new_key] = value
# Add program information.
result['program_version'] = __version__
result['program_updated'] = __updated__
# Special case: subcommand from command-line
if args.subcommand:
result['subcommand'] = args.subcommand
# Special case: Change boolean strings to booleans.
booleans = [
'debug',
'rabbitmq_use_existing_entities',
]
for boolean in booleans:
boolean_value = result.get(boolean)
if isinstance(boolean_value, str):
boolean_value_lower_case = boolean_value.lower()
if boolean_value_lower_case in ['true', '1', 't', 'y', 'yes']:
result[boolean] = True
else:
result[boolean] = False
# Special case: Change integer strings to integers.
integers = [
'csv_rows_in_chunk',
'delay_in_seconds',
'kafka_poll_interval',
'monitoring_period_in_seconds',
'read_queue_maxsize',
'record_max',
'record_min',
'record_size_max',
'record_monitor',
'sleep_time_in_seconds',
'sqs_delay_seconds',
'threads_per_print',
'records_per_message'
]
for integer in integers:
integer_string = result.get(integer)
if integer_string:
result[integer] = int(integer_string)
# Initialize counters.
counters = [
'input_counter',
'output_counter',
'output_counter_reported',
]
for counter in counters:
result[counter] = 0
# Normalize SENZING_INPUT_URL
if result.get('input_url', "").startswith("file://"):
result['input_url'] = result.get('input_url')[7:]
return result
def validate_configuration(config):
''' Check aggregate configuration from commandline options, environment variables, config files, and defaults. '''
user_warning_messages = []
user_error_messages = []
# Perform subcommand specific checking.
subcommand = config.get('subcommand')
if subcommand in ['task1']:
if not config.get('example'):
user_error_messages.append(message_error(414))
# Log warning messages.
for user_warning_message in user_warning_messages:
logging.warning(user_warning_message)
# Log error messages.
for user_error_message in user_error_messages:
logging.error(user_error_message)
# Log where to go for help.
if len(user_warning_messages) > 0 or len(user_error_messages) > 0:
logging.info(message_info(293))
# If there are error messages, exit.
if len(user_error_messages) > 0:
exit_error(697)
def redact_configuration(config):
''' Return a shallow copy of config with certain keys removed. '''
result = config.copy()
for key in keys_to_redact:
try:
result.pop(key)
except Exception:
pass
return result
# -----------------------------------------------------------------------------
# Class: Governor
# -----------------------------------------------------------------------------
class Governor:
def __init__(self, g2_engine=None, hint=None, *args, **kwargs):
self.g2_engine = g2_engine
self.hint = hint
def govern(self, *args, **kwargs):
return
def close(self):
return
def __enter__(self):
return self
def __exit__(self, exception_type, exception_value, exception_traceback):
self.close()
# -----------------------------------------------------------------------------
# Utility functions
# -----------------------------------------------------------------------------
def bootstrap_signal_handler(signal, frame):
sys.exit(0)
def create_signal_handler_function(args):
''' Tricky code. Uses currying technique. Create a function for signal handling.
that knows about "args".
'''
def result_function(signal_number, frame):
logging.info(message_info(298, args))
sys.exit(0)
return result_function
def delay(config):
delay_in_seconds = config.get('delay_in_seconds')
if delay_in_seconds > 0:
logging.info(message_info(120, delay_in_seconds))
time.sleep(delay_in_seconds)
def entry_template(config):
''' Format of entry message. '''
debug = config.get("debug", False)
config['start_time'] = time.time()
if debug:
final_config = config
else:
final_config = redact_configuration(config)
config_json = json.dumps(final_config, sort_keys=True)
return message_info(297, config_json)
def exit_template(config):
''' Format of exit message. '''
debug = config.get("debug", False)
stop_time = time.time()
config['stop_time'] = stop_time
config['elapsed_time'] = stop_time - config.get('start_time', stop_time)
config['rate'] = int(config.get('output_counter', 0) /
config.get('elapsed_time', 1))
if debug:
final_config = config
else:
final_config = redact_configuration(config)
config_json = json.dumps(final_config, sort_keys=True)
return message_info(298, config_json)
def exit_error(index, *args):
''' Log error message and exit program. '''
logging.error(message_error(index, *args))
logging.error(message_error(698))
logging.shutdown()
os._exit(1)
def exit_silently():
''' Exit program. '''
sys.exit(0)
# -----------------------------------------------------------------------------
# Class: MonitorThread
# -----------------------------------------------------------------------------
class MonitorThread(threading.Thread):
'''
Periodically log operational metrics.
'''
def __init__(self, config=None, workers=None):
threading.Thread.__init__(self)
self.config = config
self.workers = workers
self.record_min = config.get('record_min', 0)
if self.record_min is None:
self.record_min = 0
def run(self):
'''Periodically monitor what is happening.'''
# Show that thread is starting in the log.
logging.info(message_info(129, threading.current_thread().name))
# Initialize variables.
last = {
"input_counter": 0,
"output_counter": 0,
}
# Define monitoring report interval.
sleep_time_in_seconds = self.config.get('monitoring_period_in_seconds')
# Sleep-monitor loop.
active_workers = len(self.workers)