summaryrefslogtreecommitdiff
path: root/cloudinit/DataSourceOVF.py
blob: b4990b04ae34b339cff9f65a95470a787ecb3c02 (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
# vi: ts=4 expandtab
#
#    Copyright (C) 2011 Canonical Ltd.
#
#    Author: Scott Moser <scott.moser@canonical.com>
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License version 3, as
#    published by the Free Software Foundation.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.

import DataSource

import cloudinit
import cloudinit.util as util
import sys
import os.path
import os
import errno
from xml.dom import minidom
from xml.dom import Node

class DataSourceOVF(DataSource.DataSource):
    seed = None
    seeddir = cloudinit.seeddir + '/ovf'

    def __init__(self):
        pass

    def __str__(self):
        mstr="DataSourceOVF"
        mstr = mstr + " [seed=%s]" % self.seed
        return(mstr)

    def get_data(self):
        (seedfile, contents) = get_ovf_env(seeddir)
        if seedfile:
            # found a seed dir
            self.seed = "%s/%s" % (dirname,seedfile)
            ret = read_ovf_environment(contents)
            # self.user_data=ret['user-data']
            # self.meta_data=ret['meta-data']
            return(True)

        for tranfunc in [ transport_iso9660, transport_vmware_guestd ]:
            (contents, dev, fname) = tranfunc()
            if contents: break

        if not dev:
            return False

        ret = read_ovf_environment(contents)
        # self.user_data=ret['user-data']
        # self.meta_data=ret['meta-data']
        return(True)


# this will return a dict with some content
#  meta-data, user-data
def read_ovf_environment(contents):
    # this should basically shove into python objects
    # the values we read from ovf environment
    self.metadata = md;
    self.userdata_raw = ud
        

# returns tuple of filename (in 'dirname', and the contents of the file)
# on "not found", returns 'None' for filename and False for contents
def get_ovf_env(dirname):
    env_names = ("ovf-env.xml", "ovf_env.xml", "OVF_ENV.XML", "OVF-ENV.XML" )
    for fname in env_names:
        if os.path.isfile("%s/%s" % (dirname,fname)):
            fp = open("%s/%s" % (dirname,fname))
            contents = fp.read()
            fp.close()
            return(fname,contents)
    return(None,False)

# transport functions take no input and return
# a 3 tuple of content, path, filename
def transport_iso9660(require_iso=False):

    # default_regex matches values in 
    # /lib/udev/rules.d/60-cdrom_id.rules
    # KERNEL!="sr[0-9]*|hd[a-z]|xvd*", GOTO="cdrom_end"
    envname = "CLOUD_INIT_CDROM_DEV_REGEX"
    default_regex = "^(sr[0-9]+|hd[a-z]|xvd.*)"

    devname_regex = os.environ.get(envname,default_regex)
    cdmatch = re.compile(devname_regex)

    # go through mounts to see if it was already mounted
    fp = open("/proc/mounts")
    mounts = fp.readlines()
    fp.close()

    mounted = { }
    for mpline in mounts:
        (dev,mp,fstype,opts,freq,passno) = mpline.split()
        mounted[dev]=(dev,fstype,mp,False)
        mp = mp.replace("\\040"," ")
        if fstype != "iso9660" and require_iso: continue

        if cdmatch.match(dev[5:]) == None: # take off '/dev/'
            continue
        
        (fname,contents) = get_ovf_env(mp)
        if contents is not False:
            return(contents,dev,fname)

    tmpd = None
    dvnull = None

    devs = os.listdir("/dev/")
    devs.sort()

    for dev in devs:
        fullp = "/dev/%s" % dev

        if fullp in mounted or not cdmatch.match(dev) or os.path.isdir(fullp):
            continue

        if tmpd is None:
            tmpd = tempfile.mkdtemp()
        if dvnull is None:
            try:
                dvnull = open("/dev/null")
            except:
                pass

        cmd = [ "mount", "-o", "ro", fullp, tmpd ]
        if require_iso: cmd.extend(('-t','iso9660'))

        rc = subprocess.call(cmd, stderr=dvnull, stdout=dvnull, stdin=dvnull)
        if rc:
            continue

        (fname,contents) = get_ovf_env(tmpd)

        subprocess.call(["umount", tmpd])

        if contents is not False:
            os.rmdir(tmpd)
            return(contents,fullp,fname)

    if tmpd:
        os.rmdir(tmpd)

    if dvnull:
        dvnull.close()

    return(False, None, None)

def transport_vmware_guestd():
    # http://blogs.vmware.com/vapp/2009/07/selfconfiguration-and-the-ovf-environment.html
    # sub
    # try:
    #     cmd = ['vmware-guestd', '--cmd', 'info-get guestinfo.ovfEnv']
    #     (out,err) = subp(cmd)
    #     return(out, 'guestinfo.ovfEnv', 'vmware-guestd')
    # except:
    #     # would need to error check here and see why this failed
    #     # to know if log/error should be raised
    #     return(False, None, None)
    return(False, None, None)


def findChild(node,filter_func):
    ret = []
    if not node.hasChildNodes(): return ret
    for child in node.childNodes:
        if filter_func(child): ret.append(child)
    return(ret)

def getProperties(environString):
    dom = minidom.parseString(environString)
    if dom.documentElement.localName != "Environment":
        raise Exception("No Environment Node")

    if not dom.documentElement.hasChildNodes():
        raise Exception("No Child Nodes")

    envNsURI = "http://schemas.dmtf.org/ovf/environment/1"

    # could also check here that elem.namespaceURI == 
    #   "http://schemas.dmtf.org/ovf/environment/1"
    propSections = findChild(dom.documentElement,
        lambda n: n.localName == "PropertySection")

    if len(propSections) == 0:
        raise Exception("No 'PropertySection's")

    props = { }
    propElems = findChild(propSections[0], lambda n: n.localName == "Property")

    for elem in propElems:
        key = elem.attributes.getNamedItemNS(envNsURI,"key").value
        val = elem.attributes.getNamedItemNS(envNsURI,"value").value
        props[key] = val

    return(props)

if __name__ == "__main__":
    import sys
    envStr = open(sys.argv[1]).read()
    props = getProperties(envStr)
    import pprint
    pprint.pprint(props)
    
    read_ovf_environment