Completed
Pull Request — master (#731)
by Sean
04:26
created

DNDeployment::enqueueDeployment()   B

Complexity

Conditions 3
Paths 4

Size

Total Lines 39
Code Lines 27

Duplication

Lines 11
Ratio 28.21 %

Importance

Changes 0
Metric Value
dl 11
loc 39
rs 8.8571
c 0
b 0
f 0
cc 3
eloc 27
nc 4
nop 0
1
<?php
2
3
/**
4
 * Class representing a single deplyoment (passed or failed) at a time to a particular environment
5
 *
6
 * @property string $SHA
7
 * @property string $ResqueToken
8
 * @property string $State
9
 * @property int $RefType
10
 * @property SS_Datetime $DeployStarted
11
 * @property SS_Datetime $DeployRequested
12
 *
13
 * @method DNEnvironment Environment()
14
 * @property int EnvironmentID
15
 * @method Member Deployer()
16
 * @property int DeployerID
17
 */
18
class DNDeployment extends DataObject implements Finite\StatefulInterface, HasStateMachine {
0 ignored issues
show
Coding Style introduced by
The property $has_one is not named in camelCase.

This check marks property names that have not been written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection string becomes databaseConnectionString.

Loading history...
Coding Style introduced by
The property $default_sort is not named in camelCase.

This check marks property names that have not been written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection string becomes databaseConnectionString.

Loading history...
Coding Style introduced by
The property $summary_fields is not named in camelCase.

This check marks property names that have not been written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection string becomes databaseConnectionString.

Loading history...
Coding Style introduced by
The property $new_deploy_form is not named in camelCase.

This check marks property names that have not been written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection string becomes databaseConnectionString.

Loading history...
19
20
	const STATE_NEW = 'New';
21
	const STATE_SUBMITTED = 'Submitted';
22
	const STATE_INVALID = 'Invalid';
23
	const STATE_APPROVED = 'Approved';
24
	const STATE_REJECTED = 'Rejected';
25
	const STATE_QUEUED = 'Queued';
26
	const STATE_DEPLOYING = 'Deploying';
27
	const STATE_ABORTING = 'Aborting';
28
	const STATE_COMPLETED = 'Completed';
29
	const STATE_FAILED = 'Failed';
30
31
	const TR_NEW = 'new';
32
	const TR_SUBMIT = 'submit';
33
	const TR_INVALIDATE = 'invalidate';
34
	const TR_APPROVE = 'approve';
35
	const TR_REJECT = 'reject';
36
	const TR_QUEUE = 'queue';
37
	const TR_DEPLOY = 'deploy';
38
	const TR_ABORT = 'abort';
39
	const TR_COMPLETE = 'complete';
40
	const TR_FAIL = 'fail';
41
42
	/**
43
	 * @var array
44
	 */
45
	private static $db = array(
46
		"SHA" => "GitSHA",
47
		"ResqueToken" => "Varchar(255)",
48
		// The branch that was used to deploy this. Can't really be inferred from Git history because
49
		// the commit could appear in lots of branches that are irrelevant to the user when it comes
50
		// to deployment history, and the branch may have been deleted.
51
		"Branch" => "Varchar(255)",
52
		// is it a branch, tag etc, see GitDispatcher REF_TYPE_* constants
53
		"RefType" => "Int",
54
		"State" => "Enum('New, Submitted, Invalid, Approved, Rejected, Queued, Deploying, Aborting, Completed, Failed', 'New')",
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 122 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...
55
		// JSON serialised DeploymentStrategy.
56
		"Strategy" => "Text",
57
		"Title" => "Varchar(255)",
58
		"Summary" => "Text",
59
		// the date and time the deploy was queued
60
		"DeployStarted" => "SS_Datetime",
61
		// the date and time a deployment was requested to be approved
62
		"DeployRequested" => "SS_Datetime"
63
	);
64
65
	/**
66
	 * @var array
67
	 */
68
	private static $has_one = array(
69
		"Environment" => "DNEnvironment",
70
		"Deployer" => "Member",
71
		"Approver" => "Member",
72
		"BackupDataTransfer" => "DNDataTransfer" // denotes an automated backup done for this deployment
73
	);
74
75
	private static $default_sort = '"LastEdited" DESC';
76
77
	private static $dependencies = [
78
		'stateMachineFactory' => '%$StateMachineFactory'
79
	];
80
81
	private static $summary_fields = array(
82
		'LastEdited' => 'Last Edited',
83
		'SHA' => 'SHA',
84
		'State' => 'State',
85
		'Deployer.Name' => 'Deployer'
86
	);
87
88
	/**
89
	 * Set to true to ensure links go to the new deployment form.
90
	 * @var bool
91
	 */
92
	private static $new_deploy_form = false;
0 ignored issues
show
Unused Code introduced by
The property $new_deploy_form is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
93
94
	public function setResqueToken($token) {
95
		$this->ResqueToken = $token;
96
	}
97
98
	public function getFiniteState() {
99
		return $this->State;
100
	}
101
102
	public function setFiniteState($state) {
103
		$this->State = $state;
104
		$this->write();
105
	}
106
107
	public function getStatus() {
108
		return $this->State;
109
	}
110
111
	public function getMachine() {
112
		return $this->stateMachineFactory->forDNDeployment($this);
0 ignored issues
show
Documentation introduced by
The property stateMachineFactory does not exist on object<DNDeployment>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
113
	}
114
115
	public function Link() {
116
		if ($this->config()->new_deploy_form) {
117
			return Controller::join_links($this->Environment()->Link('overview'), 'deployment', $this->ID);
118
		} else {
119
			return Controller::join_links($this->Environment()->Link(), 'deploy', $this->ID);
120
		}
121
	}
122
123
	public function LogLink() {
124
		return $this->Link() . '/log';
125
	}
126
127
	public function canView($member = null) {
128
		return $this->Environment()->canView($member);
129
	}
130
131
	/**
132
	 * Return a path to the log file.
133
	 * @return string
134
	 */
135
	protected function logfile() {
136
		return sprintf(
137
			'%s.%s.log',
138
			$this->Environment()->getFullName('.'),
139
			$this->ID
140
		);
141
	}
142
143
	/**
144
	 * @return DeploynautLogFile
145
	 */
146
	public function log() {
147
		return Injector::inst()->createWithArgs('DeploynautLogFile', array($this->logfile()));
148
	}
149
150
	public function LogContent() {
151
		return $this->log()->content();
152
	}
153
154
	/**
155
	 * This remains here for backwards compatibility - we don't want to expose Resque status in here.
156
	 * Resque job (DeployJob) will change statuses as part of its execution.
157
	 *
158
	 * @return string
159
	 */
160
	public function ResqueStatus() {
161
		return $this->State;
162
	}
163
164
	/**
165
	 * Fetch the git repository
166
	 *
167
	 * @return \Gitonomy\Git\Repository|null
168
	 */
169
	public function getRepository() {
170
		if(!$this->SHA) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->SHA 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...
171
			return null;
172
		}
173
		return $this->Environment()->Project()->getRepository();
174
	}
175
176
	/**
177
	 * Gets the commit from source. The result is cached upstream in Repository.
178
	 *
179
	 * @return \Gitonomy\Git\Commit|null
180
	 */
181 View Code Duplication
	public function getCommit() {
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...
182
		$repo = $this->getRepository();
183
		if($repo) {
184
			try {
185
				return $this->Environment()->getCommit($this->SHA);
186
			} catch(Gitonomy\Git\Exception\ReferenceNotFoundException $ex) {
187
				return null;
188
			}
189
		}
190
191
		return null;
192
	}
193
194
	/**
195
	 * Get the commit URL to the commit associated with this deployment.
196
	 * @return null|string
197
	 */
198
	public function getCommitURL() {
199
		$environment = $this->Environment();
200
		if (!$environment) {
201
			return null;
202
		}
203
		$project = $environment->Project();
204
		if (!$project) {
205
			return null;
206
		}
207
		$interface = $project->getRepositoryInterface();
208
		if (!$interface) {
209
			return null;
210
		}
211
		return $interface->CommitURL . '/' . $this->SHA;
212
	}
213
214
	/**
215
	 * Gets the commit message.
216
	 *
217
	 * @return string|null
218
	 */
219 View Code Duplication
	public function getCommitMessage() {
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...
220
		$commit = $this->getCommit();
221
		if($commit) {
222
			try {
223
				return Convert::raw2xml($this->Environment()->getCommitMessage($commit));
224
			} catch(Gitonomy\Git\Exception\ReferenceNotFoundException $e) {
225
				return null;
226
			}
227
		}
228
		return null;
229
	}
230
231
	/**
232
	 * Return all tags for the deployed commit.
233
	 *
234
	 * @return ArrayList
235
	 */
236
	public function getTags() {
237
		$commit = $this->Environment()->getCommit($this->SHA);
238
		if(!$commit) {
239
			return new ArrayList([]);
240
		}
241
		$tags = $this->Environment()->getCommitTags($commit);
242
		$returnTags = [];
243
		if (!empty($tags)) {
244
			foreach($tags as $tag) {
245
				$field = Varchar::create('Tag', '255');
246
				$field->setValue($tag->getName());
247
				$returnTags[] = $field;
248
			}
249
		}
250
		return new ArrayList($returnTags);
251
	}
252
253
	/**
254
	 * Collate the list of additional flags to affix to this deployment.
255
	 * Elements of the array will be rendered literally.
256
	 *
257
	 * @return ArrayList
258
	 */
259
	public function getFullDeployMessages() {
260
		$strategy = $this->getDeploymentStrategy();
261
		if ($strategy->getActionCode()!=='full') return null;
262
263
		$changes = $strategy->getChangesModificationNeeded();
264
		$messages = [];
265
		foreach ($changes as $change => $details) {
266
			if ($change==='Code version') continue;
267
268
			$messages[] = [
269
				'Flag' => sprintf(
270
					'<span class="label label-default full-deploy-info-item">%s</span>',
271
					$change[0]
272
				),
273
				'Text' => sprintf('%s changed', $change)
274
			];
275
		}
276
277
		if (empty($messages)) {
278
			$messages[] = [
279
				'Flag' => '',
280
				'Text' => '<i>Environment changes have been made.</i>'
281
			];
282
		}
283
284
		return new ArrayList($messages);
285
	}
286
287
	/**
288
	 * Fetches the latest tag for the deployed commit
289
	 *
290
	 * @return \Varchar|null
291
	 */
292
	public function getTag() {
293
		$tags = $this->getTags();
294
		if($tags->count() > 0) {
295
			return $tags->last();
296
		}
297
		return null;
298
	}
299
300
	/**
301
	 * @return DeploymentStrategy
302
	 */
303
	public function getDeploymentStrategy() {
304
		$environment = $this->Environment();
305
		$strategy = new DeploymentStrategy($environment);
306
		$strategy->fromJSON($this->Strategy);
0 ignored issues
show
Documentation introduced by
The property Strategy does not exist on object<DNDeployment>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
307
		return $strategy;
308
	}
309
310
	/**
311
	 * Return a list of things that are going to be deployed, such
312
	 * as the code version, and any infrastructural changes.
313
	 *
314
	 * @return ArrayList
315
	 */
316
	public function getChanges() {
317
		$list = new ArrayList();
318
		$strategy = $this->getDeploymentStrategy();
319
		foreach($strategy->getChanges() as $name => $change) {
320
			$changed = (isset($change['from']) && isset($change['to'])) ? $change['from'] != $change['to'] : null;
321
			$description = isset($change['description']) ? $change['description'] : '';
322
			$compareUrl = null;
323
324
			// if there is a compare URL, and a description or a change (something actually changed)
325
			// then show the URL. Otherwise don't show anything, as there is no comparison to be made.
326
			if ($changed || $description) {
327
				$compareUrl = isset($change['compareUrl']) ? $change['compareUrl'] : '';
328
			}
329
330
			$list->push(new ArrayData([
331
				'Name' => $name,
332
				'From' => isset($change['from']) ? $change['from'] : null,
333
				'To' => isset($change['to']) ? $change['to'] : null,
334
				'Description' => $description,
335
				'Changed' => $changed,
336
				'CompareUrl' => $compareUrl
337
			]));
338
		}
339
340
		return $list;
341
	}
342
343
	/**
344
	 * Start a resque job for this deployment
345
	 *
346
	 * @return string Resque token
347
	 */
348
	public function enqueueDeployment() {
349
		$environment = $this->Environment();
350
		$project = $environment->Project();
351
		$log = $this->log();
352
353
		$args = array(
354
			'environmentName' => $environment->Name,
355
			'repository' => $project->getLocalCVSPath(),
356
			'logfile' => $this->logfile(),
357
			'projectName' => $project->Name,
358
			'env' => $project->getProcessEnv(),
359
			'deploymentID' => $this->ID,
360
			'sigFile' => $this->getSigFile(),
361
		);
362
363
		$strategy = $this->getDeploymentStrategy();
364
		// Inject options.
365
		$args = array_merge($args, $strategy->getOptions());
366
		// Make sure we use the SHA as it was written into this DNDeployment.
367
		$args['sha'] = $this->SHA;
368
369
		if(!$this->DeployerID) {
370
			$this->DeployerID = Member::currentUserID();
371
		}
372
373 View Code Duplication
		if($this->DeployerID) {
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...
374
			$deployer = $this->Deployer();
375
			$message = sprintf(
376
				'Deploy to %s initiated by %s (%s), with IP address %s',
377
				$environment->getFullName(),
378
				$deployer->getName(),
379
				$deployer->Email,
380
				Controller::curr()->getRequest()->getIP()
381
			);
382
			$log->write($message);
383
		}
384
385
		return Resque::enqueue('deploy', 'DeployJob', $args, true);
386
	}
387
388
	public function getSigFile() {
389
		$dir = DNData::inst()->getSignalDir();
390
		if (!is_dir($dir)) {
391
			`mkdir $dir`;
392
		}
393
		return sprintf(
394
			'%s/deploynaut-signal-%s-%s',
395
			DNData::inst()->getSignalDir(),
396
			$this->ClassName,
397
			$this->ID
398
		);
399
	}
400
401
	/**
402
	 * Signal the worker to self-abort. If we had a reliable way of figuring out the right PID,
403
	 * we could posix_kill directly, but Resque seems to not provide a way to find out the PID
404
	 * from the job nor worker.
405
	 */
406
	public function setSignal($signal) {
407
		$sigFile = $this->getSigFile();
408
		// 2 is SIGINT - we can't use SIGINT constant in the Apache context, only available in workers.
409
		file_put_contents($sigFile, $signal);
410
	}
411
}
412