Completed
Pull Request — master (#602)
by Sean
14:12 queued 10:30
created

CapistranoDeploymentBackend::getDeployOptions()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 5
rs 9.4285
cc 1
eloc 3
nc 1
nop 0
1
<?php
2
3
class CapistranoDeploymentBackend extends Object implements DeploymentBackend {
4
5
	protected $packageGenerator;
6
7
	public function getPackageGenerator() {
8
		return $this->packageGenerator;
9
	}
10
11
	public function setPackageGenerator(PackageGenerator $packageGenerator) {
12
		$this->packageGenerator = $packageGenerator;
13
	}
14
15
	/**
16
	 * Create a deployment strategy.
17
	 *
18
	 * @param DNEnvironment $environment
19
	 * @param array $options
20
	 *
21
	 * @return DeploymentStrategy
22
	 */
23
	public function planDeploy(DNEnvironment $environment, $options) {
24
		$strategy = new DeploymentStrategy($environment, $options);
25
26
		$currentBuild = $environment->CurrentBuild();
27
		$currentSha = $currentBuild ? $currentBuild->SHA : '-';
28
		if($currentSha !== $options['sha']) {
29
			$strategy->setChange('Code version', $currentSha, $options['sha']);
30
		}
31
		$strategy->setActionTitle('Confirm deployment');
32
		$strategy->setActionCode('fast');
33
		$strategy->setEstimatedTime('2');
34
35
		return $strategy;
36
	}
37
38
	/**
39
	 * Deploy the given build to the given environment.
40
	 *
41
	 * @param DNEnvironment $environment
42
	 * @param DeploynautLogFile $log
43
	 * @param DNProject $project
44
	 * @param array $options
45
	 */
46
	public function deploy(
47
		DNEnvironment $environment,
48
		DeploynautLogFile $log,
49
		DNProject $project,
50
		$options
51
	) {
52
		$name = $environment->getFullName();
53
		$repository = $project->getLocalCVSPath();
54
		$sha = $options['sha'];
55
56
		$args = array(
57
			'branch' => $sha,
58
			'repository' => $repository,
59
		);
60
61
		$this->extend('deployStart', $environment, $sha, $log, $project);
62
63
		$log->write(sprintf('Deploying "%s" to "%s"', $sha, $name));
64
65
		$this->enableMaintenance($environment, $log, $project);
66
67
		// Use a package generator if specified, otherwise run a direct deploy, which is the default behaviour
68
		// if build_filename isn't specified
69
		if($this->packageGenerator) {
70
			$log->write(sprintf('Using package generator "%s"', get_class($this->packageGenerator)));
71
72
			try {
73
				$args['build_filename'] = $this->packageGenerator->getPackageFilename($project->Name, $sha, $repository, $log);
74
			} catch (Exception $e) {
75
				$log->write($e->getMessage());
76
				throw $e;
77
			}
78
79
			if(empty($args['build_filename'])) {
80
				throw new RuntimeException('Failed to generate package.');
81
			}
82
		}
83
84
		$command = $this->getCommand('deploy', 'web', $environment, $args, $log);
85
		$command->run(function($type, $buffer) use($log) {
86
			$log->write($buffer);
87
		});
88
89
		// Deployment cleanup. We assume it is always safe to run this at the end, regardless of the outcome.
90
		$self = $this;
91
		$cleanupFn = function() use($self, $environment, $args, $log, $sha, $project) {
92
			$command = $self->getCommand('deploy:cleanup', 'web', $environment, $args, $log);
93
			$command->run(function($type, $buffer) use($log) {
94
				$log->write($buffer);
95
			});
96
97
			if(!$command->isSuccessful()) {
98
				$self->extend('cleanupFailure', $environment, $sha, $log, $project);
99
				$log->write('Warning: Cleanup failed, but fine to continue. Needs manual cleanup sometime.');
100
			}
101
		};
102
103
		// Once the deployment has run it's necessary to update the maintenance page status
104
		if(!empty($options['leaveMaintenancePage'])) {
105
			$this->enableMaintenance($environment, $log, $project);
106
		}
107
108
		if(!$command->isSuccessful() || !$this->smokeTest($environment, $log)) {
109
			$cleanupFn();
110
			$this->extend('deployFailure', $environment, $sha, $log, $project);
111
			throw new RuntimeException($command->getErrorOutput());
112
		}
113
114
		// Check if maintenance page should be removed
115
		if(empty($options['leaveMaintenancePage'])) {
116
			$this->disableMaintenance($environment, $log, $project);
117
		}
118
119
		$cleanupFn();
120
121
		$log->write(sprintf('Deploy of "%s" to "%s" finished', $sha, $name));
122
123
		$this->extend('deployEnd', $environment, $sha, $log, $project);
124
	}
125
126
	/**
127
	 * @return array
128
	 */
129
	public function getDeployOptions() {
130
		return [
131
			new PredeployBackupOption(true),
132
		];
133
	}
134
135
	/**
136
	 * Enable a maintenance page for the given environment using the maintenance:enable Capistrano task.
137
	 */
138 View Code Duplication
	public function enableMaintenance(DNEnvironment $environment, DeploynautLogFile $log, DNProject $project) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
139
		$name = $environment->getFullName();
140
		$command = $this->getCommand('maintenance:enable', 'web', $environment, null, $log);
141
		$command->run(function($type, $buffer) use($log) {
142
			$log->write($buffer);
143
		});
144
		if(!$command->isSuccessful()) {
145
			$this->extend('maintenanceEnableFailure', $environment, $log);
146
			throw new RuntimeException($command->getErrorOutput());
147
		}
148
		$log->write(sprintf('Maintenance page enabled on "%s"', $name));
149
	}
150
151
	/**
152
	 * Disable the maintenance page for the given environment using the maintenance:disable Capistrano task.
153
	 */
154 View Code Duplication
	public function disableMaintenance(DNEnvironment $environment, DeploynautLogFile $log, DNProject $project) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
155
		$name = $environment->getFullName();
156
		$command = $this->getCommand('maintenance:disable', 'web', $environment, null, $log);
157
		$command->run(function($type, $buffer) use($log) {
158
			$log->write($buffer);
159
		});
160
		if(!$command->isSuccessful()) {
161
			$this->extend('maintenanceDisableFailure', $environment, $log);
162
			throw new RuntimeException($command->getErrorOutput());
163
		}
164
		$log->write(sprintf('Maintenance page disabled on "%s"', $name));
165
	}
166
167
	/**
168
	 * Check the status using the deploy:check capistrano method
169
	 */
170
	public function ping(DNEnvironment $environment, DeploynautLogFile $log, DNProject $project) {
171
		$command = $this->getCommand('deploy:check', 'web', $environment, null, $log);
172
		$command->run(function($type, $buffer) use($log) {
173
			$log->write($buffer);
174
			echo $buffer;
175
		});
176
	}
177
178
	/**
179
	 * @inheritdoc
180
	 */
181
	public function dataTransfer(DNDataTransfer $dataTransfer, DeploynautLogFile $log) {
182
		if($dataTransfer->Direction == 'get') {
183
			$this->dataTransferBackup($dataTransfer, $log);
184
		} else {
185
			$environment = $dataTransfer->Environment();
186
			$project = $environment->Project();
187
			$workingDir = TEMP_FOLDER . DIRECTORY_SEPARATOR . 'deploynaut-transfer-' . $dataTransfer->ID;
188
			$archive = $dataTransfer->DataArchive();
189
190
			// extract the sspak contents, we'll need these so capistrano can restore that content
191
			try {
192
				$archive->extractArchive($workingDir);
193
			} catch(Exception $e) {
194
				$log->write($e->getMessage());
195
				throw new RuntimeException($e->getMessage());
196
			}
197
198
			// validate the contents match the requested transfer mode
199
			$result = $archive->validateArchiveContents($dataTransfer->Mode);
200
			if(!$result->valid()) {
201
				// do some cleaning, get rid of the extracted archive lying around
202
				$process = new AbortableProcess(sprintf('rm -rf %s', escapeshellarg($workingDir)));
203
				$process->setTimeout(120);
204
				$process->run();
205
206
				// log the reason why we can't restore the snapshot and halt the process
207
				$log->write($result->message());
208
				throw new RuntimeException($result->message());
209
			}
210
211
			// Put up a maintenance page during a restore of db or assets.
212
			$this->enableMaintenance($environment, $log, $project);
213
			$this->dataTransferRestore($workingDir, $dataTransfer, $log);
214
			$this->disableMaintenance($environment, $log, $project);
215
		}
216
	}
217
218
	/**
219
	 * @param string $action Capistrano action to be executed
220
	 * @param string $roles Defining a server role is required to target only the required servers.
221
	 * @param DNEnvironment $environment
222
	 * @param array<string>|null $args Additional arguments for process
223
	 * @param DeploynautLogFile $log
224
	 * @return \Symfony\Component\Process\Process
225
	 */
226
	public function getCommand($action, $roles, DNEnvironment $environment, $args = null, DeploynautLogFile $log) {
227
		$name = $environment->getFullName();
228
		$env = $environment->Project()->getProcessEnv();
229
230
		if(!$args) {
231
			$args = array();
232
		}
233
		$args['history_path'] = realpath(DEPLOYNAUT_LOG_PATH . '/');
234
		$args['environment_id'] = $environment->ID;
235
236
		// Inject env string directly into the command.
237
		// Capistrano doesn't like the $process->setEnv($env) we'd normally do below.
238
		$envString = '';
239
		if(!empty($env)) {
240
			$envString .= 'env ';
241
			foreach($env as $key => $value) {
242
				$envString .= "$key=\"$value\" ";
243
			}
244
		}
245
246
		$data = DNData::inst();
247
		// Generate a capfile from a template
248
		$capTemplate = file_get_contents(BASE_PATH . '/deploynaut/Capfile.template');
249
		$cap = str_replace(
250
			array('<config root>', '<ssh key>', '<base path>'),
251
			array($data->getEnvironmentDir(), DEPLOYNAUT_SSH_KEY, BASE_PATH),
252
			$capTemplate
253
		);
254
255
		if(defined('DEPLOYNAUT_CAPFILE')) {
256
			$capFile = DEPLOYNAUT_CAPFILE;
257
		} else {
258
			$capFile = ASSETS_PATH . '/Capfile';
259
		}
260
		file_put_contents($capFile, $cap);
261
262
		$command = "{$envString}cap -f " . escapeshellarg($capFile) . " -vv $name $action ROLES=$roles";
263
		foreach($args as $argName => $argVal) {
264
			$command .= ' -s ' . escapeshellarg($argName) . '=' . escapeshellarg($argVal);
265
		}
266
267
		$log->write(sprintf('Running command: %s', $command));
268
269
		$process = new AbortableProcess($command);
270
		$process->setTimeout(3600);
271
		return $process;
272
	}
273
274
	/**
275
	 * Backs up database and/or assets to a designated folder,
276
	 * and packs up the files into a single sspak.
277
	 *
278
	 * @param DNDataTransfer    $dataTransfer
279
	 * @param DeploynautLogFile $log
280
	 */
281
	protected function dataTransferBackup(DNDataTransfer $dataTransfer, DeploynautLogFile $log) {
282
		$environment = $dataTransfer->Environment();
283
		$name = $environment->getFullName();
284
285
		// Associate a new archive with the transfer.
286
		// Doesn't retrieve a filepath just yet, need to generate the files first.
287
		$dataArchive = DNDataArchive::create();
288
		$dataArchive->Mode = $dataTransfer->Mode;
289
		$dataArchive->AuthorID = $dataTransfer->AuthorID;
290
		$dataArchive->OriginalEnvironmentID = $environment->ID;
291
		$dataArchive->EnvironmentID = $environment->ID;
292
		$dataArchive->IsBackup = $dataTransfer->IsBackupDataTransfer();
293
294
		// Generate directory structure with strict permissions (contains very sensitive data)
295
		$filepathBase = $dataArchive->generateFilepath($dataTransfer);
296
		mkdir($filepathBase, 0700, true);
297
298
		$databasePath = $filepathBase . DIRECTORY_SEPARATOR . 'database.sql';
299
300
		// Backup database
301 View Code Duplication
		if(in_array($dataTransfer->Mode, array('all', 'db'))) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
302
			$log->write(sprintf('Backup of database from "%s" started', $name));
303
			$command = $this->getCommand('data:getdb', 'db', $environment, array('data_path' => $databasePath), $log);
304
			$command->run(function($type, $buffer) use($log) {
305
				$log->write($buffer);
306
			});
307
			if(!$command->isSuccessful()) {
308
				$this->extend('dataTransferFailure', $environment, $log);
309
				throw new RuntimeException($command->getErrorOutput());
310
			}
311
			$log->write(sprintf('Backup of database from "%s" done', $name));
312
		}
313
314
		// Backup assets
315 View Code Duplication
		if(in_array($dataTransfer->Mode, array('all', 'assets'))) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
316
			$log->write(sprintf('Backup of assets from "%s" started', $name));
317
			$command = $this->getCommand('data:getassets', 'web', $environment, array('data_path' => $filepathBase), $log);
318
			$command->run(function($type, $buffer) use($log) {
319
				$log->write($buffer);
320
			});
321
			if(!$command->isSuccessful()) {
322
				$this->extend('dataTransferFailure', $environment, $log);
323
				throw new RuntimeException($command->getErrorOutput());
324
			}
325
			$log->write(sprintf('Backup of assets from "%s" done', $name));
326
		}
327
328
		// ensure the database connection is re-initialised, which is needed if the transfer
329
		// above took a really long time because the handle to the db may have become invalid.
330
		global $databaseConfig;
331
		DB::connect($databaseConfig);
332
333
		$log->write('Creating sspak...');
334
335
		$sspakFilename = sprintf('%s.sspak', $dataArchive->generateFilename($dataTransfer));
336
		$sspakFilepath = $filepathBase . DIRECTORY_SEPARATOR . $sspakFilename;
337
338
		try {
339
			$dataArchive->attachFile($sspakFilepath, $dataTransfer);
340
			$dataArchive->setArchiveFromFiles($filepathBase);
341
		} catch(Exception $e) {
342
			$log->write($e->getMessage());
343
			throw new RuntimeException($e->getMessage());
344
		}
345
346
		// Remove any assets and db files lying around, they're not longer needed as they're now part
347
		// of the sspak file we just generated. Use --force to avoid errors when files don't exist,
348
		// e.g. when just an assets backup has been requested and no database.sql exists.
349
		$process = new AbortableProcess(sprintf('rm -rf %s/assets && rm -f %s', escapeshellarg($filepathBase), escapeshellarg($databasePath)));
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 137 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
350
		$process->setTimeout(120);
351
		$process->run();
352
		if(!$process->isSuccessful()) {
353
			$log->write('Could not delete temporary files');
354
			throw new RuntimeException($process->getErrorOutput());
355
		}
356
357
		$log->write(sprintf('Creating sspak file done: %s', $dataArchive->ArchiveFile()->getAbsoluteURL()));
358
	}
359
360
	/**
361
	 * Utility function for triggering the db rebuild and flush.
362
	 * Also cleans up and generates new error pages.
363
	 * @param DeploynautLogFile $log
364
	 */
365 View Code Duplication
	public function rebuild(DNEnvironment $environment, $log) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
366
		$name = $environment->getFullName();
367
		$command = $this->getCommand('deploy:migrate', 'web', $environment, null, $log);
368
		$command->run(function($type, $buffer) use($log) {
369
			$log->write($buffer);
370
		});
371
		if(!$command->isSuccessful()) {
372
			$log->write(sprintf('Rebuild of "%s" failed: %s', $name, $command->getErrorOutput()));
373
			throw new RuntimeException($command->getErrorOutput());
374
		}
375
		$log->write(sprintf('Rebuild of "%s" done', $name));
376
	}
377
378
	/**
379
	 * Extracts a *.sspak file referenced through the passed in $dataTransfer
380
	 * and pushes it to the environment referenced in $dataTransfer.
381
	 *
382
	 * @param string $workingDir Directory for the unpacked files.
383
	 * @param DNDataTransfer $dataTransfer
384
	 * @param DeploynautLogFile $log
385
	 */
386
	protected function dataTransferRestore($workingDir, DNDataTransfer $dataTransfer, DeploynautLogFile $log) {
387
		$environment = $dataTransfer->Environment();
388
		$name = $environment->getFullName();
389
390
		// Rollback cleanup.
391
		$self = $this;
392 View Code Duplication
		$cleanupFn = function() use($self, $workingDir, $environment, $log) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
393
			// Rebuild makes sense even if failed - maybe we can at least partly recover.
394
			$self->rebuild($environment, $log);
395
			$process = new AbortableProcess(sprintf('rm -rf %s', escapeshellarg($workingDir)));
396
			$process->setTimeout(120);
397
			$process->run();
398
		};
399
400
		// Restore database into target environment
401 View Code Duplication
		if(in_array($dataTransfer->Mode, array('all', 'db'))) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
402
			$log->write(sprintf('Restore of database to "%s" started', $name));
403
			$args = array('data_path' => $workingDir . DIRECTORY_SEPARATOR . 'database.sql');
404
			$command = $this->getCommand('data:pushdb', 'db', $environment, $args, $log);
405
			$command->run(function($type, $buffer) use($log) {
406
				$log->write($buffer);
407
			});
408
			if(!$command->isSuccessful()) {
409
				$cleanupFn();
410
				$log->write(sprintf('Restore of database to "%s" failed: %s', $name, $command->getErrorOutput()));
411
				$this->extend('dataTransferFailure', $environment, $log);
412
				throw new RuntimeException($command->getErrorOutput());
413
			}
414
			$log->write(sprintf('Restore of database to "%s" done', $name));
415
		}
416
417
		// Restore assets into target environment
418 View Code Duplication
		if(in_array($dataTransfer->Mode, array('all', 'assets'))) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
419
			$log->write(sprintf('Restore of assets to "%s" started', $name));
420
			$args = array('data_path' => $workingDir . DIRECTORY_SEPARATOR . 'assets');
421
			$command = $this->getCommand('data:pushassets', 'web', $environment, $args, $log);
422
			$command->run(function($type, $buffer) use($log) {
423
				$log->write($buffer);
424
			});
425
			if(!$command->isSuccessful()) {
426
				$cleanupFn();
427
				$log->write(sprintf('Restore of assets to "%s" failed: %s', $name, $command->getErrorOutput()));
428
				$this->extend('dataTransferFailure', $environment, $log);
429
				throw new RuntimeException($command->getErrorOutput());
430
			}
431
			$log->write(sprintf('Restore of assets to "%s" done', $name));
432
		}
433
434
		$log->write('Rebuilding and cleaning up');
435
		$cleanupFn();
436
	}
437
438
	/**
439
	 * This is mostly copy-pasted from Anthill/Smoketest.
440
	 *
441
	 * @param DNEnvironment $environment
442
	 * @param DeploynautLogFile $log
443
	 * @return bool
444
	 */
445
	protected function smokeTest(DNEnvironment $environment, DeploynautLogFile $log) {
446
		$url = $environment->getBareURL();
447
		$timeout = 600;
448
		$tick = 60;
449
450
		if(!$url) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $url of type string|null is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
451
			$log->write('Skipping site accessible check: no URL found.');
452
			return true;
453
		}
454
455
		$start = time();
456
		$infoTick = time() + $tick;
457
458
		$log->write(sprintf(
459
			'Waiting for "%s" to become accessible... (timeout: %smin)',
460
			$url,
461
			$timeout / 60
462
		));
463
464
		// configure curl so that curl_exec doesn't wait a long time for a response
465
		$ch = curl_init();
466
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
467
		curl_setopt($ch, CURLOPT_TIMEOUT, 5);
468
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
469
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
470
		curl_setopt($ch, CURLOPT_MAXREDIRS, 10); // set a high number of max redirects (but not infinite amount) to avoid a potential infinite loop
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 141 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
471
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
472
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
473
		curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
474
		curl_setopt($ch, CURLOPT_URL, $url);
475
		curl_setopt($ch, CURLOPT_USERAGENT, 'Rainforest');
476
		$success = false;
477
478
		// query the site every second. Note that if the URL doesn't respond,
479
		// curl_exec will take 5 seconds to timeout (see CURLOPT_CONNECTTIMEOUT and CURLOPT_TIMEOUT above)
480
		do {
481
			if(time() > $start + $timeout) {
482
				$log->write(sprintf(' * Failed: check for %s timed out after %smin', $url, $timeout / 60));
483
				return false;
484
			}
485
486
			$response = curl_exec($ch);
487
488
			// check the HTTP response code for HTTP protocols
489
			$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
490
			if($status && !in_array($status, [500, 501, 502, 503, 504])) {
491
				$success = true;
492
			}
493
494
			// check for any curl errors, mostly for checking the response state of non-HTTP protocols,
495
			// but applies to checks of any protocol
496
			if($response && !curl_errno($ch)) {
497
				$success = true;
498
			}
499
500
			// Produce an informational ticker roughly every $tick
501
			if (time() > $infoTick) {
502
				$message = [];
503
504
				// Collect status information from different sources.
505
				if ($status) {
506
					$message[] = sprintf('HTTP status code is %s', $status);
507
				}
508
				if (!$response) {
509
					$message[] = 'response is empty';
510
				}
511
				if ($error = curl_error($ch)) {
512
					$message[] = sprintf('request error: %s', $error);
513
				}
514
515
				$log->write(sprintf(
516
					' * Still waiting: %s...',
517
					implode(', ', $message)
518
				));
519
520
				$infoTick = time() + $tick;
521
			}
522
523
			sleep(1);
524
		} while(!$success);
525
526
		curl_close($ch);
527
		$log->write(' * Success: site is accessible!');
528
		return true;
529
	}
530
531
}
532