-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathproxy.txt
1612 lines (1066 loc) · 52.8 KB
/
proxy.txt
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
.. _proxy:
User Manual
===========
Glossary
--------
Familiarizing with the glossary would help to understand the rest of this guide.
Host
~~~~
Hostname is defined by incoming ``Host`` header. E.g. ``curl http://example.com/alice`` generates the following request:
.. code-block:: sh
GET /alice HTTP/1.1
User-Agent: curl/7.35.0
Host: example.com
Vulcand hosts contain associated information and settings, such as SNI options and TLS certificates.
Listener
~~~~~~~~
Listener is a dynamic socket that can be attached or detached to Vulcand without restart. Vulcand can have multiple http and https listeners
attached to it, providing service on multiple interfaces and protocols.
Frontend
~~~~~~~~
Frontends match the requests and forward it to the backends.
Each frontend defines a route - a special expression that matches the request, e.g. ``Path("/v1/path")``.
Frontends are linked to backend and Vulcand will use the servers from this backend to serve the request.
Backend
~~~~~~~
Backend is a collection of servers, they control connection pools to servers and transport options, such as connection, read and write timeouts.
Server
~~~~~~
Server is a final destination of the incoming request, each server is defined by URL ``<schema>://<host>:<port>``, e.g. ``http://localhost:5000``.
Middleware
~~~~~~~~~~
Vulcand supports pluggable middlewares. Middlewares can intercept or transform the request to any frontend. Examples of the supported middlewares are rate limits and connection limits.
You can add or remove middlewares using command line, API or directly via backends.
Circuit Breaker
~~~~~~~~~~~~~~~
Circuit breakers are special type of middlewares that observe various metrics for a particular frontend and can activate failover scenario whenever the condition matches e.g. error rate exceeds the threshold.
Secret storage
~~~~~~~~~~~~~~
Vulcand supports secret storage - running process acts like encryption/decryption service every time it reads and writes sensitive data, e.g. TLS certificates to the backend.
To use this feature, users generate ``sealKey`` using command line utility and pass this key to the process for encryption and decryption of the data in the backends.
Failover Predicates
~~~~~~~~~~~~~~~~~~~
Sometimes it is handy to retry the request on error. The good question is what constitutes an error? Sometimes it's a read/write timeout, and somethimes it's a special error code.
Failover predicates are expressions that define when the request can be failed over, e.g. ``IsNetworkError() && Attempts <= 2``
.. code-block:: bash
IsNetworkError() # failover on network error
Attempts() <= 1 # allows only 1 failover attempt
RequestMethod() == "GET" # failover for GET requests only
ResponseCode() == 408 # failover on 408 HTTP response code
.. warning:: if you omit `Attempts`, failover will max out after 10 attempts.
Route
~~~~~
Route is a simple routing language for matching http requests with Go syntax: ``Method("POST") && Path("/path")``, here are a couple of examples:
.. code-block:: go
Host("<user>.example.com") // Match by host with trie syntax
HostRegexp(".*.example.com") // Match by host with regexp syntax
Path("/v1/users/<user>") // Match by path with trie syntax
Method("POST") && Path("/v1/users") // Match by method and path with trie syntax
PathRegexp("/v1/users/.*") // Match by path with regexp syntax
MethodRegexp("DELETE|GET") && PathRegexp("/v1/users/.*") // Match by method and path with regexp syntax
Header("Content-Type", "application/<subtype>") // trie-based matcher for headers
HeaderRegexp("Content-Type", "application/.*") // regexp based matcher for headers
Configuration
-------------
Vulcand can be configured via Etcd, API or command line tool - ``vctl``. You can switch between different configuration examples using the samples switch.
Backends and servers
~~~~~~~~~~~~~~~~~~~~~~~
.. figure:: _static/img/VulcanUpstream.png
:align: left
Backend is a collection of servers. Vulcand load-balances requests within the backend and keeps the connection pool to every server.
Frontends using the same backend will share the connections.
Adding and removing servers to the backend will change the traffic in real-time, removing the backend will lead to graceful drain off of the connections.
.. code-block:: etcd
# Upsert backend and add a server to it
etcdctl set /vulcand/backends/b1/backend '{"Type": "http"}'
etcdctl set /vulcand/backends/b1/servers/srv1 '{"URL": "http://localhost:5000"}'
.. code-block:: cli
# Upsert backend and add a server to it
vctl backend upsert -id b1
vctl server upsert -b b1 -id srv1 -url http://localhost:5000
.. code-block:: api
# Upsert backend and add a server to it
curl -X POST -H "Content-Type: application/json" http://localhost:8182/v2/backends\
-d '{"Backend": {"Id":"b1", "Type":"http"}}'
curl -X POST -H "Content-Type: application/json" http://localhost:8182/v2/backends/b1/servers\
-d '{"Server": {"Id":"srv1", "URL":"http://localhost:5000"}}'
**Backend settings**
Backends define the configuration options to the servers, such as the amount of idle connections and timeouts.
Backend options are represented as JSON dictionary.
.. code-block:: javascript
{
"Timeouts": {
"Read": "1s", // Socket read timeout (before we receive the first reply header)
"Dial": "2s", // Socket connect timeout
"TLSHandshake": "3s", // TLS handshake timeout
},
"KeepAlive": {
"Period": "4s", // Keepalive period for idle connections
"MaxIdleConnsPerHost": 3, // How many idle connections will be kept per host
}
}
You can update the settings at any time, that will initiate graceful reload of the underlying settings in Vulcand.
.. code-block:: etcd
etcdctl set /vulcand/backends/b1/backend '{"Type": "http", "Settings": {"KeepAlive": {"MaxIdleConnsPerHost": 128, "Period": "4s"}}}'
.. code-block:: cli
vctl backend upsert -id b1 \
-readTimeout=1s -dialTimeout=2s -handshakeTimeout=3s\
-keepAlivePeriod=4s -maxIdleConns=128
.. code-block:: api
curl -X POST -H "Content-Type: application/json" http://localhost:8182/v2/backends\
-d '{"Backend": {"Id":"b1", "Type":"http", "Settings": {"KeepAlive": {"MaxIdleConnsPerHost": 128, "Period": "4s"}}}}'
**Server heartbeat**
Heartbeat allows to automatically de-register the server when it crashes or wishes to be de-registered.
Server can heartbeat it's presense, and once the heartbeat is stopped, Vulcand will gracefully remove the server from the rotation.
.. code-block:: etcd
# Upsert a server with TTL 5 seconds
etcdctl set --ttl 5 /vulcand/backends/b1/servers/srv2 '{"URL": "http://localhost:5001"}'
.. code-block:: cli
# Upsert a server with TTL 5 seconds
vctl server upsert -b b1 -id srv2 -ttl 5s -url http://localhost:5002
.. code-block:: api
# Upsert a server with TTL 5 seconds
curl -X POST -H "Content-Type: application/json" http://localhost:8182/v2/backends/b1/servers\
-d '{"Server": {"Id":"srv2", "URL":"http://localhost:5001"}, "TTL": "5s"}'
Frontends
~~~~~~~~~
.. figure:: _static/img/VulcanFrontend.png
:align: left
If request matches a frontend route it is redirected to one of the servers of the associated backend.
It is recommended to specify a frontend per API method, e.g. ``Host("api.example.com") && Method("POST") && Path("/v1/users")``.
Route can be any valid route expression, e.g. ``Path("/v1/users")`` will match for all hosts and
``Host("api.example.com") && Path("/v1/users")`` will match only for ``api.example.com``.
.. code-block:: etcd
# upsert frontend connected to backend b1 and matching path "/"
etcdctl set /vulcand/frontends/f1/frontend '{"Type": "http", "BackendId": "b1", "Route": "Path(`/`)"}'
.. code-block:: cli
# upsert frontend connected to backend b1 and matching path "/"
vctl frontend upsert -id f1 -b b1 -route 'Path("/")'
.. code-block:: api
# upsert frontend connected to backend b1 and matching path "/"
curl -X POST -H "Content-Type: application/json" http://localhost:8182/v2/frontends\
-d '{"Frontend": {"Id":"f1", "Type": "http", "BackendId": "b1", "Route": "Path(\"/\")"}}'
**Frontend settings**
Frontends control various limits, forwarding and failover settings.
.. code-block:: javascript
{
"Limits": {
"MaxMemBodyBytes": 12, // Maximum request body size to keep in memory before buffering to disk
"MaxBodyBytes": 400, // Maximum request body size to allow for this frontend
},
"FailoverPredicate": "IsNetworkError() && Attempts() <= 1", // Predicate that defines when requests are allowed to failover
"Hostname": "host1", // Host to set in forwarding headers
"TrustForwardHeader": true, // Time provider (useful for testing purposes)
}
Setting frontend settings upates the limits and parameters for the newly arriving requests in real-time.
.. code-block:: etcd
etcdctl set /vulcand/frontends/f1/frontend '{"Id": "f1", "Type": "http", "BackendId": "b1", "Route": "Path(`/`)", "Settings": {"FailoverPredicate":"(IsNetworkError() || ResponseCode() == 503) && Attempts() <= 2"}}'
.. code-block:: cli
vctl frontend upsert\
-id=f1\
-route='Path("/")'\
-b=b1\
-maxMemBodyKB=6 -maxBodyKB=7\
-failoverPredicate='IsNetworkError()'\
-trustForwardHeader\
-forwardHost=host1
.. code-block:: api
curl -X POST -H "Content-Type: application/json" http://localhost:8182/v2/frontends\
-d '{"Frontend": {"Id": "f1", "Type": "http", "BackendId": "b1", "Route": "Path(`/`)", "Settings": {"FailoverPredicate":"(IsNetworkError() || ResponseCode() == 503) && Attempts() <= 2"}}}'
**Switching backends**
Updating frontend's backend property gracefully re-routes the traffic to the new servers assigned to this backend:
.. code-block:: etcd
# redirect the traffic of the frontend "loc1" to the servers of the backend "b2"
etcdctl set /vulcand/frontends/f1/frontend '{"Type": "http", "BackendId": "b2", "Route": "Path(`/`)"}'
.. code-block:: cli
# redirect the traffic of the frontend "f1" to the servers of the backend "b2"
vctl frontend upsert -id=f1 -route='Path("/")' -b=b2
.. code-block:: api
# redirect the traffic of the frontend "loc1" to the servers of the backend "up2"
curl -X POST -H "Content-Type: application/json" http://localhost:8182/v2/frontends -d '{"Frontend": {"Id": "f1", "Type": "http", "BackendId": "b2", "Route": "Path(`/`)"}}'
.. note:: you can add and remove servers to the existing backend, and Vulcand will start redirecting the traffic to them automatically
Hosts
~~~~~
One can use Host entries to specify host-related settings, such as TLS certificates and SNI options.
**TLS Certificates**
Certificates are stored as encrypted JSON dictionaries. Updating a certificate will gracefully reload it for all running HTTP servers.
.. code-block:: etcd
# Set keypair
etcdctl set /vulcand/hosts/localhost/host '{"Settings": {"KeyPair": {...}}}'
.. code-block:: cli
vctl host upsert -name <host> -cert=</path-to/chain.crt> -privateKey=</path-to/key>
.. code-block:: api
curl -X POST -H "Content-Type: application/json" http://localhost:8182/v2/hosts\
-d '{"Host": { "Name": "localhost", "Settings": {"KeyPair": {"Cert": "base64", Key: "base64"}}}}'
.. note:: When setting keypair via Etcd you need to encrypt keypair. This is explained in `TLS`_ section of this document.
**OCSP**
`Online Certificate Status Protocol <http://en.wikipedia.org/wiki/Online_Certificate_Status_Protocol>`_ is a protocol for certificate revocation checking. Vulcand checks OCSP status in the background and
includes the OCSP staple response in the TLS handshake when this feature turned on.
Read more about turning OCSP for hosts in `OCSP`_ section of this document.
Routing Language
~~~~~~~~~~~~~~~~
Vulcand uses a special type of a routing language to match requests - called ``route`` and implemented as a `standalone library <https://github.com/mailgun/route>`_
It uses Go syntax to route http requests by by hostname, method, path and headers. Every Vulcand frontend has a special ``Route`` field for routing requests.
Here is the syntax explained:
.. code-block:: go
Matcher("value") // matches value using trie
Matcher("<string>.value") // uses trie-based matching for a.value and b.value
MatcherRegexp(".*value") // uses regexp-based matching
Host matcher:
.. code-block:: go
Host("<subdomain>.localhost") // trie-based matcher for a.localhost, b.localhost, etc.
HostRegexp(".*localhost") // regexp based matcher
Path matcher:
.. code-block:: go
Path("/hello/<value>") // trie-based matcher for raw request path
PathRegexp("/hello/.*") // regexp-based matcher for raw request path
Method matcher:
.. code-block:: go
Method("GET") // trie-based matcher for request method
MethodRegexp("POST|PUT") // regexp based matcher for request method
Header matcher:
.. code-block:: go
Header("Content-Type", "application/<subtype>") // trie-based matcher for headers
HeaderRegexp("Content-Type", "application/.*") // regexp based matcher for headers
Matchers can be combined using ``&&`` operator:
.. code-block:: go
Host("localhost") && Method("POST") && Path("/v1")
Vulcan will join the trie-based matchers into one trie matcher when possible, for example:
.. code-block:: go
Host("localhost") && Method("POST") && Path("/v1")
Host("localhost") && Method("GET") && Path("/v2")
Will be combined into one trie for performance. If you add a third route:
.. code-block:: go
Host("localhost") && Method("GET") && PathRegexp("/v2/.*")
It wont be joined ito the trie, and would be matched separately instead.
.. warning:: Vulcan can not merge regexp-based routes into efficient structure, so if you have hundreds/thousands of frontends, use trie-based routes!
Host based routing
//////////////////
Vulcand does not require host-specific routing, e.g. the frontend with the following route will match all requests regardless of their hostname:
.. code-block:: go
PathRegexp("/.*")
.. code-block:: bash
curl -H "Host:example.com" http://localhost/hello # works
curl -H "Host:hello.com" http://localhost/hello # also works
In case if you need Host-based routing (just as Apache's ``VHost`` or Nginx's ``Server`` names), you can use the routes:
.. code-block:: go
Host("example.com") && PathRegexp("/.*")
.. code-block:: bash
curl -H "Host:example.com" http://localhost/hello # works
curl -H "Host:hello.com" http://localhost/hello # not found
.. note:: The example above do not set up host entries in Vulcand. You only need them when using HTTPS to supply certificates.
Method matching
///////////////
Vulcand works better when creating a separate frontend for each HTTP method in your API:
.. code-block:: go
Host("localhost") && Method("POST") && Path("/users")
Host("localhost") && Method("GET") && Path("/users")
In this case each frontend collects separate set of realtime metrics that are different for creating and gettings users. This separation will provide separate histograms and separate load balancing logic for different request types what helps to understand the performance better.
Listeners
~~~~~~~~~
.. figure:: _static/img/VulcanListener.png
:align: left
Listeners allow attaching and detaching sockets on various interfaces and networks.
Vulcand can have multiple listeners attached and share the same listener.
.. code-block:: javascript
{
"Protocol":"http", // 'http' or 'https'
"Scope": "", // optional scope field, read below for details
"Address":{
"Network":"tcp", // 'tcp' or 'unix'
"Address":"localhost:8183" // 'host:port' or '/path/to.socket'
},
}
.. code-block:: etcd
# Add http listener accepting requests on 127.0.0.1:8183
etcdctl set /vulcand/listeners/ls1\
'{"Protocol":"http", "Address":{"Network":"tcp", "Address":"127.0.0.1:8183"}}'
.. code-block:: cli
# Add http listener accepting requests on 127.0.0.1:80
vctl listener upsert --id ls1 --proto=http --net=tcp -addr=127.0.0.1:8080
.. code-block:: api
# Add http listener accepting requests on 127.0.0.1:8183
curl -X POST -H "Content-Type: application/json" http://localhost:8182/v2/listeners\
-d '{"Listener":{"Id": "ls1", "Protocol":"http", "Address":{"Network":"tcp", "Address":"127.0.0.1:8183"}}}'
**Listener scopes**
Listeners support scopes as the way to limit operational scope of socket.
Scope field uses Vulcand `Routing Language`_.
Here's an example of Listener that only allows requests with hostname ``example.com``
.. code-block:: javascript
{
"Protocol":"http", // 'http' or 'https'
"Scope": "Host(`example.com`)", // operational scope
"Address":{
"Network":"tcp", // 'tcp' or 'unix'
"Address":"0.0.0.0:8183" // 'host:port' or '/path/to.socket'
},
}
E.g. if we have two frontends defined:
.. code-block:: javascript
Host("example.com") && Path("/users")
Host("localhost") && Path("/users")
Only first frontend is reachable for requests coming to port ``8183``.
Middlewares
~~~~~~~~~~~
.. figure:: _static/img/VulcanMiddleware.png
:align: left
Middlewares are allowed to observe, modify and intercept http requests and responses. Vulcand provides several middlewares.
Users can write their own middlewares for Vulcand in Go.
To specify execution order of the middlewares, one can define the priority. Middlewares with smaller priority values will be executed first.
Rate Limits
~~~~~~~~~~~
Vulcan supports controlling request rates. Rate can be checked against different request parameters and is set up via limiting variable.
.. code-block:: bash
client.ip # client ip
request.header.X-Special-Header # request header
Adding and removing middlewares will modify the frontend behavior in real time. One can set expiring middlewares as well.
.. code-block:: etcd
# Update or set rate limit the request to frontend "f1" to 1 request per second per client ip
# with bursts up to 3 requests per second.
etcdctl set /vulcand/frontends/f1/middlewares/rl1 '{
"Priority": 0,
"Type": "ratelimit",
"Middleware":{
"Requests":1,
"PeriodSeconds":1,
"Burst":3,
"Variable": "client.ip"}}'
.. code-block:: cli
# Update or set rate limit the request to frontend "f1" to 1 request per second per client ip
# with bursts up to 3 requests per second.
vctl ratelimit upsert -id=rl1 -frontend=f1 -requests=1 -burst=3 -period=1 --priority=0
.. code-block:: api
# Update or set rate limit the request to frontend "f1" to 1 request per second per client ip
# with bursts up to 3 requests per second.
curl -X POST -H "Content-Type: application/json" http://localhost:8182/v2/frontends/f1/middlewares\
-d '{"Middleware": {
"Priority": 0,
"Type": "ratelimit",
"Id": "rl1",
"Middleware":{
"Requests":1,
"PeriodSeconds":1,
"Burst":3,
"Variable": "client.ip"}}}'
**Programmatic rate limits**
Sometimes you have to change rate limits based on various parameters, e.g. account billing plan. Instead of setting hard-coded rate limits, Vulcand can accept rate limits
set via headers for each individual request.
Each HTTP header should contain a JSON-encoded list with rates in the following format:
.. code-block:: json
[{"PeriodSeconds": 1, "Requests": 2, "Burst": 3}]
That means that you should write a middleware that sets the header to the right value and place it before the ratelimit middleware.
After it's done you can activate the ratelimit plugin:
.. code-block:: etcd
# Update or set rate limit the request to frontend "f1" to get the rates from the X-Custom-Rates.
# in case if the header is missing, ratelimit will default to 1 request per second per client ip
# with bursts up to 3 requests per second.
etcdctl set /vulcand/frontends/f1/middlewares/rl1 '{
"Id":"rl1",
"Priority":0,
"Type":"ratelimit",
"Middleware":{
"PeriodSeconds":1,
"Requests":1,
"Burst":3,
"Variable":"client.ip",
"RateVar":"request.header.X-Custom-Rates"}}'
.. code-block:: cli
# Update or set rate limit the request to frontend "f1" to get the rates from the X-Custom-Rates.
# in case if the header is missing, ratelimit will default to 1 request per second per client ip
# with bursts up to 3 requests per second.
vctl ratelimit upsert -id=rl1 -frontend=f1 -requests=1 -burst=3 -period=1 --priority=0 --rateVar="request.header.X-Custom-Rates"
.. code-block:: api
# Update or set rate limit the request to frontend "f1" to get the rates from the X-Custom-Rates.
# in case if the header is missing, ratelimit will default to 1 request per second per client ip
# with bursts up to 3 requests per second.
curl -X POST -H "Content-Type: application/json" http://localhost:8182/v2/frontends/f1/middlewares -d '{
"Middleware": {
"Id":"rl1",
"Priority":0,
"Type":"ratelimit",
"Middleware":{
"PeriodSeconds":1,
"Requests":1,
"Burst":3,
"Variable":"client.ip",
"RateVar":"request.header.X-Custom-Rates"}}}'
Connection Limits
~~~~~~~~~~~~~~~~~
Connection limits control the amount of simultaneous connections per frontend. Frontends re-use the same variables as rate limits.
.. code-block:: etcd
# limit the amount of connections per frontend to 16 per client ip
etcdctl set /vulcand/frontends/f1/middlewares/cl1\
'{"Priority": 0, "Type": "connlimit", "Middleware":{"Connections":16, "Variable": "client.ip"}}'
.. code-block:: cli
# limit the amount of connections per frontend to 16 per client ip
vctl connlimit upsert -id=cl1 -frontend=f1 -connections=1 --priority=0 --variable=client.ip
.. code-block:: api
# limit the amount of connections per frontend to 16 per client ip
curl -X POST -H "Content-Type: application/json" http://localhost:8182/v2/frontends/f1/middlewares\
-d '{"Middleware": {"Id": "cl1", "Priority": 0, "Type": "connlimit", "Middleware":{"Connections":16, "Variable": "client.ip"}}}'
Rewrites and redirects
~~~~~~~~~~~~~~~~~~~~~~
Rewrite plugin enables rewriting request URLs, returning redirect responses and changing response bodies.
**Rewrites**
.. code-block:: etcd
# remove /foo prefix from the url
etcdctl set /vulcand/frontends/f1/middlewares/r1 '{
"Id":"r1",
"Priority":1,
"Type":"rewrite",
"Middleware":{
"Regexp":"/foo(.*)",
"Replacement":"$1",
"RewriteBody":false,
"Redirect":false}}'
.. code-block:: cli
# remove /foo prefix from the url, note the single quotes for '$1'
vctl rewrite upsert -f f1 -id r1 --regexp="/foo(.*)" --replacement='$1'
.. code-block:: api
# remove /foo prefix from the url
curl -X POST -H "Content-Type: application/json" http://localhost:8182/v2/frontends/f1/middlewares\
-d '{"Middleware": {
"Id":"r1",
"Priority":1,
"Type":"rewrite",
"Middleware":{
"Regexp":"/foo(.*)",
"Replacement":"$1",
"RewriteBody":false,
"Redirect":false}}}'
**Redirects**
Setting a ``redirect`` parameter to rewrite will make it to generate ``302 Found`` response with ``Location`` header
set to the new URL:
.. code-block:: etcd
# remove /foo prefix from the url
etcdctl set /vulcand/frontends/f1/middlewares/r1 '{
"Id":"r1",
"Priority":1,
"Type":"rewrite",
"Middleware":{
"Regexp":"^http://localhost/(.*)",
"Replacement":"https://localhost/$1",
"RewriteBody":false,
"Redirect":true}}'
.. code-block:: cli
# redirect http requests to https location
vctl rewrite upsert -f f1 -id r1 --regexp="^http://localhost/(.*)" --replacement='https://localhost/$1' --redirect
.. code-block:: api
# remove /foo prefix from the url
curl -X POST -H "Content-Type: application/json" http://localhost:8182/v2/frontends/f1/middlewares\
-d '{"Middleware": {
"Id":"r1",
"Priority":1,
"Type":"rewrite",
"Middleware":{
"Regexp":"^http://localhost/(.*)",
"Replacement":"https://localhost/$1",
"RewriteBody":false,
"Redirect":true}}}'
**Templating**
Rewrite can treat the response body as a template. Consider the following example:
.. code-block:: etcd
# treat response body as a template
etcdctl set /vulcand/frontends/f1/middlewares/r1 '{
"Id":"r1",
"Priority":1,
"Type":"rewrite",
"Middleware":{"RewriteBody":true}}'
.. code-block:: cli
# treat response body as a template
vctl rewrite upsert -f f1 -id r1 --rewriteBody
.. code-block:: api
# treat response body as a template
curl -X POST -H "Content-Type: application/json" http://localhost:8182/v2/frontends/f1/middlewares\
-d '{"Middleware": {
"Id":"r1",
"Priority":1,
"Type":"rewrite",
"Middleware":{"RewriteBody":true}}}'
The backend server can now reply:
.. code-block:: go
handler := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
w.WriteHeader(200)
w.Write([]byte(`{"foo": "{{.Request.Header.Get "variable-value"}}"}`))
})
And the client will get as a response:
.. code-block:: go
{"foo": "variable-value"}
Structured logs
~~~~~~~~~~~~~~~
.. warning:: We are still polishing the log format, so it may change soon.
``trace`` plugin supports output in syslog-compatible format of the structured logs to UDP or Unix socket.
Here's the example of the log entry:
.. code-block:: bash
Jan 13 15:07:51 vulcan pid:[3634]: @cee: {"request":{"method":"GET","url":"http://h:5000"},"response":{"code":404,"roundtrip":0.333712}}
The prefix is a standard syslog prefix, and the part after ``@cee:`` is a structured log entry. Here's the entry format explained:
.. code-block:: js
{
"request": {
"method": "GET", // request method
"url": "http://localhost:5000", // request URL
"headers": { // optional captured request headers
"User-Agent": [ // captured request User-Agent header values
"curl\/7.35.0"
]
},
"tls": { // tls is an optonal field, used when it's a TLS connection
"version": "TLS12", // TLS version used
"resume": false, // whether it's a session resumed with session ticket
"cipher_suite": "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA", // cipher used in a connection
"server": "vulcand.io" // server name used in SNI
}
},
"response": {
"code": 404, // response code
"roundtrip": 0.408372, // roundtrip in milliseconds, part after '.' is microseconds
"headers": { // optional captured response headers
"Content-Type": [
"text\/plain; charset=utf-8" // captured response Content-Type header values
]
}
}
}
Adding and removing trace middleware will turn on/off tracing in real time.
.. code-block:: etcd
# turn tracing on, pointing output to unix syslog facility.
# capture request header values 'X-A' and 'X-B' and response headers 'X-C' and 'X-D'
etcdctl set /vulcand/frontends/f1/middlewares/t1 '{
"Id":"t1",
"Priority":1,
"Type":"trace",
"Middleware":{
"ReqHeaders":["X-A","X-B"],
"RespHeaders":["X-C","X-D"],
"Addr":"syslog://"}}'
.. code-block:: cli
# turn tracing on, pointing output to unix syslog facility.
# capture request header values 'X-A' and 'X-B' and response headers 'X-C' and 'X-D'
vctl trace upsert -f f1 -id t1 --addr='syslog://'\
--reqHeader=X-A --reqHeader=X-B --respHeader=X-C --respHeader=X-D
.. code-block:: api
# turn tracing on, pointing output to unix syslog facility.
# capture request header values 'X-A' and 'X-B' and response headers 'X-C' and 'X-D'
curl -X POST -H "Content-Type: application/json" http://localhost:8182/v2/frontends/f1/middlewares -d '{
"Middleware": {
"Id":"t1",
"Priority":1,
"Type":"trace",
"Middleware":{
"ReqHeaders":["X-A","X-B"],
"RespHeaders":["X-C","X-D"],
"Addr":"syslog://"}}}'
**Controlling output**
You can control output using the following form of address values:
.. code-block:: bash
# UDP socket formats
syslog://localhost:5000 # host localhost, port 5000, LOG_LOCAL0 facility
syslog://localhost:5000?f=MAIL&sev=INFO # host localhost, port 5000, MAIL facility, INFO severity
syslog://localhost:5000?f=MAIL # host localhost, port 5000, MAIL facility, INFO severity
syslog://localhost:5000?f=LOG_LOCAL0&sev=DEBUG # host localhost, port 5000, LOG_LOCAL0 facility, INFO severity
# unixgram socket format
syslog:///tmp/out.sock # /tmp/out.sock unixgram socket
syslog:///tmp/out.sock?f=MAIL # /tmp/out.sock unixgram socket
# default syslog
syslog:// # default OS-specific unix/unixgram socket
syslog://?f=LOG_LOCAL0&sev=INFO # default OS-specific unix/unixgram socket
Circuit Breakers
~~~~~~~~~~~~~~~~
.. figure:: _static/img/CircuitStandby.png
:align: left
Circuit breaker is a special middleware that is designed to provide a fail-over action in case if service has degraded.
It is very helpful to prevent cascading failures - where the failure of the one service leads to failure of another.
Circuit breaker observes requests statistics and checks the stats against special error condition.
.. figure:: _static/img/CircuitTripped.png
:align: left
In case if condition matches, CB activates the fallback scenario: returns the response code or redirects the request to another frontend.
**Circuit Breaker states**
CB provides a set of explicit states and transitions explained below:
.. figure:: _static/img/CBFSM.png
:align: left
- Initial state is ``Standby``. CB observes the statistics and does not modify the request.
- In case if condition matches, CB enters ``Tripped`` state, where it responds with predefines code or redirects to another frontend.
- CB can execute the special HTTP callback when going from ``Standby`` to ``Tripped`` state
- CB sets a special timer that defines how long does it spend in the ``Tripped`` state
- Once ``Tripped`` timer expires, CB enters ``Recovering`` state and resets all stats
- In ``Recovering`` state Vulcand will start routing the portion of the traffic linearly increasing it over the period specified in ``Recovering`` timer.
- In case if the condition matches in ``Recovering`` state, CB enters ``Tripped`` state again
- In case if the condition does not match and recovery timer expries, CB enters ``Standby`` state.
- CB can execute the special HTTP callback when going from ``Recovering`` to ``Standby`` state
**Conditions**
CB defines a simple language that allows us to specify simple conditions that watch the stats for a frontend:
.. code-block:: javascript
NetworkErrorRatio() > 0.5 // watch error ratio over 10 second sliding window for a frontend
LatencyAtQuantileMS(50.0) > 50 // watch latency at quantile in milliseconds.
ResponseCodeRatio(500, 600, 0, 600) > 0.5 // ratio of response codes in range [500-600) to [0-600)
.. note:: Quantiles should be provided as floats - don't forget to add .0 to hint it as float
**Response fallback**
Response fallback will tell CB to reply with a predefined response instead of forwarding the request to the backend
.. code-block:: javascript
{
"Type": "response",
"Action": {
"ContentType": "text/plain",
"StatusCode": 400,
"Body": "Come back later"
}
}
**Redirect fallback**
Redirect fallback will redirect the request to another frontend.
.. note:: It won't work for frontends not defined in the Vulcand config.
.. code-block:: javascript
{
"Type": "redirect",
"Action": {
"URL": "https://example.com/fallback"
}
}
**Webhook Action**
Circuit breaker can notify extenral sources on it's state transitions, e.g. it can create a pager duty incident by issuing a webhook:
.. code-block:: javascript
{
"Body": {
"client": "Sample Monitoring Service",
"client_url": "https://example.com",
"description": "FAILURE for production/HTTP on machine srv01.acme.com",
"event_type": "trigger",
"incident_key": "srv01/HTTP",
"service_key": "-pager-duty-service-key"
},
"Headers": {
"Content-Type": [
"application/json"
]
},
"Method": "POST",
"URL": "https://events.pagerduty.com/generic/2010-04-15/create_event.json"
}
**Setup**
Circuit breaker setup is can be done via Etcd, command line or API:
.. code-block:: etcd
etcdctl set /vulcand/frontends/f1/middlewares/cb1 '{
"Id":"cb1",
"Priority":1,
"Type":"cbreaker",
"Middleware":{
"Condition":"NetworkErrorRatio() > 0.5",
"Fallback":{"Type": "response", "Action": {"StatusCode": 400, "Body": "Come back later"}},
"FallbackDuration": 10000000000,
"RecoveryDuration": 10000000000,
"CheckPeriod": 100000000
}
}'
.. code-block:: cli
vctl cbreaker upsert \
--frontend=f1 \
--id=cb1\
--condition="NetworkErrorRatio() > 0.5" \
--fallback='{"Type": "response", "Action": {"StatusCode": 400, "Body": "Come back later"}}'
.. code-block:: api
curl -X POST -H "Content-Type: application/json"\