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 VagrantVms 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 VagrantVms, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
66 | class VagrantVms implements SupportedHost |
||
67 | { |
||
68 | /** |
||
69 | * |
||
70 | * @var StoryTeller |
||
71 | */ |
||
72 | protected $st; |
||
73 | |||
74 | /** |
||
75 | * |
||
76 | * @param StoryTeller $st |
||
77 | */ |
||
78 | public function __construct(StoryTeller $st) |
||
79 | { |
||
80 | // remember |
||
81 | $this->st = $st; |
||
82 | } |
||
83 | |||
84 | /** |
||
85 | * Check environmental details |
||
86 | * |
||
87 | * @param stdClass $groupDef |
||
88 | */ |
||
89 | protected function checkGroupDefinition($groupDef) |
||
90 | { |
||
91 | // make sure we like the provided details |
||
92 | if (!isset($groupDef->details)) { |
||
93 | throw Exceptions::newActionFailedException(__METHOD__, "missing groupDef->details"); |
||
94 | } |
||
95 | if (!isset($groupDef->details->machines)) { |
||
96 | throw Exceptions::newActionFailedException(__METHOD__, "missing groupDef->details->machines"); |
||
97 | } |
||
98 | if (empty($groupDef->details->machines)) { |
||
99 | throw Exceptions::newActionFailedException(__METHOD__, "groupDef->details->machines cannot be empty"); |
||
100 | } |
||
101 | |||
102 | // make sure we have a Vagrantfile |
||
103 | $expectedVagrantfile = $this->getVagrantDir($groupDef) . "/Vagrantfile"; |
||
104 | if (!file_exists($expectedVagrantfile)) { |
||
105 | throw Exceptions::newActionFailedException(__METHOD__, "no Vagrantfile; expected it to be here: {$expectedVagrantfile}"); |
||
106 | } |
||
107 | |||
108 | } |
||
109 | |||
110 | /** |
||
111 | * Get the Vagrant directory |
||
112 | * |
||
113 | * @param stdClass $groupDef |
||
114 | * |
||
115 | * @return string |
||
116 | */ |
||
117 | protected function getVagrantDir($groupDef) |
||
118 | { |
||
119 | if (isset($groupDef->baseFolder)) { |
||
120 | return $groupDef->baseFolder; |
||
121 | } |
||
122 | |||
123 | return getcwd(); |
||
124 | } |
||
125 | |||
126 | /** |
||
127 | * |
||
128 | * @param stdClass $groupDef |
||
129 | * @param array $provisioningVars |
||
130 | * @return void |
||
131 | */ |
||
132 | public function createHost($groupDef, $provisioningVars = array()) |
||
133 | { |
||
134 | // what are we doing? |
||
135 | $log = Log::usingLog()->startAction('create new VM'); |
||
136 | |||
137 | // make sure we're happy with this group |
||
138 | $this->checkGroupDefinition($groupDef); |
||
139 | |||
140 | // where is the action? |
||
141 | $baseFolder = $this->getVagrantDir($groupDef); |
||
142 | |||
143 | // make sure we're happy with details about the machine |
||
144 | View Code Duplication | foreach($groupDef->details->machines as $hostId => $machine) { |
|
145 | // TODO: it would be great to autodetect this one day |
||
146 | if (!isset($machine->osName)) { |
||
147 | throw Exceptions::newActionFailedException(__METHOD__, "missing groupDef->details->machines['$hostId']->osName"); |
||
148 | } |
||
149 | if (!isset($machine->roles)) { |
||
150 | throw Exceptions::newActionFailedException(__METHOD__, "missing groupDef->details->machines['$hostId']->roles"); |
||
151 | } |
||
152 | } |
||
153 | |||
154 | // make sure the VM is stopped, if it is running |
||
155 | $log->addStep('stop vagrant VM in '.$baseFolder.' if already running', function() use($baseFolder) { |
||
156 | $command = "vagrant destroy --force"; |
||
157 | $this->runCommandAgainstHostManager($baseFolder, $command); |
||
158 | }); |
||
159 | |||
160 | // remove any existing hosts table entry |
||
161 | foreach ($groupDef->details->machines as $hostId => $machine) { |
||
162 | // remove any roles |
||
163 | usingRolesTable()->removeHostFromAllRoles($hostId); |
||
164 | |||
165 | // now drop the host |
||
166 | usingHostsTable()->removeHost($hostId); |
||
167 | } |
||
168 | $this->st->saveRuntimeConfig(); |
||
169 | |||
170 | // work out which network interface to use |
||
171 | $this->setVagrantBridgedInterface(); |
||
172 | |||
173 | // let's start the VM |
||
174 | $command = "vagrant up"; |
||
175 | $result = $log->addStep('create vagrant VM(s) in '.$baseFolder, function() use($baseFolder, $command) { |
||
176 | return $this->runCommandAgainstHostManager($baseFolder, $command); |
||
177 | }); |
||
178 | |||
179 | // did it work? |
||
180 | if ($result->returnCode != 0) { |
||
181 | $log->endAction("VM failed to start or provision :("); |
||
182 | throw Exceptions::newActionFailedException(__METHOD__); |
||
183 | } |
||
184 | |||
185 | // yes it did!! |
||
186 | |||
187 | // store the details |
||
188 | foreach($groupDef->details->machines as $hostId => $machine) |
||
189 | { |
||
190 | // we want all the details from the config file |
||
191 | $vmDetails = clone $machine; |
||
192 | |||
193 | // this allows the story to perform actions against a single |
||
194 | // machine if required |
||
195 | $vmDetails->type = 'VagrantVm'; |
||
196 | |||
197 | // new in v2.x: |
||
198 | // |
||
199 | // when provisioning a folder of vagrant vms, we now use |
||
200 | // the same name for the VM that vagrant uses |
||
201 | $vmDetails->hostId = $hostId; |
||
202 | |||
203 | // remember where the machine lives |
||
204 | $vmDetails->dir = $baseFolder; |
||
205 | |||
206 | // we need to remember how to SSH into the box |
||
207 | $vmDetails->sshUsername = 'vagrant'; |
||
208 | $vmDetails->sshKeyFile = $this->determinePrivateKey($vmDetails); |
||
209 | $vmDetails->sshOptions = [ |
||
210 | "-i '" . $vmDetails->sshKeyFile . "'", |
||
211 | "-o StrictHostKeyChecking=no", |
||
212 | "-o UserKnownHostsFile=/dev/null", |
||
213 | "-o LogLevel=quiet", |
||
214 | ]; |
||
215 | $vmDetails->scpOptions = [ |
||
216 | "-i '" . $vmDetails->sshKeyFile . "'", |
||
217 | "-o StrictHostKeyChecking=no", |
||
218 | ]; |
||
219 | |||
220 | // remember how to connect to the machine via the network |
||
221 | $vmDetails->ipAddress = $this->determineIpAddress($vmDetails); |
||
222 | $vmDetails->hostname = $this->determineHostname($vmDetails); |
||
223 | |||
224 | // mark the box as provisioned |
||
225 | // we will use this in stopBox() to avoid destroying VMs that failed |
||
226 | // to provision |
||
227 | $vmDetails->provisioned = true; |
||
228 | |||
229 | // remember this vm, now that it is running |
||
230 | usingHostsTable()->addHost($vmDetails->hostId, $vmDetails); |
||
231 | foreach ($vmDetails->roles as $role) { |
||
232 | usingRolesTable()->addHostToRole($vmDetails, $role); |
||
233 | } |
||
234 | |||
235 | // now, let's get this VM into our SSH known_hosts file, to avoid |
||
236 | // prompting people when we try and provision this VM |
||
237 | $log->addStep("get the VM into the SSH known_hosts file", function() use($vmDetails) { |
||
238 | Shell::onHost($vmDetails->hostId)->runCommand("ls"); |
||
239 | }); |
||
240 | } |
||
241 | |||
242 | // all done |
||
243 | $log->endAction(); |
||
244 | } |
||
245 | |||
246 | /** |
||
247 | * |
||
248 | * @param stdClass $envDetails |
||
249 | * @return void |
||
250 | */ |
||
251 | public function startHost($envDetails) |
||
252 | { |
||
253 | // if you really want to do this from your story, use |
||
254 | // $st->usingVagrantVm()->startHost() |
||
255 | throw Exceptions::newActionFailedException(__METHOD__, "unsupported operation"); |
||
256 | } |
||
257 | |||
258 | /** |
||
259 | * |
||
260 | * @param stdClass $envDetails |
||
261 | * @return void |
||
262 | */ |
||
263 | public function stopHost($envDetails) |
||
264 | { |
||
265 | // if you really want to do this from your story, use |
||
266 | // $st->usingVagrantVm()->stopHost() |
||
267 | throw Exceptions::newActionFailedException(__METHOD__, "unsupported operation"); |
||
268 | } |
||
269 | |||
270 | /** |
||
271 | * |
||
272 | * @param stdClass $envDetails |
||
273 | * @return void |
||
274 | */ |
||
275 | public function restartHost($envDetails) |
||
276 | { |
||
277 | // if you really want to do this from your story, use |
||
278 | // $st->usingVagrantVm()->restartHost() |
||
279 | throw Exceptions::newActionFailedException(__METHOD__, "unsupported operation"); |
||
280 | } |
||
281 | |||
282 | /** |
||
283 | * |
||
284 | * @param stdClass $envDetails |
||
285 | * @return void |
||
286 | */ |
||
287 | public function powerOffHost($envDetails) |
||
288 | { |
||
289 | // if you really want to do this from your story, use |
||
290 | // $st->usingVagrantVm()->powerOffHost() |
||
291 | throw Exceptions::newActionFailedException(__METHOD__, "unsupported operation"); |
||
292 | } |
||
293 | |||
294 | /** |
||
295 | * |
||
296 | * @param stdClass $groupDef |
||
297 | * @return void |
||
298 | */ |
||
299 | public function destroyHost($groupDef) |
||
300 | { |
||
301 | // what are we doing? |
||
302 | $log = Log::usingLog()->startAction("destroy VM(s)"); |
||
303 | |||
304 | // stop all the VMs, one by one |
||
305 | foreach ($groupDef->details->machines as $hostId => $machine) { |
||
306 | // get the machine details |
||
307 | $vmDetails = fromHostsTable()->getDetailsForHost($hostId); |
||
308 | if ($vmDetails) { |
||
309 | // is the VM actually running? |
||
310 | if (fromHost($hostId)->getHostIsRunning()) { |
||
311 | // delete the VM from disk |
||
312 | // |
||
313 | // this will also deregister the host from the |
||
314 | // HostsTable and RolesTable |
||
315 | usingVagrant()->destroyVm($hostId); |
||
316 | } |
||
317 | } |
||
318 | } |
||
319 | |||
320 | // all done |
||
321 | $log->endAction(); |
||
322 | } |
||
323 | |||
324 | /** |
||
325 | * |
||
326 | * @param string $baseFolder |
||
327 | * @param string $command |
||
328 | * @return CommandResult |
||
329 | */ |
||
330 | View Code Duplication | public function runCommandAgainstHostManager($baseFolder, $command) |
|
331 | { |
||
332 | // what are we doing? |
||
333 | $log = Log::usingLog()->startAction("run vagrant command '{$command}'"); |
||
334 | |||
335 | // build the command |
||
336 | $fullCommand = "cd '{$baseFolder}' && $command 2>&1"; |
||
337 | |||
338 | // run the command |
||
339 | $commandRunner = new CommandRunner(); |
||
340 | $result = $commandRunner->runSilently($fullCommand); |
||
341 | |||
342 | // all done |
||
343 | $log->endAction("return code was '{$result->returnCode}'"); |
||
344 | return $result; |
||
345 | } |
||
346 | |||
347 | /** |
||
348 | * @param string $baseFolder |
||
349 | * @param string $command |
||
350 | * @return CommandResult |
||
351 | */ |
||
352 | View Code Duplication | public function runCommandViaHostManager($baseFolder, $command) |
|
353 | { |
||
354 | // what are we doing? |
||
355 | $log = Log::usingLog()->startAction("run vagrant command '{$command}'"); |
||
356 | |||
357 | // build the command |
||
358 | $fullCommand = "cd '{$baseFolder}' && vagrant ssh -c \"$command\""; |
||
359 | |||
360 | // run the command |
||
361 | $commandRunner = new CommandRunner(); |
||
362 | $result = $commandRunner->runSilently($fullCommand); |
||
363 | |||
364 | // all done |
||
365 | $log->endAction("return code was '{$result->returnCode}'"); |
||
366 | return $result; |
||
367 | } |
||
368 | |||
369 | /** |
||
370 | * |
||
371 | * @param stdClass $envDetails |
||
372 | * @return boolean |
||
373 | */ |
||
374 | public function isRunning($envDetails) |
||
378 | |||
379 | /** |
||
380 | * |
||
381 | * @param stdClass $vmDetails |
||
382 | * @return string |
||
383 | */ |
||
384 | View Code Duplication | public function determineIpAddress($vmDetails) |
|
385 | { |
||
386 | // what are we doing? |
||
387 | $log = Log::usingLog()->startAction("determine IP address of Vagrant VM '{$vmDetails->hostId}'"); |
||
388 | |||
389 | // create an adapter to talk to the host operating system |
||
399 | |||
400 | /** |
||
401 | * |
||
402 | * @param stdClass $vmDetails |
||
403 | * @return string |
||
404 | */ |
||
405 | View Code Duplication | public function determineHostname($vmDetails) |
|
420 | |||
421 | /** |
||
422 | * Set the VAGRANT_BRIDGE_ADAPTER and VIRTUALBOX_BRIDGE_ADAPTER |
||
423 | * environmental variables. |
||
424 | */ |
||
425 | public function setVagrantBridgedInterface() { |
||
430 | |||
431 | /** |
||
432 | * @return string |
||
433 | */ |
||
434 | public function determineBridgedInterface() |
||
493 | |||
494 | public function determinePrivateKey($vmDetails) |
||
523 | } |
||
524 |