Completed
Pull Request — master (#588)
by Mateusz
11:08
created

DNDeployment::setResqueToken()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 3
rs 10
cc 1
eloc 2
nc 1
nop 1
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
 *
10
 * @method DNEnvironment Environment()
11
 * @property int EnvironmentID
12
 * @method Member Deployer()
13
 * @property int DeployerID
14
 */
15
class DNDeployment extends DataObject implements Finite\StatefulInterface, HasStateMachine {
16
17
	const STATE_NEW = 'New';
18
	const STATE_SUBMITTED = 'Submitted';
19
	const STATE_INVALID = 'Invalid';
20
	const STATE_QUEUED = 'Queued';
21
	const STATE_DEPLOYING = 'Deploying';
22
	const STATE_ABORTING = 'Aborting';
23
	const STATE_COMPLETED = 'Completed';
24
	const STATE_FAILED = 'Failed';
25
26
	const TR_SUBMIT = 'submit';
27
	const TR_INVALIDATE = 'invalidate';
28
	const TR_QUEUE = 'queue';
29
	const TR_DEPLOY = 'deploy';
30
	const TR_ABORT = 'abort';
31
	const TR_COMPLETE = 'complete';
32
	const TR_FAIL = 'fail';
33
34
	/**
35
	 * @var array
36
	 */
37
	private static $db = array(
38
		"SHA" => "GitSHA",
39
		"ResqueToken" => "Varchar(255)",
40
		// The branch that was used to deploy this. Can't really be inferred from Git history because
41
		// the commit could appear in lots of branches that are irrelevant to the user when it comes
42
		// to deployment history, and the branch may have been deleted.
43
		"Branch" => "Varchar(255)",
44
		"State" => "Enum('New, Submitted, Invalid, Queued, Deploying, Aborting, Completed, Failed', 'New')",
45
		// JSON serialised DeploymentStrategy.
46
		"Strategy" => "Text",
47
		"Summary" => "Text",
48
		"DatePlanned" => "SS_Datetime"
49
	);
50
51
	/**
52
	 * @var array
53
	 */
54
	private static $has_one = array(
55
		"Environment" => "DNEnvironment",
56
		"Deployer" => "Member",
57
		"Approver" => "Member"
58
	);
59
60
	private static $default_sort = '"LastEdited" DESC';
61
62
	private static $dependencies = [
63
		'stateMachineFactory' => '%$StateMachineFactory'
64
	];
65
66
	public function getTitle() {
67
		return "#{$this->ID}: {$this->SHA} (Status: {$this->Status})";
0 ignored issues
show
Documentation introduced by
The property Status 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...
68
	}
69
70
	private static $summary_fields = array(
71
		'LastEdited' => 'Last Edited',
72
		'SHA' => 'SHA',
73
		'State' => 'State',
74
		'Deployer.Name' => 'Deployer'
75
	);
76
77
	public function setResqueToken($token) {
78
		$this->ResqueToken = $token;
79
	}
80
81
	public function getFiniteState() {
82
		return $this->State;
83
	}
84
85
	public function setFiniteState($state) {
86
		$this->State = $state;
87
		$this->write();
88
	}
89
90
	public function getStatus() {
91
		return $this->State;
92
	}
93
94
	public function getMachine() {
95
		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...
96
	}
97
98
	public function Link() {
99
		return Controller::join_links($this->Environment()->Link(), 'deploy', $this->ID);
100
	}
101
102
	public function LogLink() {
103
		return $this->Link() . '/log';
104
	}
105
106
	public function canView($member = null) {
107
		return $this->Environment()->canView($member);
108
	}
109
110
	/**
111
	 * Return a path to the log file.
112
	 * @return string
113
	 */
114
	protected function logfile() {
115
		return sprintf(
116
			'%s.%s.log',
117
			$this->Environment()->getFullName('.'),
118
			$this->ID
119
		);
120
	}
121
122
	/**
123
	 * @return DeploynautLogFile
124
	 */
125
	public function log() {
126
		return Injector::inst()->createWithArgs('DeploynautLogFile', array($this->logfile()));
127
	}
128
129
	public function LogContent() {
130
		return $this->log()->content();
131
	}
132
133
	/**
134
	 * This remains here for backwards compatibility - we don't want to expose Resque status in here.
135
	 * Resque job (DeployJob) will change statuses as part of its execution.
136
	 *
137
	 * @return string
138
	 */
139
	public function ResqueStatus() {
140
		return $this->State;
141
	}
142
143
144
	/**
145
	 * Fetch the git repository
146
	 *
147
	 * @return \Gitonomy\Git\Repository|null
148
	 */
149
	public function getRepository() {
150
		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...
151
			return null;
152
		}
153
		return $this->Environment()->Project()->getRepository();
154
	}
155
156
157
	/**
158
	 * Gets the commit from source. The result is cached upstream in Repository.
159
	 *
160
	 * @return \Gitonomy\Git\Commit|null
161
	 */
162
	public function getCommit() {
163
		$repo = $this->getRepository();
164
		if($repo) {
165
			try {
166
				return $repo->getCommit($this->SHA);
167
			} catch(Gitonomy\Git\Exception\ReferenceNotFoundException $ex) {
168
				return null;
169
			}
170
		}
171
172
		return null;
173
	}
174
175
176
	/**
177
	 * Gets the commit message.
178
	 *
179
	 * @return string|null
180
	 */
181
	public function getCommitMessage() {
182
		$commit = $this->getCommit();
183
		if($commit) {
184
			try {
185
				return Convert::raw2xml($commit->getMessage());
186
			} catch(Gitonomy\Git\Exception\ReferenceNotFoundException $e) {
187
				return null;
188
			}
189
		}
190
		return null;
191
	}
192
193
	/**
194
	 * Return all tags for the deployed commit.
195
	 *
196
	 * @return ArrayList
197
	 */
198
	public function getTags() {
199
		$returnTags = array();
200
		$repo = $this->getRepository();
201
		if($repo) {
202
			$tags = $repo->getReferences()->resolveTags($this->SHA);
203
			if(!empty($tags)) {
204
				foreach($tags as $tag) {
205
					$field = Varchar::create('Tag', '255');
206
					$field->setValue($tag->getName());
207
					$returnTags[] = $field;
208
				}
209
			}
210
		}
211
		return new ArrayList($returnTags);
212
	}
213
214
	/**
215
	 * Collate the list of additional flags to affix to this deployment.
216
	 * Elements of the array will be rendered literally.
217
	 *
218
	 * @return ArrayList
219
	 */
220
	public function getFullDeployMessages() {
221
		$strategy = $this->getDeploymentStrategy();
222
		if ($strategy->getActionCode()!=='full') return null;
223
224
		$changes = $strategy->getChangesModificationNeeded();
225
		$messages = [];
226
		foreach ($changes as $change => $details) {
227
			if ($change==='Code version') continue;
228
229
			$messages[] = [
230
				'Flag' => sprintf(
231
					'<span class="label label-default full-deploy-info-item">%s</span>',
232
					$change[0]
233
				),
234
				'Text' => sprintf('%s changed', $change)
235
			];
236
		}
237
238
		if (empty($messages)) {
239
			$messages[] = [
240
				'Flag' => '',
241
				'Text' => '<i>Environment changes have been made.</i>'
242
			];
243
		}
244
245
		return new ArrayList($messages);
246
	}
247
248
	/**
249
	 * Fetches the latest tag for the deployed commit
250
	 *
251
	 * @return \Varchar|null
252
	 */
253
	public function getTag() {
254
		$tags = $this->getTags();
255
		if($tags->count() > 0) {
256
			return $tags->last();
257
		}
258
		return null;
259
	}
260
261
	/**
262
	 * @return DeploymentStrategy
263
	 */
264
	public function getDeploymentStrategy() {
265
		$environment = $this->Environment();
266
		$strategy = new DeploymentStrategy($environment);
267
		$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...
268
		return $strategy;
269
	}
270
271
	/**
272
	 * Return a list of things that are going to be deployed, such
273
	 * as the code version, and any infrastrucutral changes.
274
	 *
275
	 * @return ArrayList
276
	 */
277
	public function getChanges() {
278
		$list = new ArrayList();
279
		$strategy = $this->getDeploymentStrategy();
280
		foreach($strategy->getChanges() as $name => $change) {
281
			$changed = (isset($change['from']) && isset($change['to'])) ? $change['from'] != $change['to'] : null;
282
			$description = isset($change['description']) ? $change['description'] : '';
283
			$compareUrl = null;
284
285
			// if there is a compare URL, and a description or a change (something actually changed)
286
			// then show the URL. Otherwise don't show anything, as there is no comparison to be made.
287
			if ($changed || $description) {
288
				$compareUrl = isset($change['compareUrl']) ? $change['compareUrl'] : '';
289
			}
290
291
			$list->push(new ArrayData([
292
				'Name' => $name,
293
				'From' => isset($change['from']) ? $change['from'] : null,
294
				'To' => isset($change['to']) ? $change['to'] : null,
295
				'Description' => $description,
296
				'Changed' => $changed,
297
				'CompareUrl' => $compareUrl
298
			]));
299
		}
300
301
		return $list;
302
	}
303
304
	/**
305
	 * Start a resque job for this deployment
306
	 *
307
	 * @return string Resque token
308
	 */
309
	public function enqueueDeployment() {
310
		$environment = $this->Environment();
311
		$project = $environment->Project();
312
		$log = $this->log();
313
314
		$args = array(
315
			'environmentName' => $environment->Name,
316
			'repository' => $project->getLocalCVSPath(),
317
			'logfile' => $this->logfile(),
318
			'projectName' => $project->Name,
319
			'env' => $project->getProcessEnv(),
320
			'deploymentID' => $this->ID,
321
			'sigFile' => $this->getSigFile(),
322
		);
323
324
		$strategy = $this->getDeploymentStrategy();
325
		// Inject options.
326
		$args = array_merge($args, $strategy->getOptions());
327
		// Make sure we use the SHA as it was written into this DNDeployment.
328
		$args['sha'] = $this->SHA;
329
330
		if(!$this->DeployerID) {
331
			$this->DeployerID = Member::currentUserID();
332
		}
333
334 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...
335
			$deployer = $this->Deployer();
336
			$message = sprintf(
337
				'Deploy to %s initiated by %s (%s), with IP address %s',
338
				$environment->getFullName(),
339
				$deployer->getName(),
340
				$deployer->Email,
341
				Controller::curr()->getRequest()->getIP()
342
			);
343
			$log->write($message);
344
		}
345
346
		return Resque::enqueue('deploy', 'DeployJob', $args, true);
347
	}
348
349
	public function getSigFile() {
350
		$dir = DNData::inst()->getSignalDir();
351
		if (!is_dir($dir)) {
352
			`mkdir $dir`;
353
		}
354
		return sprintf(
355
			'%s/deploynaut-signal-%s-%s',
356
			DNData::inst()->getSignalDir(),
357
			$this->ClassName,
358
			$this->ID
359
		);
360
	}
361
362
	/**
363
	 * Signal the worker to self-abort. If we had a reliable way of figuring out the right PID,
364
	 * we could posix_kill directly, but Resque seems to not provide a way to find out the PID
365
	 * from the job nor worker.
366
	 */
367
	public function setSignal($signal) {
368
		$sigFile = $this->getSigFile();
369
		// 2 is SIGINT - we can't use SIGINT constant in the Apache context, only available in workers.
370
		file_put_contents($sigFile, $signal);
371
	}
372
}
373