/
spark-streaming-kafka-bucket-counter.py
467 lines (380 loc) · 12.9 KB
/
spark-streaming-kafka-bucket-counter.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
#
# 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.
#
import sys
from pyspark import SparkContext, AccumulatorParam
from pyspark.streaming import StreamingContext
from pyspark.streaming.kafka import KafkaUtils
from multiprocessing import Process, Queue
from kafka import SimpleProducer, KafkaClient
from audit_utils.utils import json_file_to_dict, avro_decoder_func, json_dict_bucket_parse, open_or_none, read_config_file, json_to_dict
from audit_utils.models import RecentArrayDumpTable, Switch, RecentSqlite3table
from audit_utils.http_endpoint import setup_site_RADT, set_site_sqlite
from flask import Flask
CONFIG_TYPES = {
'KafkaSettings': {
'broker': str,
'topic': str,
'avro_val_schema': str,
},
'MsgSettings': {
'bucket_interval': int,
'bucket_field': str,
'msg_map_schema': str,
'bucket_type': str,
},
'HTTPEndpointSetting': {
'sqlite_schema': str,
'sqlite_db': str,
'sqlite_table': str,
'0': int,
'clean_freq': int,
},
}
DEFAULT_CONFIG = {
'KafkaSettings': {
'broker': 'localhost:2181',
'topic': 'logstash-test',
'avro_val_schema': None,
},
'MsgSettings': {
'bucket_interval': 20,
'bucket_field': None,
'msg_map_schema': None,
'bucket_type': 'epoch',
},
'HTTPEndpointSetting': {
'sqlite_schema': None,
'sqlite_db': ':memory:',
'sqlite_table': 'default',
'clean_interval': 100,
'clean_freq': 10,
},
}
class AccumDict(AccumulatorParam):
"""An Spark Accumulator used to keep track of
"""
def zero(self, initialValue):
"""A zero dict should just have no entries
"""
return {}
def addInPlace(self, v1, v2):
for key in v2:
if key not in v1:
v1[key] = 0
v1[key] += v2[key]
return v1
def ss_kafka_bucket_counter(broker, topic, bucket_interval, output_msg,
message_parse, valueDecoder=None):
"""Starts a Spark Streaming job from a Kafka input and parses message time
Args:
broker: the kafka broker that we look at for the topic
topic: the kafka topic for input
bucket_interval: the time interval in seconds (int) that the job will
bucket
output_msg: a function that takes in a spark SparkContext (sc) and
StreamingContext (ssc) and returns a function that takes a rdd that
performs the output task
message_parse: how the message is to be parsed
valueDecoder: same as Spark's valueDecoder
Returns:
None
"""
sc = SparkContext(appName="PythonKafkaBucketCounter")
ssc = StreamingContext(sc, bucket_interval + 5)
if valueDecoder:
kvs = KafkaUtils.createStream(
ssc, broker, "spark-streaming-consumer", {topic: 1},
valueDecoder=valueDecoder
)
else:
kvs = KafkaUtils.createStream(
ssc, broker, "spark-streaming-consumer", {topic: 1},
)
# I assume that we do not store kafka keys
lines = kvs.map(lambda x: x[1])
interval_counts = (lines.map(lambda line: (message_parse(line), 1))
.reduceByKey(lambda a, b: a+b))
output_msg_func = output_msg(sc, ssc)
interval_counts.foreachRDD(output_msg_func)
ssc.start()
ssc.awaitTermination()
def ss_direct_kafka_bucket_counter(brokers, topic, bucket_interval,
output_msg, message_parse, valueDecoder=None):
"""Starts a Spark Streaming job from a Kafka input and parses message time
WARNING!! This function only works for spark 1.4.0+
Args:
brokers: the kafka broker that we look at for the topic
topic: the kafka topic for input
timeinterval: the time interval in seconds (int) that the job will
bucket
Returns:
None
"""
sc = SparkContext(appName="PythonKafkaBucketCounter")
ssc = StreamingContext(sc, timeinterval + 5)
if valueDecoder:
kvs = KafkaUtils.createDirectStream(
ssc, [topic], {"metadata.broker.list": brokers},
valueDecoder=valueDecoder
)
else:
kvs = KafkaUtils.createDirectStream(
ssc, [topic], {"metadata.broker.list": brokers}
)
lines = kvs.map(lambda x: x[1])
interval_counts = (lines.map(lambda line: (message_parse(line), 1))
.reduceByKey(lambda a, b: a+b))
output_msg_func = output_msg(sc, ssc)
interval_counts.foreachRDD(output_msg_func)
ssc.start()
ssc.awaitTermination()
def combine_count_json(json_msg, count):
"""Adds the count as a counts field in the json_msg
Args:
json_msg: the string representation of the json msg
count: the count for the count field that we will add
Returns:
a json message with the counts appended to it
"""
return '{0}, "count": {1}'.format(json_msg[:-1], count) + '}'
def create_http_share_func(mp_queue):
"""Generates a func that consolidates all the data in a stream and puts it on a
queue
Args:
mp_queue: a queue that the function will write its consolidated data to
Returns:
A function that consolidates all the data in a stream and puts it on a
queue
"""
def wrapper(sc, scc):
"""The wrapper function
"""
accumOdd = sc.accumulator({}, AccumDict())
accumEven = sc.accumulator({}, AccumDict())
counter = Switch()
def share_msg(iters, accum):
"""What to do with each individual message
"""
for key, val in iters:
accum.add({key:val})
def per_rdd_do(rdd):
"""What to do with each rdd
"""
if counter.value:
to_use_accum = accumOdd
other_accum = accumEven
else:
to_use_accum = accumEven
other_accum = accumOdd
counter.switch()
share_msg_func = lambda iters: share_msg(iters, to_use_accum)
rdd.foreachPartition(share_msg_func)
#TODO: Make this into a generator
add_to_q = []
for key in to_use_accum.value:
val = to_use_accum.value[key]
json_dict = json_to_dict(combine_count_json(key, val))
add_to_q.append(json_dict)
mp_queue.put(add_to_q)
other_accum.value.clear()
return per_rdd_do
return wrapper
def kafka_http_sqlite(broker, topic, bucket_interval, conversion_dict,
bucket_field, bucket_type, avro_schema, sqlite_schema, db, table_name,
clean_interval, clean_freq_interval):
"""Generates a func that writes the inputed values to a datastructure that
the HTTP
Args:
broker: the broker (str) for the kafka topic (bellow)
topic: Kafka topic (str) for the spark streaming job to listen to
bucket_interval: an int of how frequent the spark streaming batch job
should run
Returns:
A function that will populate the RecentArrayDumpTable given an iter
"""
q = Queue()
http_func = create_http_share_func(q)
message_parse = lambda json_str: json_dict_bucket_parse(
json_str, conversion_dict, bucket_field, bucket_interval, bucket_type
)
if avro_schema:
value_decoder = avro_decoder_func(avro_schema)
else:
value_decoder = None
s = lambda: ss_kafka_bucket_counter(
broker, topic, bucket_interval, http_func, message_parse,
valueDecoder=value_decoder
)
spark_streaming = Process(target=s)
app = Flask(__name__)
set_site_sqlite(app, q, sqlite_schema, db=db, table_name=table_name,
clean_interval=clean_interval, clean_freq_interval=clean_freq_interval
)
h = lambda: app.run(debug=False)
http = Process(target=h)
http.start()
spark_streaming.start()
http.join()
spark_streaming.join()
def read_KHS_config_file(config_file_path):
"""Reads a Kafka bucket counter HTTP Service config file and outputs all the
params from the config_file
"""
config = read_config_file(config_file_path, DEFAULT_CONFIG)
for header in CONFIG_TYPES:
for key in CONFIG_TYPES[header]:
cast = CONFIG_TYPES[header][key]
if config[header][key]:
config[header][key] = cast(config[header][key])
broker = config['KafkaSettings']['broker']
topic = config['KafkaSettings']['topic']
bucket_interval = config['MsgSettings']['bucket_interval']
bucket_field = config['MsgSettings']['bucket_field']
bucket_type = config['MsgSettings']['bucket_type']
db = config['HTTPEndpointSetting']['sqlite_db']
table_name = config['HTTPEndpointSetting']['sqlite_table']
clean_interval = config['HTTPEndpointSetting']['clean_interval']
clean_freq_interval = config['HTTPEndpointSetting']['clean_freq']
conversion_dict = json_file_to_dict(config['MsgSettings']['msg_map_schema'])
avro_schema = open_or_none(config['KafkaSettings']['avro_val_schema'])
sqlite_schema = json_file_to_dict(
config['HTTPEndpointSetting']['sqlite_schema']
)
return (
broker, topic, bucket_interval, conversion_dict, bucket_field,
bucket_type, avro_schema, sqlite_schema, db, table_name, clean_interval,
clean_freq_interval
)
if __name__ == "__main__":
"""Main function
Usage: kafka_parse_message_time.py <config_file_path>
"""
if len(sys.argv) == 2:
config_file_path = sys.argv[1:]
kafka_http_sqlite(*read_KHS_config_file(config_file_path))
else:
print >> sys.stderr, ("kafka_parse_message_time.py <config_file_path>")
exit(-1)
#################################################################
##Trunk##########################################################
#################################################################
def create_send_kafka_msg_func(kafka_host, topic):
"""Generates the function that takes in a stream of messages and sends them
to the specified kafka sever/topic
Args:
kafka_host: the string of the kafka host location
topic: the string name of the topic in the kafka host that the msgs are
sent
Returns:
A function that can take a iter of messages and sends them to the
specified kafka server
"""
def send_kafka_msg(iters):
#TODO: Add try/catch statements for kafka connection
kafka = KafkaClient(kafka_host)
producer = SimpleProducer(kafka)
for key, val in iters:
msg = combine_count_json(key, val)
producer.send_messages(
str(topic).encode('utf-8'), str(msg).encode('utf-8')
)
kafka.close()
def per_rdd_do(rdd):
rdd.foreachPartition(send_kafka_msg)
return lambda sc, ssc: per_rdd_do
#####
import MySQLdb
def create_send_mysql_msg_func(mysql_host, mysql_usr, mysql_pwd, mysql_db,
mysql_parse):
"""Generates a function that takes in a stream of messages and sends thme to
to both a specified
Args:
mysql_host: the mysql host location (str)
mysql_usr: the user intended to write to the mysql database (str)
mysql_pwd: the pwd of the user for mysql (str)
mysql_db: the database in the mysql host intended to write to (str)
mysql_parse: a function that will parse the msgs into mysql exec
commands (func)
Returns:
A function that can take a iter of messages and sends them to the
specified mysql table
"""
def send_mysql_msg(iters):
db = MySQLdb.connect(host=mysql_host, user=mysql_usr,
passwd=mysql_pwd, db=mysql_db)
cursor = db.cursor()
for key, val in iters:
json_msg = combine_count_json(key, val)
cursor.execute(mysql_parse(json_msg))
db.commit()
db.close()
def per_rdd_do(rdd):
rdd.foreachPartition(send_mysql_msg)
return lambda sc, scc: per_rdd_do
def create_mysql_parse_func(schema):
"""Generates the mysql insert statement to update a database
Args:
schema: the schema in which to parse the msgs with. Is a dict that
follows the following format.
{
'table_name': 'tablename',
'dup_key_update': {
'column_val = column_val + {0}': 'column_name',
'column_val1 = column_val1 * {0}': 'column_name1',
...
},
'msg_map_schema': {
'mysql_column': 'corresponding_dict_field',
'mysql_column1': 'corresponding_dict_field1',
...
}
}
Returns:
The sql command that inserts the msg data into the database
Example:
>>> schema = {'table_name': 'tablename', 'dup_key_update': {
... 'column_val = column_val + {0}': 'column_name',
... 'column_val1 = column_val1 * {0}': 'column_name1'
... },
... 'msg_map_schema': {
... 'mysql_column': 'corresponding_dict_field',
... 'mysql_column1': 'corresponding_dict_field1',
... }
... }
>>> f = create_mysql_parse_func(schema)
>>> dict_msg = {
... 'column_name': 1,
... 'column_name1': 2,
... 'corresponding_dict_field': 3,
... 'corresponding_dict_field1': 4,
... }
>>> f(dict_msg)[:70]
'INSERT INTO tablename (mysql_column1,mysql_column) VALUES (4,3) ON DUP'
"""
sql_action = (
"INSERT INTO {0} ({1}) VALUES ({2}) ON DUPLICATE KEY UPDATE {3};"
)
table_name = schema['table_name']
dup_key_update = schema['dup_key_update']
msg_map = schema['msg_map_schema']
column_str = ','.join(key for key in msg_map)
def mysql_parse(dict_msg):
vals = ','.join(str(dict_msg[msg_map[key]]) for key in msg_map)
update = ','.join(key.format(dict_msg[dup_key_update[key]])
for key in dup_key_update)
return sql_action.format(table_name, column_str, vals, update)
return mysql_parse