-
Notifications
You must be signed in to change notification settings - Fork 0
/
atom.xml
1463 lines (1141 loc) · 180 KB
/
atom.xml
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
<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
<title>Coding it my way</title>
<link href="http://madhur.co.in/atom.xml" rel="self"/>
<link href="http://madhur.co.in/blogindex.html/"/>
<updated>2017-04-30T21:34:27+05:30</updated>
<id>http://madhur.co.in/blogindex.html</id>
<author>
<name>Jitender Dev</name>
<email>[email protected]</email>
</author>
<entry>
<title>Handling stack traces in Elasticsearch Logstash Kibana (ELK)</title>
<link href="http://madhur.co.in/blog/2017/04/30/view-exceptions-in-elk.html"/>
<updated>2017-04-30T00:00:00+05:30</updated>
<id>id:/blog/2017/04/30/view-exceptions-in-elk</id>
<content type="html"><p>I use <a href="https://www.elastic.co/webinars/introduction-elk-stack">Elasticsearch Logstash Kibana (ELK)</a> stack for visualizing lot of things like Nginx logs, HaProxy logs etc.</p>
<p>I also ingest application logs into the ELK. One thing I have been looking to do is visualization of errors happening into the system. Surely, Nginx and Haproxy logs can give you visualization of 500 status codes but there are many cases where the status code is 2xx but the internal error in the system is logged.</p>
<p>Our most of the microservices are written in Java / Python / Node.js and so I am only concentrating on those. A typical java exception stack trace when logged looks like this:</p>
<figure class="highlight"><pre><code class="language-text" data-lang="text">Exception in thread "main" java.lang.NullPointerException
at com.example.myproject.Book.getTitle(Book.java:16)
at com.example.myproject.Author.getBookTitles(Author.java:25)
at com.example.myproject.Bootstrap.main(Bootstrap.java:14)</code></pre></figure>
<p>Normally, this will be ingested line by line in ELK stack, which breaks the entire message.</p>
<p>For entire stack trace to be ingested as a single message, we need to configure the <code>multiline</code> plugin either in <a href="https://www.elastic.co/products/logstash">Logstash</a> or <a href="https://www.elastic.co/products/beats/filebeat">Filebeat</a>.</p>
<p>I prefer to do this configuration in filebeat, here is how my typical configuration looks like:</p>
<figure class="highlight"><pre><code class="language-yaml" data-lang="yaml"><span class="na">filebeat</span><span class="pi">:</span>
<span class="na">tail_files</span><span class="pi">:</span> <span class="s">true</span>
<span class="na">prospectors</span><span class="pi">:</span>
<span class="pi">-</span>
<span class="na">paths</span><span class="pi">:</span>
<span class="pi">-</span> <span class="s">/var/log/example.log</span>
<span class="na">input_type</span><span class="pi">:</span> <span class="s">log</span>
<span class="na">document_type</span><span class="pi">:</span> <span class="s">log</span>
<span class="s">multiline.pattern</span><span class="pi">:</span> <span class="s1">'</span><span class="s">^[[:space:]]'</span>
<span class="s">multiline.negate</span><span class="pi">:</span> <span class="s">false</span>
<span class="s">multiline.match</span><span class="pi">:</span> <span class="s">after</span>
<span class="na">registry_file</span><span class="pi">:</span> <span class="s">/var/lib/filebeat/registry</span>
<span class="na">output</span><span class="pi">:</span>
<span class="na">logstash</span><span class="pi">:</span>
<span class="na">hosts</span><span class="pi">:</span> <span class="pi">[</span><span class="s2">"</span><span class="nv"> </span><span class="s">logstash_server</span><span class="nv"> </span><span class="s">"</span><span class="pi">]</span>
<span class="na">worker</span><span class="pi">:</span> <span class="s">4</span>
<span class="na">bulk_max_size </span><span class="pi">:</span> <span class="s">8192</span>
<span class="na">shipper</span><span class="pi">:</span>
<span class="na">logging</span><span class="pi">:</span>
<span class="na">files</span><span class="pi">:</span>
<span class="na">path</span><span class="pi">:</span> <span class="s">/var/log/filebeat</span>
<span class="na">rotateeverybytes</span><span class="pi">:</span> <span class="s">10485760</span> <span class="c1"># = 10MB</span>
<span class="na">level</span><span class="pi">:</span> <span class="s">info</span></code></pre></figure>
<p>The lines below in the configuration configures the multiline processing. i.e. If a line starts with series of spaces (as in the case of stack trace), it should be considered as a part of previous line.</p>
<figure class="highlight"><pre><code class="language-text" data-lang="text">multiline.pattern: '^[[:space:]]'
multiline.negate: false
multiline.match: after</code></pre></figure>
<p>Once, we configure the multiline, here is how our messages should look like:</p>
<p><img src="/images/stacktrace.png" alt=""></p>
<p>The next step is to parse this exception stacktrace and extract useful information like Exception class etc.</p>
<p>For this, we can use built in logstash parser <code>JAVASTACKTRACEPART</code></p>
<figure class="highlight"><pre><code class="language-text" data-lang="text">grok {
match =&gt; { "message" =&gt;[
"%{JAVASTACKTRACEPART}"
]
}
}</code></pre></figure>
<p>This will extract various useful fields like line no, class and method name from the exception stack trace.</p>
</content>
</entry>
<entry>
<title>Using curator to delete older elasticsearch indices</title>
<link href="http://madhur.co.in/blog/2017/04/09/usingcuratordeleteelasticindex.html"/>
<updated>2017-04-09T00:00:00+05:30</updated>
<id>id:/blog/2017/04/09/usingcuratordeleteelasticindex</id>
<content type="html"><p>We use <a href="https://www.elastic.co/webinars/introduction-elk-stack">ELK stack</a> heavily in our production systems for log aggregation and monitoring.</p>
<p>Our daily log size generated is aroudn 100GB. Since, we do not intend to keep the log files in ELK for more than a month, it becomes important that we delete those indices to free up disk space.</p>
<p>Fortunately, <a href="https://www.elastic.co/products/logstash">Logstash</a> creates a new index every day by default.</p>
<p>Thus, we can ask <a href="https://github.com/elastic/curator">Curator</a> to simply delete the indices x days old and which follow a particular naming pattern.</p>
<h3>Installing Curator</h3>
<p>Simple use <code>pip install elasticsearch-curator</code> to install Curator on your machine. I prefer to install it on the Elasticsearch machine itself.</p>
<h3>Configuring Curator</h3>
<p>Create a file <code>curator.yml</code> with following contents.</p>
<figure class="highlight"><pre><code class="language-yaml" data-lang="yaml"><span class="nn">---</span>
<span class="na">client</span><span class="pi">:</span>
<span class="na">hosts</span><span class="pi">:</span>
<span class="pi">-</span> <span class="s">127.0.0.1</span>
<span class="na">port</span><span class="pi">:</span> <span class="s">9200</span>
<span class="na">url_prefix</span><span class="pi">:</span>
<span class="na">use_ssl</span><span class="pi">:</span> <span class="s">False</span>
<span class="na">certificate</span><span class="pi">:</span>
<span class="na">client_cert</span><span class="pi">:</span>
<span class="na">client_key</span><span class="pi">:</span>
<span class="na">ssl_no_validate</span><span class="pi">:</span> <span class="s">False</span>
<span class="na">http_auth</span><span class="pi">:</span>
<span class="na">timeout</span><span class="pi">:</span> <span class="s">30</span>
<span class="na">master_only</span><span class="pi">:</span> <span class="s">False</span>
<span class="na">logging</span><span class="pi">:</span>
<span class="na">loglevel</span><span class="pi">:</span> <span class="s">INFO</span>
<span class="na">logfile</span><span class="pi">:</span>
<span class="na">logformat</span><span class="pi">:</span> <span class="s">default</span>
<span class="na">blacklist</span><span class="pi">:</span> <span class="pi">[</span><span class="s1">'</span><span class="s">elasticsearch'</span><span class="pi">,</span> <span class="s1">'</span><span class="s">urllib3'</span><span class="pi">]</span></code></pre></figure>
<p>Now, we need to define an action. i.e. What will curator do. There are many actions to choose from. Check the <a href="https://www.elastic.co/guide/en/elasticsearch/client/curator/current/actions.html">documentation</a> for more information</p>
<ul>
<li>Alias</li>
<li>Allocation</li>
<li>Close</li>
<li>Cluster Routing</li>
<li>Create Index</li>
<li>Delete Indices</li>
<li>Delete Snapshots</li>
<li>Open</li>
<li>forceMerge</li>
<li>Replicas</li>
<li>Restore</li>
<li>Snapshot</li>
</ul>
<p>For this dicussion, we will use <code>Delete Indices</code> as the action, since this is what we want to do.</p>
<p>Below is the sample action file <code>delete_indices.yml</code> , which will delete the logstash indices which are older than 10 days.</p>
<figure class="highlight"><pre><code class="language-yaml" data-lang="yaml"><span class="nn">---</span>
<span class="na">actions</span><span class="pi">:</span>
<span class="na">1</span><span class="pi">:</span>
<span class="na">action</span><span class="pi">:</span> <span class="s">delete_indices</span>
<span class="na">description</span><span class="pi">:</span> <span class="pi">&gt;-</span>
<span class="no">Delete indices older than 45 days (based on index name), for logstash-</span>
<span class="no">prefixed indices. Ignore the error if the filter does not result in an</span>
<span class="no">actionable list of indices (ignore_empty_list) and exit cleanly.</span>
<span class="no">options:</span>
<span class="no">ignore_empty_list: True</span>
<span class="no">timeout_override:</span>
<span class="no">continue_if_exception: False</span>
<span class="no">disable_action: False</span>
<span class="no">filters:</span>
<span class="no">- filtertype: pattern</span>
<span class="no">kind: prefix</span>
<span class="no">value: logstash-</span>
<span class="no">exclude:</span>
<span class="no">- filtertype: age</span>
<span class="no">source: name</span>
<span class="no">direction: older</span>
<span class="no">timestring: '%Y.%m.%d'</span>
<span class="no">unit: days</span>
<span class="no">unit_count: 10</span>
<span class="no">exclude:</span></code></pre></figure>
<p>To run this action, simple use the command </p>
<figure class="highlight"><pre><code class="language-text" data-lang="text">curator ./delete_index.yml --config ./curator.yml --dry-run
2017-04-09 17:27:46,075 INFO Preparing Action ID: 1, "delete_indices"
2017-04-09 17:27:46,080 INFO Trying Action ID: 1, "delete_indices": Delete indices older than 45 days (based on index name), for logstash- prefixed indices. Ignore the error if the filter does not result in an actionable list of indices (ignore_empty_list) and exit cleanly.
2017-04-09 17:27:46,538 INFO DRY-RUN MODE. No changes will be made.
2017-04-09 17:27:46,538 INFO (CLOSED) indices may be shown that may not be acted on by action "delete_indices".
2017-04-09 17:27:46,538 INFO Action ID: 1, "delete_indices" completed.
2017-04-09 17:27:46,538 INFO Job completed.</code></pre></figure>
<p>The <code>--dry-run</code> mode will not actually delete the index. It can be used to test the output of the action.</p>
<p>If you want to schedule it in a cron, you can do so using <code>crontab -e</code></p>
<figure class="highlight"><pre><code class="language-text" data-lang="text">00 8 * * * root curator /path/delete_index.yml --config /path/curator.yml </code></pre></figure>
<p>The above configuration will cleanup the indices older than 10 days everyday at 8 AM.</p>
</content>
</entry>
<entry>
<title>Angular2 Confirmation Dialog component</title>
<link href="http://madhur.co.in/blog/2017/03/26/angular-confirmation-dialog.html"/>
<updated>2017-03-26T00:00:00+05:30</updated>
<id>id:/blog/2017/03/26/angular-confirmation-dialog</id>
<content type="html"><p>Recently, I have been working on Angular2 quite a lot. We had a requirement to come up with a reusable confirmation dialog component. Below is the quick implementation I came up with. I will
soon wrap it into a npm module. Any feedbacks?</p>
<p><code>confirmation-dialog.component.ts</code></p>
<figure class="highlight"><pre><code class="language-typescript" data-lang="typescript"><span class="k">import</span> <span class="p">{</span> <span class="nx">Component</span><span class="p">,</span> <span class="nx">OnInit</span> <span class="p">}</span> <span class="k">from</span> <span class="s1">'@angular/core'</span><span class="p">;</span>
<span class="k">import</span> <span class="p">{</span> <span class="nx">MdDialogRef</span> <span class="p">}</span> <span class="k">from</span> <span class="s1">'@angular/material'</span><span class="p">;</span>
<span class="p">@</span><span class="nd">Component</span><span class="p">({</span>
<span class="na">selector</span><span class="p">:</span> <span class="s1">'app-confirmation-dialog'</span><span class="p">,</span>
<span class="na">templateUrl</span><span class="p">:</span> <span class="s1">'./confirmation-dialog.component.html'</span><span class="p">,</span>
<span class="na">styleUrls</span><span class="p">:</span> <span class="p">[</span><span class="s1">'./confirmation-dialog.component.scss'</span><span class="p">]</span>
<span class="p">})</span>
<span class="k">export</span> <span class="kr">class</span> <span class="nx">ConfirmationDialogComponent</span> <span class="k">implements</span> <span class="nx">OnInit</span> <span class="p">{</span>
<span class="k">public</span> <span class="nx">title</span><span class="p">:</span> <span class="kr">string</span><span class="p">;</span>
<span class="k">public</span> <span class="nx">message</span><span class="p">:</span> <span class="kr">string</span><span class="p">;</span>
<span class="k">public</span> <span class="nx">titleAlign</span><span class="p">?:</span> <span class="kr">string</span><span class="p">;</span>
<span class="k">public</span> <span class="nx">messageAlign</span><span class="p">?:</span> <span class="kr">string</span><span class="p">;</span>
<span class="k">public</span> <span class="nx">btnOkText</span><span class="p">?:</span> <span class="kr">string</span><span class="p">;</span>
<span class="k">public</span> <span class="nx">btnCancelText</span><span class="p">?:</span> <span class="kr">string</span><span class="p">;</span>
<span class="kd">constructor</span><span class="p">(</span><span class="k">public</span> <span class="nx">dialogRef</span><span class="p">:</span> <span class="nx">MdDialogRef</span><span class="o">&lt;</span><span class="nx">ConfirmationDialogComponent</span><span class="o">&gt;</span><span class="p">)</span> <span class="p">{</span> <span class="p">}</span>
<span class="nx">ngOnInit</span><span class="p">()</span> <span class="p">{</span>
<span class="p">}</span>
<span class="p">}</span></code></pre></figure>
<p><code>confirmation-dialog.service.ts</code></p>
<figure class="highlight"><pre><code class="language-typescript" data-lang="typescript"><span class="k">import</span> <span class="p">{</span> <span class="nx">Observable</span> <span class="p">}</span> <span class="k">from</span> <span class="s1">'rxjs/Rx'</span><span class="p">;</span>
<span class="k">import</span> <span class="p">{</span> <span class="nx">ConfirmationDialogComponent</span> <span class="p">}</span> <span class="k">from</span> <span class="s1">'./confirmation-dialog.component'</span><span class="p">;</span>
<span class="k">import</span> <span class="p">{</span> <span class="nx">MdDialogRef</span><span class="p">,</span> <span class="nx">MdDialog</span><span class="p">,</span> <span class="nx">MdDialogConfig</span> <span class="p">}</span> <span class="k">from</span> <span class="s1">'@angular/material'</span><span class="p">;</span>
<span class="k">import</span> <span class="p">{</span> <span class="nx">Injectable</span><span class="p">,</span> <span class="nx">ViewContainerRef</span> <span class="p">}</span> <span class="k">from</span> <span class="s1">'@angular/core'</span><span class="p">;</span>
<span class="p">@</span><span class="nd">Injectable</span><span class="p">()</span>
<span class="k">export</span> <span class="kr">class</span> <span class="nx">ConfirmationDialogsService</span> <span class="p">{</span>
<span class="kd">constructor</span><span class="p">(</span><span class="k">private</span> <span class="nx">dialog</span><span class="p">:</span> <span class="nx">MdDialog</span><span class="p">)</span> <span class="p">{</span> <span class="p">}</span>
<span class="k">public</span> <span class="nx">confirm</span><span class="p">(</span><span class="nx">title</span><span class="p">:</span> <span class="kr">string</span><span class="p">,</span> <span class="nx">message</span><span class="p">:</span> <span class="kr">string</span><span class="p">,</span> <span class="nx">viewContainerRef</span><span class="p">:</span> <span class="nx">ViewContainerRef</span><span class="p">,</span> <span class="nx">btnOkText</span><span class="p">:</span> <span class="kr">string</span> <span class="o">=</span><span class="s1">'Ok'</span><span class="p">,</span> <span class="nx">btnCancelText</span><span class="p">:</span> <span class="kr">string</span> <span class="o">=</span><span class="s1">'Cancel'</span><span class="p">):</span> <span class="nx">Observable</span><span class="o">&lt;</span><span class="kr">boolean</span><span class="o">&gt;</span> <span class="p">{</span>
<span class="kd">let</span> <span class="na">dialogRef</span><span class="p">:</span> <span class="nx">MdDialogRef</span><span class="o">&lt;</span><span class="nx">ConfirmationDialogComponent</span><span class="o">&gt;</span><span class="p">;</span>
<span class="kd">let</span> <span class="nx">config</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">MdDialogConfig</span><span class="p">();</span>
<span class="nx">config</span><span class="p">.</span><span class="nx">viewContainerRef</span> <span class="o">=</span> <span class="nx">viewContainerRef</span><span class="p">;</span>
<span class="nx">dialogRef</span> <span class="o">=</span> <span class="k">this</span><span class="p">.</span><span class="nx">dialog</span><span class="p">.</span><span class="nx">open</span><span class="p">(</span><span class="nx">ConfirmationDialogComponent</span><span class="p">,</span> <span class="nx">config</span><span class="p">);</span>
<span class="nx">dialogRef</span><span class="p">.</span><span class="nx">componentInstance</span><span class="p">.</span><span class="nx">title</span> <span class="o">=</span> <span class="nx">title</span><span class="p">;</span>
<span class="nx">dialogRef</span><span class="p">.</span><span class="nx">componentInstance</span><span class="p">.</span><span class="nx">message</span> <span class="o">=</span> <span class="nx">message</span><span class="p">;</span>
<span class="nx">dialogRef</span><span class="p">.</span><span class="nx">componentInstance</span><span class="p">.</span><span class="nx">btnOkText</span> <span class="o">=</span> <span class="nx">btnOkText</span><span class="p">;</span>
<span class="nx">dialogRef</span><span class="p">.</span><span class="nx">componentInstance</span><span class="p">.</span><span class="nx">btnCancelText</span> <span class="o">=</span> <span class="nx">btnCancelText</span><span class="p">;</span>
<span class="k">return</span> <span class="nx">dialogRef</span><span class="p">.</span><span class="nx">afterClosed</span><span class="p">();</span>
<span class="p">}</span>
<span class="k">public</span> <span class="nx">confirmWithoutContainer</span><span class="p">(</span><span class="na">title</span><span class="p">:</span> <span class="kr">string</span><span class="p">,</span> <span class="na">message</span><span class="p">:</span> <span class="kr">string</span><span class="p">,</span> <span class="na">titleAlign</span><span class="p">:</span> <span class="kr">string</span><span class="o">=</span><span class="s1">'center'</span><span class="p">,</span> <span class="na">messageAlign</span><span class="p">:</span> <span class="kr">string</span><span class="o">=</span><span class="s1">'center'</span><span class="p">,</span> <span class="na">btnOkText</span><span class="p">:</span> <span class="kr">string</span> <span class="o">=</span><span class="s1">'Ok'</span><span class="p">,</span> <span class="na">btnCancelText</span><span class="p">:</span> <span class="kr">string</span> <span class="o">=</span><span class="s1">'Cancel'</span> <span class="p">):</span> <span class="nx">Observable</span><span class="o">&lt;</span><span class="kr">boolean</span><span class="o">&gt;</span> <span class="p">{</span>
<span class="kd">let</span> <span class="na">dialogRef</span><span class="p">:</span> <span class="nx">MdDialogRef</span><span class="o">&lt;</span><span class="nx">ConfirmationDialogComponent</span><span class="o">&gt;</span><span class="p">;</span>
<span class="kd">let</span> <span class="nx">config</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">MdDialogConfig</span><span class="p">();</span>
<span class="c1">// config.viewContainerRef = viewContainerRef;</span>
<span class="nx">dialogRef</span> <span class="o">=</span> <span class="k">this</span><span class="p">.</span><span class="nx">dialog</span><span class="p">.</span><span class="nx">open</span><span class="p">(</span><span class="nx">ConfirmationDialogComponent</span><span class="p">,</span> <span class="nx">config</span><span class="p">);</span>
<span class="nx">dialogRef</span><span class="p">.</span><span class="nx">componentInstance</span><span class="p">.</span><span class="nx">title</span> <span class="o">=</span> <span class="nx">title</span><span class="p">;</span>
<span class="nx">dialogRef</span><span class="p">.</span><span class="nx">componentInstance</span><span class="p">.</span><span class="nx">message</span> <span class="o">=</span> <span class="nx">message</span><span class="p">;</span>
<span class="nx">dialogRef</span><span class="p">.</span><span class="nx">componentInstance</span><span class="p">.</span><span class="nx">titleAlign</span> <span class="o">=</span> <span class="nx">titleAlign</span><span class="p">;</span>
<span class="nx">dialogRef</span><span class="p">.</span><span class="nx">componentInstance</span><span class="p">.</span><span class="nx">messageAlign</span> <span class="o">=</span> <span class="nx">messageAlign</span><span class="p">;</span>
<span class="nx">dialogRef</span><span class="p">.</span><span class="nx">componentInstance</span><span class="p">.</span><span class="nx">btnOkText</span> <span class="o">=</span> <span class="nx">btnOkText</span><span class="p">;</span>
<span class="nx">dialogRef</span><span class="p">.</span><span class="nx">componentInstance</span><span class="p">.</span><span class="nx">btnCancelText</span> <span class="o">=</span> <span class="nx">btnCancelText</span><span class="p">;</span>
<span class="k">return</span> <span class="nx">dialogRef</span><span class="p">.</span><span class="nx">afterClosed</span><span class="p">();</span>
<span class="p">}</span>
<span class="p">}</span></code></pre></figure>
<p><code>confirmation-dialog.component.html</code></p>
<figure class="highlight"><pre><code class="language-html" data-lang="html"><span class="nt">&lt;div</span> <span class="na">class=</span><span class="s">"box-holder"</span><span class="nt">&gt;</span>
<span class="nt">&lt;div</span> <span class="na">class=</span><span class="s">"header-row"</span> <span class="err">[</span><span class="na">ngClass</span><span class="err">]="{'</span><span class="na">text-center-align</span><span class="err">'</span><span class="na">:</span> <span class="na">titleAlign=</span><span class="s">='center',</span> <span class="err">'</span><span class="na">text-right-align</span><span class="err">'</span><span class="na">:</span> <span class="na">titleAlign=</span><span class="s">='right'</span> <span class="err">}"</span><span class="na">fxLayoutAlign=</span><span class="s">"space-between center"</span><span class="nt">&gt;</span>
<span class="nt">&lt;div</span> <span class="na">class=</span><span class="s">"header-title "</span><span class="nt">&gt;</span>
<span class="nt">&lt;/div&gt;</span>
<span class="nt">&lt;/div&gt;</span>
<span class="nt">&lt;div</span> <span class="na">class=</span><span class="s">"content-holder"</span> <span class="err">[</span><span class="na">ngClass</span><span class="err">]="{'</span><span class="na">text-center-align</span><span class="err">'</span><span class="na">:</span> <span class="na">messageAlign=</span><span class="s">='center',</span> <span class="err">'</span><span class="na">text-right-align</span><span class="err">'</span><span class="na">:</span> <span class="na">messageAlign=</span><span class="s">='right'</span> <span class="err">}"</span> <span class="na">fxLayoutAlign=</span><span class="s">"start start"</span><span class="nt">&gt;</span>
<span class="nt">&lt;/div&gt;</span>
<span class="nt">&lt;div</span> <span class="na">class=</span><span class="s">"action-container"</span> <span class="na">fxLayoutAlign=</span><span class="s">"end end"</span><span class="nt">&gt;</span>
<span class="nt">&lt;button</span> <span class="na">type=</span><span class="s">"button"</span> <span class="na">md-button</span> <span class="na">class=</span><span class="s">"od-button od-ripple action-button"</span> <span class="err">(</span><span class="na">click</span><span class="err">)="</span><span class="na">dialogRef</span><span class="err">.</span><span class="na">close</span><span class="err">()"</span><span class="nt">&gt;&lt;/button&gt;</span>
<span class="nt">&lt;button</span> <span class="na">type=</span><span class="s">"button"</span> <span class="na">md-raised-button</span> <span class="na">class=</span><span class="s">"od-button od-ripple action-button"</span> <span class="err">(</span><span class="na">click</span><span class="err">)="</span><span class="na">dialogRef</span><span class="err">.</span><span class="na">close</span><span class="err">(</span><span class="na">true</span><span class="err">)"</span><span class="nt">&gt;</span> <span class="nt">&lt;/button&gt;</span>
<span class="nt">&lt;/div&gt;</span>
<span class="nt">&lt;/div&gt;</span></code></pre></figure>
</content>
</entry>
<entry>
<title>Useful tcpdump usages</title>
<link href="http://madhur.co.in/blog/2017/02/18/useful-tcpdump-netcat-usages.html"/>
<updated>2017-02-18T00:00:00+05:30</updated>
<id>id:/blog/2017/02/18/useful-tcpdump-netcat-usages</id>
<content type="html"><p><a href="http://www.tcpdump.org/tcpdump_man.html">Tcpdump</a> and <a href="http://nc110.sourceforge.net/">Netcat</a> are one of the most useful utilities for Linux network debugging.</p>
<p>Some of the examples where I have found <code>tcpdump</code> to be extremely useful are given below. In the next post, I will cover netcat.</p>
<h3>Look for traffic based on IP address</h3>
<figure class="highlight"><pre><code class="language-text" data-lang="text">tcpdump host 1.2.3.4</code></pre></figure>
<h3>Capture based on protocol</h3>
<figure class="highlight"><pre><code class="language-text" data-lang="text">tcpdump udp</code></pre></figure>
<h3>Capture based on interface</h3>
<figure class="highlight"><pre><code class="language-text" data-lang="text">tcpdump -i eth1</code></pre></figure>
<h3>Capture filter based on certain port</h3>
<figure class="highlight"><pre><code class="language-text" data-lang="text">tcpdump port 80</code></pre></figure>
<h3>Capture filter based on source port or destination port</h3>
<figure class="highlight"><pre><code class="language-text" data-lang="text">tcpdump src port 80
tcpdump dst port 80</code></pre></figure>
<h3>Capture based on port range</h3>
<figure class="highlight"><pre><code class="language-text" data-lang="text">tcpdump portrange 80-90</code></pre></figure>
<h3>Capture display in ASCII</h3>
<figure class="highlight"><pre><code class="language-text" data-lang="text">tcpdump -A -i eth0</code></pre></figure>
<h3>Capture to a file</h3>
<figure class="highlight"><pre><code class="language-text" data-lang="text">tcpdump -w 08232010.pcap -i eth0</code></pre></figure>
</content>
</entry>
<entry>
<title>Bulk git clone repositories</title>
<link href="http://madhur.co.in/blog/2017/02/12/git-bulk-clone.html"/>
<updated>2017-02-12T00:00:00+05:30</updated>
<id>id:/blog/2017/02/12/git-bulk-clone</id>
<content type="html"><p>Recently, I was looking a way to do a git clone in bulk. I came across this nifty little script to do the same</p>
<figure class="highlight"><pre><code class="language-bash" data-lang="bash"><span class="c">#!/bin/bash</span>
<span class="c"># The script clones all repositories of an GitHub organization.</span>
<span class="c"># Author: Jens-Andre Koch</span>
<span class="c"># the github organization to fetch all repositories for</span>
<span class="nv">GITHUB_ORGANIZATION</span><span class="o">=</span><span class="nv">$1</span>
<span class="c"># the git clone cmd used for cloning each repository</span>
<span class="c"># the parameter recursive is used to clone submodules, too.</span>
<span class="nv">GIT_CLONE_CMD</span><span class="o">=</span><span class="s2">"git clone "</span>
<span class="c"># fetch repository list via github api</span>
<span class="c"># grep fetches the json object key ssh_url, which contains the ssh url for the repository</span>
<span class="nv">REPOLIST</span><span class="o">=</span><span class="sb">`</span>curl --silent https://api.github.com/orgs/<span class="k">${</span><span class="nv">GITHUB_ORGANIZATION</span><span class="k">}</span>/repos?per_page<span class="o">=</span>200 -q | grep <span class="s2">"</span><span class="se">\"</span><span class="s2">ssh_url</span><span class="se">\"</span><span class="s2">"</span> | awk -F<span class="s1">': "'</span> <span class="s1">'{print $2}'</span> | sed -e <span class="s1">'s/",//g'</span><span class="sb">`</span>
<span class="c"># loop over all repository urls and execute clone</span>
<span class="k">for </span>REPO <span class="k">in</span> <span class="nv">$REPOLIST</span>; <span class="k">do</span>
<span class="k">${</span><span class="nv">GIT_CLONE_CMD</span><span class="k">}${</span><span class="nv">REPO</span><span class="k">}</span>
<span class="k">done</span></code></pre></figure>
<p>You can just invoke it with the argument of either user or organization. For example</p>
<p><code>./clone.sh madhur</code></p>
<p>The problem with this is that it will not clone the private repos since the API used in this request is unauthenticated and will not have access to the private repos.</p>
<p>I wrote a small little python script which will also clone the private repos.</p>
<p>First, you need to obtain your <a href="https://github.com/settings/tokens">personal access token</a></p>
<p>The gist is available <a href="https://gist.github.com/madhur/b21e142b529a958ab6413e92bca39e17">here</a></p>
<figure class="highlight"><pre><code class="language-bash" data-lang="bash">import requests
import json
import subprocess
GITHUB_ORGANIZATION <span class="o">=</span> <span class="s2">"madhur"</span>
<span class="nv">ACCESS_TOKEN</span><span class="o">=</span><span class="s2">""</span>
<span class="nv">CLONE_DIR</span><span class="o">=</span><span class="s2">"./"</span>
r <span class="o">=</span> requests.get<span class="o">(</span><span class="s2">"https://api.github.com/orgs/"</span> + GITHUB_ORGANIZATION + <span class="s2">"/repos?per_page=200&amp;access_token="</span> + ACCESS_TOKEN<span class="o">)</span>
data <span class="o">=</span> json.loads<span class="o">(</span>r.text<span class="o">)</span>
<span class="k">for </span>repo <span class="k">in </span>data:
print repo[<span class="s1">'full_name'</span><span class="o">]</span>
p <span class="o">=</span> subprocess.Popen<span class="o">([</span><span class="s2">"git"</span>,<span class="s2">"clone"</span>, repo[<span class="s1">'clone_url'</span><span class="o">]]</span>, <span class="nv">cwd</span><span class="o">=</span>CLONE_DIR<span class="o">)</span>
p.wait<span class="o">()</span></code></pre></figure>
</content>
</entry>
<entry>
<title>Tuning Linux servers for scalability</title>
<link href="http://madhur.co.in/blog/2017/01/30/tuning-linux-servers-scalability.html"/>
<updated>2017-01-30T00:00:00+05:30</updated>
<id>id:/blog/2017/01/30/tuning-linux-servers-scalability</id>
<content type="html"><p>Focus on performance and scalablity is one of my primary personal and professional goal when working with tech products.</p>
<p>The server can be any Linux based server such as <a href="https://www.centos.org/">CentOS</a> or <a href="https://www.debian.org/">Debian</a> derivative such as <a href="https://www.ubuntu.com/">Ubuntu</a>.</p>
<p>In this post, I will outline my learnings on scaling the Linux server. Scaling here implies many things such as </p>
<ul>
<li><p>Being able to open many files at once. Here files can be generally applied to concept such as open ports, threads etc and not necessary physical files</p></li>
<li><p>Being able to handle many concurrent network connections</p></li>
</ul>
<p>Knowing Linux OS and related concepts such as <a href="https://en.wikipedia.org/wiki/Iptables">Iptables</a> is a pre-requisite.</p>
<h2>Open files</h2>
<p>We need to keep our file limit high for any linux production server. Check the current value using <code>ulimit -a</code></p>
<p>We can configure this limit using <code>/etc/security/limits.conf</code></p>
<figure class="highlight"><pre><code class="language-text" data-lang="text">* hard nofile 300000
* soft nofile 300000
tomcat hard nofile 300000
tomcat soft nofile 300000</code></pre></figure>
<p>Note that we can also specify per user limit as shown above (special limits for tomcat user)</p>
<p>The file descriptor limit for a running process can be seen in the following file under Max open files.</p>
<figure class="highlight"><pre><code class="language-text" data-lang="text">$ cat /proc/&lt;pid&gt;/limits
Max open files 30000</code></pre></figure>
<h2>Ephemeral Ports</h2>
<p>Increase the number of ephemeal ports availabl to your application. The default value is <code>32768 - 61000</code>. </p>
<h2>TIME_WAIT state</h2>
<p>TCP connections go through lot of states, last of them is <code>TIME_WAIT</code> state.
The default <code>TIME_WAIT</code> timeout is for 2 minutes, Which means you’ll run out of available ports if you receive more than about 400 requests a second, or if we look back to how nginx does proxies, this actually translates to 200 requests per second.</p>
<p>These parameters can be tuned using these settings in <code>/etc/sysctl.conf</code></p>
<figure class="highlight"><pre><code class="language-text" data-lang="text">net.ipv4.ip_local_port_range = 18000 65535
net.ipv4.netfilter.ip_conntrack_tcp_timeout_time_wait = 1</code></pre></figure>
<h2>Connection Tracking</h2>
<p>The next parameter we looked at was Connection Tracking. This is a side effect of using <code>iptables</code>. Since <code>iptables</code> needs to allow two-way communication between established HTTP and ssh connections, it needs to keep track of which connections are established, and it puts these into a connection tracking table. This table grows. And grows. And grows.</p>
<p>You can see the current size of this table using <code>sysctl net.netfilter.nf_conntrack_count</code> and its limit using <code>sysctl net.nf_conntrack_max</code>. If count crosses max, your linux system will stop accepting new TCP connections and you’ll never know about this. The only indication that this has happened is a single line hidden somewhere in <code>/var/log/syslog</code> saying that you’re out of connection tracking entries. One line, once, when it first happens.</p>
<p>A better indication is if count is always very close to max. You might think, “Hey, we’ve set max exactly right.”, but you’d be wrong.</p>
<p>What you need to do (or at least that’s what you first think) is to increase max.</p>
<p>Keep in mind though, that the larger this value, the more RAM the kernel will use to keep track of these entries. RAM that could be used by your application.</p>
<p>We started down this path, increasing net.nf_conntrack_max, but soon we were just pushing it up every day. Connections that were getting in there were never getting out.</p>
<h2>Maximum number of pending connections on a socket</h2>
<p>During some of our initial load testing, we ran into a strange problem where we were unable to open more than approximately 128 concurrent connections at once.</p>
<p>After some investigation, we learned about the following kernel parameter.</p>
<figure class="highlight"><pre><code class="language-text" data-lang="text">net.core.somaxconn</code></pre></figure>
<p>This kernel parameter is the size of the backlog of TCP connections waiting to be accepted by the application. If a connection indication arrives when the queue is full, the connection is refused. The default value for this parameters is 128 on most modern operating systems.</p>
<p>Bumping up this limit in <code>/etc/sysctl.conf</code> helped us get rid of the “connection refused” issues on our Linux machines.</p>
<h2>JVM thread count</h2>
<p>A few hours after we allowed a significant percentage of production traffic to hit our server for the first time, we were alerted to the fact that the load balancer was unable to connect to a few of our machines. On further investigation, we saw the following all over our server logs.</p>
<figure class="highlight"><pre><code class="language-text" data-lang="text">java.lang.OutOfMemoryError: unable to create new native thread</code></pre></figure>
<p>If you hit the JVM thread limit, chances are that there is a thread leak in your code that needs to be fixed. However, if you find that all your threads are actually doing useful work, is there a way to tweak the system to let you create more threads and accept more connections?</p>
<p>The answer, as always, is fun. It’s interesting to discuss how available memory limits the number of threads that can be created on a JVM. The stack size of a thread determines the memory available for static memory allocation. Thus, the absolute theoretical maximum number of threads is a process’s user address space divided by the thread stack size. However, the reality is that the JVM also uses memory for dynamic allocation on the heap. With a few quick tests with a small Java process, we could verify that as more memory is allocated for the heap, less is available for the stack. Thus, the limit on the number of threads decreases with increasing heap size.</p>
<p>To summarize, you can increase the thread count limit by decreasing the stack size per thread <code>(-Xss)</code> or by decreasing the memory allocated to the heap <code>(-Xms, -Xmx).</code></p>
</content>
</entry>
<entry>
<title>Close look at proxy_cache_lock and proxy_cache_use_stale in Nginx</title>
<link href="http://madhur.co.in/blog/2016/12/25/proxy-cache-lock-nginx.html"/>
<updated>2016-12-25T00:00:00+05:30</updated>
<id>id:/blog/2016/12/25/proxy-cache-lock-nginx</id>
<content type="html"><p>If you have worked with Nginx cache, one must know and understand <a href="http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_cache_lock"><code>proxy_cache_lock</code></a> and <a href="http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_cache_use_stale"><code>proxy_cache_use_stale</code></a> directives.</p>
<p>To configure simply Nginx caching, we basically add these 2 lines in our configuration block:</p>
<figure class="highlight"><pre><code class="language-text" data-lang="text">proxy_ignore_headers X-Accel-Expires Expires Cache-Control;
proxy_cache_valid any 30s;</code></pre></figure>
<p>This will ignore any of the cache related headers from upstream and keep the cache valid for 30 seconds. This means that a request will only go out to upstream every 30 seconds. But it won&#39;t be one request: it&#39;s very possible that multiple requests will be made when multiple people request the same stale cache. To solve this problem, we add two more configuration directives:</p>
<figure class="highlight"><pre><code class="language-text" data-lang="text">proxy_cache_lock on; </code></pre></figure>
<figure class="highlight"><pre><code class="language-text" data-lang="text">proxy_cache_use_stale updating;</code></pre></figure>
<p>Using these two extra configuration directives, Nginx will send only one request to upstream every 30 secs while still responding quickly with stale data.</p>
<p>An important point to consider here is that default value of <a href="http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_cache_use_stale"><code>proxy_cache_use_stale</code></a> is <code>off</code>. That means, if you have set, <a href="http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_cache_lock"><code>proxy_cache_lock</code></a> to <code>on</code>, all the requests which will arrive at Ngix while the cache is being updated will &quot;essentially wait&quot;. During heavy traffic, this can considerably slowdown the performance and response times of the requests.</p>
<p>Quoting from NGINX docs:</p>
<blockquote>
<p>When enabled, only one request at a time will be allowed to populate a new cache element identified according to the proxy_cache_key directive by passing a request to a proxied server. Other requests of the same cache element will either wait for a response to appear in the cache or the cache lock for this element to be released, up to the time set by the proxy_cache_lock_timeout directive</p>
</blockquote>
<p>Thus, it is very important to consider the scenarios in which <a href="http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_cache_lock"><code>proxy_cache_lock</code></a> is being used. If it is not possible to serve the stale data to the client, it becomes even more important to configure the <a href="http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_cache_lock_timeout"><code>proxy_cache_lock_timeout</code></a> value, otherwise performance can be severely degraded during heavy traffic. The default value of <a href="http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_cache_lock_timeout"><code>proxy_cache_lock_timeout</code></a> is 5 seconds which is quite high.</p>
</content>
</entry>
<entry>
<title>Improving performance using Batch APIs</title>
<link href="http://madhur.co.in/blog/2016/12/25/batch-api-framework-nodejs.html"/>
<updated>2016-12-25T00:00:00+05:30</updated>
<id>id:/blog/2016/12/25/batch-api-framework-nodejs</id>
<content type="html"><p>Recently, there is lot of focus on dividing a complex application into small microservices communicating over REST. In most of the cases, REST is implemented over HTTP protocol. All this is great, but HTTP protocol adds lot of communciation overhead. There is a Request header, response headers which adds to considerable bytes in payload. Apart from that, you need to take care of things like <code>keepalive</code> to eliminate TCP connection time overhead.</p>
<p>The keepalive does work well for microservices, but it certainly doesn&#39;t work well for let&#39;s say &quot;mobile REST client applications&quot;, where changing network conditions and cell tower will not allow for keep alives. Establishing an HTTP connection, especially when using secure sockets (HTTPS), will result in a handshake being performed between the mobile client and the server. These handshakes will occur N times when N requests are being sent, and your app will incur the associated extra cost of network traffic and battery consumption.</p>
<p>To mitigate these issues, it is generally advisable to batch HTTP requests whenever possible and send them over a persistent HTTP connection.</p>
<p>We implemented a very simple Batch API framework in Node.js. It is very looosely based on Facebook&#39;s Graph API documentation, specifically <a href="https://developers.facebook.com/docs/graph-api/making-multiple-requests">Graph API, Making Batch Requests</a>.</p>
<p>The request format is very simple, you just specify the end points and the type of requests they are (GET, POST, PUT DELETE, HEAD) etc. For example,</p>
<figure class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="p">[</span>
<span class="p">{</span>
<span class="s2">"method"</span><span class="p">:</span> <span class="s2">"GET"</span><span class="p">,</span>
<span class="s2">"path"</span><span class="p">:</span> <span class="s2">"/me"</span>
<span class="p">},</span>
<span class="p">{</span>
<span class="s2">"method"</span><span class="p">:</span> <span class="s2">"GET"</span><span class="p">,</span>
<span class="s2">"path"</span><span class="p">:</span> <span class="s2">"/me/friends?limit=50"</span>
<span class="p">},</span>
<span class="p">{</span>
<span class="s2">"method"</span><span class="p">:</span> <span class="s2">"POST"</span><span class="p">,</span>
<span class="s2">"path"</span><span class="p">:</span> <span class="s2">"/notification"</span><span class="p">,</span>
<span class="s2">"body"</span><span class="p">:</span> <span class="p">{</span>
<span class="s2">"title"</span><span class="p">:</span> <span class="s2">"hi there"</span><span class="p">,</span>
<span class="s2">"body"</span><span class="p">:</span> <span class="s2">"hi there as well"</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="p">]</span></code></pre></figure>
<p>For each operation, the response includes a status code, header information, and the body. These are equivalent to the response you could expect from each operation if performed as raw requests.</p>
<figure class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="p">[</span>
<span class="p">{</span> <span class="s2">"code"</span><span class="p">:</span> <span class="mi">200</span><span class="p">,</span>
<span class="s2">"body"</span><span class="p">:</span> <span class="s2">"{\"id\":\"…\"}"</span>
<span class="p">},</span>
<span class="p">{</span> <span class="s2">"code"</span><span class="p">:</span> <span class="mi">200</span><span class="p">,</span>
<span class="s2">"body"</span><span class="p">:</span><span class="s2">"{\"data\"</span><span class="p">:</span> <span class="p">[{</span><span class="err">…</span><span class="p">}]}</span>
<span class="p">}</span>
<span class="p">]</span></code></pre></figure>
<p>One could have also included <code>headers</code> in the output if required, but I believe it adds unnecessary overhead in the payload.</p>
<h3>Handling errors</h3>
<p>Its possible that one of the requested operations may throw an error. In this scenario, the batch API throws a similar response to the standard Graph API, but encapsulated in the batch response syntax:</p>
<p>Other requests within the batch should still complete successfully and will be returned, as normal, with a 200 status code.</p>
<h3>Implementation</h3>
<p>The batch API framework is implemented in Node.js using <a href="https://github.com/caolan/async">async</a> and <a href="https://github.com/request/request">request</a> module. </p>
<figure class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="nx">performBatch</span><span class="p">:</span> <span class="kd">function</span><span class="p">(</span><span class="nx">req</span><span class="p">,</span> <span class="nx">callback</span><span class="p">)</span> <span class="p">{</span>
<span class="kd">var</span> <span class="nx">items</span> <span class="o">=</span> <span class="nx">req</span><span class="p">.</span><span class="nx">body</span><span class="p">;</span>
<span class="kd">var</span> <span class="nx">headers</span> <span class="o">=</span> <span class="nx">util</span><span class="p">.</span><span class="nx">getHeaders</span><span class="p">(</span><span class="nx">req</span><span class="p">);</span>
<span class="kd">var</span> <span class="nx">responses</span> <span class="o">=</span> <span class="p">[];</span>
<span class="nx">async</span><span class="p">.</span><span class="nx">forEachOf</span><span class="p">(</span><span class="nx">items</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">item</span><span class="p">,</span> <span class="nx">index</span><span class="p">,</span> <span class="nx">callback</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">performRequest</span><span class="p">(</span><span class="nx">item</span><span class="p">,</span> <span class="nx">headers</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">err</span><span class="p">,</span> <span class="nx">response</span><span class="p">)</span> <span class="p">{</span>
<span class="k">if</span><span class="p">(</span><span class="nx">err</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">responses</span><span class="p">.</span><span class="nx">push</span><span class="p">({</span><span class="na">code</span><span class="p">:</span><span class="mi">500</span><span class="p">,</span> <span class="na">body</span><span class="p">:</span> <span class="kc">null</span><span class="p">,</span> <span class="na">o</span><span class="p">:</span><span class="nx">index</span> <span class="p">});</span>
<span class="p">}</span>
<span class="k">else</span> <span class="p">{</span>
<span class="nx">responses</span><span class="p">.</span><span class="nx">push</span><span class="p">({</span><span class="na">code</span><span class="p">:</span> <span class="nx">response</span><span class="p">.</span><span class="nx">statusCode</span><span class="p">,</span> <span class="na">body</span><span class="p">:</span> <span class="nx">response</span><span class="p">.</span><span class="nx">body</span><span class="p">,</span> <span class="na">o</span><span class="p">:</span> <span class="nx">index</span><span class="p">});</span>
<span class="p">}</span>
<span class="nx">callback</span><span class="p">();</span>
<span class="p">});</span>
<span class="p">},</span> <span class="kd">function</span><span class="p">(</span><span class="nx">err</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">responses</span><span class="p">.</span><span class="nx">sort</span><span class="p">(</span><span class="nx">util</span><span class="p">.</span><span class="nx">keysrt</span><span class="p">(</span><span class="s1">'o'</span><span class="p">));</span>
<span class="k">return</span> <span class="nx">callback</span><span class="p">(</span><span class="kc">null</span><span class="p">,</span> <span class="nx">responses</span><span class="p">);</span>
<span class="p">});</span>
<span class="p">}</span></code></pre></figure>
<p>The <a href="http://caolan.github.io/async/docs.html#eachOf"><code>eachOf</code></a> function of <a href="http://caolan.github.io/async/docs.html#">async</a> is used to send the HTTP request for each item in array in parallel. Note, that since this function calls HTTP request for each item in parallel, there is no guarantee that the functions will complete in order. Hence, the <code>index</code> is used to keep track of order and pushed with each response.</p>
<p><code>performRequest</code> is a simple function which makes an HTTP request according to the parameters and returns the response in a callback. In case of any error, it simply returns <code>error</code> parameter as <code>true</code></p>
<figure class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="kd">function</span> <span class="nx">performRequest</span><span class="p">(</span><span class="nx">item</span><span class="p">,</span> <span class="nx">headers</span><span class="p">,</span> <span class="nx">callback</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">request</span><span class="p">({</span>
<span class="na">url</span><span class="p">:</span> <span class="nx">config</span><span class="p">.</span><span class="nx">self_host</span> <span class="o">+</span> <span class="nx">item</span><span class="p">.</span><span class="nx">path</span><span class="p">,</span>
<span class="na">method</span><span class="p">:</span> <span class="nx">item</span><span class="p">.</span><span class="nx">method</span><span class="p">,</span>
<span class="na">json</span><span class="p">:</span> <span class="kc">true</span><span class="p">,</span>
<span class="na">timeout</span><span class="p">:</span> <span class="mi">5000</span><span class="p">,</span>
<span class="na">headers</span><span class="p">:</span> <span class="nx">headers</span><span class="p">,</span>
<span class="na">body</span><span class="p">:</span> <span class="nx">item</span><span class="p">.</span><span class="nx">body</span>
<span class="p">},</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">error</span><span class="p">,</span> <span class="nx">response</span><span class="p">,</span> <span class="nx">body</span><span class="p">)</span> <span class="p">{</span>
<span class="k">if</span><span class="p">(</span><span class="nx">error</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">error</span><span class="p">);</span>
<span class="k">return</span> <span class="nx">callback</span><span class="p">(</span><span class="kc">true</span><span class="p">);</span>
<span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
<span class="k">return</span> <span class="nx">callback</span><span class="p">(</span><span class="kc">null</span><span class="p">,</span> <span class="nx">response</span><span class="p">);</span>
<span class="p">}</span>
<span class="p">});</span>
<span class="p">}</span></code></pre></figure>
<p>Once all the responses are received, they are sorted according to the <code>index</code> key using the below function.</p>
<figure class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="kd">function</span> <span class="nx">keysrt</span><span class="p">(</span><span class="nx">key</span><span class="p">,</span> <span class="nx">desc</span><span class="p">)</span> <span class="p">{</span>
<span class="k">return</span> <span class="kd">function</span><span class="p">(</span><span class="nx">a</span><span class="p">,</span><span class="nx">b</span><span class="p">){</span>
<span class="k">return</span> <span class="nx">desc</span> <span class="p">?</span> <span class="o">~~</span><span class="p">(</span><span class="nx">a</span><span class="p">[</span><span class="nx">key</span><span class="p">]</span> <span class="o">&lt;</span> <span class="nx">b</span><span class="p">[</span><span class="nx">key</span><span class="p">])</span> <span class="p">:</span> <span class="o">~~</span><span class="p">(</span><span class="nx">a</span><span class="p">[</span><span class="nx">key</span><span class="p">]</span> <span class="o">&gt;</span> <span class="nx">b</span><span class="p">[</span><span class="nx">key</span><span class="p">]);</span>
<span class="p">};</span>
<span class="p">}</span></code></pre></figure>
</content>
</entry>
<entry>
<title>Integrate node.js logging with Sentry</title>
<link href="http://madhur.co.in/blog/2016/12/04/integrating-sentry-node.html"/>
<updated>2016-12-04T00:00:00+05:30</updated>
<id>id:/blog/2016/12/04/integrating-sentry-node</id>
<content type="html"><p>Effective logging is crucial to any application deployed in production. For node.js, <a href="http://expressjs.com/">express</a> based applications, we use <a href="https://github.com/winstonjs/winston">Winston</a> as our logging framework.</p>
<p>In our scenario, we also want some crucial logs to be logged to <a href="https://sentry.io/welcome/">Sentry</a>. </p>
<p>A simple setup of Sentry is described below. This is same as what is described in <a href="https://docs.sentry.io/clients/node/integrations/express/">sentry docs</a>.</p>
<figure class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="kd">var</span> <span class="nx">sentry_enabled</span> <span class="o">=</span> <span class="kc">false</span><span class="p">;</span>
<span class="k">if</span> <span class="p">(</span><span class="nx">process</span><span class="p">.</span><span class="nx">env</span><span class="p">.</span><span class="nx">NODE_ENV</span> <span class="o">==</span> <span class="s1">'production'</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">sentry_enabled</span> <span class="o">=</span> <span class="kc">true</span><span class="p">;</span>
<span class="p">}</span>
<span class="k">if</span> <span class="p">(</span><span class="nx">sentry_enabled</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">app</span><span class="p">.</span><span class="nx">use</span><span class="p">(</span><span class="nx">raven</span><span class="p">.</span><span class="nx">middleware</span><span class="p">.</span><span class="nx">express</span><span class="p">.</span><span class="nx">requestHandler</span><span class="p">(</span><span class="nx">config</span><span class="p">.</span><span class="nx">sentry_dsn</span><span class="p">));</span>
<span class="p">}</span>
<span class="c1">// setup routes</span>
<span class="nx">app</span><span class="p">.</span><span class="nx">use</span><span class="p">(</span><span class="s1">'/'</span><span class="p">,</span> <span class="nx">healthcheck</span><span class="p">);</span>
<span class="k">if</span> <span class="p">(</span><span class="nx">sentry_enabled</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">app</span><span class="p">.</span><span class="nx">use</span><span class="p">(</span><span class="nx">raven</span><span class="p">.</span><span class="nx">middleware</span><span class="p">.</span><span class="nx">express</span><span class="p">.</span><span class="nx">errorHandler</span><span class="p">(</span><span class="nx">config</span><span class="p">.</span><span class="nx">sentry_dsn</span><span class="p">));</span>
<span class="p">}</span></code></pre></figure>
<p>All good uptil now, except that this setup logs only unhandled exceptions to Sentry. For sending manual log lines to Sentry, sentry recommends using <code>client.captureException(e)</code> or <code>client.captureMessage(msg)</code> as per these <a href="http://expressjs.com/">docs</a></p>
<p>However, it could be great if we send our winston <code>error</code> level logs to sentry.</p>
<p>That&#39;s where <a href="https://github.com/guzru/winston-sentry">winston-sentry</a> packages comes to help. It can send your winston logs to sentry automatically.</p>
<p>All that is needed is to add a Sentry transport to the winston logger.</p>
<figure class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="kd">var</span> <span class="nx">winston</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="s1">'winston'</span><span class="p">);</span>
<span class="kd">var</span> <span class="nx">Sentry</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="s1">'winston-sentry'</span><span class="p">);</span>
<span class="nx">winston</span><span class="p">.</span><span class="nx">emitErrs</span> <span class="o">=</span> <span class="kc">true</span><span class="p">;</span>
<span class="kd">var</span> <span class="nx">logger</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">winston</span><span class="p">.</span><span class="nx">Logger</span><span class="p">({</span>
<span class="na">transports</span><span class="p">:</span> <span class="p">[</span>
<span class="k">new</span> <span class="nx">winston</span><span class="p">.</span><span class="nx">transports</span><span class="p">.</span><span class="nx">File</span><span class="p">({</span>
<span class="na">level</span><span class="p">:</span> <span class="s1">'0'</span><span class="p">,</span>
<span class="na">filename</span><span class="p">:</span> <span class="s1">'/opt/logfile.log'</span><span class="p">,</span>
<span class="na">handleExceptions</span><span class="p">:</span> <span class="kc">true</span><span class="p">,</span>
<span class="na">json</span><span class="p">:</span> <span class="kc">false</span><span class="p">,</span>
<span class="na">colorize</span><span class="p">:</span> <span class="kc">false</span><span class="p">,</span>
<span class="na">timestamp</span><span class="p">:</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span> <span class="k">return</span> <span class="k">new</span> <span class="nb">Date</span><span class="p">().</span><span class="nx">toLocaleString</span><span class="p">(</span><span class="s1">'ca'</span><span class="p">);</span> <span class="p">}</span>
<span class="p">}),</span>
<span class="k">new</span> <span class="nx">winston</span><span class="p">.</span><span class="nx">transports</span><span class="p">.</span><span class="nx">Console</span><span class="p">({</span>
<span class="na">level</span><span class="p">:</span> <span class="s1">'info'</span><span class="p">,</span>
<span class="na">handleExceptions</span><span class="p">:</span> <span class="kc">true</span><span class="p">,</span>
<span class="na">json</span><span class="p">:</span> <span class="kc">false</span><span class="p">,</span>
<span class="na">colorize</span><span class="p">:</span> <span class="kc">true</span>
<span class="p">}),</span>
<span class="k">new</span> <span class="nx">Sentry</span><span class="p">({</span>
<span class="na">level</span><span class="p">:</span> <span class="s1">'error'</span><span class="p">,</span>
<span class="na">dsn</span><span class="p">:</span> <span class="nx">config</span><span class="p">.</span><span class="nx">sentry_dsn</span><span class="p">,</span>
<span class="na">tags</span><span class="p">:</span> <span class="p">{</span> <span class="na">key</span><span class="p">:</span> <span class="s1">'value'</span> <span class="p">},</span>
<span class="na">extra</span><span class="p">:</span> <span class="p">{</span> <span class="na">key</span><span class="p">:</span> <span class="s1">'value'</span> <span class="p">}</span>
<span class="p">})</span>
<span class="p">],</span>
<span class="na">exitOnError</span><span class="p">:</span> <span class="kc">false</span>
<span class="p">});</span>
<span class="nx">module</span><span class="p">.</span><span class="nx">exports</span> <span class="o">=</span> <span class="nx">logger</span><span class="p">;</span></code></pre></figure>
</content>
</entry>
<entry>
<title>Couchbase exception handling in Node.js</title>
<link href="http://madhur.co.in/blog/2016/12/04/handling-couchbase-node.html"/>
<updated>2016-12-04T00:00:00+05:30</updated>
<id>id:/blog/2016/12/04/handling-couchbase-node</id>
<content type="html"><p>We use <a href="http://www.couchbase.com/">Couchbase</a> as our NOSQL document store. Couchbase provides lots of software development kits (SDKs) in different programming languages, including one in Node.js, so JavaScript development integrates Couchbase into the product very easily. For example:</p>
<figure class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="kd">var</span> <span class="nx">couchbase</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="s1">'couchbase'</span><span class="p">);</span>
<span class="kd">var</span> <span class="nx">cluster</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">couchbase</span><span class="p">.</span><span class="nx">Cluster</span><span class="p">(</span><span class="s1">'couchbase://127.0.01'</span><span class="p">);</span>
<span class="kd">var</span> <span class="nx">bucket</span> <span class="o">=</span> <span class="nx">cluster</span><span class="p">.</span><span class="nx">openBucket</span><span class="p">(</span><span class="s1">'default'</span><span class="p">);</span>
<span class="nx">bucket</span><span class="p">.</span><span class="nx">get</span><span class="p">(</span><span class="nx">userId</span><span class="p">,</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">err</span><span class="p">,</span> <span class="nx">res</span><span class="p">)</span> <span class="p">{</span>
<span class="k">if</span> <span class="p">(</span><span class="nx">err</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">err</span><span class="p">);</span>
<span class="c1">//handle error</span>
<span class="p">}</span>
<span class="k">else</span> <span class="p">{</span>
<span class="c1">//access data here</span>
<span class="p">}</span>
<span class="p">});</span></code></pre></figure>
<p>However, there are some caveats which we have discovered. Suppose, the application was not able to connect to couchbase when it was started. There will never be a connection to couchbase and <code>bucket.get</code> will throw an exception <code>cannot perform operations on a shutdown bucket</code>. Note that, this will not fall into an error case, infact this will be treated as an unhandled exception.</p>
<p>This was really undesirable for us, since we were using couchbase as a caching store. An error in connecting to couchbase is ideally a miss, which our code should handle and lookup the data in our persistent store, MySQL.</p>
<h2>Solution</h2>
<p>There are few solutions to this problem. I am describing here what we choose.
Some of them are described <a href="https://wiredcraft.com/blog/reconnect-couchbase-nodejs/">here</a> as well.</p>
<p>First is to track the connection status of couchbase at startup. And then connect to couchbase, only if the status indicated success. For example,</p>
<figure class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="kd">var</span> <span class="nx">couchbase</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="s1">'couchbase'</span><span class="p">);</span>
<span class="kd">var</span> <span class="nx">cluster</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">couchbase</span><span class="p">.</span><span class="nx">Cluster</span><span class="p">(</span><span class="nx">config</span><span class="p">.</span><span class="nx">couch</span><span class="p">);</span>
<span class="kd">var</span> <span class="nx">bucket</span> <span class="o">=</span> <span class="nx">cluster</span><span class="p">.</span><span class="nx">openBucket</span><span class="p">(</span><span class="s1">'default'</span><span class="p">);</span>
<span class="c1">// connection status</span>
<span class="kd">var</span> <span class="nx">couchbaseConnected</span> <span class="o">=</span> <span class="kc">false</span><span class="p">;</span>
<span class="nx">bucket</span><span class="p">.</span><span class="nx">on</span><span class="p">(</span><span class="s1">'error'</span><span class="p">,</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">err</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">couchbaseConnected</span> <span class="o">=</span> <span class="kc">false</span><span class="p">;</span>
<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="s1">'CONNECT ERROR:'</span><span class="p">,</span> <span class="nx">err</span><span class="p">);</span>
<span class="p">});</span>
<span class="nx">bucket</span><span class="p">.</span><span class="nx">on</span><span class="p">(</span><span class="s1">'connect'</span><span class="p">,</span> <span class="kd">function</span> <span class="p">()</span> <span class="p">{</span>
<span class="nx">couchbaseConnected</span> <span class="o">=</span> <span class="kc">true</span><span class="p">;</span>
<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="s1">'connected couchbase'</span><span class="p">);</span>
<span class="p">});</span></code></pre></figure>
<p>Now, since we have the status at startup, we can use it to decide weather to connect to couchbase or not.</p>
<figure class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="k">if</span> <span class="p">(</span><span class="nx">couchbaseConnected</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">bucket</span><span class="p">.</span><span class="nx">get</span><span class="p">(</span><span class="nx">userId</span><span class="p">,</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">err</span><span class="p">,</span> <span class="nx">res</span><span class="p">)</span> <span class="p">{</span>
<span class="k">if</span> <span class="p">(</span><span class="nx">err</span><span class="p">)</span> <span class="p">{</span>
<span class="c1">// handle error</span>
<span class="p">}</span>
<span class="k">else</span> <span class="p">{</span>
<span class="c1">// access data</span>
<span class="p">}</span>
<span class="p">});</span>
<span class="p">}</span>
<span class="k">else</span> <span class="p">{</span>
<span class="c1">// get data from persistent store, such as mysql</span>
<span class="p">}</span></code></pre></figure>
<p>The disadvantage of this approach is that if the couchbase later becomes available, the application has no way of knowing it and it will not reconnect.</p>
<p>One solution to it is to try and reconnect the bucket. For example, we modify our code as follows:</p>
<figure class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="kd">var</span> <span class="nx">couchbase</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="s1">'couchbase'</span><span class="p">);</span>
<span class="kd">var</span> <span class="nx">cluster</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">couchbase</span><span class="p">.</span><span class="nx">Cluster</span><span class="p">(</span><span class="nx">config</span><span class="p">.</span><span class="nx">couch</span><span class="p">);</span>
<span class="kd">var</span> <span class="nx">bucket</span><span class="p">;</span>
<span class="kd">var</span> <span class="nx">couchbaseConnected</span> <span class="o">=</span> <span class="kc">false</span><span class="p">;</span>
<span class="nx">tryOpenBucket</span><span class="p">();</span>
<span class="kd">function</span> <span class="nx">tryOpenBucket</span><span class="p">()</span> <span class="p">{</span>
<span class="nx">bucket</span><span class="o">=</span> <span class="nx">cluster</span><span class="p">.</span><span class="nx">openBucket</span><span class="p">(</span><span class="s1">'default'</span><span class="p">);</span>
<span class="nx">bucket</span><span class="p">.</span><span class="nx">on</span><span class="p">(</span><span class="s1">'error'</span><span class="p">,</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">err</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">couchbaseConnected</span> <span class="o">=</span> <span class="kc">false</span><span class="p">;</span>
<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="s1">'CONNECT ERROR:'</span><span class="p">,</span> <span class="nx">err</span><span class="p">);</span>
<span class="p">});</span>
<span class="nx">bucket</span><span class="p">.</span><span class="nx">on</span><span class="p">(</span><span class="s1">'connect'</span><span class="p">,</span> <span class="kd">function</span> <span class="p">()</span> <span class="p">{</span>
<span class="nx">couchbaseConnected</span> <span class="o">=</span> <span class="kc">true</span><span class="p">;</span>
<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="s1">'connected couchbase'</span><span class="p">);</span>
<span class="p">});</span>
<span class="p">}</span></code></pre></figure>
<p>And, while accessing any key:</p>
<figure class="highlight"><pre><code class="language-javascript" data-lang="javascript"> <span class="k">if</span> <span class="p">(</span><span class="nx">couchbaseConnected</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">bucket</span><span class="p">.</span><span class="nx">get</span><span class="p">(</span><span class="nx">userId</span><span class="p">,</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">err</span><span class="p">,</span> <span class="nx">res</span><span class="p">)</span> <span class="p">{</span>
<span class="k">if</span> <span class="p">(</span><span class="nx">err</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">err</span><span class="p">);</span>
<span class="c1">// handle error</span>
<span class="p">}</span>
<span class="k">else</span> <span class="p">{</span>
<span class="c1">// access data</span>
<span class="p">}</span>
<span class="p">});</span>
<span class="p">}</span>
<span class="k">else</span> <span class="p">{</span>
<span class="c1">// We try and open bucket again here. If its successful, couchbaseConnected will bet set to true and next time data will be fetched from couchbase </span>
<span class="nx">tryOpenBucket</span><span class="p">();</span>
<span class="c1">// Get data from persistent store, mysql</span>
<span class="p">}</span></code></pre></figure>
<p>In this solution, We try and open bucket again everytime we access the key. If its successful, <code>couchbaseConnected</code> will bet set to true and next time data will be fetched from couchbase.</p>
</content>
</entry>
<entry>
<title>Debugging SSL Issues in Java</title>
<link href="http://madhur.co.in/blog/2016/10/30/debugging-ssl-issues-java.html"/>
<updated>2016-10-30T00:00:00+05:30</updated>
<id>id:/blog/2016/10/30/debugging-ssl-issues-java</id>
<content type="html"><p>Recently we faced an issue, where all are calls to a third party vendor were failing with following stack trace in Java</p>
<figure class="highlight"><pre><code class="language-text" data-lang="text">javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure
at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
at sun.security.ssl.Alerts.getSSLException(Alerts.java:154)
at sun.security.ssl.SSLSocketImpl.recvAlert(SSLSocketImpl.java:1979)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1086)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1332)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1359)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1343)
at org.apache.http.conn.ssl.SSLConnectionSocketFactory.createLayeredSocket(SSLConnectionSocketFactory.java:394)
at org.apache.http.conn.ssl.SSLConnectionSocketFactory.connectSocket(SSLConnectionSocketFactory.java:353)
at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:141)
at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:353)
at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:380)
at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:236)
at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:184)
at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:88)
at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:110)
at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:184)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:107)
at HttpURLConnectionExample.sendGet1(HttpURLConnectionExample.java:83)
at HttpURLConnectionExample.main(HttpURLConnectionExample.java:48)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144) [Raw read]: length = 5 </code></pre></figure>
<p>As per the vendor, there was no issue with their site. Other partners were able to call their API&#39;s successfully.</p>
<p>This is one of the peculiar problem which happens with Java 7, due to the mismatch of ciphers between Java 7 and the destination webserver.</p>
<p>In order to debug this in Java, we need to add the parameter <code>-Djavax.net.debug=all</code> to the command line. Through this command line, we get full debug output such as follows:</p>
<figure class="highlight"><pre><code class="language-text" data-lang="text">main, READ: TLSv1.2 Handshake, length = 333
*** ECDH ServerKeyExchange
Signature Algorithm SHA512withRSA
Server key: Sun EC public key, 256 bits
public x coord: 52151221190485581151214316798815876713912665823307283797594930350231973293152
public y coord: 5451449004300784798879937097030816531206591013653597175688384253361719134656
parameters: secp256r1 [NIST P-256, X9.62 prime256v1] (1.2.840.10045.3.1.7)
[read] MD5 and SHA1 hashes: len = 333
...
[Raw read]: length = 5
0000: 16 03 03 00 04 .....
[Raw read]: length = 4
0000: 0E 00 00 00 ....
main, READ: TLSv1.2 Handshake, length = 4
*** ServerHelloDone
[read] MD5 and SHA1 hashes: len = 4
0000: 0E 00 00 00 ....
*** ECDHClientKeyExchange
ECDH Public value: { 4, 247, 183, 127, 41, 28, 143, 49, 205, 39, 146, 57, 240, 102, 0, 53, 90, 244, 137, 176, 75, 192, 158, 138, 198, 115, 11, 101, 50, 2, 228, 254, 236, 211, 211, 208, 159, 105, 156, 135, 78, 234, 56, 97, 34, 209, 81, 216, 147, 185, 181, 67, 73, 84, 198, 4, 105, 61, 170, 131, 230, 115, 58, 207, 46 }
[write] MD5 and SHA1 hashes: len = 70
0000: 10 00 00 42 41 04 F7 B7 7F 29 1C 8F 31 CD 27 92 ...BA....)..1.'.
0010: 39 F0 66 00 35 5A F4 89 B0 4B C0 9E 8A C6 73 0B 9.f.5Z...K....s.
0020: 65 32 02 E4 FE EC D3 D3 D0 9F 69 9C 87 4E EA 38 e2........i..N.8
0030: 61 22 D1 51 D8 93 B9 B5 43 49 54 C6 04 69 3D AA a".Q....CIT..i=.
0040: 83 E6 73 3A CF 2E ..s:..
main, WRITE: TLSv1.2 Handshake, length = 70
[Raw write]: length = 75
...
... no IV derived for this protocol
main, WRITE: TLSv1.2 Change Cipher Spec, length = 1
[Raw write]: length = 6
0000: 14 03 03 00 01 01 ......
*** Finished
verify_data: { 162, 89, 141, 227, 142, 139, 54, 27, 241, 56, 38, 145 }
***
[write] MD5 and SHA1 hashes: len = 16
0000: 14 00 00 0C A2 59 8D E3 8E 8B 36 1B F1 38 26 91 .....Y....6..8&amp;.
Padded plaintext before ENCRYPTION: len = 64
0000: FD AD 67 A2 4D 09 37 F3 4F 7B 53 C5 D9 41 CA 17 ..g.M.7.O.S..A..
0010: 14 00 00 0C A2 59 8D E3 8E 8B 36 1B F1 38 26 91 .....Y....6..8&amp;.
0020: BF 2D 9D 66 AA EB 4C E6 4F 35 51 A2 F7 00 40 77 .-.f..L.O5Q...@w
0030: 2A EA 37 3E 0B 0B 0B 0B 0B 0B 0B 0B 0B 0B 0B 0B *.7&gt;............
main, WRITE: TLSv1.2 Handshake, length = 64
[Raw write]: length = 69
0000: 16 03 03 00 40 D3 7C 46 86 EE 71 97 63 10 93 8B [email protected]...
0010: 16 28 84 D4 72 CB 29 CA 65 FB 08 6E 5F C7 F2 83 .(..r.).e..n_...
0020: A7 45 5D 93 86 5B ED D7 AF A4 18 3A 6E AF 46 88 .E]..[.....:n.F.
0030: 83 0C 09 CC 01 5B BF 8D AB FD D9 6B 8C D1 E6 A6 .....[.....k....
0040: AD 10 69 1D 81 ..i..
[Raw read]: length = 5
0000: 14 03 03 00 01 .....
[Raw read]: length = 1
0000: 01 .
main, READ: TLSv1.2 Change Cipher Spec, length = 1
[Raw read]: length = 5
0000: 16 03 03 00 40 ....@
[Raw read]: length = 64
0000: 6C 21 89 CD 5E FF 76 BD 95 43 51 F1 E6 58 64 5C l!..^.v..CQ..Xd\
0010: 97 6D DB 98 3F 1C 25 3D 39 DF C6 D3 8C E1 E2 64 .m..?.%=9......d
0020: 18 BD 91 8A 7F B2 8E 78 82 F7 68 B2 3A 77 08 BE .......x..h.:w..
0030: B8 2C 94 2D 06 EE 7B CB 40 86 FA 1A B1 9C 06 3F .,.-....@......?
main, READ: TLSv1.2 Handshake, length = 64
Padded plaintext after DECRYPTION: len = 64
0000: 15 A8 6B 92 28 EB 61 3B 2A A0 BA 2F 0E D4 6D F5 ..k.(.a;*../..m.
0010: 14 00 00 0C 17 9E 44 19 42 D2 7F 29 74 7F 66 A8 ......D.B..)t.f.
0020: 36 A5 B7 2A 7B A7 D5 B6 DE F2 53 2B 15 E3 CA 5E 6..*......S+...^
0030: 1A 3F 1D D5 0B 0B 0B 0B 0B 0B 0B 0B 0B 0B 0B 0B .?..............
*** Finished
verify_data: { 23, 158, 68, 25, 66, 210, 127, 41, 116, 127, 102, 168 }
***
%% Cached client session: [Session-1, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA]
[read] MD5 and SHA1 hashes: len = 16
0000: 14 00 00 0C 17 9E 44 19 42 D2 7F 29 74 7F 66 A8 ......D.B..)t.f.</code></pre></figure>
<p>Unless you really know SSL protocol in detail, you won&#39;t understand all of it. But atleast I am able to figure out the following:</p>
<ul>
<li>The protocol in use is TLSv1.2</li>
<li>Cipher used was TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA</li>
<li>The handshake was successfully completed</li>
</ul>
<p>Some of the secure webservers, will only support TLS v1.2 protocol and deny any request on SSLv3 or TSL v1 protocol.</p>
<p>If that is the case, this is easy to fix in Java by adding following command line parameters</p>
<p><code>JAVACMD=&quot;$JAVACMD -Ddeployment.security.SSLv2Hello=false -Ddeployment.security.SSLv3=false -Ddeployment.security.TLSv1=false -D\
deployment.security.TLSv1.1=true -Ddeployment.security.TLSv1.2=true&quot;</code></p>
<p>or even this</p>
<p><code>-Dhttps.protocols=TLSv1.1,TLSv1.2</code></p>
<p>However, some of the webservers can force the clients to use very strong ciphers which are not available in Java 7. They are only available in Java 8.</p>
<p>The list of ciphers supported by SSL site can be found through
<a href="https://www.ssllabs.com/index.html">https://www.ssllabs.com/index.html</a></p>
<p>In that case, You can download the JCE Unlimited Strength Jurisdiction Policy files for Java 7 from <a href="http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html">http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html</a> and replace the two JARs (<code>local_policy.jar, US_export_policy.jar</code>) under your JRE&#39;s <code>lib/security</code> directory with the ones from the downloaded package. This will add additional (stronger) ciphersuites and you should be able to connect without having to make any changes to your code or enable TLSv1.2.</p>
<p>For reference, here are the ciphersuites available in Java 7 (1.7.0_79):</p>
<figure class="highlight"><pre><code class="language-text" data-lang="text"> SSL_DH_anon_WITH_3DES_EDE_CBC_SHA
SSL_DH_anon_WITH_DES_CBC_SHA
SSL_DH_anon_WITH_RC4_128_MD5
SSL_RSA_EXPORT_WITH_DES40_CBC_SHA
SSL_RSA_EXPORT_WITH_RC4_40_MD5
* SSL_RSA_WITH_3DES_EDE_CBC_SHA
SSL_RSA_WITH_DES_CBC_SHA
SSL_RSA_WITH_NULL_MD5
SSL_RSA_WITH_NULL_SHA
* SSL_RSA_WITH_RC4_128_MD5
* SSL_RSA_WITH_RC4_128_SHA
* TLS_DHE_DSS_WITH_AES_128_CBC_SHA
* TLS_DHE_DSS_WITH_AES_128_CBC_SHA256
* TLS_DHE_RSA_WITH_AES_128_CBC_SHA
* TLS_DHE_RSA_WITH_AES_128_CBC_SHA256
TLS_DH_anon_WITH_AES_128_CBC_SHA
TLS_DH_anon_WITH_AES_128_CBC_SHA256
* TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA
* TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA
* TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256
TLS_ECDHE_ECDSA_WITH_NULL_SHA
* TLS_ECDHE_ECDSA_WITH_RC4_128_SHA
* TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA
* TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA
* TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256
TLS_ECDHE_RSA_WITH_NULL_SHA
* TLS_ECDHE_RSA_WITH_RC4_128_SHA
* TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA
* TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA
* TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256
TLS_ECDH_ECDSA_WITH_NULL_SHA
* TLS_ECDH_ECDSA_WITH_RC4_128_SHA
* TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA
* TLS_ECDH_RSA_WITH_AES_128_CBC_SHA
* TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256
TLS_ECDH_RSA_WITH_NULL_SHA
* TLS_ECDH_RSA_WITH_RC4_128_SHA
TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA
TLS_ECDH_anon_WITH_AES_128_CBC_SHA
TLS_ECDH_anon_WITH_NULL_SHA