Completed
Pull Request — master (#575)
by Mateusz
12:05
created

DeployJob::set_signal()   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 2
1
<?php
2
3
/**
4
 * Runs a deployment via the most appropriate backend
5
 */
6
class DeployJob extends DeploynautJob {
7
8
	/**
9
	 * @var array
10
	 */
11
	public $args;
12
13
	public static function sig_file_for_data_object($dataObject) {
14
		$dir = DNData::inst()->getSignalDir();
15
		if (!is_dir($dir)) {
16
			`mkdir $dir`;
17
		}
18
		return sprintf(
19
			'%s/deploynaut-signal-%s-%s',
20
			DNData::inst()->getSignalDir(),
21
			$dataObject->ClassName,
22
			$dataObject->ID
23
		);
24
	}
25
26
	/**
27
	 * Signal the worker to self-abort. If we had a reliable way of figuring out the right PID,
28
	 * we could posix_kill directly, but Resque seems to not provide a way to find out the PID
29
	 * from the job nor worker.
30
	 */
31
	public static function set_signal($dataObject, $signal) {
32
		$sigFile = DeployJob::sig_file_for_data_object($dataObject);
33
		// 2 is SIGINT - we can't use SIGINT constant in the Apache context, only available in workers.
34
		file_put_contents($sigFile, $signal);
35
	}
36
37
	/**
38
	 * Poll the sigFile looking for a signal to self-deliver.
39
	 * This is useful if we don't know the PID of the worker - we can easily deliver signals
40
	 * if we only know the ClassName and ID of the DataObject.
41
	 */
42
	public function alarmHandler() {
43
		$sigFile = $this->args['sigFile'];
44
		if (file_exists($sigFile) && is_readable($sigFile) && is_writable($sigFile)) {
45
			$signal = (int)file_get_contents($sigFile);
46
			if (is_int($signal) && in_array((int)$signal, [
47
				// The following signals are trapped by both Resque and Rainforest.
48
				SIGTERM,
49
				SIGINT,
50
				SIGQUIT,
51
				// The following are Resque only.
52
				SIGUSR1,
53
				SIGUSR2,
54
				SIGCONT
55
			])) {
56
				echo sprintf(
57
					'[-] Signal "%s" received, delivering to own process group, PID "%s".' . PHP_EOL,
58
					$signal,
59
					getmypid()
60
				);
61
				// Mark the signal as received.
62
				unlink($sigFile);
63
				// Dispatch to own process group.
64
				$pgid = posix_getpgid(getmypid());
65
				posix_kill(-$pgid, $signal);
66
			}
67
		}
68
69
		// Wake up again soon.
70
		pcntl_alarm(1);
71
	}
72
73
	public function setUp() {
74
		// Make this process a session leader so we can send signals
75
		// to this job as a whole (including any subprocesses such as spawned by Symfony).
76
		posix_setsid();
77
78
		if(function_exists('pcntl_alarm') && function_exists('pcntl_signal')) {
79
			if (!empty($this->args['sigFile'])) {
80
				echo sprintf('[-] Signal file requested, polling "%s".' . PHP_EOL, $this->args['sigFile']);
81
				declare(ticks = 1);
82
				pcntl_signal(SIGALRM, [$this, 'alarmHandler']);
83
				pcntl_alarm(1);
84
			}
85
		}
86
87
		$this->updateStatus('Started');
88
		chdir(BASE_PATH);
89
	}
90
91
	public function perform() {
92
		echo "[-] DeployJob starting" . PHP_EOL;
93
		$log = new DeploynautLogFile($this->args['logfile']);
94
95
		$deployment = DNDeployment::get()->byID($this->args['deploymentID']);
96
		$environment = $deployment->Environment();
97
		$project = $environment->Project();
98
		// This is a bit icky, but there is no easy way of capturing a failed deploy by using the PHP Resque
99
		try {
100
			// Disallow concurrent deployments (don't rely on queuing implementation to restrict this)
101
			// Only consider deployments started in the last 30 minutes (older jobs probably got stuck)
102
			$runningDeployments = $environment->runningDeployments()->exclude('ID', $this->args['deploymentID']);
103 View Code Duplication
			if($runningDeployments->count()) {
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...
104
				$runningDeployment = $runningDeployments->first();
105
				$log->write(sprintf(
106
					'[-] Error: another deployment is in progress (started at %s by %s)',
107
					$runningDeployment->dbObject('Created')->Nice(),
108
					$runningDeployment->Deployer()->Title
109
				));
110
				throw new RuntimeException(sprintf(
111
					'Another deployment is in progress (started at %s by %s)',
112
					$runningDeployment->dbObject('Created')->Nice(),
113
					$runningDeployment->Deployer()->Title
114
				));
115
			}
116
117
			$environment->Backend()->deploy(
118
				$environment,
119
				$log,
120
				$project,
121
				// Pass all args to give the backend full visibility. These args also contain
122
				// all options from the DeploymentStrategy merged in, including sha.
123
				$this->args
124
			);
125
		} catch(Exception $e) {
126
			echo "[-] DeployJob failed" . PHP_EOL;
127
			throw $e;
128
		}
129
		$this->updateStatus('Finished');
130
		echo "[-] DeployJob finished" . PHP_EOL;
131
	}
132
133
	/**
134
	 * @param string $status
135
	 * @global array $databaseConfig
136
	 */
137
	protected function updateStatus($status) {
138
		global $databaseConfig;
139
		DB::connect($databaseConfig);
140
		$dnDeployment = DNDeployment::get()->byID($this->args['deploymentID']);
141
		$dnDeployment->Status = $status;
142
		$dnDeployment->write();
143
	}
144
145
	/**
146
	 * @return DNData
147
	 */
148
	protected function DNData() {
149
		return DNData::inst();
150
	}
151
}
152