-
Notifications
You must be signed in to change notification settings - Fork 6
/
sandwich_club.html
639 lines (566 loc) · 18.7 KB
/
sandwich_club.html
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
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=1024, user-scalable=no">
<title>Kafka, Storm, node.js and D3</title>
<!-- Required stylesheet -->
<link rel="stylesheet" href="core/deck.core.css">
<!-- Extension CSS files go here. Remove or add as needed. -->
<link rel="stylesheet" href="extensions/goto/deck.goto.css">
<link rel="stylesheet" href="extensions/menu/deck.menu.css">
<!-- <link rel="stylesheet" href="extensions/navigation/deck.navigation.css"> -->
<link rel="stylesheet" href="extensions/status/deck.status.css">
<link rel="stylesheet" href="extensions/hash/deck.hash.css">
<link rel="stylesheet" href="extensions/scale/deck.scale.css">
<!-- Style theme. More available in /themes/style/ or create your own. -->
<link rel="stylesheet" href="themes/style/swiss.css">
<!-- Transition theme. More available in /themes/transition/ or create your own. -->
<link rel="stylesheet" href="themes/transition/fade.css">
<link rel="stylesheet" href="prettify.css">
<!-- Required Modernizr file -->
<script src="modernizr.custom.js"></script>
<script src="prettify.js"></script>
</head>
<body class="deck-container">
<!-- Begin slides. Just make elements with a class of slide. -->
<section class="slide" id="intro">
<div>
<hgroup><h1>Kafka, Storm+Redis, Node and D3</h1><h2>LivePerson</h2></hgroup>
</div>
</section>
<section class="slide" id="intro">
<h2>The Stack</h2>
<ul>
<li><strong>Kafka</strong>. Data Motion.
<ul>
<li>Developed at LinkedIn to manage communication between services, replacing ActiveMQ</li>
<li>Simple producer/consumer model</li>
</ul></li>
<li><strong>Storm + Redis</strong>. Streaming Data Processing.
<ul>
<li>Developed by Backtype, acquired by Twitter.</li>
<li>Manages distributed computation.</li>
</ul></li>
<li><strong>node.js</strong>. Server-side Javascript.
<ul>
<li>The V8 engine that powers Chrome</li>
<li>Event-driven for high connection concurrency</li>
</ul></li>
<li><strong>D3</strong>. Data Driven Documents.
<ul>
<li>Manipulate document object models with data.</li>
<li>Focus on visualization</li>
<li>Many useful plugins</li>
</ul></li>
</ul>
</section>
<section class="slide">
<h2>Getting Started With Kafka</h2>
<ul>
<li><strong>Producers</strong> are application that produces messages on a <strong>topic</strong><ul>
<li>The current producer protocol is very simple with libraries for many languages</li>
<li>Kafka 0.8 introduces a more sophisticated producer protocol for applications that have strong delivery requiments</li>
<li>Snappy and GZIP compression is supported.</li>
</ul></li>
<li><strong>Topics</strong> are a collection of related messages.<ul>
<li>Topics are created on the fly by producers, no configuration required</li>
<li>Most organizations use a relatively small number of topics (< 100).</li>
</ul></li>
<li><strong>Brokers</strong> hold the data. Messages for each topic are split across each broker in a <strong>cluster</strong>.<ul>
<li>Messages are split evenly across each broker</li>
<li>Broker clusters can be mirrored and/or combined to manage multiple datacenter transfers.</li>
<li>Data is kept for a certain amount of <strong>time</strong> not space. Making sure there is enough disk space is an important part of Kafka maintenance</li>
</ul></li>
<li><strong>Consumers</strong> read data from the brokers.<ul>
<li>Because the reads are distributed, the read order will be different than the write ordering.</li>
<li>Uses an at-least-once semantic. You need to handle deduplication in your application logic</li>
</ul></li>
</ul>
</section>
<section class="slide" id="kafka">
<h2>Simple Producer</h2>
<pre class="prettyprint lang-js">
var X = require('node-xml')
, kafka = require('kafka');
var producer = new kafka.Producer({topic:'hamlet'}).connect(function() {
function send(i,line) {
setTimeout(function() {
line.TIMESTAMP = (new Date().getTime());
producer.send(JSON.stringify(line));
},1000*i + Math.floor(300*Math.random()));
}
var parser = new X.SaxParser(function(c) {
var i = 0;
var line = {};
var field = [];
c.onStartElementNS(function(e) {
field.push(e);
switch(e) {
case 'SPEECH':
line = {};
break;
}
});
c.onEndElementNS(function(e) {
field.pop();
switch(e) {
case 'SPEECH':
delete line['SPEECH'];
delete line['SCENE'];
send(i++,line);
break;
}
});
c.onCharacters(function(e) {
line[field[field.length-1]] = (line[field[field.length-1]]||"") + e;
});
});
parser.parseFile("hamlet.xml");
});
</pre>
</section>
<section class="slide">
<h2>Simple Consumer</h2>
<pre class="prettyprint">
var http = require('http')
, connect = require('connect')
, kafka = require('kafka');
function consumer(req,res) {
console.log("Subscribing to topic");
req.socket.setTimeout(Infinity);
res.writeHead(200,{
'Content-Type':'text/event-stream',
'Cache-Control':'no-cache',
'Connection':'keepalive'
});
res.message = function(msg,event) {
if(event)
res.write('event: '+event+'\n');
res.write('data: '+msg+'\n\n');
}
res.json = function(obj,event) {
this.message(JSON.stringify(obj),event);
};
var consumer = new kafka.Consumer()
.on('message',function(topic,message,offset) {
res.message(message);
})
.on('lastmessage',function(topic,offset) {
consumer.fetchTopic({name:topic,offset:offset});
})
.on('lastoffset',function(topic,offset) {
consumer.fetchTopic({name:topic,offset:offset});
})
.connect(function() {
console.log("connected");
consumer.fetchOffsets('hamlet');
});
}</pre>
</section>
<section class="slide">
<h2>Simple Front-End</h2>
<pre class="prettyprint">
$(function() {
var stream = new EventSource("/consumer");
stream.addEventListener("message",function(e) {
var data = e.data;
try{
data = JSON.parse(data);
if(data.SPEAKER && data.LINE) {
$('#timestamp').html(""+(new Date(data.TIMESTAMP)));
$('#speaker').html(data.SPEAKER);
$('#line').html(data.LINE);
}
} catch(e) { console.log(e); }
});
});
</pre>
</section>
<section class="slide">
<h2>Kafka Producer Output</h2>
<h3><strong>Time:</strong> <span id="timestamp"></span></h3>
<h3><strong>Speaker:</strong> <span id="speaker"></span></h3>
<h3><strong>Line:</strong> <span id="line"></span></h3>
</section>
<section class="slide">
<h1>Doing Things With Data: Storm</h1>
</section>
<section class="slide" id="storm">
<h2>Storm</h2>
<ul>
<li>A platform for managing a collection of processing steps for streaming data.<ul>
<li>Inputs are called <strong>Spouts</strong></li>
<li>Processors are called <strong>Bolts</strong></li>
<li>Data is transferred between <strong>spouts</strong> and <strong>bolts</strong> using <strong>tuples</strong>.</li>
<li>A group of <strong>spouts</strong> and <strong>bolts</strong> are called a <strong>topology</strong>.
</ul></li>
<li>Let's make a topology<ol>
<li>Read data from Kafka using a <strong>Kafka Spout</strong></li>
<li>Parse the input JSON into a structured <strong>tuple</strong></li>
<li>Count the frequency of each word used</li>
<li>Track the activity of different speakers</li>
<li>Store this data in Redis so we can render it on our front-end</li>
</ol></li>
</ul>
</section>
<section class="slide">
<h2>Configure the Kafka Spout</h2>
<pre class="prettyprint lang-js">
public static void main(String[] args) throws Exception {
LOG.info("Starting topology");
if(args.length < 4) {
System.out.println("usage: <kafka brokers> <partitions> <topic> <redis master>");
System.exit(1);
}
TopologyBuilder builder = new TopologyBuilder();
builder.setSpout("spout", Kafka.spoutFromArgs(args, "/demo-topology", "v1",args.length > 4 && "true".equals(args[4])));
</pre>
</section>
<section class="slide">
<h2>Configuring the Spout</h2>
<pre class="prettyprint lang-js">
public static KafkaSpout spoutFromArgs(String[] args,String offsetPath,String consumerId,boolean force) {
ArrayList<String> hosts = new ArrayList<String>();
for(String s : args[0].split(","))
hosts.add(s);
int partitions = Integer.parseInt(args[1]);
SpoutConfig kafkaConfig = new SpoutConfig(
KafkaConfig.StaticHosts.fromHostString(hosts, partitions),
args[2],
offsetPath,
consumerId);
if(force)
kafkaConfig.forceStartOffsetTime(-1);
kafkaConfig.bufferSizeBytes = 1024*1024;
kafkaConfig.fetchSizeBytes = 1024*1024;
kafkaConfig.scheme = new StringScheme();
return new KafkaSpout(kafkaConfig);
}
</pre>
</section>
<section class="slide">
<h2>Attach the Bolts</h2>
<pre class="prettyprint">
public TopologyBuilder configure(TopologyBuilder builder) {
builder.setBolt("events", new EventParserBolt())
.shuffleGrouping("spout");
builder.setBolt("tokenize", new WordTokenBolt().redis(redisUrl))
.shuffleGrouping("events","lines");
builder.setBolt("speaker", new SpeakerTranscriptBolt().redis(redisUrl))
.fieldsGrouping("events", "lines",new Fields("speaker"));
return builder;
}
</pre>
</section>
<section class="slide">
<h2>Word Tokenizing</h2>
<pre class="prettyprint">
public void execute(Tuple input) {
try {
String line = input.getStringByField("line");
long timestamp = input.getLongByField("timestamp");
for(String word : line.replaceAll("\\p{Punct}|\\d"," ").toLowerCase().split("\\s+")) {
conn.zadd("Word:"+word, timestamp,""+timestamp);
synchronized(updated) {
updated.add(word);
}
}
} catch(Exception e) {
collector.reportError(e);
} finally {
collector.ack(input);
}
}
</pre>
</section>
<section class="slide">
<h2>Background Word Events</h2>
<pre class="prettyprint">
updateTimer = new Timer("Word Tokenizer Updater");
updateTimer.schedule(new TimerTask() {
@Override
public void run() {
long time = System.currentTimeMillis()/1000;
long segment = (time % 86400)/60;
HashSet<String> toUpdate;
synchronized(updated) {
toUpdate = updated;
updated = new HashSet<String>();
}
for(String word : toUpdate) {
long size = conn.zcard("Word:"+word);
conn.hset("WordCount", word, ""+size);
conn.hset("WordCount:"+segment, word, ""+size);
}
conn.publish("WordCount",""+toUpdate.size());
}
}, 1000, 1000);
</pre>
</section>
<section class="slide">
<h1>Visualizing the Output</h1>
</section>
<section class="slide">
<h2>D3 Introduction</h2>
<ul>
<li>Uses selections in a way similar to jQuery:
<pre class="prettyprint">$('span.word');</pre>
<pre class="prettyprint">d3.select('body').selectAll('span.word');</pre>
</li>
<li>With the addition of data binding
<pre class="prettyprint">
var words = ['one','two','three','four','five'];
var w = d3.select('div#test').selectAll('span.word').data(words);
</pre>
</li>
<li>New elements are created using "enter()"
<pre class="prettyprint">w.enter().append("span").attr("class","word").text(function(d) { return d; })</pre></li>
<li>Deleted elements are removed using "exit()"
<pre class="prettyprint">w.exit().remove();</pre></li>
<li>Updated elements are simply updated
<pre class="prettyprint">w.text(function(d) { return d; });</pre></li>
</ul>
</section>
<section class="slide">
<h2>Creating new Elements</h2>
<div id="create-new-table" style="width: 700px;height: 350px;margin-left: auto;margin-right: auto;"></div>
<input type="button" id="start-create" value="Toggle"/>
</section>
<section class="slide">
<h2>The Code</h2>
<pre class="prettyprint">
$('#start-create').bind('click',function() {
if(!timeout) {
var data = [];
var i = 0;
var svg = d3.select('#create-new-table').append('svg').attr({width: 700,height: 350});
timeout = setInterval(function() {
data.push({name:i++,x:700*Math.random(),y:350*Math.random(),r:30*Math.random()});
svg.selectAll('circle.event').data(data).enter()
.append('circle')
.style({stroke:"#000",fill:"#ccc"})
.attr({
r:function(d) { return d.r; },
cx:function(d) { return d.x; },
cy:function(d) { return d.y; },
}).text(function(d) { return d.name;}).transition().attr({opacity:1});
},500);
} else clearInterval(timeout);
});
});
</pre>
</section>
<section class="slide">
<h2>Modify Elements</h2>
<div id="modify-new-table" style="width: 700px;height: 350px;margin-left: auto;margin-right: auto;"></div>
<input type="button" id="start-modify" value="Toggle"/>
</section>
<section class="slide">
<h2>Modifying Elements</h2>
<pre class="prettyprint">
timeout = setInterval(function() {
for(var i in data) {
data[i].x = 700*Math.random();
data[i].y = 350*Math.random();
data[i].r = 30*Math.random();
}
svg.selectAll('circle.event').data(data).transition().attr({
r:function(d) { return d.r; },
cx:function(d) { return d.x; },
cy:function(d) { return d.y; },
});
},500);
</pre>
</section>
<section class="slide">
<h2>Connecting the Server</h2>
<pre class="prettyprint">
var http = require('http')
, connect = require('connect')
, kafka = require('kafka')
, pubsub = require('redis').createClient()
, redis = require('redis').createClient();
var subs = {};
pubsub.on('message',function(channel,message) {
if(subs[channel])
subs[channel](message);
});
function words(req,res) {
req.socket.setTimeout(Infinity);
res.writeHead(200,{
'Content-Type':'text/event-stream',
'Cache-Control':'no-cache',
'Connection':'keepalive'
});
res.message = function(msg,event) {
if(event)
res.write('event: '+event+'\n');
res.write('data: '+msg+'\n\n');
}
res.json = function(obj,event) {
this.message(JSON.stringify(obj),event);
};
redis.hgetall("WordCount",function(err,data) {
if(data != null)
res.json(dict(data));
subs['WordCount'] = function(message) {
console.log("update");
redis.hgetall("WordCount",function(err,data) {
if(data != null)
res.json(dict(data));
});
};
pubsub.subscribe("WordCount");
});
}
</pre>
</section>
<section class="slide">
<h2>Rendering a Word Cloud</h2>
<div style="margin-left: auto;margin-right: auto;" id="words"></div>
</section>
<section class="slide">
<h2>Rendering the Cloud</h2>
<pre class="prettyprint">
(function($) {
var words = d3.select('div#words').append("svg").attr({width: 700,height:300}).append("g").attr({transform:"translate(350,150)"});
var layout = d3.layout.cloud()
.size([700,300])
.rotate(0)
.font('Helvetica')
.fontSize(function(d) { return d.size; })
.on("end",function(data) {
var w = words.selectAll("text.word").data(data,function(d) { return d.text; })
w.enter().append("text").attr("class","word").style({
"font-size":function(d) { return d.size+"px"; },
})
.attr("transform",function(d) { return "translate("+[d.x,d.y]+")rotate("+d.rotate+")"; })
.text(function(d) { return d.text; })
.on('click',function(d) {window.location = '/search?q='+d.text;});
w.transition()
.style("font-size",function(d) { return d.size+"px"; })
.attr("transform",function(d) { return "translate("+[d.x,d.y]+")rotate("+d.rotate+")"; });
w.exit().remove();
})
.start();
var stream = new EventSource("/words");
stream.addEventListener("message",function(e) {
var data = e.data;
try{
data = d3.entries(JSON.parse(data));
var max = d3.max(data,function(d) { return d.value; });
console.log(max);
layout.words(data.map(function(d) { return {text:d.key,size:10+45*d.value/max }})).start();
} catch(e) { console.log(e); }
});
})(jQuery);
</pre>
</section?
<!-- End slides. -->
<!-- Begin extension snippets. Add or remove as needed. -->
<!-- deck.navigation snippet -->
<a href="#" class="deck-prev-link" title="Previous">←</a>
<a href="#" class="deck-next-link" title="Next">→</a>
<!-- deck.status snippet -->
<p class="deck-status">
<span class="deck-status-current"></span>
/
<span class="deck-status-total"></span>
</p>
<!-- deck.goto snippet -->
<form action="." method="get" class="goto-form">
<label for="goto-slide">Go to slide:</label>
<input type="text" name="slidenum" id="goto-slide" list="goto-datalist">
<datalist id="goto-datalist"></datalist>
<input type="submit" value="Go">
</form>
<!-- deck.hash snippet -->
<a href="." title="Permalink to this slide" class="deck-permalink">#</a>
<!-- End extension snippets. -->
<!-- Required JS files. -->
<script src="jquery-1.7.2.min.js"></script>
<script src="core/deck.core.js"></script>
<!-- Extension JS files. Add or remove as needed. -->
<script src="core/deck.core.js"></script>
<script src="extensions/hash/deck.hash.js"></script>
<script src="extensions/menu/deck.menu.js"></script>
<script src="extensions/goto/deck.goto.js"></script>
<script src="extensions/status/deck.status.js"></script>
<script src="extensions/navigation/deck.navigation.js"></script>
<script src="extensions/scale/deck.scale.js"></script>
<script src="d3.v3.js"></script>
<script src="d3.layout.cloud.js"></script>
<script src="consumer.js"></script>
<script src="wordcloud.js"></script>
<!-- Initialize the deck. You can put this in an external file if desired. -->
<script>
$(function() {
$.deck('.slide');
$('code[data-src]').each(function(i,x) {
var $x = $(x);
var url = $x.attr('data-src');
$.getScript(url);
});
prettyPrint();
});
$(function() {
var timeout;
$('#start-create').bind('click',function() {
if(!timeout) {
var data = [];
var i = 0;
var svg = d3.select('#create-new-table').append('svg').attr({width: 700,height: 350});
timeout = setInterval(function() {
data.push({name:i++,x:700*Math.random(),y:350*Math.random(),r:30*Math.random()});
svg.selectAll('circle.event').data(data).enter()
.append('circle')
.style({stroke:"#000",fill:"#ccc"})
.attr({
class:"event",
r:function(d) { return d.r; },
cx:function(d) { return d.x; },
cy:function(d) { return d.y; },
}).text(function(d) { return d.name;}).transition().attr({opacity:1});
},500);
} else clearInterval(timeout);
});
});
$(function() {
var timeout;
$('#start-modify').bind('click',function() {
var data = [];
for(var i=0;i<100;i++) {
data.push({name:i,x:700*Math.random(),y:350*Math.random(),r:30*Math.random()});
}
var svg = d3.select('#modify-new-table').append('svg').attr({width: 700,height: 350});
//Create the events
svg.selectAll('circle.event').data(data).enter()
.append('circle')
.style({stroke:"#000",fill:"#ccc"})
.attr({
class:"event",
r:function(d) { return d.r; },
cx:function(d) { return d.x; },
cy:function(d) { return d.y; },
}).text(function(d) { return d.name;});
if(!timeout)
timeout = setInterval(function() {
for(var i in data) {
data[i].x = 700*Math.random();
data[i].y = 350*Math.random();
data[i].r = 30*Math.random();
}
svg.selectAll('circle.event').data(data).transition().attr({
r:function(d) { return d.r; },
cx:function(d) { return d.x; },
cy:function(d) { return d.y; },
});
},500);
else clearInterval(timeout);
});
});
</script>
</body>
</html>