summaryrefslogtreecommitdiffstats
path: root/tools/laas-fog/source/api/libvirt_api.py
blob: 4e19736f8cc2196e3f9895ce558ea31b8abedfd4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
"""
#############################################################################
#Copyright 2017 Parker Berberian and others                                 #
#                                                                           #
#Licensed under the Apache License, Version 2.0 (the "License");            #
#you may not use this file except in compliance with the License.           #
#You may obtain a copy of the License at                                    #
#                                                                           #
#    http://www.apache.org/licenses/LICENSE-2.0                             #
#                                                                           #
#Unless required by applicable law or agreed to in writing, software        #
#distributed under the License is distributed on an "AS IS" BASIS,          #
#WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   #
#See the License for the specific language governing permissions and        #
#limitations under the License.                                             #
#############################################################################
"""

import libvirt
import time
import xml.dom
import xml.dom.minidom
from domain import Domain
from network import Network
from utilities import Utilities


class Libvirt:
    """
    This class talks to the Libvirt api.
    Given a config file, this class should create all networks and
    domains.

    TODO: convert prints to logging and remove uneeded pass statements
    """

    def __init__(self, hostAddr, net_conf=None, dom_conf=None):
        """
        init function
        hostAddr is the ip address of the host
        net_conf and dom_conf are the paths
        to the config files
        """
        self.host = hostAddr
        self.URI = "qemu+ssh://root@"+str(hostAddr)+"/system"
        self.hypervisor = None
        self.domains = []
        self.networks = []
        self.net_conf = net_conf
        self.dom_conf = dom_conf

    def setLogger(self, log):
        """
        Saves the logger in self.log
        """
        self.log = log

    def bootMaster(self):
        """
        starts the previously defined master node
        """
        for dom in self.domains:
            if 'master' in dom.name():
                try:
                    dom.create()
                except Exception:
                    pass

    def bootSlaves(self):
        """
        boots every defined vm with 'slave' in its name
        """
        for dom in self.domains:
            if 'slave' in dom.name():
                try:
                    dom.create()
                    self.log.info("Booting %s", dom.name())
                except Exception:
                    self.log.exception("%s", "failed to boot domain")
                time.sleep(5)

    def getMacs(self, domName):
        """
        returns a dictionary with a network name
        mapped to the mac address of the domain on that net
        """
        try:
            dom = self.hypervisor.lookupByName(domName)
            xmlDesc = dom.XMLDesc(0)
            parsedXML = xml.dom.minidom.parseString(xmlDesc)
            interfacesXML = parsedXML.getElementsByTagName('interface')
            netDict = {}
            for iface in interfacesXML:
                src = iface.getElementsByTagName('source')[0]
                mac = iface.getElementsByTagName('mac')[0]
                netDict[src] = mac
            return netDict
        except Exception:
            self.log.exception("%s", "Domain not found")

    def defineVM(self, xmlConfig):
        """
        Generic method to define a persistent vm with the
        given config.
        Assumes that self.hypervisor is already connected.
        """
        if self.checkForVM(xmlConfig):
            vm = self.hypervisor.defineXML(xmlConfig)
            if vm is None:
                name = self.getName(xmlConfig)
                self.log.error("Failed to define vm %s. exiting", name)
                exit(1)
            else:
                self.log.info("Successfully created vm %s", vm.name())
                pass
            self.domains.append(vm)

    def checkForVM(self, xmlConfig):
        """
        Checks if another vm with the same name exists
        on the remote host already. If it does, it will
        delete that vm
        """
        allGood = False
        vms = self.hypervisor.listAllDomains(0)
        names = []
        for dom in vms:
            names.append(dom.name())
        vmName = Utilities.getName(xmlConfig)
        if vmName in names:
            self.log.warning("domain %s already exists", vmName)
            self.log.warning("%s", "Atempting to delete it")
            self.deleteVM(vmName)
            allGood = True
        else:
            allGood = True
        return allGood

    def deleteVM(self, name):
        """
        removes the given vm from the remote host
        """
        try:
            vm = self.hypervisor.lookupByName(name)
        except:
            return
        active = vm.isActive()
        persistent = vm.isPersistent()
        if active:
            try:
                vm.destroy()
            except:
                self.log.exception("%s", "Failed to destroy vm")

        if persistent:
            try:
                vm.undefine()
            except:
                self.log.exception("%s", "Failed to undefine domain")
                pass

    def openConnection(self):
        """
        opens a connection to the remote host
        and stores it in self.hypervisor
        """
        self.log.info("Attempting to connect to libvirt at %s", self.host)
        try:
            hostHypervisor = libvirt.open(self.URI)
        except:
            self.log.warning(
                    "Failed to connect to %s. Trying again", self.host
                    )
            time.sleep(5)
            try:
                hostHypervisor = libvirt.open(self.URI)
            except:
                self.log.exception("Cannot connect to %s. Exiting", self.host)
                exit(1)

        if hostHypervisor is None:
            self.log.error("Failed to connect to %s. Exiting", self.host)
            exit(1)
        self.hypervisor = hostHypervisor

    def restartVM(self, vm):
        """
        causes the given vm to reboot
        """
        dom = self.hypervisor.lookupByName(vm)
        dom.destroy()
        time.sleep(15)
        dom.create()

    def close(self):
        """
        Closes connection to remote hypervisor
        """
        self.log.info("Closing connection to the hypervisor %s", self.host)
        self.hypervisor.close()

    def defineAllDomains(self, path):
        """
        Defines a domain from all the xml files in a directory
        """
        files = Utilities.getXMLFiles(path)
        definitions = []
        for xml_desc in files:
            definitions.append(xml_desc.read())

        for definition in definitions:
            self.defineVM(definition)

    def createAllNetworks(self, path):
        """
        Creates a network from all xml files in a directory
        """
        files = Utilities.getXMLFiles(path)
        definitions = []
        for xml_desc in files:
            definitions.append(Utilities.fileToString(xml_desc))

        for definition in definitions:
            self.createNet(definition)

    def createNet(self, config):
        """
        creates the network on the remote host
        config is the xml in string representation
        that defines the network
        """
        if self.checkNet(config):
            network = self.hypervisor.networkDefineXML(config)

            if network is None:
                name = self.getName(config)
                self.log.warning("Failed to define network %s", name)
            network.create()
            if network.isActive() == 1:
                net = network.name()
                self.log.info("Successfully defined network %s", net)
            self.networks.append(network)

    def checkNet(self, config):
        """
        Checks if another net with the same name exists, and
        deletes that network if one is found
        """
        allGood = False
        netName = Utilities.getName(config)
        if netName not in self.hypervisor.listNetworks():
            return True
        else:  # net name is already used
            self.log.warning(
                    "Network %s already exists. Trying to delete it", netName
                    )
            network = self.hypervisor.networkLookupByName(netName)
            self.deleteNet(network)
            allGood = True
        return allGood

    def deleteNet(self, net):
        """
        removes the given network from the host
        """
        active = net.isActive()
        persistent = net.isPersistent()
        if active:
            try:
                net.destroy()
            except:
                self.log.warning("%s", "Failed to destroy network")

        if persistent:
            try:
                net.undefine()
            except:
                self.log.warning("%s", "Failed to undefine network")

    def go(self):
        """
        This method does all the work of this class,
        Parsing the net and vm config files and creating
        all the requested nets/domains
        returns a list of all networks and a list of all domains
        as Network and Domain objects
        """
        nets = self.makeNetworks(self.net_conf)
        doms = self.makeDomains(self.dom_conf)
        return doms, nets

    def makeNetworks(self, conf):
        """
        Given a path to a  config file, this method
        parses the config and creates all requested networks,
        and returns them in a list of Network objects
        """
        networks = []
        definitions = Network.parseConfigFile(conf)
        for definition in definitions:
            network = Network(definition)
            networks.append(network)
            self.createNet(network.toXML())
        return networks

    def makeDomains(self, conf):
        """
        Given a path to a config file, this method
        parses the config and creates all requested vm's,
        and returns them in a list of Domain objects
        """
        domains = []
        definitions = Domain.parseConfigFile(conf)
        for definition in definitions:
            domain = Domain(definition)
            domains.append(domain)
            self.defineVM(domain.toXML())
        return domains

    @staticmethod
    def getName(xmlString):
        """
        given xml with a name tag, this returns the value of name
        eg:
            <name>Parker</name>
        returns 'Parker'
        """
        xmlDoc = xml.dom.minidom.parseString(xmlString)
        nameNode = xmlDoc.documentElement.getElementsByTagName('name')
        name = str(nameNode[0].firstChild.nodeValue)
        return name