Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
Complex classes like CapistranoDeploymentBackend often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use CapistranoDeploymentBackend, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
4 | class CapistranoDeploymentBackend extends Object implements DeploymentBackend { |
||
5 | |||
6 | protected $packageGenerator; |
||
7 | |||
8 | public function getPackageGenerator() { |
||
11 | |||
12 | public function setPackageGenerator(PackageGenerator $packageGenerator) { |
||
15 | |||
16 | /** |
||
17 | * Create a deployment strategy. |
||
18 | * |
||
19 | * @param DNEnvironment $environment |
||
20 | * @param array $options |
||
21 | * |
||
22 | * @return DeploymentStrategy |
||
23 | */ |
||
24 | public function planDeploy(DNEnvironment $environment, $options) { |
||
38 | |||
39 | /** |
||
40 | * Deploy the given build to the given environment. |
||
41 | * |
||
42 | * @param DNEnvironment $environment |
||
43 | * @param DeploynautLogFile $log |
||
44 | * @param DNProject $project |
||
45 | * @param array $options |
||
46 | */ |
||
47 | public function deploy( |
||
48 | DNEnvironment $environment, |
||
49 | DeploynautLogFile $log, |
||
50 | DNProject $project, |
||
51 | $options |
||
52 | ) { |
||
53 | $name = $environment->getFullName(); |
||
54 | $repository = $project->getLocalCVSPath(); |
||
55 | $sha = $options['sha']; |
||
56 | |||
57 | $args = array( |
||
58 | 'branch' => $sha, |
||
59 | 'repository' => $repository, |
||
60 | ); |
||
61 | |||
62 | $this->extend('deployStart', $environment, $sha, $log, $project); |
||
63 | |||
64 | $log->write(sprintf('Deploying "%s" to "%s"', $sha, $name)); |
||
65 | |||
66 | $this->enableMaintenance($environment, $log, $project); |
||
67 | |||
68 | // Use a package generator if specified, otherwise run a direct deploy, which is the default behaviour |
||
69 | // if build_filename isn't specified |
||
70 | if($this->packageGenerator) { |
||
71 | $log->write(sprintf('Using package generator "%s"', get_class($this->packageGenerator))); |
||
72 | |||
73 | try { |
||
74 | $args['build_filename'] = $this->packageGenerator->getPackageFilename($project->Name, $sha, $repository, $log); |
||
75 | } catch (Exception $e) { |
||
76 | $log->write($e->getMessage()); |
||
77 | throw $e; |
||
78 | } |
||
79 | |||
80 | if(empty($args['build_filename'])) { |
||
81 | throw new RuntimeException('Failed to generate package.'); |
||
82 | } |
||
83 | } |
||
84 | |||
85 | $command = $this->getCommand('deploy', 'web', $environment, $args, $log); |
||
86 | $command->run(function($type, $buffer) use($log) { |
||
87 | $log->write($buffer); |
||
88 | }); |
||
89 | |||
90 | // Deployment cleanup. We assume it is always safe to run this at the end, regardless of the outcome. |
||
91 | $self = $this; |
||
92 | $cleanupFn = function() use($self, $environment, $args, $log, $sha, $project) { |
||
93 | $command = $self->getCommand('deploy:cleanup', 'web', $environment, $args, $log); |
||
94 | $command->run(function($type, $buffer) use($log) { |
||
95 | $log->write($buffer); |
||
96 | }); |
||
97 | |||
98 | if(!$command->isSuccessful()) { |
||
99 | $self->extend('cleanupFailure', $environment, $sha, $log, $project); |
||
100 | $log->write('Warning: Cleanup failed, but fine to continue. Needs manual cleanup sometime.'); |
||
101 | } |
||
102 | }; |
||
103 | |||
104 | // Once the deployment has run it's necessary to update the maintenance page status |
||
105 | if(!empty($options['leaveMaintenancePage'])) { |
||
106 | $this->enableMaintenance($environment, $log, $project); |
||
107 | } |
||
108 | |||
109 | if(!$command->isSuccessful() || !$this->smokeTest($environment, $log)) { |
||
110 | $cleanupFn(); |
||
111 | $this->extend('deployFailure', $environment, $sha, $log, $project); |
||
112 | throw new RuntimeException($command->getErrorOutput()); |
||
113 | } |
||
114 | |||
115 | // Check if maintenance page should be removed |
||
116 | if(empty($options['leaveMaintenancePage'])) { |
||
117 | $this->disableMaintenance($environment, $log, $project); |
||
118 | } |
||
119 | |||
120 | $cleanupFn(); |
||
121 | |||
122 | $log->write(sprintf('Deploy of "%s" to "%s" finished', $sha, $name)); |
||
123 | |||
124 | $this->extend('deployEnd', $environment, $sha, $log, $project); |
||
125 | } |
||
126 | |||
127 | /** |
||
128 | * Enable a maintenance page for the given environment using the maintenance:enable Capistrano task. |
||
129 | */ |
||
130 | View Code Duplication | public function enableMaintenance(DNEnvironment $environment, DeploynautLogFile $log, DNProject $project) { |
|
142 | |||
143 | /** |
||
144 | * Disable the maintenance page for the given environment using the maintenance:disable Capistrano task. |
||
145 | */ |
||
146 | View Code Duplication | public function disableMaintenance(DNEnvironment $environment, DeploynautLogFile $log, DNProject $project) { |
|
158 | |||
159 | /** |
||
160 | * Check the status using the deploy:check capistrano method |
||
161 | */ |
||
162 | public function ping(DNEnvironment $environment, DeploynautLogFile $log, DNProject $project) { |
||
169 | |||
170 | /** |
||
171 | * @inheritdoc |
||
172 | */ |
||
173 | public function dataTransfer(DNDataTransfer $dataTransfer, DeploynautLogFile $log) { |
||
174 | if($dataTransfer->Direction == 'get') { |
||
175 | $this->dataTransferBackup($dataTransfer, $log); |
||
176 | } else { |
||
177 | $environment = $dataTransfer->Environment(); |
||
178 | $project = $environment->Project(); |
||
179 | $workingDir = TEMP_FOLDER . DIRECTORY_SEPARATOR . 'deploynaut-transfer-' . $dataTransfer->ID; |
||
180 | $archive = $dataTransfer->DataArchive(); |
||
181 | |||
182 | // extract the sspak contents, we'll need these so capistrano can restore that content |
||
183 | try { |
||
184 | $archive->extractArchive($workingDir); |
||
185 | } catch(Exception $e) { |
||
186 | $log->write($e->getMessage()); |
||
187 | throw new RuntimeException($e->getMessage()); |
||
188 | } |
||
189 | |||
190 | // validate the contents match the requested transfer mode |
||
191 | $result = $archive->validateArchiveContents($dataTransfer->Mode); |
||
192 | if(!$result->valid()) { |
||
193 | // do some cleaning, get rid of the extracted archive lying around |
||
194 | $process = new Process(sprintf('rm -rf %s', escapeshellarg($workingDir))); |
||
195 | $process->setTimeout(120); |
||
196 | $process->run(); |
||
197 | |||
198 | // log the reason why we can't restore the snapshot and halt the process |
||
199 | $log->write($result->message()); |
||
200 | throw new RuntimeException($result->message()); |
||
201 | } |
||
202 | |||
203 | // Put up a maintenance page during a restore of db or assets. |
||
204 | $this->enableMaintenance($environment, $log, $project); |
||
205 | $this->dataTransferRestore($workingDir, $dataTransfer, $log); |
||
206 | $this->disableMaintenance($environment, $log, $project); |
||
207 | } |
||
208 | } |
||
209 | |||
210 | /** |
||
211 | * @param string $action Capistrano action to be executed |
||
212 | * @param string $roles Defining a server role is required to target only the required servers. |
||
213 | * @param DNEnvironment $environment |
||
214 | * @param array<string>|null $args Additional arguments for process |
||
215 | * @param DeploynautLogFile $log |
||
216 | * @return \Symfony\Component\Process\Process |
||
217 | */ |
||
218 | public function getCommand($action, $roles, DNEnvironment $environment, $args = null, DeploynautLogFile $log) { |
||
219 | $name = $environment->getFullName(); |
||
220 | $env = $environment->Project()->getProcessEnv(); |
||
221 | |||
222 | if(!$args) { |
||
223 | $args = array(); |
||
224 | } |
||
225 | $args['history_path'] = realpath(DEPLOYNAUT_LOG_PATH . '/'); |
||
226 | $args['environment_id'] = $environment->ID; |
||
227 | |||
228 | // Inject env string directly into the command. |
||
229 | // Capistrano doesn't like the $process->setEnv($env) we'd normally do below. |
||
230 | $envString = ''; |
||
231 | if(!empty($env)) { |
||
232 | $envString .= 'env '; |
||
233 | foreach($env as $key => $value) { |
||
234 | $envString .= "$key=\"$value\" "; |
||
235 | } |
||
236 | } |
||
237 | |||
238 | $data = DNData::inst(); |
||
239 | // Generate a capfile from a template |
||
240 | $capTemplate = file_get_contents(BASE_PATH . '/deploynaut/Capfile.template'); |
||
241 | $cap = str_replace( |
||
242 | array('<config root>', '<ssh key>', '<base path>'), |
||
243 | array($data->getEnvironmentDir(), DEPLOYNAUT_SSH_KEY, BASE_PATH), |
||
244 | $capTemplate |
||
245 | ); |
||
246 | |||
247 | if(defined('DEPLOYNAUT_CAPFILE')) { |
||
248 | $capFile = DEPLOYNAUT_CAPFILE; |
||
249 | } else { |
||
250 | $capFile = ASSETS_PATH . '/Capfile'; |
||
251 | } |
||
252 | file_put_contents($capFile, $cap); |
||
253 | |||
254 | $command = "{$envString}cap -f " . escapeshellarg($capFile) . " -vv $name $action ROLES=$roles"; |
||
255 | foreach($args as $argName => $argVal) { |
||
256 | $command .= ' -s ' . escapeshellarg($argName) . '=' . escapeshellarg($argVal); |
||
257 | } |
||
258 | |||
259 | $log->write(sprintf('Running command: %s', $command)); |
||
260 | |||
261 | $process = new Process($command); |
||
262 | $process->setTimeout(3600); |
||
263 | return $process; |
||
264 | } |
||
265 | |||
266 | /** |
||
267 | * Backs up database and/or assets to a designated folder, |
||
268 | * and packs up the files into a single sspak. |
||
269 | * |
||
270 | * @param DNDataTransfer $dataTransfer |
||
271 | * @param DeploynautLogFile $log |
||
272 | */ |
||
273 | protected function dataTransferBackup(DNDataTransfer $dataTransfer, DeploynautLogFile $log) { |
||
274 | $environment = $dataTransfer->Environment(); |
||
275 | $name = $environment->getFullName(); |
||
276 | |||
277 | // Associate a new archive with the transfer. |
||
278 | // Doesn't retrieve a filepath just yet, need to generate the files first. |
||
279 | $dataArchive = DNDataArchive::create(); |
||
280 | $dataArchive->Mode = $dataTransfer->Mode; |
||
281 | $dataArchive->AuthorID = $dataTransfer->AuthorID; |
||
282 | $dataArchive->OriginalEnvironmentID = $environment->ID; |
||
283 | $dataArchive->EnvironmentID = $environment->ID; |
||
284 | $dataArchive->IsBackup = $dataTransfer->IsBackupDataTransfer(); |
||
285 | |||
286 | // Generate directory structure with strict permissions (contains very sensitive data) |
||
287 | $filepathBase = $dataArchive->generateFilepath($dataTransfer); |
||
288 | mkdir($filepathBase, 0700, true); |
||
289 | |||
290 | $databasePath = $filepathBase . DIRECTORY_SEPARATOR . 'database.sql'; |
||
291 | |||
292 | // Backup database |
||
293 | View Code Duplication | if(in_array($dataTransfer->Mode, array('all', 'db'))) { |
|
294 | $log->write(sprintf('Backup of database from "%s" started', $name)); |
||
295 | $command = $this->getCommand('data:getdb', 'db', $environment, array('data_path' => $databasePath), $log); |
||
296 | $command->run(function($type, $buffer) use($log) { |
||
297 | $log->write($buffer); |
||
298 | }); |
||
299 | if(!$command->isSuccessful()) { |
||
300 | $this->extend('dataTransferFailure', $environment, $log); |
||
301 | throw new RuntimeException($command->getErrorOutput()); |
||
302 | } |
||
303 | $log->write(sprintf('Backup of database from "%s" done', $name)); |
||
304 | } |
||
305 | |||
306 | // Backup assets |
||
307 | View Code Duplication | if(in_array($dataTransfer->Mode, array('all', 'assets'))) { |
|
308 | $log->write(sprintf('Backup of assets from "%s" started', $name)); |
||
309 | $command = $this->getCommand('data:getassets', 'web', $environment, array('data_path' => $filepathBase), $log); |
||
310 | $command->run(function($type, $buffer) use($log) { |
||
311 | $log->write($buffer); |
||
312 | }); |
||
313 | if(!$command->isSuccessful()) { |
||
314 | $this->extend('dataTransferFailure', $environment, $log); |
||
315 | throw new RuntimeException($command->getErrorOutput()); |
||
316 | } |
||
317 | $log->write(sprintf('Backup of assets from "%s" done', $name)); |
||
318 | } |
||
319 | |||
320 | // ensure the database connection is re-initialised, which is needed if the transfer |
||
321 | // above took a really long time because the handle to the db may have become invalid. |
||
322 | global $databaseConfig; |
||
323 | DB::connect($databaseConfig); |
||
324 | |||
325 | $log->write('Creating sspak...'); |
||
326 | |||
327 | $sspakFilename = sprintf('%s.sspak', $dataArchive->generateFilename($dataTransfer)); |
||
328 | $sspakFilepath = $filepathBase . DIRECTORY_SEPARATOR . $sspakFilename; |
||
329 | |||
330 | try { |
||
331 | $dataArchive->attachFile($sspakFilepath, $dataTransfer); |
||
332 | $dataArchive->setArchiveFromFiles($filepathBase); |
||
333 | } catch(Exception $e) { |
||
334 | $log->write($e->getMessage()); |
||
335 | throw new RuntimeException($e->getMessage()); |
||
336 | } |
||
337 | |||
338 | // Remove any assets and db files lying around, they're not longer needed as they're now part |
||
339 | // of the sspak file we just generated. Use --force to avoid errors when files don't exist, |
||
340 | // e.g. when just an assets backup has been requested and no database.sql exists. |
||
341 | $process = new Process(sprintf('rm -rf %s/assets && rm -f %s', escapeshellarg($filepathBase), escapeshellarg($databasePath))); |
||
342 | $process->setTimeout(120); |
||
343 | $process->run(); |
||
344 | if(!$process->isSuccessful()) { |
||
345 | $log->write('Could not delete temporary files'); |
||
346 | throw new RuntimeException($process->getErrorOutput()); |
||
347 | } |
||
348 | |||
349 | $log->write(sprintf('Creating sspak file done: %s', $dataArchive->ArchiveFile()->getAbsoluteURL())); |
||
350 | } |
||
351 | |||
352 | /** |
||
353 | * Utility function for triggering the db rebuild and flush. |
||
354 | * Also cleans up and generates new error pages. |
||
355 | * @param DeploynautLogFile $log |
||
356 | */ |
||
357 | View Code Duplication | public function rebuild(DNEnvironment $environment, $log) { |
|
369 | |||
370 | /** |
||
371 | * Extracts a *.sspak file referenced through the passed in $dataTransfer |
||
372 | * and pushes it to the environment referenced in $dataTransfer. |
||
373 | * |
||
374 | * @param string $workingDir Directory for the unpacked files. |
||
375 | * @param DNDataTransfer $dataTransfer |
||
376 | * @param DeploynautLogFile $log |
||
377 | */ |
||
378 | protected function dataTransferRestore($workingDir, DNDataTransfer $dataTransfer, DeploynautLogFile $log) { |
||
429 | |||
430 | /** |
||
431 | * This is mostly copy-pasted from Anthill/Smoketest. |
||
432 | * |
||
433 | * @param DNEnvironment $environment |
||
434 | * @param DeploynautLogFile $log |
||
435 | * @return bool |
||
436 | */ |
||
437 | protected function smokeTest(DNEnvironment $environment, DeploynautLogFile $log) { |
||
522 | |||
523 | } |
||
524 |
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.