| 68 | |
| 69 | |
| 70 | class SystemVM(object): |
| 71 | def __init__(self, |
| 72 | host='default', |
| 73 | vagrantDir=None, |
| 74 | controlVagrant=True): |
| 75 | global _defaultVagrantDir |
| 76 | self.host = host |
| 77 | self._controlVagrant = controlVagrant |
| 78 | if vagrantDir is None: |
| 79 | vagrantDir = _defaultVagrantDir |
| 80 | self._vagrant = Vagrant(root=vagrantDir) |
| 81 | self._startedVagrant = False |
| 82 | self._sshClient = None |
| 83 | self._sshConfigStr = None |
| 84 | self._sshConfig = None |
| 85 | self._sshHostConfig = None |
| 86 | |
| 87 | def maybeUp(self): |
| 88 | if not self._controlVagrant: |
| 89 | return |
| 90 | state = self._vagrant.status(vm_name=self.host)[0].state |
| 91 | if state == Vagrant.NOT_CREATED: |
| 92 | self._vagrant.up(vm_name=self.host) |
| 93 | self._startedVagrant = True |
| 94 | elif state in [Vagrant.POWEROFF, Vagrant.SAVED, Vagrant.ABORTED]: |
| 95 | raise Exception( |
| 96 | "SystemVM testing does not support resume(), do not use vagrant suspend/halt") |
| 97 | elif state == Vagrant.RUNNING: |
| 98 | self._startedVagrant = False |
| 99 | else: |
| 100 | raise Exception("Unrecognized vagrant state %s" % state) |
| 101 | |
| 102 | def maybeDestroy(self): |
| 103 | if not self._controlVagrant or not self._startedVagrant: |
| 104 | return |
| 105 | self._vagrant.destroy(vm_name=self.host) |
| 106 | if self._sshClient is not None: |
| 107 | self._sshClient.close() |
| 108 | |
| 109 | def loadSshConfig(self): |
| 110 | if self._sshConfig is None: |
| 111 | self._sshConfigStr = self._vagrant.ssh_config(vm_name=self.host) |
| 112 | configObj = StringIO(self._sshConfigStr) |
| 113 | self._sshConfig = SSHConfig() |
| 114 | # noinspection PyTypeChecker |
| 115 | self._sshConfig.parse(configObj) |
| 116 | self._sshHostConfig = self._sshConfig.lookup(self.host) |
| 117 | |
| 118 | @property |
| 119 | def sshConfig(self): |
| 120 | if self._sshConfig is None: |
| 121 | self.loadSshConfig() |
| 122 | return self._sshConfig |
| 123 | |
| 124 | @property |
| 125 | def sshConfigStr(self): |
| 126 | if self._sshConfigStr is None: |
| 127 | self.loadSshConfig() |