/
varnish_tutorial.rst
4054 lines (3004 loc) · 153 KB
/
varnish_tutorial.rst
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
.. include:: util/frontpage.rst
.. include:: build/version.rst
.. include:: util/printheaders.rst
.. contents::
:class: handout
.. include:: util/control.rst
.. include:: util/param.rst
Introduction
============
- About the course
- Goals and prerequisites
- Introduction to Varnish
- History
- Design Principles
About the course
----------------
The course is split in two:
1. Architecture, command line tools, installation, parameters, etc
2. The Varnish Configuration Language
The course has roughly 50% exercises and 50% instruction, and you will find
all the information on the slides in the supplied training material.
The supplied training material also has additional information for most
chapters.
.. container:: handout
The agenda is adjusted based on the progress made. There is usually
ample time to investigate specific aspects of Varnish that may be of
special interest to some of the participants.
The exercises will occasionally offer multiple means to reach the same
goals. Specially when you start working on VCL, you will notice that
there are almost always more than one way to solve a specific problem,
and it isn't necessarily given that the solution offered by the
instructor or this course material is better than what you might come up
with yourself.
Always feel free to interrupt the instructor if something is unclear.
Goals and Prerequisites
-----------------------
Prerequisites:
- Comfortable working in a shell on a Linux/UNIX machine, including editing
text files and starting daemons.
- Basic understanding of HTTP and related internet protocols
Goals:
- Thorough understanding of Varnish
- Understanding of how VCL works and how to use it
.. container:: handout
The course is oriented around a GNU/Linux server-platform, but the
majority of the tasks only require minimal knowledge of GNU/Linux.
The course starts out by installing Varnish and navigating some of the
common configuration files, which is perhaps the most UNIX-centric part
of the course. Do not hesitate to ask for help.
The goal of the course is to make you a better system administrator of
Varnish and let you adjust Varnish to your exact needs. If you have any
specific area you are particularly interested in, the course is usually
flexible enough to make room for it.
Introduction to Varnish
-----------------------
- What is Varnish?
- Open Source / Free Software
- History
- Varnish Governance Board (VGB)
.. container:: handout
Varnish is a reverse HTTP proxy, sometimes referred to as a HTTP
accelerator or a web accelerator. It is designed for modern hardware,
modern operating systems and modern work loads. This uncompromising
philosophy has helped make Varnish a very clean and fast piece of
software, able to scale and evolve to unexpected heights.
At the same time, Varnish is flexible. The Varnish Configuration
Language is lighting fast and allows the administrator to express their
wanted policy rather than being constrained by what the Varnish
developers want to cater for or could think of. Varnish has shown itself
to work well both on large (and expensive) servers and tiny appliances.
Varnish is also an open source project, or free software. The
development process is public and everyone can submit patches, or just
take a peek at the code if there is some uncertainty as to how Varnish
works. There is a community of volunteers who help each other and
newcomers. The BSD license used by Varnish is the most restraint-free
license among the free licenses, which conceptually makes it easier to
use Varnish in combination with non-free environments.
Varnish is developed and tested on GNU/Linux and FreeBSD. The code-base
is kept as self-contained as possible to avoid introducing out-side bugs
and unneeded complexity.
Varnish development is governed by the Varnish Governance Board (VGB),
which thus far has not needed to intervene. The VGB consists of an
architect, a community representative and a representative from Varnish
Software. As of February 2011, the positions are filled by Poul-Henning
Kamp (Architect), Artur Bergman (Community) and Kristian Lyngstøl
(Varnish Software). On a day-to-day basis, there is little need to
interfere with the general flow of development.
The history of Varnish
----------------------
- Initiated by VG, the largest newspaper in Norway, in 2006.
- Redpill Linpro performed Varnish development.
- Later development has been financed through service subscriptions
- Varnish Software was established in 2010 as an independent company to
service the increasing commercial interest in Varnish.
.. container:: handout
VG, a large Norwegian newspaper, initiated the Varnish-project in
cooperation with Linpro. The lead developer, Poul-Henning Kamp is
an experienced FreeBSD kernel hacker and continues to bring his
wisdom to Varnish in most areas where it counts.
From 2006 throughout 2008, most of the development was sponsored by
VG, API, Escenic and Aftenposten, with project management,
infrastructure and extra man-power provided by Redpill Linpro. At
the time, Redpill Linpro had roughly 140 employees mostly centered
around consulting services.
Today Varnish Software is able to fund the core development with
income from service agreements, in addition to offering development
of specific features on a case-by-case basis.
The interest in Varnish continue to increase on an almost daily
basis. An informal study based on the list of most popular web
sites in Norway indicates that about 75% or more of the web traffic
that originates in Norway is served through Varnish.
Design principles
-----------------
- Optimized for 64-bit - supports 32bit
- Optimized for multi-core/CPU
- Work with the kernel, not against it
- Innovate - not copy/paste
- VCL, shared memory log, bheaps
- Make the fast-path really fast. Delegate.
- Solve real problems.
.. container:: handout
The focus of Varnish has always been performance and flexibility.
That has required some sacrifices.
Varnish is designed for hardware that you buy today, not the hardware
you bought 15 years ago. Varnish is designed to run on 64-bit
architectures and will scale almost proportional to the number of CPU cores
you have available. Though CPU-power is rarely a problem.
If you choose to run Varnish on a 32-bit system, you are limited to 3GB
of virtual memory address space, which puts a limit on the number
of threads you can run and the size of your cache. This is a
trade-off to gain a simpler design and reduce the amount of work
Varnish needs to do.
Varnish does not keep track of whether your cache is on disk or in
memory. Instead, Varnish will request a large chump of memory and
leave it to the operating system to figure out where that memory
really is. The operating system can generally do a better job than
a user-space program.
Accept filters, epoll and kqueue are advanced features of the
operating system that are designed for high-performance services
like Varnish.
In addition, Varnish uses a configuration language that is translated to
C-code, compiled with a normal C compiler and then linked directly into
Varnish at run-time. This has several advantages. The most practical of
which is the freedom you get as a system administrator. You can use
VCL to decide how you want to interface with Varnish, instead of
having a developer try to predict every possible scenario. That it
boils down to C and a C compiler also gives you very high
performance, and if you really wanted to, you could by-pass the VCL
to C translation and write raw C code (this is called in-line C in
VCL). In short: Varnish provides the features, VCL allow you to
specify exactly how you use and combine them.
The shared memory log allows Varnish to log large amounts of
information at almost no cost by having other applications parse
the data and extract the useful bits. This reduces the
lock-contention in the heavily threaded environment of Varnish.
Lock-contention is one of the reasons why Varnish uses a
workspace-oriented memory-model instead of only allocating the
exact amount of space it needs at run-time.
To summarize: Varnish is designed to run on realistic hardware
under real work-loads and to solve real problems. Varnish does not
cater to the "I want to make varnish run on my 486 just
because"-crowd. If it does work on your 486, then that's fine, but
that's not where you will see our focus. Nor will you see us
sacrifice performance or simplicity for the sake of niche use-cases
that can easily be solved by other means - like using a 64-bit OS.
Getting started
===============
In this chapter, we will:
- Install and test a backend
- Install Varnish
- Make Varnish and the backend-server work together
- Cover basic configuration
.. container:: handout
You want to use packages for your operating system whenever possible,
but today you can choose for yourself.
If the computer you will be using throughout this course has Varnish
3.0.0 or more recent available through the package system, you are
encouraged to use that package if you do not feel you need the exercise
in installing from source.
We will be using Apache as a web server.
Configuration
-------------
Varnish has two categories of configuration:
- Command line configuration and tunable parameters
- VCL
To re-load varnish configuration, you have several commands:
+-------------------------------+-----------------------------------------+
| Command | Result |
+===============================+=========================================+
| ``service varnish restart`` | Completely restarts Varnish, using the |
| | operating system mechanisms |
+-------------------------------+-----------------------------------------+
| ``service varnish reload`` | Only reloads VCL. Cache is not affected.|
+-------------------------------+-----------------------------------------+
| ``varnishadm vcl.load ..`` | Can be used to manually reload VCL. The |
| and ``varnishadm vcl.use ..`` | ``service varnish reload`` command does |
| | this for you automatically. |
+-------------------------------+-----------------------------------------+
| ``varnishadm param.set ...`` | Can be used to set parameters without |
| | restarting Varnish |
+-------------------------------+-----------------------------------------+
Using the ``service`` commands is recommended. It's safe and fast.
.. container:: handout
Varnish has two conceptually different configuration sets. Tunable
parameters and command line arguments are used to define how varnish should
work with operating system and hardware in addition to setting some default
values, while VCL define how Varnish should interact with web servers and
clients.
Almost every aspect of Varnish can be reconfigured without restarting
Varnish. Notable exceptions are cache size and location, the username and
group that Varnish runs as and hashing algorithm.
While you can change the values, some changes might require restarting
the child to take effect (modifying the listening port, for instance) or
might not be visible immediately. Changes to how long objects are cached,
for instance, usually only take effect after the currently cached objects
expire and are fetched again.
Command line configuration
--------------------------
-a <[hostname]:port> listen address
-b <hostname:port> backend address
-f <filename> VCL
-p <parameter=value> set tunable parameters
-S <secretfile> authentication secret for management
-d debug
-T <hostname:port> Telnet interface
-s <storagetype,options> where and how to store objects
.. container:: handout
All the options that you can pass to the 'varnishd' binary are
documented in the varnsihd manual page ("man varnishd"). You may
want to take a moment to skim over the options mentioned above.
The only option that is strictly needed to start Varnish is the -b
option to specify a backend or the mutually exclusive -f to specify a VCL
file. Note that you can not specify both -b and -f at the same time. Until
you start working with VCL, use -b to tell Varnish where your web server
is.
Though they are not strictly required, you almost always want to specify
a ``-s`` to select a storage backend, ``-a`` to make sure Varnish
listens for clients on the port you expect and ``-T`` to enable a
management interface, often referred to as a telnet interface.
Both for ``-T`` and ``-a``, you do not need to specify an IP, but
can use ":80" to tell Varnish to listen to port 80 on all IPs
available. Make sure you don't forget the colon, as ``-a 80`` will
tell Varnish to listen to the IP with the decimal-representation
"80", which is almost certainly not what you want. This is a result
of the underlying function that accept this kind of syntax.
You can specify ``-p`` for parameters multiple times. The workflow
for tuning varnish parameters usually means that you first try the
parameter on a running varnish through the management interface to
find the value you want, then store it in a configuration file that
will pass it to varnish with ``-p`` next time you start it up. We
will look at these files later on.
The ``-S`` option specifies a file which contains a secret to be
used for authentication. This can be used to authenticate with
``varnishadm -S`` as long as varnishadm can read the same secret
file - or rather the same content: The content of the file can be
copied to an other machine to allow varnishadm to access the
management interface remotely.
Configuration files
-------------------
Most Varnish-installations use two configuration-files. One of them is used
by the operating system to start Varnish, while the other contains your
VCL.
+------------------------------+-----------------------------------------+
| File | Usage |
+==============================+=========================================+
| ``/etc/default/varnish`` | Used for parameters and command line |
| | arguments. When you change this, you |
| | need to run ``service varnish restart`` |
| | for the changes to take effect. |
| | On RedHat-based OS's, this is kept in |
| | ``/etc/sysconfig/varnish`` instead. |
+------------------------------+-----------------------------------------+
| ``/etc/varnish/default.vcl`` | The VCL file. You can change the name |
| | file by editing `/etc/default/varnish` |
| | if you want to, but it's normal to use |
| | the default name. This contains your |
| | VCL and backend-definitions. After |
| | changing this, you can run either |
| | ``service varnish reload``, which will |
| | not restart Varnish, or you can run |
| | ``service varnish restart``, which |
| | empties the cache. |
+------------------------------+-----------------------------------------+
.. container:: handout
There are other ways to reload VCL and make parameter take effect,
mostly using the ``varnishadm`` tool. However, using the ``service
varnish reload`` and ``service varnish restart`` commands is a good
habit.
.. note::
If you want to know how the ``service varnish``-commands work, you
can always look at the script that runs behind the scenes. If you are
used to UNIX-like systems, it will come as no surprise that the
script can be found in ``/etc/init.d/varnish``.
Exercise: Installation
-----------------------
#. Install "apache2" and verify it works by going to `http://localhost/`
#. Change Apache's ports from 80 to 8080, in `/etc/apache2/ports.conf` and
`/etc/apache2/sites-enabled/000-default`.
#. Install Varnish:
- Either use ``apt-get install varnish`` for Ubuntu or Debian systems
- or ``yum install varnish`` for Red Hat-based systems.
#. Start Varnish with ``service varnish start``, listening on port `80`,
management interface listening on port `1234` and with `127.0.0.1:8080` as the backend.
The end result should be:
+------------+------------------------+--------------------------------------------+
| Service | Result | Related config-files |
+============+========================+============================================+
| Apache | Answers on port `8080` | ``/etc/apache2/ports.conf`` and |
| | | ``/etc/apache2/sites-enabled/000-default`` |
+------------+------------------------+--------------------------------------------+
| Varnish | Answers on port `80` | ``/etc/default/varnish`` |
+------------+------------------------+--------------------------------------------+
| Varnish | Talks to apache on | ``/etc/varnish/default.vcl`` |
| | `localhost:80` | |
+------------+------------------------+--------------------------------------------+
.. container:: handout
We use Apache for these exercises.
Using the Varnish packages provided by your distribution is often just
as good as compiling from source. Alternatively, you can add the
repository provided by Varnish Software, with the base URL of
http://repo.varnish-cache.org/
.. note::
This course is based on Varnish 3.0 and it's strongly advised that
you use Varnish 3.0. There is a list of VCL and configuration-related
changes between Varnish 2.1 and 3.0 in the final chapter.
After you ave started Varnish, you can connect to the management
interface using ``varnishadm`` with the same ``-T`` argument as you gave
to Varnish. The management interface is some times referred to as the
CLI or even the telenet interface.
When working in the management interface it is important to keep two
things in mind:
1. Any changes you make are done immediately on the running Varnish
instance
2. Changes are not persistent across restarts of Varnish. If you change
a parameter and you want the change to apply if you restart Varnish,
you need to also store it in the regular configuration for the boot
script.
One important concern that regards the management interface is security.
Because the management interface is not encrypted, only has limited
authentication and still allows almost total control over Varnish, it is
important to protect it. The easiest way of doing that is by having it
only listen to localhost (127.0.0.1). An other possibility is firewall
rules to only allow specific (local) users to connect.
It is also possible to protect the management interface through a shared
secret, and this has become normal in later Varnish versions. The shared
secret is typically a file stored in `/etc/varnish/secret` and specified
with the ``-S`` option to both Varnish and ``varnishadm``. As long as a
user can read that file (or more specifically: read the content of it),
the user can access the management interface.
Exercise: Fetch data through Varnish
------------------------------------
#. Install ``libwww-perl``
#. Execute ``GET -Used http://localhost:80/`` (on the command line)
#. Compare the results from multiple executions.
.. container:: handout
GET and HEAD is actually the same tool; lwp-request. A HTTP HEAD request
tells the web server - or Varnish in this case - to only reply with the
HTTP headers, while GET returns everything.
``GET -Used`` tells lwp-request to do a GET-request, print the
request headers (U), print the response status code (s), which is
typically "200 OK" or "404 File not found", print the response
headers "-e" and finally to not display the content of the
response. Feel free to try remove some of the options to see the
effect.
GET is also useful to generate requests with custom headers, as you can
supply extra headers with ``-H "Header: value"``, which can be used
multiple times.
You may also be familiar with firebug, an add-on for Firefox used
for web development and related affairs. This too can show you the
response headers.
Web browsers have their own cache which you may not immediately be
able to tell if you're using or not. It's often helpful to
double-check with GET or HEAD if you are in doubt if what you're
seeing is coming from Varnish or is part of your browser cache.
Defining a backend in VCL
-------------------------
/etc/varnish/default.vcl
.. include:: vcl/backend.vcl
:literal:
.. container:: handout
You almost always want to use VCL: we might as well get started!
The above example defines a backend named ``default``. The name
`default` is not special, and the real default backend that Varnish will
use is the first backend you specify.
You can specify many backends at the same time.
Log data
--------
- Varnishlog and varnishstat, the bread and butter of Varnish
- Real time data
.. container:: handout
If you look for logging data for Varnish you may discover that
`/var/log/varnish/` is either non-existent or empty. There's a reason
for that.
Varnish logs all its information to a shared memory log which is
overwritten repeatedly every time it's filled up. To use the log data,
you need to use specific tools to parse the content.
The downside is that you don't have historic data unless you set it up
yourself, which is not covered in this chapter, but the upside is that
you get an abundance of information when you need it.
Through the course you will become familiar with varnishlog and
varnishstat, which are the two most important tools you have at your
disposal.
varnishlog
----------
::
97 ReqStart c 10.1.0.10 50866 117511506
97 RxRequest c GET
97 RxURL c /style.css
97 RxProtocol c HTTP/1.1
97 RxHeader c Host: www.example.com
97 VCL_call c recv lookup
97 VCL_call c hash hash
97 Hit c 117505004
97 VCL_call c hit deliver
97 Length c 3218
97 VCL_call c deliver deliver
97 TxProtocol c HTTP/1.1
97 TxStatus c 200
97 TxResponse c OK
97 TxHeader c Content-Length: 3218
97 TxHeader c Date: Sat, 22 Aug 2008 01:10:10 GMT
97 TxHeader c X-Varnish: 117511501 117505004
97 TxHeader c Age: 2
97 TxHeader c Via: 1.1 varnish
97 ReqEnd c 117511501 1227316210.534358978 \
1227316210.535176039 0.035283089 0.000793934 0.000023127
.. container:: handout
As you can see, the above input is quite extensive. The above output is
a single cache hit, as processed by Varnish. If you are dealing with
several thousand requests per second, it is impossible to review all
that information.
The displayed data is categorized as follows:
1. The number on the left is a semi-unique identifier of the request. It
is used to distinguish different requests.
2. Each piece of log information belongs to a tag, as seen on the second
left-most column. TxHeader, RxHeader, VCL_call etc. You can later use
those tags for intelligent filtering.
3. Varnishlog will try to decipher if a request is related to a client
(c), backend (b) or "misc" (-). This can be used to filter the log.
The misc-category will contain data related to thread-collection,
object expiry and similar internal data.
varnishlog options
------------------
-b only show traffic to backend
-c only show traffic to client
-O do not group by request
-m <tag:filter> Show *requests* where the <tag> matches <filter>. Example:
``varnishlog -m TxStatus:500`` to show requests
returned to a client with status code 500.
.. container:: handout
Some options of note are:
-n <name> The name of the varnish instance, or path to the shmlog.
Useful for running multiple instances of Varnish.
-i <tag> Only show one tag.
-I <regex> Filter the tag provided by -i, using the regular expression for -I.
.. warning::
varnishlog sometimes accept arguments that are technically
incorrect, which can have surprising results on filtering. Make sure
you double-check the filter logic. You most likely want to specify -b
or -c too.
.. tip::
Many of the arguments above are valid for most of the other tools
too. Try them out!
varnishstat
-----------
::
0+00:44:50 foobar
Hitrate ratio: 10 100 175
Hitrate avg: 0.9507 0.9530 0.9532
574660 241.00 213.63 Client connections accepted
2525317 937.00 938.78 Client requests received
2478794 931.00 921.48 Cache hits
7723 3.00 2.87 Cache hits for pass
140055 36.00 52.07 Cache misses
47974 12.00 17.83 Backend conn. success
109526 31.00 40.72 Backend conn. reuses
46676 5.00 17.35 Backend conn. was closed
156211 41.00 58.07 Backend conn. recycles
110500 34.00 41.08 Fetch with Length
46519 6.00 17.29 Fetch chunked
456 0.00 0.17 Fetch wanted close
5091 . . N struct sess_mem
3473 . . N struct sess
53570 . . N struct object
50070 . . N struct objecthead
20 . . N struct vbe_conn
.. container:: handout
varnishstat gives a good representation of the general health of
Varnish, including cache hit rate, uptime, number of failed backend
connections and many other statistics.
There are close to a hundred different counters available. To increase
the usefulness of varnishstat, only counters with a value different from
0 is shown by default.
Varnishstat can be executed either as a one-shot tool which simply
prints the current values of all the counters, using the '-1' option, or
interactively. Both methods allow you to specify specific counters using
'-f field1,field2,...' to limit the list.
In interactive mode, varnishstat starts out by printing the uptime(45
minutes, in the example above) and hostname(foobar).
The `Hitrate ratio` and `Hitrate avg` are related. The Hitrate average
measures the cache hit rate for a period of time stated by `hitrate
ratio`. In the example above, the hitrate average for the last 10
seconds is 0.9507 (or 95.07%), 0.9530 for the last 100 seconds and
0.9532 for the last 1000 seconds. As you start Varnish, all of these
will start at 1 second, then grow to 10, 100 and 1000. This is because
varnishstat has to compute the average while it is running; there is no
historic data of counters available.
The bulk of varnishstat is the counters. The left column is the raw
value, the second column is "change per second in real time" and the
third column is "change per second on average since Varnish started". We
can see on the above example that it has served 574660 requests and is
currently serving roughly 241 requests per second.
Some counters do not have 'per second' data. These are counters which
both increase and decrease.
We will look at the specific counters in more detail when we investigate
monitoring and troubleshooting Varnish. There are, however, far too many
counters to keep track of for non-developers, and many of the counters
are only there for debugging purposes. This allows you to provide the
developers of Varnish with real and detailed data whenever you run into
a performance issue or bug. It allows us, the developers, to test ideas
and get feedback on how it works in production environments without
creating specific "test versions" of Varnish. In short: It allows
Varnish to be developed according to how it is used.
.. note::
If you suddenly see varnishstat counters restarting, this probably
means that varnish restarted. Check your syslog!
.. note::
You may have to specify an ``-n`` option to read the stats for the
correct Varnish instance if you have multiple instances.
Exercise: Define a backend with VCL
-----------------------------------
#. Open the startup script configuration for varnish:
- On Red Hat or CentOS: /etc/sysconfig/varnish
- On Debian or Ubuntu: /etc/default/varnish
#. With comments removed, it should look similar to::
NFILES=131072
MEMLOCK=82000
INSTANCE=$(uname -n)
DAEMON_OPTS="-a :80 \
-T localhost:6082 \
-f /etc/varnish/default.vcl \
-s file,/var/lib/varnish/$INSTANCE/varnish_storage.bin,1G"
#. Edit `/etc/varnish/default.vcl` to add your Apache server as the only
backend.
#. Stop any running Varnish instance you have started manually and restart
Varnish the way your distribution would do it.
#. Run a few requests through Varnish to see that it still works.
#. Observe how this is reflected in ``varnishstat`` and ``varnishlog``. Try
using both ``varnishlog -c`` and ``varnishlog -b`` to compare.
.. container:: handout
Most of the time, you use VCL to configure backends for Varnish, and
in this exercise, we set it up. The first step is to verify that it is
used by Varnish. The snippet above represents a typical configuration
file for the Varnish init script. Your copy might use variables or
malloc instead, but it should be otherwise similar.
You can chose a different location than `/etc/varnish/default.vcl` if
you wish to.
.. warning::
The script-configuration (located in `/etc/sysconfig` or
`/etc/default`) is directly sourced as a shell script. Pay special
attention to any backslashes (\\) and quotation marks that might move
around as you edit the DAEMON_OPTS environmental variable.
As you are finishing up this exercise, you hopefully begin to see the
usefulness of the various Varnish tools. ``varnishstat`` and
``varnishlog`` are the two most used tools, and are usually what you
need for sites that are not in production yet.
The various arguments for ``varnishlog`` are mostly designed to help you
find exactly what you want, and filter out the noise. On production
traffic, the amount of log data that Varnish produces is staggering, and
filtering is a requirement for using ``varnishlog`` effectively.
Tuning
======
- Architecture
- Best practices
- Parameters
.. container:: handout
Tuning Varnish is two-fold. Perhaps the most important aspect of it is
is getting your VCL straight. For now, though, we will focus on tuning
Varnish for your hardware, operating system and network.
To be able to do that, knowledge of the process- and thread-architecture
is helpful.
The internal architecture of Varnish is of some interest, both because
it is chiefly responsible for the performance you will be able to
achieve with Varnish, and because it affects how you integrate Varnish
in your own architecture.
There are several aspects of the design that was unique to Varnish when
it was originally implemented. Truly good solutions is the aim of
Varnish, regardless of whether that means reusing ancient ideas or
coming up with something radically different.
Process Architecture
--------------------
The multi-process architecture:
.. image:: ui/img/architecture.png
:align: center
:width: 80%
.. class:: handout
The management process
......................
Varnish has two main process: the management process and the child process.
The management process apply configuration changes (VCL and parameters),
compile VCL, monitor Varnish, initialize Varnish and provides a command
line interface, accessible either directly on the terminal or through a
telnet interface.
By default, the management process polls the child process every few
seconds to see if it's still there. If it doesn't get a reply within a
reasonable time, the management process will kill the child and start it
back up again. The same happens if the child unexpectedly exits, for
example from a segmentation fault or assert error.
This ensures that even if Varnish does contain a critical bug, it will
start back up again fast. Usually within a few seconds, depending on the
conditions.
All of this is logged to syslog. This makes it crucially important to
monitor the syslog, otherwise you may never even know unless you look for
them, because the perceived downtime is so short.
.. note::
Varnish Software and the Varnish community at large occasionally get
requests for assistance in performance tuning Varnish that turn out to
be crash-issues. Because the Varnish management thread starts the child
up so fast, the users don't even notice the down time, only the extra
loading time as Varnish is constantly emptying its cache.
This is easily avoidable by paying attention to syslog.
.. raw:: pdf
PageBreak
.. class:: handout
The child process
.................
The child process is where the real magic goes on. The child process
consist of several different types of threads, including, but not limited
to:
- Acceptor thread to accept new connections and delegate them
- Worker threads - one per session. It's common to use hundreds of worker
threads.
- Expiry thread, to evict old content from the cache
Varnish uses workspaces to reduce the contention between each thread when
they need to acquire or modify some part of the memory. There are multiple
work spaces, but the most important one is the session workspace, which is
used to manipulate session data. An example is changing `www.example.com`
to `example.com` before it is entered into the cache, to reduce the number
of duplicates.
It is important to remember that even if you have 5MB of session workspace
and are using 1000 threads, the actual memory usage is not 5GB. The virtual
memory usage will indeed be 5GB, but unless you actually use the memory,
this is not a problem. Your memory controller and operating system will
keep track of what you actually use.
To communicate with the rest of the system, the child process uses a shared
memory log accessible from the file system. This means that if a thread
needs to log something, all it has to do is grab a lock, write to a memory
area and then free the lock. In addition to that, each worker thread has a
cache for log data to avoid overly frequent locking.
The log file is usually about 90MB, and split in two. The first part is
counters, the second part is request data. To view the actual data, a
number of tools exist that parses the shared memory log. Because the
log-data is not meant to be written to disk in its raw form, Varnish can
afford to be very verbose. You then use one of the log-parsing tools to
extract the piece of information you want - either to store it permanently
or to monitor Varnish in real-time.
.. class:: handout
VCL compilation
...............
Configuring the caching policies of Varnish is done in the Varnish
Configuration Language (VCL). Your VCL is then interpreted by the
management process into to C and then compiled by a normal C compiler -
typically gcc. Lastly, it is linked into the running Varnish instance.
As a result of this, changing configuration while Varnish is running is
very cheap. Varnish may want to keep the old configuration around for a bit
in case it still has references to it, but the policies of the new VCL
takes effect immediately.
Because the compilation is done outside of the child process, there is
virtually no risk of affecting the running Varnish by accidentally loading
an ill-formated VCL.
Storage backends
----------------
- Different ways for Varnish to store cache
- Rule of thumb: malloc if it fits in memory, file if it doesn't
- Expect around 1kB of overhead per object cached
- file
- malloc
- persistent (experimental)
.. container:: handout
Varnish supports different methods of allocating space for the
cache, and you choose which one you want with the '-s' argument.
They approach the same basic problem from two different angles. With the
`malloc`-method, Varnish will request the entire size of the cache with a
malloc() (memory allocation) system call. The operating system will then
divide the cache between memory and disk by swapping out what it
can't fit in memory.
The alternative is to use the `file` storage backend, which instead
creates a file on a filesystem to contain the entire cache, then tell the
operating system through the mmap() (memory map) system call to map the
entire file into memory if possible.
*The file storage method does not retain data when you stop or restart
Varnish!* This is what persistent storage is for. While it might
seem like that's what it would do, remember that Varnish does not
know which parts of the cache is actually written to the file and
which are just kept in memory. In fact, the content written to disk
is likely going to be the least accessed content you have. Varnish
will not try to read the content, though.
While malloc will use swap to store data to disk, file will use
memory to cache the data instead. Varnish allow you to choose
between the two because the performance of the two approaches have
varied historically.
The persistent storage backend is similar to file, but only
released in an experimental state. It does not yet gracefully
handle situations where you run out of space. We only recommend
using persistent if you have a large amount of data that you must
cache and are prepared to work with us to track down bugs.
When choosing storage backend, the rule of thumb is to use malloc if
your cache will be contained entirely or mostly in memory, while the file
storage backend performs far better when you need a large cache that
exceeds the physical memory available. This might vary based on the kernel
you use, but seems to be the case for 2.6.18 and later Linux kernel, in
addition to FreeBSD.
It is important to keep in mind that the size you specify with the
'-s' argument is the size for the actual cache. Varnish has an
overhead on top of this for keeping track of the cache, so the
actual memory footprint of Varnish will exceed what the '-s'
argument specifies if the cache is full. The current estimate
(subject to change on individual Varnish-versions) is that about
1kB of overhead needed for each object. For 1 million objects, that
means 1GB extra memory usage.
The shm-log
-----------
- Round-robin log for Varnish
- Put it on tmpfs to avoid I/O
.. container:: handout
The shared memory log, or shm-log, is Varnish' log. It is not
persistent, so do not expect it to contain any real history. We'll
discuss how to use it in detail in later chapters.
Since the shm-log is a round-robin log and writes a lot of verbose log
information, keeping it in memory is key. It will do this by default,
but due to the way shared memory mapped to files work it might cause
unnecessary I/O. To solve this, put it on a tmpfs.
This is typically done in '/etc/fstab', and the shmlog is normally kept
in '/var/lib/varnish' or equivalent locations. All the content in that
directory is safe to delete.
.. warning::
Some packages will use '-s file' by default with a path that puts the
storage file in the same directory as the shmlog. You want to avoid
this.
Threading model
---------------
- The child process runs multiple threads
- Worker threads are the bread and butter of the Varnish architecture
- Utility-threads
- Balance
.. container:: handout
The child process of Varnish is where the magic takes place. It consists
of several distinct threads performing different tasks. The following
table lists some interesting threads, to give you an idea of what goes
on. The table is not complete.
+---------------+---------------------------+------------------------+
| Thread | # instances | Task |
+===============+===========================+========================+
| cache-worker | One per active connection | Handle requests |
+---------------+---------------------------+------------------------+
| cache-main | One | Startup |
+---------------+---------------------------+------------------------+
| ban lurker | One | Clean bans |
+---------------+---------------------------+------------------------+
| acceptor | One | Accept new connections |
+---------------+---------------------------+------------------------+
| epoll/kqueue | Configurable, default: 2 | Manage thread pools |
+---------------+---------------------------+------------------------+
| expire | One | Remove old content |