Completed
Push — master ( 914da3...5086d9 )
by Sean
15:12 queued 10:12
created

DNDeployment::getTitle()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
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...
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
	public function setResqueToken($token) {
89
		$this->ResqueToken = $token;
90
	}
91
92
	public function getFiniteState() {
93
		return $this->State;
94
	}
95
96
	public function setFiniteState($state) {
97
		$this->State = $state;
98
		$this->write();
99
	}
100
101
	public function getStatus() {
102
		return $this->State;
103
	}
104
105
	public function getMachine() {
106
		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...
107
	}
108
109
	public function Link() {
110
		return Controller::join_links($this->Environment()->Link(), 'deploy', $this->ID);
111
	}
112
113
	public function LogLink() {
114
		return $this->Link() . '/log';
115
	}
116
117
	public function canView($member = null) {
118
		return $this->Environment()->canView($member);
119
	}
120
121
	/**
122
	 * Return a path to the log file.
123
	 * @return string
124
	 */
125
	protected function logfile() {
126
		return sprintf(
127
			'%s.%s.log',
128
			$this->Environment()->getFullName('.'),
129
			$this->ID
130
		);
131
	}
132
133
	/**
134
	 * @return DeploynautLogFile
135
	 */
136
	public function log() {
137
		return Injector::inst()->createWithArgs('DeploynautLogFile', array($this->logfile()));
138
	}
139
140
	public function LogContent() {
141
		return $this->log()->content();
142
	}
143
144
	/**
145
	 * This remains here for backwards compatibility - we don't want to expose Resque status in here.
146
	 * Resque job (DeployJob) will change statuses as part of its execution.
147
	 *
148
	 * @return string
149
	 */
150
	public function ResqueStatus() {
151
		return $this->State;
152
	}
153
154
	/**
155
	 * Fetch the git repository
156
	 *
157
	 * @return \Gitonomy\Git\Repository|null
158
	 */
159
	public function getRepository() {
160
		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...
161
			return null;
162
		}
163
		return $this->Environment()->Project()->getRepository();
164
	}
165
166
	/**
167
	 * Gets the commit from source. The result is cached upstream in Repository.
168
	 *
169
	 * @return \Gitonomy\Git\Commit|null
170
	 */
171 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...
172
		$repo = $this->getRepository();
173
		if($repo) {
174
			try {
175
				return $this->Environment()->getCommit($this->SHA);
176
			} catch(Gitonomy\Git\Exception\ReferenceNotFoundException $ex) {
177
				return null;
178
			}
179
		}
180
181
		return null;
182
	}
183
184
	/**
185
	 * Get the commit URL to the commit associated with this deployment.
186
	 * @return null|string
187
	 */
188
	public function getCommitURL() {
189
		$environment = $this->Environment();
190
		if (!$environment) {
191
			return null;
192
		}
193
		$project = $environment->Project();
194
		if (!$project) {
195
			return null;
196
		}
197
		$interface = $project->getRepositoryInterface();
198
		if (!$interface) {
199
			return null;
200
		}
201
		return $interface->CommitURL . '/' . $this->SHA;
202
	}
203
204
	/**
205
	 * Gets the commit message.
206
	 *
207
	 * @return string|null
208
	 */
209 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...
210
		$commit = $this->getCommit();
211
		if($commit) {
212
			try {
213
				return Convert::raw2xml($this->Environment()->getCommitMessage($commit));
214
			} catch(Gitonomy\Git\Exception\ReferenceNotFoundException $e) {
215
				return null;
216
			}
217
		}
218
		return null;
219
	}
220
221
	/**
222
	 * Return all tags for the deployed commit.
223
	 *
224
	 * @return ArrayList
225
	 */
226
	public function getTags() {
227
		$commit = $this->Environment()->getCommit($this->SHA);
228
		$tags = $this->Environment()->getCommitTags($commit);
229
		$returnTags = [];
230
		if (!empty($tags)) {
231
			foreach($tags as $tag) {
232
				$field = Varchar::create('Tag', '255');
233
				$field->setValue($tag->getName());
234
				$returnTags[] = $field;
235
			}
236
		}
237
		return new ArrayList($returnTags);
238
	}
239
240
	/**
241
	 * Collate the list of additional flags to affix to this deployment.
242
	 * Elements of the array will be rendered literally.
243
	 *
244
	 * @return ArrayList
245
	 */
246
	public function getFullDeployMessages() {
247
		$strategy = $this->getDeploymentStrategy();
248
		if ($strategy->getActionCode()!=='full') return null;
249
250
		$changes = $strategy->getChangesModificationNeeded();
251
		$messages = [];
252
		foreach ($changes as $change => $details) {
253
			if ($change==='Code version') continue;
254
255
			$messages[] = [
256
				'Flag' => sprintf(
257
					'<span class="label label-default full-deploy-info-item">%s</span>',
258
					$change[0]
259
				),
260
				'Text' => sprintf('%s changed', $change)
261
			];
262
		}
263
264
		if (empty($messages)) {
265
			$messages[] = [
266
				'Flag' => '',
267
				'Text' => '<i>Environment changes have been made.</i>'
268
			];
269
		}
270
271
		return new ArrayList($messages);
272
	}
273
274
	/**
275
	 * Fetches the latest tag for the deployed commit
276
	 *
277
	 * @return \Varchar|null
278
	 */
279
	public function getTag() {
280
		$tags = $this->getTags();
281
		if($tags->count() > 0) {
282
			return $tags->last();
283
		}
284
		return null;
285
	}
286
287
	/**
288
	 * @return DeploymentStrategy
289
	 */
290
	public function getDeploymentStrategy() {
291
		$environment = $this->Environment();
292
		$strategy = new DeploymentStrategy($environment);
293
		$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...
294
		return $strategy;
295
	}
296
297
	/**
298
	 * Return a list of things that are going to be deployed, such
299
	 * as the code version, and any infrastructural changes.
300
	 *
301
	 * @return ArrayList
302
	 */
303
	public function getChanges() {
304
		$list = new ArrayList();
305
		$strategy = $this->getDeploymentStrategy();
306
		foreach($strategy->getChanges() as $name => $change) {
307
			$changed = (isset($change['from']) && isset($change['to'])) ? $change['from'] != $change['to'] : null;
308
			$description = isset($change['description']) ? $change['description'] : '';
309
			$compareUrl = null;
310
311
			// if there is a compare URL, and a description or a change (something actually changed)
312
			// then show the URL. Otherwise don't show anything, as there is no comparison to be made.
313
			if ($changed || $description) {
314
				$compareUrl = isset($change['compareUrl']) ? $change['compareUrl'] : '';
315
			}
316
317
			$list->push(new ArrayData([
318
				'Name' => $name,
319
				'From' => isset($change['from']) ? $change['from'] : null,
320
				'To' => isset($change['to']) ? $change['to'] : null,
321
				'Description' => $description,
322
				'Changed' => $changed,
323
				'CompareUrl' => $compareUrl
324
			]));
325
		}
326
327
		return $list;
328
	}
329
330
	/**
331
	 * Start a resque job for this deployment
332
	 *
333
	 * @return string Resque token
334
	 */
335
	public function enqueueDeployment() {
336
		$environment = $this->Environment();
337
		$project = $environment->Project();
338
		$log = $this->log();
339
340
		$args = array(
341
			'environmentName' => $environment->Name,
342
			'repository' => $project->getLocalCVSPath(),
343
			'logfile' => $this->logfile(),
344
			'projectName' => $project->Name,
345
			'env' => $project->getProcessEnv(),
346
			'deploymentID' => $this->ID,
347
			'sigFile' => $this->getSigFile(),
348
		);
349
350
		$strategy = $this->getDeploymentStrategy();
351
		// Inject options.
352
		$args = array_merge($args, $strategy->getOptions());
353
		// Make sure we use the SHA as it was written into this DNDeployment.
354
		$args['sha'] = $this->SHA;
355
356
		if(!$this->DeployerID) {
357
			$this->DeployerID = Member::currentUserID();
358
		}
359
360 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...
361
			$deployer = $this->Deployer();
362
			$message = sprintf(
363
				'Deploy to %s initiated by %s (%s), with IP address %s',
364
				$environment->getFullName(),
365
				$deployer->getName(),
366
				$deployer->Email,
367
				Controller::curr()->getRequest()->getIP()
368
			);
369
			$log->write($message);
370
		}
371
372
		return Resque::enqueue('deploy', 'DeployJob', $args, true);
373
	}
374
375
	public function getSigFile() {
376
		$dir = DNData::inst()->getSignalDir();
377
		if (!is_dir($dir)) {
378
			`mkdir $dir`;
379
		}
380
		return sprintf(
381
			'%s/deploynaut-signal-%s-%s',
382
			DNData::inst()->getSignalDir(),
383
			$this->ClassName,
384
			$this->ID
385
		);
386
	}
387
388
	/**
389
	 * Signal the worker to self-abort. If we had a reliable way of figuring out the right PID,
390
	 * we could posix_kill directly, but Resque seems to not provide a way to find out the PID
391
	 * from the job nor worker.
392
	 */
393
	public function setSignal($signal) {
394
		$sigFile = $this->getSigFile();
395
		// 2 is SIGINT - we can't use SIGINT constant in the Apache context, only available in workers.
396
		file_put_contents($sigFile, $signal);
397
	}
398
}
399