summaryrefslogtreecommitdiff
path: root/debian/patches/lp-1506187-azure_use_unique_vm_id.patch
blob: 327a9fbe25ab6e6b3a55ed4abdc8e7a369eba16f (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
Author: Daniel Watkins <daniel.watkins@canonical.com>
Origin: upstream
Bug: https://launchpad.net/bugs/1506187
Description: Handle new Azure instance IDs
--- a/cloudinit/DataSourceAzure.py
+++ b/cloudinit/DataSourceAzure.py
@@ -41,7 +41,6 @@
 AGENT_START = ['service', 'walinuxagent', 'start']
 BOUNCE_COMMAND = ['sh', '-xc',
     "i=$interface; x=0; ifdown $i || x=$?; ifup $i || x=$?; exit $x"]
-DATA_DIR_CLEAN_LIST = ['SharedConfig.xml']
 
 BUILTIN_DS_CONFIG = {
     'agent_command': AGENT_START,
@@ -139,21 +138,6 @@
         mycfg = self.ds_cfg
         ddir = mycfg['data_dir']
 
-        if found != ddir:
-            cached_ovfenv = util.load_file(
-                os.path.join(ddir, 'ovf-env.xml'), quiet=True)
-            if cached_ovfenv != files['ovf-env.xml']:
-                # source was not walinux-agent's datadir, so we have to clean
-                # up so 'wait_for_files' doesn't return early due to stale data
-                cleaned = []
-                for f in [os.path.join(ddir, f) for f in DATA_DIR_CLEAN_LIST]:
-                    if os.path.exists(f):
-                        futil.del_file(f)
-                        cleaned.append(f)
-                if cleaned:
-                    LOG.info("removed stale file(s) in '%s': %s",
-                             ddir, str(cleaned))
-
         # walinux agent writes files world readable, but expects
         # the directory to be protected.
         write_files(ddir, files, dirmode=0700)
@@ -185,9 +169,6 @@
             LOG.warn("agent command '%s' failed.", mycfg['agent_command'])
             util.logexc(LOG)
 
-        shcfgxml = os.path.join(mycfg['data_dir'], "SharedConfig.xml")
-        wait_for = [shcfgxml]
-
         fp_files = []
         key_value = None
         for pk in self.cfg.get('_pubkeys', []):
@@ -200,24 +181,17 @@
                 LOG.debug("ssh authentication: using fingerprint from fabric")
 
         start = time.time()
-        missing = wait_for_files(wait_for + fp_files)
+        missing = wait_for_files(fp_files)
         if len(missing):
             LOG.warn("Did not find files, but going on: %s", missing)
         else:
-            LOG.debug("waited %.3f seconds for %d files to appear",
-                      time.time() - start, len(wait_for))
-
-        if shcfgxml in missing:
-            LOG.warn("SharedConfig.xml missing, using static instance-id")
-        else:
-            try:
-                self.metadata['instance-id'] = iid_from_shared_config(shcfgxml)
-            except ValueError as e:
-                LOG.warn("failed to get instance id in %s: %s" % (shcfgxml, e))
+            LOG.debug("waited %.3f seconds for files to appear",
+                      time.time() - start)
 
         pubkeys = key_value or pubkeys_from_crt_files(fp_files)
 
         self.metadata['public-keys'] = pubkeys
+        self.metadata['instance-id'] = get_instance_id()
 
         found_ephemeral = find_fabric_formatted_ephemeral_disk()
         if found_ephemeral:
@@ -239,6 +213,14 @@
 def count_files(mp):
     return len(fnmatch.filter(os.listdir(mp), '*[!cdrom]*'))
 
+
+def get_instance_id():
+    """
+    Read the instance ID from dmi data
+    """
+    return util.read_dmi_data('system-uuid')
+
+
 def find_fabric_formatted_ephemeral_part():
     """
     Locate the first fabric formatted ephemeral device.
@@ -683,25 +665,6 @@
     return (md, ud, cfg, {'ovf-env.xml': contents})
 
 
-def iid_from_shared_config(path):
-    with open(path, "rb") as fp:
-        content = fp.read()
-    return iid_from_shared_config_content(content)
-
-
-def iid_from_shared_config_content(content):
-    """
-    find INSTANCE_ID in:
-    <?xml version="1.0" encoding="utf-8"?>
-    <SharedConfig version="1.0.0.0" goalStateIncarnation="1">
-      <Deployment name="INSTANCE_ID" guid="{...}" incarnation="0">
-        <Service name="..." guid="{00000000-0000-0000-0000-000000000000}" />
-    """
-    dom = minidom.parseString(content)
-    depnode = single_node_at_path(dom, ["SharedConfig", "Deployment"])
-    return depnode.attributes.get('name').value
-
-
 class BrokenAzureDataSource(Exception):
     pass
 
--- a/cloudinit/util.py
+++ b/cloudinit/util.py
@@ -46,6 +46,31 @@
 except ImportError:
     HAVE_LIBSELINUX = False
 
+# Path for DMI Data
+DMI_SYS_PATH = "/sys/class/dmi/id"
+
+# dmidecode and /sys/class/dmi/id/* use different names for the same value,
+# this allows us to refer to them by one canonical name
+DMIDECODE_TO_DMI_SYS_MAPPING = {
+    'baseboard-asset-tag': 'board_asset_tag',
+    'baseboard-manufacturer': 'board_vendor',
+    'baseboard-product-name': 'board_name',
+    'baseboard-serial-number': 'board_serial',
+    'baseboard-version': 'board_version',
+    'bios-release-date': 'bios_date',
+    'bios-vendor': 'bios_vendor',
+    'bios-version': 'bios_version',
+    'chassis-asset-tag': 'chassis_asset_tag',
+    'chassis-manufacturer': 'chassis_vendor',
+    'chassis-serial-number': 'chassis_serial',
+    'chassis-version': 'chassis_version',
+    'system-manufacturer': 'sys_vendor',
+    'system-product-name': 'product_name',
+    'system-serial-number': 'product_serial',
+    'system-uuid': 'product_uuid',
+    'system-version': 'product_version',
+}
+
 _DNS_REDIRECT_IP = None
 LOG = logging.getLogger("cloudinit")
 
@@ -982,3 +1007,90 @@
 
     return os.path.isfile("/sys/class/block/%s/partition" % device)
 
+
+def _read_dmi_syspath(key):
+    """
+    Reads dmi data with from /sys/class/dmi/id
+    """
+    if key not in DMIDECODE_TO_DMI_SYS_MAPPING:
+        return None
+    mapped_key = DMIDECODE_TO_DMI_SYS_MAPPING[key]
+    dmi_key_path = "{0}/{1}".format(DMI_SYS_PATH, mapped_key)
+    LOG.debug("querying dmi data %s", dmi_key_path)
+    try:
+        if not os.path.exists(dmi_key_path):
+            LOG.debug("did not find %s", dmi_key_path)
+            return None
+
+        key_data = load_file(dmi_key_path)
+        if not key_data:
+            LOG.debug("%s did not return any data", dmi_key_path)
+            return None
+
+        LOG.debug("dmi data %s returned %s", dmi_key_path, key_data)
+        return key_data.strip()
+
+    except Exception:
+        LOG.warn("failed read of %s", dmi_key_path)
+        logexc(LOG)
+        return None
+
+
+def _call_dmidecode(key, dmidecode_path):
+    """
+    Calls out to dmidecode to get the data out. This is mostly for supporting
+    OS's without /sys/class/dmi/id support.
+    """
+    try:
+        cmd = [dmidecode_path, "--string", key]
+        (result, _err) = subp(cmd)
+        LOG.debug("dmidecode returned '%s' for '%s'", result, key)
+        return result
+    except (IOError, OSError) as _err:
+        LOG.debug('failed dmidecode cmd: %s\n%s', cmd, _err.message)
+        return None
+
+
+def which(program):
+    # Return path of program for execution if found in path
+    def is_exe(fpath):
+        return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
+
+    _fpath, _ = os.path.split(program)
+    if _fpath:
+        if is_exe(program):
+            return program
+    else:
+        for path in os.environ.get("PATH", "").split(os.pathsep):
+            path = path.strip('"')
+            exe_file = os.path.join(path, program)
+            if is_exe(exe_file):
+                return exe_file
+
+    return None
+
+
+def read_dmi_data(key):
+    """
+    Wrapper for reading DMI data.
+
+    This will do the following (returning the first that produces a
+    result):
+        1) Use a mapping to translate `key` from dmidecode naming to
+           sysfs naming and look in /sys/class/dmi/... for a value.
+        2) Use `key` as a sysfs key directly and look in /sys/class/dmi/...
+        3) Fall-back to passing `key` to `dmidecode --string`.
+
+    If all of the above fail to find a value, None will be returned.
+    """
+    syspath_value = _read_dmi_syspath(key)
+    if syspath_value is not None:
+        return syspath_value
+
+    dmidecode_path = which('dmidecode')
+    if dmidecode_path:
+        return _call_dmidecode(key, dmidecode_path)
+
+    LOG.warn("did not find either path %s or dmidecode command",
+             DMI_SYS_PATH)
+    return None