This repository has been archived by the owner on Feb 2, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 22
/
VarnishAdminSocket.php
352 lines (296 loc) · 9.48 KB
/
VarnishAdminSocket.php
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
<?php
/**
* Varnish admin socket for executing varnishadm CLI commands.
* @see http://varnish-cache.org/wiki/CLI
* @author Tim Whitlock http://twitter.com/timwhitlock
*
* @todo add all short cut methods to commands listed below
* @todo sanitise command parameters, such as regexp
*
* Tested with varnish-2.1.3 SVN 5049:5055;
* varnish-2.1.5 SVN 0843d7a
* CLI commands available as follows:
help [command]
ping [timestamp]
auth response
quit
banner
status
start
stop
stats
vcl.load <configname> <filename>
vcl.inline <configname> <quoted_VCLstring>
vcl.use <configname>
vcl.discard <configname>
vcl.list
vcl.show <configname>
param.show [-l] [<param>]
param.set <param> <value>
purge.url <regexp>
purge <field> <operator> <arg> [&& <field> <oper> <arg>]...
purge.list
*/
/**
* varnishadm connection class
*/
class VarnishAdminSocket {
/**
* Socket pointer
* @var resource
*/
private $fp;
/**
* Host on which varnishadm is listening
* @var string
*/
private $host;
/**
* Port on which varnishadm is listening, usually 6082
* @var string port
*/
private $port;
/**
* Secret to use in authentication challenge.
* @var string
*/
private $secret;
/**
* Major version of Varnish top which you're connecting; 2 or 3
* @var int
*/
private $version;
/**
* Minor version of Varnish top which you're connecting
* @var int
*/
private $version_minor;
/**
* Either ban or purge based on the version of Varnish top
* @var string
*/
private $ban = '';
/**
* Constructor
* @param string host
* @param int port
* @param string optional version, defaults to 2.1
*/
public function __construct( $host = '127.0.0.1', $port = 6082, $v = '2.1' ){
$this->host = $host;
$this->port = $port;
// parse expected version number
$vers = explode('.',$v,3);
$this->version = isset($vers[0]) ? (int) $vers[0] : 2;
$this->version_minor = isset($vers[1]) ? (int) $vers[1] : 1;
if( 2 === $this->version ){
// @todo sanity check 2.x number
}
else if( 3 === $this->version ){
// @todo sanity check 3.x number
}
else if( 4 === $this->version ){
// @todo sanity check 4.x number
}
else if( 5 === $this->version ){
// @todo sanity check 5.x number
}
else {
throw new Exception('Only Varnish versions from 2 to 5 are supported');
}
$this->ban = in_array($this->version,[3,4,5]) ? 'ban' : 'purge';
}
/**
* Set authentication secret.
* Warning: may require a trailing newline if passed to varnishadm from a text file
* @param string
* @return void
*/
public function set_auth( $secret ){
$this->secret = $secret;
}
/**
* Connect to admin socket
* @param int optional timeout in seconds, defaults to 5; used for connect and reads
* @return string the banner, in case you're interested
*/
public function connect( $timeout = 5 ){
$this->fp = fsockopen( $this->host, $this->port, $errno, $errstr, $timeout );
if( ! is_resource( $this->fp ) ){
// error would have been raised already by fsockopen
throw new Exception( sprintf('Failed to connect to varnishadm on %s:%s; "%s"', $this->host, $this->port, $errstr ));
}
// set socket options
stream_set_blocking( $this->fp, 1 );
stream_set_timeout( $this->fp, $timeout );
// connecting should give us the varnishadm banner with a 200 code, or 107 for auth challenge
$banner = $this->read( $code );
if( $code === 107 ){
if( ! $this->secret ){
throw new Exception('Authentication required; see VarnishAdminSocket::set_auth');
}
try {
$challenge = substr( $banner, 0, 32 );
$response = hash('sha256', $challenge."\n".$this->secret.$challenge."\n");
$banner = $this->command('auth '.$response, $code, 200 );
}
catch( Exception $Ex ){
throw new Exception('Authentication failed');
}
}
if( $code !== 200 ){
throw new Exception( sprintf('Bad response from varnishadm on %s:%s', $this->host, $this->port));
}
return $banner;
}
/**
* Write data to the socket input stream
* @param string
* @return bool
*/
private function write( $data ){
$bytes = fputs( $this->fp, $data );
if( $bytes !== strlen($data) ){
throw new Exception( sprintf('Failed to write to varnishadm on %s:%s', $this->host, $this->port) );
}
return true;
}
/**
* Write a command to the socket with a trailing line break and get response straight away
* @param string
* @return string
*/
public function command( $cmd, &$code, $ok = 200 ){
$cmd and $this->write( $cmd );
$this->write("\n");
$response = $this->read( $code );
if( $code !== $ok ){
$response = implode("\n > ", explode("\n",trim($response) ) );
throw new Exception( sprintf("%s command responded %d:\n > %s", $cmd, $code, $response), $code );
}
return $response;
}
/**
* @param int reference for reply code
* @return string
*/
private function read( &$code ){
$code = null;
// get bytes until we have either a response code and message length or an end of file
// code should be on first line, so we should get it in one chunk
while ( ! feof($this->fp) ) {
$response = fgets( $this->fp, 1024 );
if( ! $response ){
$meta = stream_get_meta_data($this->fp);
if( $meta['timed_out'] ){
throw new Exception(sprintf('Timed out reading from socket %s:%s',$this->host,$this->port));
}
}
if( preg_match('/^(\d{3}) (\d+)/', $response, $r) ){
$code = (int) $r[1];
$len = (int) $r[2];
break;
}
}
if( is_null($code) ){
throw new Exception('Failed to get numeric code in response');
}
$response = '';
while ( ! feof($this->fp) && strlen($response) < $len ) {
$response .= fgets( $this->fp, 1024 );
}
return $response;
}
/**
* Brutal close, doesn't send quit command to varnishadm
* @return void
*/
public function close(){
is_resource($this->fp) and fclose($this->fp);
$this->fp = null;
}
/**
* Graceful close, sends quit command
* @return void
*/
public function quit(){
try {
$this->command('quit', $code, 500 );
}
catch( Exception $Ex ){
// slient fail - force close of socket
}
$this->close();
}
/**
* Shortcut to purge function
* @see http://varnish-cache.org/wiki/Purging
* @param string purge expression in form "<field> <operator> <arg> [&& <field> <oper> <arg>]..."
* @return string
*/
public function purge( $expr ){
return $this->command( $this->ban.' '.$expr, $code );
}
/**
* Shortcut to purge.url function
* @see http://varnish-cache.org/wiki/Purging
* @param string url to purge
* @return string
*/
public function purge_url( $expr ){
$domain = parse_url($expr, PHP_URL_HOST);
$path = parse_url($expr, PHP_URL_PATH);
if ($this->version <= 3) {
return $this->command( $this->ban.'.url '.$domain.$path, $code );
} else {
return $this->command( $this->ban . ' req.http.host == ' . $domain . ' && req.url ~ ' . $path . '/.*', $code );
}
}
/**
* Shortcut to purge.list function
* @todo should we parse the reponse lines?
* @return array
*/
public function purge_list(){
$response = $this->command( $this->ban.'.list', $code );
return explode( "\n", trim($response) );
}
/**
* Test varnish child status
* @return bool whether child is alive
*/
public function status(){
try {
$response = $this->command( 'status', $code );
if( ! preg_match('/Child in state (\w+)/', $response, $r ) ) {
return false;
}
return $r[1] === 'running';
}
catch( Exception $Ex ){
return false;
}
}
/**
* @return bool
*/
public function stop(){
if( ! $this->status() ){
trigger_error(sprintf('varnish host already stopped on %s:%s', $this->host, $this->port), E_USER_NOTICE);
return true;
}
$this->command( 'stop', $code );
return true;
}
/**
* @return bool
*/
public function start(){
if( $this->status() ){
trigger_error(sprintf('varnish host already started on %s:%s', $this->host, $this->port), E_USER_NOTICE);
return true;
}
$this->command( 'start', $code );
return true;
}
}