Merge ~chad.smith/cloud-init:ubuntu/devel into cloud-init:ubuntu/devel

Proposed by Chad Smith on 2017-11-20
Status: Merged
Merged at revision: 302c9e8fbc509abd104da40a23e597ef31c0f1e7
Proposed branch: ~chad.smith/cloud-init:ubuntu/devel
Merge into: cloud-init:ubuntu/devel
Diff against target: 2196 lines (+783/-454)
50 files modified
cloudinit/cloud.py (+2/-2)
cloudinit/config/cc_ntp.py (+7/-2)
cloudinit/config/cc_rh_subscription.py (+28/-18)
cloudinit/config/cc_update_etc_hosts.py (+2/-2)
cloudinit/net/dhcp.py (+9/-3)
cloudinit/net/tests/test_dhcp.py (+8/-1)
cloudinit/sources/DataSourceAzure.py (+2/-23)
cloudinit/sources/DataSourceEc2.py (+33/-11)
cloudinit/user_data.py (+23/-10)
debian/changelog (+25/-3)
dev/null (+0/-26)
sysvinit/gentoo/cloud-config (+0/-0)
sysvinit/gentoo/cloud-final (+0/-0)
sysvinit/gentoo/cloud-init (+0/-0)
sysvinit/gentoo/cloud-init-local (+0/-0)
templates/hosts.suse.tmpl (+8/-2)
templates/ntp.conf.opensuse.tmpl (+88/-0)
templates/ntp.conf.sles.tmpl (+0/-12)
tests/cloud_tests/collect.py (+16/-2)
tests/cloud_tests/images/base.py (+3/-16)
tests/cloud_tests/images/lxd.py (+18/-14)
tests/cloud_tests/images/nocloudkvm.py (+18/-24)
tests/cloud_tests/instances/base.py (+4/-77)
tests/cloud_tests/instances/lxd.py (+56/-48)
tests/cloud_tests/instances/nocloudkvm.py (+51/-91)
tests/cloud_tests/testcases/examples/run_commands.yaml (+2/-2)
tests/cloud_tests/testcases/modules/apt_configure_sources_ppa.py (+3/-3)
tests/cloud_tests/testcases/modules/apt_configure_sources_ppa.yaml (+3/-3)
tests/cloud_tests/testcases/modules/keys_to_console.py (+4/-4)
tests/cloud_tests/testcases/modules/runcmd.yaml (+2/-2)
tests/cloud_tests/testcases/modules/set_hostname.py (+3/-1)
tests/cloud_tests/testcases/modules/set_hostname.yaml (+2/-1)
tests/cloud_tests/testcases/modules/set_hostname_fqdn.py (+8/-3)
tests/cloud_tests/testcases/modules/set_hostname_fqdn.yaml (+3/-2)
tests/cloud_tests/testcases/modules/set_password_expire.py (+1/-1)
tests/cloud_tests/testcases/modules/set_password_expire.yaml (+2/-0)
tests/cloud_tests/testcases/modules/set_password_list.yaml (+1/-0)
tests/cloud_tests/testcases/modules/set_password_list_string.yaml (+1/-0)
tests/cloud_tests/testcases/modules/ssh_auth_key_fingerprints_disable.py (+0/-8)
tests/cloud_tests/testcases/modules/ssh_auth_key_fingerprints_disable.yaml (+0/-1)
tests/cloud_tests/testcases/modules/ssh_keys_generate.py (+0/-5)
tests/cloud_tests/testcases/modules/ssh_keys_generate.yaml (+0/-6)
tests/cloud_tests/testcases/modules/ssh_keys_provided.py (+0/-11)
tests/cloud_tests/testcases/modules/ssh_keys_provided.yaml (+0/-6)
tests/cloud_tests/util.py (+154/-8)
tests/unittests/test_data.py (+50/-0)
tests/unittests/test_datasource/test_ec2.py (+33/-0)
tests/unittests/test_handler/test_handler_etc_hosts.py (+69/-0)
tests/unittests/test_handler/test_handler_ntp.py (+26/-0)
tests/unittests/test_rh_subscription.py (+15/-0)
Reviewer Review Type Date Requested Status
Server Team CI bot continuous-integration Approve on 2017-11-20
Scott Moser 2017-11-20 Pending
Review via email: mp+333999@code.launchpad.net

Description of the change

Upstream snapshot into bionic for upcoming SRU work

To post a comment you must log in.

PASSED: Continuous integration, rev:a9c51c884cc4073a64cc8ae864c33cbbf5c29353
https://jenkins.ubuntu.com/server/job/cloud-init-ci/522/
Executed test runs:
    SUCCESS: Checkout
    SUCCESS: Unit & Style Tests
    SUCCESS: Ubuntu LTS: Build
    SUCCESS: Ubuntu LTS: Integration
    SUCCESS: MAAS Compatability Testing
    IN_PROGRESS: Declarative: Post Actions

Click here to trigger a rebuild:
https://jenkins.ubuntu.com/server/job/cloud-init-ci/522/rebuild

review: Approve (continuous-integration)

Preview Diff

[H/L] Next/Prev Comment, [J/K] Next/Prev File, [N/P] Next/Prev Hunk
1diff --git a/cloudinit/cloud.py b/cloudinit/cloud.py
2index d8a9fc8..ba61678 100644
3--- a/cloudinit/cloud.py
4+++ b/cloudinit/cloud.py
5@@ -56,8 +56,8 @@ class Cloud(object):
6 def get_template_filename(self, name):
7 fn = self.paths.template_tpl % (name)
8 if not os.path.isfile(fn):
9- LOG.warning("No template found at %s for template named %s",
10- fn, name)
11+ LOG.warning("No template found in %s for template named %s",
12+ os.path.dirname(fn), name)
13 return None
14 return fn
15
16diff --git a/cloudinit/config/cc_ntp.py b/cloudinit/config/cc_ntp.py
17index d43d060..f50bcb3 100644
18--- a/cloudinit/config/cc_ntp.py
19+++ b/cloudinit/config/cc_ntp.py
20@@ -23,7 +23,7 @@ frequency = PER_INSTANCE
21 NTP_CONF = '/etc/ntp.conf'
22 TIMESYNCD_CONF = '/etc/systemd/timesyncd.conf.d/cloud-init.conf'
23 NR_POOL_SERVERS = 4
24-distros = ['centos', 'debian', 'fedora', 'opensuse', 'ubuntu']
25+distros = ['centos', 'debian', 'fedora', 'opensuse', 'sles', 'ubuntu']
26
27
28 # The schema definition for each cloud-config module is a strict contract for
29@@ -174,8 +174,13 @@ def rename_ntp_conf(config=None):
30
31 def generate_server_names(distro):
32 names = []
33+ pool_distro = distro
34+ # For legal reasons x.pool.sles.ntp.org does not exist,
35+ # use the opensuse pool
36+ if distro == 'sles':
37+ pool_distro = 'opensuse'
38 for x in range(0, NR_POOL_SERVERS):
39- name = "%d.%s.pool.ntp.org" % (x, distro)
40+ name = "%d.%s.pool.ntp.org" % (x, pool_distro)
41 names.append(name)
42 return names
43
44diff --git a/cloudinit/config/cc_rh_subscription.py b/cloudinit/config/cc_rh_subscription.py
45index 7f36cf8..a9d21e7 100644
46--- a/cloudinit/config/cc_rh_subscription.py
47+++ b/cloudinit/config/cc_rh_subscription.py
48@@ -38,14 +38,16 @@ Subscription`` example config.
49 server-hostname: <hostname>
50 """
51
52+from cloudinit import log as logging
53 from cloudinit import util
54
55+LOG = logging.getLogger(__name__)
56+
57 distros = ['fedora', 'rhel']
58
59
60 def handle(name, cfg, _cloud, log, _args):
61- sm = SubscriptionManager(cfg)
62- sm.log = log
63+ sm = SubscriptionManager(cfg, log=log)
64 if not sm.is_configured():
65 log.debug("%s: module not configured.", name)
66 return None
67@@ -86,10 +88,9 @@ def handle(name, cfg, _cloud, log, _args):
68 if not return_stat:
69 raise SubscriptionError("Unable to attach pools {0}"
70 .format(sm.pools))
71- if (sm.enable_repo is not None) or (sm.disable_repo is not None):
72- return_stat = sm.update_repos(sm.enable_repo, sm.disable_repo)
73- if not return_stat:
74- raise SubscriptionError("Unable to add or remove repos")
75+ return_stat = sm.update_repos()
76+ if not return_stat:
77+ raise SubscriptionError("Unable to add or remove repos")
78 sm.log_success("rh_subscription plugin completed successfully")
79 except SubscriptionError as e:
80 sm.log_warn(str(e))
81@@ -108,7 +109,10 @@ class SubscriptionManager(object):
82 'rhsm-baseurl', 'server-hostname',
83 'auto-attach', 'service-level']
84
85- def __init__(self, cfg):
86+ def __init__(self, cfg, log=None):
87+ if log is None:
88+ log = LOG
89+ self.log = log
90 self.cfg = cfg
91 self.rhel_cfg = self.cfg.get('rh_subscription', {})
92 self.rhsm_baseurl = self.rhel_cfg.get('rhsm-baseurl')
93@@ -130,7 +134,7 @@ class SubscriptionManager(object):
94
95 def log_warn(self, msg):
96 '''Simple wrapper for logging warning messages. Useful for unittests'''
97- self.log.warn(msg)
98+ self.log.warning(msg)
99
100 def _verify_keys(self):
101 '''
102@@ -245,7 +249,7 @@ class SubscriptionManager(object):
103 return False
104
105 reg_id = return_out.split("ID: ")[1].rstrip()
106- self.log.debug("Registered successfully with ID {0}".format(reg_id))
107+ self.log.debug("Registered successfully with ID %s", reg_id)
108 return True
109
110 def _set_service_level(self):
111@@ -347,7 +351,7 @@ class SubscriptionManager(object):
112 try:
113 self._sub_man_cli(cmd)
114 self.log.debug("Attached the following pools to your "
115- "system: %s" % (", ".join(pool_list))
116+ "system: %s", (", ".join(pool_list))
117 .replace('--pool=', ''))
118 return True
119 except util.ProcessExecutionError as e:
120@@ -355,18 +359,24 @@ class SubscriptionManager(object):
121 "due to {1}".format(pool, e))
122 return False
123
124- def update_repos(self, erepos, drepos):
125+ def update_repos(self):
126 '''
127 Takes a list of yum repo ids that need to be disabled or enabled; then
128 it verifies if they are already enabled or disabled and finally
129 executes the action to disable or enable
130 '''
131
132- if (erepos is not None) and (not isinstance(erepos, list)):
133+ erepos = self.enable_repo
134+ drepos = self.disable_repo
135+ if erepos is None:
136+ erepos = []
137+ if drepos is None:
138+ drepos = []
139+ if not isinstance(erepos, list):
140 self.log_warn("Repo IDs must in the format of a list.")
141 return False
142
143- if (drepos is not None) and (not isinstance(drepos, list)):
144+ if not isinstance(drepos, list):
145 self.log_warn("Repo IDs must in the format of a list.")
146 return False
147
148@@ -399,14 +409,14 @@ class SubscriptionManager(object):
149 for fail in enable_list_fail:
150 # Check if the repo exists or not
151 if fail in active_repos:
152- self.log.debug("Repo {0} is already enabled".format(fail))
153+ self.log.debug("Repo %s is already enabled", fail)
154 else:
155 self.log_warn("Repo {0} does not appear to "
156 "exist".format(fail))
157 if len(disable_list_fail) > 0:
158 for fail in disable_list_fail:
159- self.log.debug("Repo {0} not disabled "
160- "because it is not enabled".format(fail))
161+ self.log.debug("Repo %s not disabled "
162+ "because it is not enabled", fail)
163
164 cmd = ['repos']
165 if len(disable_list) > 0:
166@@ -422,10 +432,10 @@ class SubscriptionManager(object):
167 return False
168
169 if len(enable_list) > 0:
170- self.log.debug("Enabled the following repos: %s" %
171+ self.log.debug("Enabled the following repos: %s",
172 (", ".join(enable_list)).replace('--enable=', ''))
173 if len(disable_list) > 0:
174- self.log.debug("Disabled the following repos: %s" %
175+ self.log.debug("Disabled the following repos: %s",
176 (", ".join(disable_list)).replace('--disable=', ''))
177 return True
178
179diff --git a/cloudinit/config/cc_update_etc_hosts.py b/cloudinit/config/cc_update_etc_hosts.py
180index b394784..c96eede 100644
181--- a/cloudinit/config/cc_update_etc_hosts.py
182+++ b/cloudinit/config/cc_update_etc_hosts.py
183@@ -23,8 +23,8 @@ using the template located in ``/etc/cloud/templates/hosts.tmpl``. In the
184
185 If ``manage_etc_hosts`` is set to ``localhost``, then cloud-init will not
186 rewrite ``/etc/hosts`` entirely, but rather will ensure that a entry for the
187-fqdn with ip ``127.0.1.1`` is present in ``/etc/hosts`` (i.e.
188-``ping <hostname>`` will ping ``127.0.1.1``).
189+fqdn with a distribution dependent ip is present in ``/etc/hosts`` (i.e.
190+``ping <hostname>`` will ping ``127.0.0.1`` or ``127.0.1.1`` or other ip).
191
192 .. note::
193 if ``manage_etc_hosts`` is set ``true`` or ``template``, the contents
194diff --git a/cloudinit/net/dhcp.py b/cloudinit/net/dhcp.py
195index 0cba703..d8624d8 100644
196--- a/cloudinit/net/dhcp.py
197+++ b/cloudinit/net/dhcp.py
198@@ -8,6 +8,7 @@ import configobj
199 import logging
200 import os
201 import re
202+import signal
203
204 from cloudinit.net import find_fallback_nic, get_devicelist
205 from cloudinit import temp_utils
206@@ -41,8 +42,7 @@ def maybe_perform_dhcp_discovery(nic=None):
207 if nic is None:
208 nic = find_fallback_nic()
209 if nic is None:
210- LOG.debug(
211- 'Skip dhcp_discovery: Unable to find fallback nic.')
212+ LOG.debug('Skip dhcp_discovery: Unable to find fallback nic.')
213 return {}
214 elif nic not in get_devicelist():
215 LOG.debug(
216@@ -119,7 +119,13 @@ def dhcp_discovery(dhclient_cmd_path, interface, cleandir):
217 cmd = [sandbox_dhclient_cmd, '-1', '-v', '-lf', lease_file,
218 '-pf', pid_file, interface, '-sf', '/bin/true']
219 util.subp(cmd, capture=True)
220- return parse_dhcp_lease_file(lease_file)
221+ pid = None
222+ try:
223+ pid = int(util.load_file(pid_file).strip())
224+ return parse_dhcp_lease_file(lease_file)
225+ finally:
226+ if pid:
227+ os.kill(pid, signal.SIGKILL)
228
229
230 def networkd_parse_lease(content):
231diff --git a/cloudinit/net/tests/test_dhcp.py b/cloudinit/net/tests/test_dhcp.py
232index 1c1f504..3d8e15c 100644
233--- a/cloudinit/net/tests/test_dhcp.py
234+++ b/cloudinit/net/tests/test_dhcp.py
235@@ -2,6 +2,7 @@
236
237 import mock
238 import os
239+import signal
240 from textwrap import dedent
241
242 from cloudinit.net.dhcp import (
243@@ -114,8 +115,9 @@ class TestDHCPDiscoveryClean(CiTestCase):
244 self.assertEqual('eth9', call[0][1])
245 self.assertIn('/var/tmp/cloud-init/cloud-init-dhcp-', call[0][2])
246
247+ @mock.patch('cloudinit.net.dhcp.os.kill')
248 @mock.patch('cloudinit.net.dhcp.util.subp')
249- def test_dhcp_discovery_run_in_sandbox(self, m_subp):
250+ def test_dhcp_discovery_run_in_sandbox(self, m_subp, m_kill):
251 """dhcp_discovery brings up the interface and runs dhclient.
252
253 It also returns the parsed dhcp.leases file generated in the sandbox.
254@@ -134,6 +136,10 @@ class TestDHCPDiscoveryClean(CiTestCase):
255 """)
256 lease_file = os.path.join(tmpdir, 'dhcp.leases')
257 write_file(lease_file, lease_content)
258+ pid_file = os.path.join(tmpdir, 'dhclient.pid')
259+ my_pid = 1
260+ write_file(pid_file, "%d\n" % my_pid)
261+
262 self.assertItemsEqual(
263 [{'interface': 'eth9', 'fixed-address': '192.168.2.74',
264 'subnet-mask': '255.255.255.0', 'routers': '192.168.2.1'}],
265@@ -149,6 +155,7 @@ class TestDHCPDiscoveryClean(CiTestCase):
266 [os.path.join(tmpdir, 'dhclient'), '-1', '-v', '-lf',
267 lease_file, '-pf', os.path.join(tmpdir, 'dhclient.pid'),
268 'eth9', '-sf', '/bin/true'], capture=True)])
269+ m_kill.assert_has_calls([mock.call(my_pid, signal.SIGKILL)])
270
271
272 class TestSystemdParseLeases(CiTestCase):
273diff --git a/cloudinit/sources/DataSourceAzure.py b/cloudinit/sources/DataSourceAzure.py
274index 80c2bd1..8c3492d 100644
275--- a/cloudinit/sources/DataSourceAzure.py
276+++ b/cloudinit/sources/DataSourceAzure.py
277@@ -465,10 +465,8 @@ class DataSourceAzure(sources.DataSource):
278
279 1. Probe the drivers of the net-devices present and inject them in
280 the network configuration under params: driver: <driver> value
281- 2. If the driver value is 'mlx4_core', the control mode should be
282- set to manual. The device will be later used to build a bond,
283- for now we want to ensure the device gets named but does not
284- break any network configuration
285+ 2. Generate a fallback network config that does not include any of
286+ the blacklisted devices.
287 """
288 blacklist = ['mlx4_core']
289 if not self._network_config:
290@@ -477,25 +475,6 @@ class DataSourceAzure(sources.DataSource):
291 netconfig = net.generate_fallback_config(
292 blacklist_drivers=blacklist, config_driver=True)
293
294- # if we have any blacklisted devices, update the network_config to
295- # include the device, mac, and driver values, but with no ip
296- # config; this ensures udev rules are generated but won't affect
297- # ip configuration
298- bl_found = 0
299- for bl_dev in [dev for dev in net.get_devicelist()
300- if net.device_driver(dev) in blacklist]:
301- bl_found += 1
302- cfg = {
303- 'type': 'physical',
304- 'name': 'vf%d' % bl_found,
305- 'mac_address': net.get_interface_mac(bl_dev),
306- 'params': {
307- 'driver': net.device_driver(bl_dev),
308- 'device_id': net.device_devid(bl_dev),
309- },
310- }
311- netconfig['config'].append(cfg)
312-
313 self._network_config = netconfig
314
315 return self._network_config
316diff --git a/cloudinit/sources/DataSourceEc2.py b/cloudinit/sources/DataSourceEc2.py
317index 0ef2217..7bbbfb6 100644
318--- a/cloudinit/sources/DataSourceEc2.py
319+++ b/cloudinit/sources/DataSourceEc2.py
320@@ -65,7 +65,7 @@ class DataSourceEc2(sources.DataSource):
321 get_network_metadata = False
322
323 # Track the discovered fallback nic for use in configuration generation.
324- fallback_nic = None
325+ _fallback_interface = None
326
327 def __init__(self, sys_cfg, distro, paths):
328 sources.DataSource.__init__(self, sys_cfg, distro, paths)
329@@ -92,18 +92,17 @@ class DataSourceEc2(sources.DataSource):
330 elif self.cloud_platform == Platforms.NO_EC2_METADATA:
331 return False
332
333- self.fallback_nic = net.find_fallback_nic()
334 if self.get_network_metadata: # Setup networking in init-local stage.
335 if util.is_FreeBSD():
336 LOG.debug("FreeBSD doesn't support running dhclient with -sf")
337 return False
338- dhcp_leases = dhcp.maybe_perform_dhcp_discovery(self.fallback_nic)
339+ dhcp_leases = dhcp.maybe_perform_dhcp_discovery(
340+ self.fallback_interface)
341 if not dhcp_leases:
342 # DataSourceEc2Local failed in init-local stage. DataSourceEc2
343 # will still run in init-network stage.
344 return False
345 dhcp_opts = dhcp_leases[-1]
346- self.fallback_nic = dhcp_opts.get('interface')
347 net_params = {'interface': dhcp_opts.get('interface'),
348 'ip': dhcp_opts.get('fixed-address'),
349 'prefix_or_mask': dhcp_opts.get('subnet-mask'),
350@@ -301,21 +300,44 @@ class DataSourceEc2(sources.DataSource):
351 return None
352
353 result = None
354- net_md = self.metadata.get('network')
355+ no_network_metadata_on_aws = bool(
356+ 'network' not in self.metadata and
357+ self.cloud_platform == Platforms.AWS)
358+ if no_network_metadata_on_aws:
359+ LOG.debug("Metadata 'network' not present:"
360+ " Refreshing stale metadata from prior to upgrade.")
361+ util.log_time(
362+ logfunc=LOG.debug, msg='Re-crawl of metadata service',
363+ func=self._crawl_metadata)
364+
365 # Limit network configuration to only the primary/fallback nic
366- macs_to_nics = {
367- net.get_interface_mac(self.fallback_nic): self.fallback_nic}
368+ iface = self.fallback_interface
369+ macs_to_nics = {net.get_interface_mac(iface): iface}
370+ net_md = self.metadata.get('network')
371 if isinstance(net_md, dict):
372 result = convert_ec2_metadata_network_config(
373- net_md, macs_to_nics=macs_to_nics,
374- fallback_nic=self.fallback_nic)
375+ net_md, macs_to_nics=macs_to_nics, fallback_nic=iface)
376 else:
377- LOG.warning("unexpected metadata 'network' key not valid: %s",
378- net_md)
379+ LOG.warning("Metadata 'network' key not valid: %s.", net_md)
380 self._network_config = result
381
382 return self._network_config
383
384+ @property
385+ def fallback_interface(self):
386+ if self._fallback_interface is None:
387+ # fallback_nic was used at one point, so restored objects may
388+ # have an attribute there. respect that if found.
389+ _legacy_fbnic = getattr(self, 'fallback_nic', None)
390+ if _legacy_fbnic:
391+ self._fallback_interface = _legacy_fbnic
392+ self.fallback_nic = None
393+ else:
394+ self._fallback_interface = net.find_fallback_nic()
395+ if self._fallback_interface is None:
396+ LOG.warning("Did not find a fallback interface on EC2.")
397+ return self._fallback_interface
398+
399 def _crawl_metadata(self):
400 """Crawl metadata service when available.
401
402diff --git a/cloudinit/user_data.py b/cloudinit/user_data.py
403index 88cb7f8..cc55daf 100644
404--- a/cloudinit/user_data.py
405+++ b/cloudinit/user_data.py
406@@ -19,6 +19,7 @@ import six
407
408 from cloudinit import handlers
409 from cloudinit import log as logging
410+from cloudinit.url_helper import UrlError
411 from cloudinit import util
412
413 LOG = logging.getLogger(__name__)
414@@ -222,16 +223,28 @@ class UserDataProcessor(object):
415 if include_once_on and os.path.isfile(include_once_fn):
416 content = util.load_file(include_once_fn)
417 else:
418- resp = util.read_file_or_url(include_url,
419- ssl_details=self.ssl_details)
420- if include_once_on and resp.ok():
421- util.write_file(include_once_fn, resp.contents, mode=0o600)
422- if resp.ok():
423- content = resp.contents
424- else:
425- LOG.warning(("Fetching from %s resulted in"
426- " a invalid http code of %s"),
427- include_url, resp.code)
428+ try:
429+ resp = util.read_file_or_url(include_url,
430+ ssl_details=self.ssl_details)
431+ if include_once_on and resp.ok():
432+ util.write_file(include_once_fn, resp.contents,
433+ mode=0o600)
434+ if resp.ok():
435+ content = resp.contents
436+ else:
437+ LOG.warning(("Fetching from %s resulted in"
438+ " a invalid http code of %s"),
439+ include_url, resp.code)
440+ except UrlError as urle:
441+ message = str(urle)
442+ # Older versions of requests.exceptions.HTTPError may not
443+ # include the errant url. Append it for clarity in logs.
444+ if include_url not in message:
445+ message += ' for url: {0}'.format(include_url)
446+ LOG.warning(message)
447+ except IOError as ioe:
448+ LOG.warning("Fetching from %s resulted in %s",
449+ include_url, ioe)
450
451 if content is not None:
452 new_msg = convert_string(content)
453diff --git a/debian/changelog b/debian/changelog
454index 51d71ee..1eaf400 100644
455--- a/debian/changelog
456+++ b/debian/changelog
457@@ -1,9 +1,31 @@
458-cloud-init (17.1-27-geb292c18-0ubuntu2) UNRELEASED; urgency=medium
459-
460+cloud-init (17.1-41-g76243487-0ubuntu1) bionic; urgency=medium
461+
462+ * New upstream snapshot.
463+ - integration test: replace curtin test ppa with cloud-init test ppa.
464+ - EC2: Fix bug using fallback_nic and metadata when restoring from cache.
465+ (LP: #1732917)
466+ - EC2: Kill dhclient process used in sandbox dhclient. (LP: #1732964)
467+ - ntp: fix configuration template rendering for openSUSE and SLES
468+ (LP: #1726572)
469+ - centos: Provide the failed #include url in error messages
470+ - Catch UrlError when #include'ing URLs [Andrew Jorgensen]
471+ - hosts: Fix openSUSE and SLES setup for /etc/hosts and clarify docs.
472+ [Robert Schweikert] (LP: #1731022)
473+ - rh_subscription: Perform null checks for enabled and disabled repos.
474+ [Dave Mulford]
475+ - Improve warning message when a template is not found.
476+ [Robert Schweikert] (LP: #1731035)
477+ - Replace the temporary i9n.brickies.net with i9n.cloud-init.io.
478+ - Azure: don't generate network configuration for SRIOV devices
479+ (LP: #1721579)
480+ - tests: address some minor feedback missed in last merge.
481+ - tests: integration test cleanup and full pass of nocloud-kvm.
482+ - Gentoo: chmod +x on all files in sysvinit/gentoo/
483+ [ckonstanski] (LP: #1727126)
484 * debian/cloud-init.templates: Fix capitilazation in 'AliYun' name.
485 (LP: #1728186)
486
487- -- Scott Moser <smoser@ubuntu.com> Tue, 31 Oct 2017 17:11:17 -0400
488+ -- Chad Smith <chad.smith@canonical.com> Mon, 20 Nov 2017 15:18:52 -0700
489
490 cloud-init (17.1-27-geb292c18-0ubuntu1) bionic; urgency=medium
491
492diff --git a/sysvinit/gentoo/cloud-config b/sysvinit/gentoo/cloud-config
493old mode 100644
494new mode 100755
495index 5618472..5618472
496--- a/sysvinit/gentoo/cloud-config
497+++ b/sysvinit/gentoo/cloud-config
498diff --git a/sysvinit/gentoo/cloud-final b/sysvinit/gentoo/cloud-final
499old mode 100644
500new mode 100755
501index a9bf01f..a9bf01f
502--- a/sysvinit/gentoo/cloud-final
503+++ b/sysvinit/gentoo/cloud-final
504diff --git a/sysvinit/gentoo/cloud-init b/sysvinit/gentoo/cloud-init
505old mode 100644
506new mode 100755
507index 531a715..531a715
508--- a/sysvinit/gentoo/cloud-init
509+++ b/sysvinit/gentoo/cloud-init
510diff --git a/sysvinit/gentoo/cloud-init-local b/sysvinit/gentoo/cloud-init-local
511old mode 100644
512new mode 100755
513index 0f8cf65..0f8cf65
514--- a/sysvinit/gentoo/cloud-init-local
515+++ b/sysvinit/gentoo/cloud-init-local
516diff --git a/templates/hosts.opensuse.tmpl b/templates/hosts.opensuse.tmpl
517deleted file mode 100644
518index 655da3f..0000000
519--- a/templates/hosts.opensuse.tmpl
520+++ /dev/null
521@@ -1,26 +0,0 @@
522-*
523- This file /etc/cloud/templates/hosts.opensuse.tmpl is only utilized
524- if enabled in cloud-config. Specifically, in order to enable it
525- you need to add the following to config:
526- manage_etc_hosts: True
527-*#
528-# Your system has configured 'manage_etc_hosts' as True.
529-# As a result, if you wish for changes to this file to persist
530-# then you will need to either
531-# a.) make changes to the master file in
532-# /etc/cloud/templates/hosts.opensuse.tmpl
533-# b.) change or remove the value of 'manage_etc_hosts' in
534-# /etc/cloud/cloud.cfg or cloud-config from user-data
535-#
536-# The following lines are desirable for IPv4 capable hosts
537-127.0.0.1 localhost
538-
539-# The following lines are desirable for IPv6 capable hosts
540-::1 localhost ipv6-localhost ipv6-loopback
541-fe00::0 ipv6-localnet
542-
543-ff00::0 ipv6-mcastprefix
544-ff02::1 ipv6-allnodes
545-ff02::2 ipv6-allrouters
546-ff02::3 ipv6-allhosts
547-
548diff --git a/templates/hosts.suse.tmpl b/templates/hosts.suse.tmpl
549index b608269..8e664db 100644
550--- a/templates/hosts.suse.tmpl
551+++ b/templates/hosts.suse.tmpl
552@@ -13,12 +13,18 @@ you need to add the following to config:
553 # /etc/cloud/cloud.cfg or cloud-config from user-data
554 #
555 # The following lines are desirable for IPv4 capable hosts
556-127.0.0.1 localhost
557+127.0.0.1 {{fqdn}} {{hostname}}
558+127.0.0.1 localhost.localdomain localhost
559+127.0.0.1 localhost4.localdomain4 localhost4
560
561 # The following lines are desirable for IPv6 capable hosts
562+::1 {{fqdn}} {{hostname}}
563+::1 localhost.localdomain localhost
564+::1 localhost6.localdomain6 localhost6
565 ::1 localhost ipv6-localhost ipv6-loopback
566-fe00::0 ipv6-localnet
567
568+
569+fe00::0 ipv6-localnet
570 ff00::0 ipv6-mcastprefix
571 ff02::1 ipv6-allnodes
572 ff02::2 ipv6-allrouters
573diff --git a/templates/ntp.conf.opensuse.tmpl b/templates/ntp.conf.opensuse.tmpl
574new file mode 100644
575index 0000000..f3ab565
576--- /dev/null
577+++ b/templates/ntp.conf.opensuse.tmpl
578@@ -0,0 +1,88 @@
579+## template:jinja
580+
581+##
582+## Radio and modem clocks by convention have addresses in the
583+## form 127.127.t.u, where t is the clock type and u is a unit
584+## number in the range 0-3.
585+##
586+## Most of these clocks require support in the form of a
587+## serial port or special bus peripheral. The particular
588+## device is normally specified by adding a soft link
589+## /dev/device-u to the particular hardware device involved,
590+## where u correspond to the unit number above.
591+##
592+## Generic DCF77 clock on serial port (Conrad DCF77)
593+## Address: 127.127.8.u
594+## Serial Port: /dev/refclock-u
595+##
596+## (create soft link /dev/refclock-0 to the particular ttyS?)
597+##
598+# server 127.127.8.0 mode 5 prefer
599+
600+##
601+## Undisciplined Local Clock. This is a fake driver intended for backup
602+## and when no outside source of synchronized time is available.
603+##
604+# server 127.127.1.0 # local clock (LCL)
605+# fudge 127.127.1.0 stratum 10 # LCL is unsynchronized
606+
607+##
608+## Add external Servers using
609+## # rcntpd addserver <yourserver>
610+## The servers will only be added to the currently running instance, not
611+## to /etc/ntp.conf.
612+##
613+{% if pools %}# pools
614+{% endif %}
615+{% for pool in pools -%}
616+pool {{pool}} iburst
617+{% endfor %}
618+{%- if servers %}# servers
619+{% endif %}
620+{% for server in servers -%}
621+server {{server}} iburst
622+{% endfor %}
623+
624+# Access control configuration; see /usr/share/doc/packages/ntp/html/accopt.html for
625+# details. The web page <http://support.ntp.org/bin/view/Support/AccessRestrictions>
626+# might also be helpful.
627+#
628+# Note that "restrict" applies to both servers and clients, so a configuration
629+# that might be intended to block requests from certain clients could also end
630+# up blocking replies from your own upstream servers.
631+
632+# By default, exchange time with everybody, but don't allow configuration.
633+restrict -4 default notrap nomodify nopeer noquery
634+restrict -6 default notrap nomodify nopeer noquery
635+
636+# Local users may interrogate the ntp server more closely.
637+restrict 127.0.0.1
638+restrict ::1
639+
640+# Clients from this (example!) subnet have unlimited access, but only if
641+# cryptographically authenticated.
642+#restrict 192.168.123.0 mask 255.255.255.0 notrust
643+
644+##
645+## Miscellaneous stuff
646+##
647+
648+driftfile /var/lib/ntp/drift/ntp.drift # path for drift file
649+
650+logfile /var/log/ntp # alternate log file
651+# logconfig =syncstatus + sysevents
652+# logconfig =all
653+
654+# statsdir /tmp/ # directory for statistics files
655+# filegen peerstats file peerstats type day enable
656+# filegen loopstats file loopstats type day enable
657+# filegen clockstats file clockstats type day enable
658+
659+#
660+# Authentication stuff
661+#
662+keys /etc/ntp.keys # path for keys file
663+trustedkey 1 # define trusted keys
664+requestkey 1 # key (7) for accessing server variables
665+controlkey 1 # key (6) for accessing server variables
666+
667diff --git a/templates/ntp.conf.sles.tmpl b/templates/ntp.conf.sles.tmpl
668index 5c5fc4d..f3ab565 100644
669--- a/templates/ntp.conf.sles.tmpl
670+++ b/templates/ntp.conf.sles.tmpl
671@@ -1,17 +1,5 @@
672 ## template:jinja
673
674-################################################################################
675-## /etc/ntp.conf
676-##
677-## Sample NTP configuration file.
678-## See package 'ntp-doc' for documentation, Mini-HOWTO and FAQ.
679-## Copyright (c) 1998 S.u.S.E. GmbH Fuerth, Germany.
680-##
681-## Author: Michael Andres, <ma@suse.de>
682-## Michael Skibbe, <mskibbe@suse.de>
683-##
684-################################################################################
685-
686 ##
687 ## Radio and modem clocks by convention have addresses in the
688 ## form 127.127.t.u, where t is the clock type and u is a unit
689diff --git a/tests/cloud_tests/collect.py b/tests/cloud_tests/collect.py
690index 4a2422e..71ee764 100644
691--- a/tests/cloud_tests/collect.py
692+++ b/tests/cloud_tests/collect.py
693@@ -22,11 +22,21 @@ def collect_script(instance, base_dir, script, script_name):
694 """
695 LOG.debug('running collect script: %s', script_name)
696 (out, err, exit) = instance.run_script(
697- script, rcs=range(0, 256),
698+ script.encode(), rcs=False,
699 description='collect: {}'.format(script_name))
700 c_util.write_file(os.path.join(base_dir, script_name), out)
701
702
703+def collect_console(instance, base_dir):
704+ LOG.debug('getting console log')
705+ try:
706+ data = instance.console_log()
707+ except NotImplementedError as e:
708+ data = 'Not Implemented: %s' % e
709+ with open(os.path.join(base_dir, 'console.log'), "wb") as fp:
710+ fp.write(data)
711+
712+
713 def collect_test_data(args, snapshot, os_name, test_name):
714 """Collect data for test case.
715
716@@ -79,8 +89,12 @@ def collect_test_data(args, snapshot, os_name, test_name):
717 test_output_dir, script, script_name))
718 for script_name, script in test_scripts.items()]
719
720+ console_log = partial(
721+ run_single, 'collect console',
722+ partial(collect_console, instance, test_output_dir))
723+
724 res = run_stage('collect for test: {}'.format(test_name),
725- [start_call] + collect_calls)
726+ [start_call] + collect_calls + [console_log])
727
728 return res
729
730diff --git a/tests/cloud_tests/images/base.py b/tests/cloud_tests/images/base.py
731index 0a1e056..d503108 100644
732--- a/tests/cloud_tests/images/base.py
733+++ b/tests/cloud_tests/images/base.py
734@@ -2,8 +2,10 @@
735
736 """Base class for images."""
737
738+from ..util import TargetBase
739
740-class Image(object):
741+
742+class Image(TargetBase):
743 """Base class for images."""
744
745 platform_name = None
746@@ -43,21 +45,6 @@ class Image(object):
747 # NOTE: more sophisticated options may be requied at some point
748 return self.config.get('setup_overrides', {})
749
750- def execute(self, *args, **kwargs):
751- """Execute command in image, modifying image."""
752- raise NotImplementedError
753-
754- def push_file(self, local_path, remote_path):
755- """Copy file at 'local_path' to instance at 'remote_path'."""
756- raise NotImplementedError
757-
758- def run_script(self, *args, **kwargs):
759- """Run script in image, modifying image.
760-
761- @return_value: script output
762- """
763- raise NotImplementedError
764-
765 def snapshot(self):
766 """Create snapshot of image, block until done."""
767 raise NotImplementedError
768diff --git a/tests/cloud_tests/images/lxd.py b/tests/cloud_tests/images/lxd.py
769index fd4e93c..5caeba4 100644
770--- a/tests/cloud_tests/images/lxd.py
771+++ b/tests/cloud_tests/images/lxd.py
772@@ -24,7 +24,7 @@ class LXDImage(base.Image):
773 @param config: image configuration
774 """
775 self.modified = False
776- self._instance = None
777+ self._img_instance = None
778 self._pylxd_image = None
779 self.pylxd_image = pylxd_image
780 super(LXDImage, self).__init__(platform, config)
781@@ -38,9 +38,9 @@ class LXDImage(base.Image):
782
783 @pylxd_image.setter
784 def pylxd_image(self, pylxd_image):
785- if self._instance:
786+ if self._img_instance:
787 self._instance.destroy()
788- self._instance = None
789+ self._img_instance = None
790 if (self._pylxd_image and
791 (self._pylxd_image is not pylxd_image) and
792 (not self.config.get('cache_base_image') or self.modified)):
793@@ -49,15 +49,19 @@ class LXDImage(base.Image):
794 self._pylxd_image = pylxd_image
795
796 @property
797- def instance(self):
798- """Property function."""
799- if not self._instance:
800- self._instance = self.platform.launch_container(
801+ def _instance(self):
802+ """Internal use only, returns a instance
803+
804+ This starts an lxc instance from the image, so it is "dirty".
805+ Better would be some way to modify this "at rest".
806+ lxc-pstart would be an option."""
807+ if not self._img_instance:
808+ self._img_instance = self.platform.launch_container(
809 self.properties, self.config, self.features,
810 use_desc='image-modification', image_desc=str(self),
811 image=self.pylxd_image.fingerprint)
812- self._instance.start()
813- return self._instance
814+ self._img_instance.start()
815+ return self._img_instance
816
817 @property
818 def properties(self):
819@@ -144,20 +148,20 @@ class LXDImage(base.Image):
820 shutil.rmtree(export_dir)
821 shutil.rmtree(extract_dir)
822
823- def execute(self, *args, **kwargs):
824+ def _execute(self, *args, **kwargs):
825 """Execute command in image, modifying image."""
826- return self.instance.execute(*args, **kwargs)
827+ return self._instance._execute(*args, **kwargs)
828
829 def push_file(self, local_path, remote_path):
830 """Copy file at 'local_path' to instance at 'remote_path'."""
831- return self.instance.push_file(local_path, remote_path)
832+ return self._instance.push_file(local_path, remote_path)
833
834 def run_script(self, *args, **kwargs):
835 """Run script in image, modifying image.
836
837 @return_value: script output
838 """
839- return self.instance.run_script(*args, **kwargs)
840+ return self._instance.run_script(*args, **kwargs)
841
842 def snapshot(self):
843 """Create snapshot of image, block until done."""
844@@ -169,7 +173,7 @@ class LXDImage(base.Image):
845 # clone current instance
846 instance = self.platform.launch_container(
847 self.properties, self.config, self.features,
848- container=self.instance.name, image_desc=str(self),
849+ container=self._instance.name, image_desc=str(self),
850 use_desc='snapshot', container_config=conf)
851 # wait for cloud-init before boot_clean_script is run to ensure
852 # /var/lib/cloud is removed cleanly
853diff --git a/tests/cloud_tests/images/nocloudkvm.py b/tests/cloud_tests/images/nocloudkvm.py
854index a7af0e5..1e7962c 100644
855--- a/tests/cloud_tests/images/nocloudkvm.py
856+++ b/tests/cloud_tests/images/nocloudkvm.py
857@@ -2,6 +2,8 @@
858
859 """NoCloud KVM Image Base Class."""
860
861+from cloudinit import util as c_util
862+
863 from tests.cloud_tests.images import base
864 from tests.cloud_tests.snapshots import nocloudkvm as nocloud_kvm_snapshot
865
866@@ -19,24 +21,11 @@ class NoCloudKVMImage(base.Image):
867 @param img_path: path to the image
868 """
869 self.modified = False
870- self._instance = None
871 self._img_path = img_path
872
873 super(NoCloudKVMImage, self).__init__(platform, config)
874
875 @property
876- def instance(self):
877- """Returns an instance of an image."""
878- if not self._instance:
879- if not self._img_path:
880- raise RuntimeError()
881-
882- self._instance = self.platform.create_image(
883- self.properties, self.config, self.features, self._img_path,
884- image_desc=str(self), use_desc='image-modification')
885- return self._instance
886-
887- @property
888 def properties(self):
889 """Dictionary containing: 'arch', 'os', 'version', 'release'."""
890 return {
891@@ -46,20 +35,26 @@ class NoCloudKVMImage(base.Image):
892 'version': self.config['version'],
893 }
894
895- def execute(self, *args, **kwargs):
896+ def _execute(self, command, stdin=None, env=None):
897 """Execute command in image, modifying image."""
898- return self.instance.execute(*args, **kwargs)
899+ return self.mount_image_callback(command, stdin=stdin, env=env)
900
901- def push_file(self, local_path, remote_path):
902- """Copy file at 'local_path' to instance at 'remote_path'."""
903- return self.instance.push_file(local_path, remote_path)
904+ def mount_image_callback(self, command, stdin=None, env=None):
905+ """Run mount-image-callback."""
906
907- def run_script(self, *args, **kwargs):
908- """Run script in image, modifying image.
909+ env_args = []
910+ if env:
911+ env_args = ['env'] + ["%s=%s" for k, v in env.items()]
912
913- @return_value: script output
914- """
915- return self.instance.run_script(*args, **kwargs)
916+ mic_chroot = ['sudo', 'mount-image-callback', '--system-mounts',
917+ '--system-resolvconf', self._img_path,
918+ '--', 'chroot', '_MOUNTPOINT_']
919+ try:
920+ out, err = c_util.subp(mic_chroot + env_args + list(command),
921+ data=stdin, decode=False)
922+ return (out, err, 0)
923+ except c_util.ProcessExecutionError as e:
924+ return (e.stdout, e.stderr, e.exit_code)
925
926 def snapshot(self):
927 """Create snapshot of image, block until done."""
928@@ -82,7 +77,6 @@ class NoCloudKVMImage(base.Image):
929 framework decide whether to keep or destroy everything.
930 """
931 self._img_path = None
932- self._instance.destroy()
933 super(NoCloudKVMImage, self).destroy()
934
935 # vi: ts=4 expandtab
936diff --git a/tests/cloud_tests/instances/base.py b/tests/cloud_tests/instances/base.py
937index 9bdda60..8c59d62 100644
938--- a/tests/cloud_tests/instances/base.py
939+++ b/tests/cloud_tests/instances/base.py
940@@ -2,8 +2,10 @@
941
942 """Base instance."""
943
944+from ..util import TargetBase
945
946-class Instance(object):
947+
948+class Instance(TargetBase):
949 """Base instance object."""
950
951 platform_name = None
952@@ -22,82 +24,7 @@ class Instance(object):
953 self.properties = properties
954 self.config = config
955 self.features = features
956-
957- def execute(self, command, stdout=None, stderr=None, env=None,
958- rcs=None, description=None):
959- """Execute command in instance, recording output, error and exit code.
960-
961- Assumes functional networking and execution as root with the
962- target filesystem being available at /.
963-
964- @param command: the command to execute as root inside the image
965- if command is a string, then it will be executed as:
966- ['sh', '-c', command]
967- @param stdout, stderr: file handles to write output and error to
968- @param env: environment variables
969- @param rcs: allowed return codes from command
970- @param description: purpose of command
971- @return_value: tuple containing stdout data, stderr data, exit code
972- """
973- raise NotImplementedError
974-
975- def read_data(self, remote_path, decode=False):
976- """Read data from instance filesystem.
977-
978- @param remote_path: path in instance
979- @param decode: return as string
980- @return_value: data as str or bytes
981- """
982- raise NotImplementedError
983-
984- def write_data(self, remote_path, data):
985- """Write data to instance filesystem.
986-
987- @param remote_path: path in instance
988- @param data: data to write, either str or bytes
989- """
990- raise NotImplementedError
991-
992- def pull_file(self, remote_path, local_path):
993- """Copy file at 'remote_path', from instance to 'local_path'.
994-
995- @param remote_path: path on remote instance
996- @param local_path: path on local instance
997- """
998- with open(local_path, 'wb') as fp:
999- fp.write(self.read_data(remote_path))
1000-
1001- def push_file(self, local_path, remote_path):
1002- """Copy file at 'local_path' to instance at 'remote_path'.
1003-
1004- @param local_path: path on local instance
1005- @param remote_path: path on remote instance
1006- """
1007- with open(local_path, 'rb') as fp:
1008- self.write_data(remote_path, fp.read())
1009-
1010- def run_script(self, script, rcs=None, description=None):
1011- """Run script in target and return stdout.
1012-
1013- @param script: script contents
1014- @param rcs: allowed return codes from script
1015- @param description: purpose of script
1016- @return_value: stdout from script
1017- """
1018- script_path = self.tmpfile()
1019- try:
1020- self.write_data(script_path, script)
1021- return self.execute(
1022- ['/bin/bash', script_path], rcs=rcs, description=description)
1023- finally:
1024- self.execute(['rm', '-f', script_path], rcs=rcs)
1025-
1026- def tmpfile(self):
1027- """Get a tmp file in the target.
1028-
1029- @return_value: path to new file in target
1030- """
1031- return self.execute(['mktemp'])[0].strip()
1032+ self._tmp_count = 0
1033
1034 def console_log(self):
1035 """Instance console.
1036diff --git a/tests/cloud_tests/instances/lxd.py b/tests/cloud_tests/instances/lxd.py
1037index a43918c..3b035d8 100644
1038--- a/tests/cloud_tests/instances/lxd.py
1039+++ b/tests/cloud_tests/instances/lxd.py
1040@@ -2,8 +2,11 @@
1041
1042 """Base LXD instance."""
1043
1044-from tests.cloud_tests.instances import base
1045-from tests.cloud_tests import util
1046+from . import base
1047+
1048+import os
1049+import shutil
1050+from tempfile import mkdtemp
1051
1052
1053 class LXDInstance(base.Instance):
1054@@ -24,6 +27,8 @@ class LXDInstance(base.Instance):
1055 self._pylxd_container = pylxd_container
1056 super(LXDInstance, self).__init__(
1057 platform, name, properties, config, features)
1058+ self.tmpd = mkdtemp(prefix="%s-%s" % (type(self).__name__, name))
1059+ self._setup_console_log()
1060
1061 @property
1062 def pylxd_container(self):
1063@@ -31,74 +36,69 @@ class LXDInstance(base.Instance):
1064 self._pylxd_container.sync()
1065 return self._pylxd_container
1066
1067- def execute(self, command, stdout=None, stderr=None, env=None,
1068- rcs=None, description=None):
1069- """Execute command in instance, recording output, error and exit code.
1070-
1071- Assumes functional networking and execution as root with the
1072- target filesystem being available at /.
1073-
1074- @param command: the command to execute as root inside the image
1075- if command is a string, then it will be executed as:
1076- ['sh', '-c', command]
1077- @param stdout: file handler to write output
1078- @param stderr: file handler to write error
1079- @param env: environment variables
1080- @param rcs: allowed return codes from command
1081- @param description: purpose of command
1082- @return_value: tuple containing stdout data, stderr data, exit code
1083- """
1084+ def _setup_console_log(self):
1085+ logf = os.path.join(self.tmpd, "console.log")
1086+
1087+ # doing this ensures we can read it. Otherwise it ends up root:root.
1088+ with open(logf, "w") as fp:
1089+ fp.write("# %s\n" % self.name)
1090+
1091+ cfg = "lxc.console.logfile=%s" % logf
1092+ orig = self._pylxd_container.config.get('raw.lxc', "")
1093+ if orig:
1094+ orig += "\n"
1095+ self._pylxd_container.config['raw.lxc'] = orig + cfg
1096+ self._pylxd_container.save()
1097+ self._console_log_file = logf
1098+
1099+ def _execute(self, command, stdin=None, env=None):
1100 if env is None:
1101 env = {}
1102
1103- if isinstance(command, str):
1104- command = ['sh', '-c', command]
1105+ if stdin is not None:
1106+ # pylxd does not support input to execute.
1107+ # https://github.com/lxc/pylxd/issues/244
1108+ #
1109+ # The solution here is write a tmp file in the container
1110+ # and then execute a shell that sets it standard in to
1111+ # be from that file, removes it, and calls the comand.
1112+ tmpf = self.tmpfile()
1113+ self.write_data(tmpf, stdin)
1114+ ncmd = 'exec <"{tmpf}"; rm -f "{tmpf}"; exec "$@"'
1115+ command = (['sh', '-c', ncmd.format(tmpf=tmpf), 'stdinhack'] +
1116+ list(command))
1117
1118 # ensure instance is running and execute the command
1119 self.start()
1120+ # execute returns a ContainerExecuteResult, named tuple
1121+ # (exit_code, stdout, stderr)
1122 res = self.pylxd_container.execute(command, environment=env)
1123
1124 # get out, exit and err from pylxd return
1125- if hasattr(res, 'exit_code'):
1126- # pylxd 2.2 returns ContainerExecuteResult, named tuple of
1127- # (exit_code, out, err)
1128- (exit, out, err) = res
1129- else:
1130+ if not hasattr(res, 'exit_code'):
1131 # pylxd 2.1.3 and earlier only return out and err, no exit
1132- # LOG.warning('using pylxd version < 2.2')
1133- (out, err) = res
1134- exit = 0
1135-
1136- # write data to file descriptors if needed
1137- if stdout:
1138- stdout.write(out)
1139- if stderr:
1140- stderr.write(err)
1141-
1142- # if the command exited with a code not allowed in rcs, then fail
1143- if exit not in (rcs if rcs else (0,)):
1144- error_desc = ('Failed command to: {}'.format(description)
1145- if description else None)
1146- raise util.InTargetExecuteError(
1147- out, err, exit, command, self.name, error_desc)
1148+ raise RuntimeError(
1149+ "No 'exit_code' in pylxd.container.execute return.\n"
1150+ "pylxd > 2.2 is required.")
1151
1152- return (out, err, exit)
1153+ return res.stdout, res.stderr, res.exit_code
1154
1155 def read_data(self, remote_path, decode=False):
1156 """Read data from instance filesystem.
1157
1158 @param remote_path: path in instance
1159- @param decode: return as string
1160- @return_value: data as str or bytes
1161+ @param decode: decode data before returning.
1162+ @return_value: content of remote_path as bytes if 'decode' is False,
1163+ and as string if 'decode' is True.
1164 """
1165 data = self.pylxd_container.files.get(remote_path)
1166- return data.decode() if decode and isinstance(data, bytes) else data
1167+ return data.decode() if decode else data
1168
1169 def write_data(self, remote_path, data):
1170 """Write data to instance filesystem.
1171
1172 @param remote_path: path in instance
1173- @param data: data to write, either str or bytes
1174+ @param data: data to write in bytes
1175 """
1176 self.pylxd_container.files.put(remote_path, data)
1177
1178@@ -107,7 +107,14 @@ class LXDInstance(base.Instance):
1179
1180 @return_value: bytes of this instance’s console
1181 """
1182- raise NotImplementedError
1183+ if not os.path.exists(self._console_log_file):
1184+ raise NotImplementedError(
1185+ "Console log '%s' does not exist. If this is a remote "
1186+ "lxc, then this is really NotImplementedError. If it is "
1187+ "A local lxc, then this is a RuntimeError."
1188+ "https://github.com/lxc/lxd/issues/1129")
1189+ with open(self._console_log_file, "rb") as fp:
1190+ return fp.read()
1191
1192 def reboot(self, wait=True):
1193 """Reboot instance."""
1194@@ -144,6 +151,7 @@ class LXDInstance(base.Instance):
1195 if self.platform.container_exists(self.name):
1196 raise OSError('container {} was not properly removed'
1197 .format(self.name))
1198+ shutil.rmtree(self.tmpd)
1199 super(LXDInstance, self).destroy()
1200
1201 # vi: ts=4 expandtab
1202diff --git a/tests/cloud_tests/instances/nocloudkvm.py b/tests/cloud_tests/instances/nocloudkvm.py
1203index 8a0e531..cc82580 100644
1204--- a/tests/cloud_tests/instances/nocloudkvm.py
1205+++ b/tests/cloud_tests/instances/nocloudkvm.py
1206@@ -12,11 +12,18 @@ from cloudinit import util as c_util
1207 from tests.cloud_tests.instances import base
1208 from tests.cloud_tests import util
1209
1210+# This domain contains reverse lookups for hostnames that are used.
1211+# The primary reason is so sudo will return quickly when it attempts
1212+# to look up the hostname. i9n is just short for 'integration'.
1213+# see also bug 1730744 for why we had to do this.
1214+CI_DOMAIN = "i9n.cloud-init.io"
1215+
1216
1217 class NoCloudKVMInstance(base.Instance):
1218 """NoCloud KVM backed instance."""
1219
1220 platform_name = "nocloud-kvm"
1221+ _ssh_client = None
1222
1223 def __init__(self, platform, name, properties, config, features,
1224 user_data, meta_data):
1225@@ -35,6 +42,7 @@ class NoCloudKVMInstance(base.Instance):
1226 self.ssh_port = None
1227 self.pid = None
1228 self.pid_file = None
1229+ self.console_file = None
1230
1231 super(NoCloudKVMInstance, self).__init__(
1232 platform, name, properties, config, features)
1233@@ -51,43 +59,18 @@ class NoCloudKVMInstance(base.Instance):
1234 os.remove(self.pid_file)
1235
1236 self.pid = None
1237- super(NoCloudKVMInstance, self).destroy()
1238-
1239- def execute(self, command, stdout=None, stderr=None, env=None,
1240- rcs=None, description=None):
1241- """Execute command in instance.
1242-
1243- Assumes functional networking and execution as root with the
1244- target filesystem being available at /.
1245-
1246- @param command: the command to execute as root inside the image
1247- if command is a string, then it will be executed as:
1248- ['sh', '-c', command]
1249- @param stdout, stderr: file handles to write output and error to
1250- @param env: environment variables
1251- @param rcs: allowed return codes from command
1252- @param description: purpose of command
1253- @return_value: tuple containing stdout data, stderr data, exit code
1254- """
1255- if env is None:
1256- env = {}
1257-
1258- if isinstance(command, str):
1259- command = ['sh', '-c', command]
1260+ if self._ssh_client:
1261+ self._ssh_client.close()
1262+ self._ssh_client = None
1263
1264- if self.pid:
1265- return self.ssh(command)
1266- else:
1267- return self.mount_image_callback(command) + (0,)
1268+ super(NoCloudKVMInstance, self).destroy()
1269
1270- def mount_image_callback(self, cmd):
1271- """Run mount-image-callback."""
1272- out, err = c_util.subp(['sudo', 'mount-image-callback',
1273- '--system-mounts', '--system-resolvconf',
1274- self.name, '--', 'chroot',
1275- '_MOUNTPOINT_'] + cmd)
1276+ def _execute(self, command, stdin=None, env=None):
1277+ env_args = []
1278+ if env:
1279+ env_args = ['env'] + ["%s=%s" for k, v in env.items()]
1280
1281- return out, err
1282+ return self.ssh(['sudo'] + env_args + list(command), stdin=stdin)
1283
1284 def generate_seed(self, tmpdir):
1285 """Generate nocloud seed from user-data"""
1286@@ -109,57 +92,31 @@ class NoCloudKVMInstance(base.Instance):
1287 s.close()
1288 return num
1289
1290- def push_file(self, local_path, remote_path):
1291- """Copy file at 'local_path' to instance at 'remote_path'.
1292-
1293- If we have a pid then SSH is up, otherwise, use
1294- mount-image-callback.
1295-
1296- @param local_path: path on local instance
1297- @param remote_path: path on remote instance
1298- """
1299- if self.pid:
1300- super(NoCloudKVMInstance, self).push_file()
1301- else:
1302- local_file = open(local_path)
1303- p = subprocess.Popen(['sudo', 'mount-image-callback',
1304- '--system-mounts', '--system-resolvconf',
1305- self.name, '--', 'chroot', '_MOUNTPOINT_',
1306- '/bin/sh', '-c', 'cat - > %s' % remote_path],
1307- stdin=local_file,
1308- stdout=subprocess.PIPE,
1309- stderr=subprocess.PIPE)
1310- p.wait()
1311-
1312- def sftp_put(self, path, data):
1313- """SFTP put a file."""
1314- client = self._ssh_connect()
1315- sftp = client.open_sftp()
1316-
1317- with sftp.open(path, 'w') as f:
1318- f.write(data)
1319-
1320- client.close()
1321-
1322- def ssh(self, command):
1323+ def ssh(self, command, stdin=None):
1324 """Run a command via SSH."""
1325 client = self._ssh_connect()
1326
1327+ cmd = util.shell_pack(command)
1328 try:
1329- _, out, err = client.exec_command(util.shell_pack(command))
1330- except paramiko.SSHException:
1331- raise util.InTargetExecuteError('', '', -1, command, self.name)
1332-
1333- exit = out.channel.recv_exit_status()
1334- out = ''.join(out.readlines())
1335- err = ''.join(err.readlines())
1336- client.close()
1337-
1338- return out, err, exit
1339+ fp_in, fp_out, fp_err = client.exec_command(cmd)
1340+ channel = fp_in.channel
1341+ if stdin is not None:
1342+ fp_in.write(stdin)
1343+ fp_in.close()
1344+
1345+ channel.shutdown_write()
1346+ rc = channel.recv_exit_status()
1347+ return (fp_out.read(), fp_err.read(), rc)
1348+ except paramiko.SSHException as e:
1349+ raise util.InTargetExecuteError(
1350+ b'', b'', -1, command, self.name, reason=e)
1351
1352 def _ssh_connect(self, hostname='localhost', username='ubuntu',
1353 banner_timeout=120, retry_attempts=30):
1354 """Connect via SSH."""
1355+ if self._ssh_client:
1356+ return self._ssh_client
1357+
1358 private_key = paramiko.RSAKey.from_private_key_file(self.ssh_key_file)
1359 client = paramiko.SSHClient()
1360 client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
1361@@ -168,6 +125,7 @@ class NoCloudKVMInstance(base.Instance):
1362 client.connect(hostname=hostname, username=username,
1363 port=self.ssh_port, pkey=private_key,
1364 banner_timeout=banner_timeout)
1365+ self._ssh_client = client
1366 return client
1367 except (paramiko.SSHException, TypeError):
1368 time.sleep(1)
1369@@ -183,15 +141,19 @@ class NoCloudKVMInstance(base.Instance):
1370 tmpdir = self.platform.config['data_dir']
1371 seed = self.generate_seed(tmpdir)
1372 self.pid_file = os.path.join(tmpdir, '%s.pid' % self.name)
1373+ self.console_file = os.path.join(tmpdir, '%s-console.log' % self.name)
1374 self.ssh_port = self.get_free_port()
1375
1376- subprocess.Popen(['./tools/xkvm',
1377- '--disk', '%s,cache=unsafe' % self.name,
1378- '--disk', '%s,cache=unsafe' % seed,
1379- '--netdev',
1380- 'user,hostfwd=tcp::%s-:22' % self.ssh_port,
1381- '--', '-pidfile', self.pid_file, '-vnc', 'none',
1382- '-m', '2G', '-smp', '2'],
1383+ cmd = ['./tools/xkvm',
1384+ '--disk', '%s,cache=unsafe' % self.name,
1385+ '--disk', '%s,cache=unsafe' % seed,
1386+ '--netdev', ','.join(['user',
1387+ 'hostfwd=tcp::%s-:22' % self.ssh_port,
1388+ 'dnssearch=%s' % CI_DOMAIN]),
1389+ '--', '-pidfile', self.pid_file, '-vnc', 'none',
1390+ '-m', '2G', '-smp', '2', '-nographic',
1391+ '-serial', 'file:' + self.console_file]
1392+ subprocess.Popen(cmd,
1393 close_fds=True,
1394 stdin=subprocess.PIPE,
1395 stdout=subprocess.PIPE,
1396@@ -206,12 +168,10 @@ class NoCloudKVMInstance(base.Instance):
1397 if wait:
1398 self._wait_for_system(wait_for_cloud_init)
1399
1400- def write_data(self, remote_path, data):
1401- """Write data to instance filesystem.
1402-
1403- @param remote_path: path in instance
1404- @param data: data to write, either str or bytes
1405- """
1406- self.sftp_put(remote_path, data)
1407+ def console_log(self):
1408+ if not self.console_file:
1409+ return b''
1410+ with open(self.console_file, "rb") as fp:
1411+ return fp.read()
1412
1413 # vi: ts=4 expandtab
1414diff --git a/tests/cloud_tests/testcases/examples/run_commands.yaml b/tests/cloud_tests/testcases/examples/run_commands.yaml
1415index b0e311b..f80eb8c 100644
1416--- a/tests/cloud_tests/testcases/examples/run_commands.yaml
1417+++ b/tests/cloud_tests/testcases/examples/run_commands.yaml
1418@@ -7,10 +7,10 @@ enabled: False
1419 cloud_config: |
1420 #cloud-config
1421 runcmd:
1422- - echo cloud-init run cmd test > /tmp/run_cmd
1423+ - echo cloud-init run cmd test > /var/tmp/run_cmd
1424 collect_scripts:
1425 run_cmd: |
1426 #!/bin/bash
1427- cat /tmp/run_cmd
1428+ cat /var/tmp/run_cmd
1429
1430 # vi: ts=4 expandtab
1431diff --git a/tests/cloud_tests/testcases/modules/apt_configure_sources_ppa.py b/tests/cloud_tests/testcases/modules/apt_configure_sources_ppa.py
1432index d299e9a..dfbdead 100644
1433--- a/tests/cloud_tests/testcases/modules/apt_configure_sources_ppa.py
1434+++ b/tests/cloud_tests/testcases/modules/apt_configure_sources_ppa.py
1435@@ -11,13 +11,13 @@ class TestAptconfigureSourcesPPA(base.CloudTestCase):
1436 """Test specific ppa added."""
1437 out = self.get_data_file('sources.list')
1438 self.assertIn(
1439- 'http://ppa.launchpad.net/curtin-dev/test-archive/ubuntu', out)
1440+ 'http://ppa.launchpad.net/cloud-init-dev/test-archive/ubuntu', out)
1441
1442 def test_ppa_key(self):
1443 """Test ppa key added."""
1444 out = self.get_data_file('apt-key')
1445 self.assertIn(
1446- '1BC3 0F71 5A3B 8612 47A8 1A5E 55FE 7C8C 0165 013E', out)
1447- self.assertIn('Launchpad PPA for curtin developers', out)
1448+ '1FF0 D853 5EF7 E719 E5C8 1B9C 083D 06FB E4D3 04DF', out)
1449+ self.assertIn('Launchpad PPA for cloud init development team', out)
1450
1451 # vi: ts=4 expandtab
1452diff --git a/tests/cloud_tests/testcases/modules/apt_configure_sources_ppa.yaml b/tests/cloud_tests/testcases/modules/apt_configure_sources_ppa.yaml
1453index 9efdae5..b997bcf 100644
1454--- a/tests/cloud_tests/testcases/modules/apt_configure_sources_ppa.yaml
1455+++ b/tests/cloud_tests/testcases/modules/apt_configure_sources_ppa.yaml
1456@@ -2,7 +2,7 @@
1457 # Add a PPA to source.list
1458 #
1459 # NOTE: on older ubuntu releases the sources file added is named
1460-# 'curtin-dev-test-archive-trusty', without 'ubuntu' in the middle
1461+# 'cloud-init-dev-test-archive-trusty', without 'ubuntu' in the middle
1462 required_features:
1463 - apt
1464 - ppa
1465@@ -14,11 +14,11 @@ cloud_config: |
1466 source1:
1467 keyid: 0165013E
1468 keyserver: keyserver.ubuntu.com
1469- source: "ppa:curtin-dev/test-archive"
1470+ source: "ppa:cloud-init-dev/test-archive"
1471 collect_scripts:
1472 sources.list: |
1473 #!/bin/bash
1474- cat /etc/apt/sources.list.d/curtin-dev-ubuntu-test-archive-*.list
1475+ cat /etc/apt/sources.list.d/cloud-init-dev-ubuntu-test-archive-*.list
1476 apt-key: |
1477 #!/bin/bash
1478 apt-key finger
1479diff --git a/tests/cloud_tests/testcases/modules/keys_to_console.py b/tests/cloud_tests/testcases/modules/keys_to_console.py
1480index 88b6812..07f3811 100644
1481--- a/tests/cloud_tests/testcases/modules/keys_to_console.py
1482+++ b/tests/cloud_tests/testcases/modules/keys_to_console.py
1483@@ -10,13 +10,13 @@ class TestKeysToConsole(base.CloudTestCase):
1484 def test_excluded_keys(self):
1485 """Test excluded keys missing."""
1486 out = self.get_data_file('syslog')
1487- self.assertNotIn('DSA', out)
1488- self.assertNotIn('ECDSA', out)
1489+ self.assertNotIn('(DSA)', out)
1490+ self.assertNotIn('(ECDSA)', out)
1491
1492 def test_expected_keys(self):
1493 """Test expected keys exist."""
1494 out = self.get_data_file('syslog')
1495- self.assertIn('ED25519', out)
1496- self.assertIn('RSA', out)
1497+ self.assertIn('(ED25519)', out)
1498+ self.assertIn('(RSA)', out)
1499
1500 # vi: ts=4 expandtab
1501diff --git a/tests/cloud_tests/testcases/modules/runcmd.yaml b/tests/cloud_tests/testcases/modules/runcmd.yaml
1502index 04e5a05..8309a88 100644
1503--- a/tests/cloud_tests/testcases/modules/runcmd.yaml
1504+++ b/tests/cloud_tests/testcases/modules/runcmd.yaml
1505@@ -4,10 +4,10 @@
1506 cloud_config: |
1507 #cloud-config
1508 runcmd:
1509- - echo cloud-init run cmd test > /tmp/run_cmd
1510+ - echo cloud-init run cmd test > /var/tmp/run_cmd
1511 collect_scripts:
1512 run_cmd: |
1513 #!/bin/bash
1514- cat /tmp/run_cmd
1515+ cat /var/tmp/run_cmd
1516
1517 # vi: ts=4 expandtab
1518diff --git a/tests/cloud_tests/testcases/modules/set_hostname.py b/tests/cloud_tests/testcases/modules/set_hostname.py
1519index 6e96a75..1dbe64c 100644
1520--- a/tests/cloud_tests/testcases/modules/set_hostname.py
1521+++ b/tests/cloud_tests/testcases/modules/set_hostname.py
1522@@ -7,9 +7,11 @@ from tests.cloud_tests.testcases import base
1523 class TestHostname(base.CloudTestCase):
1524 """Test hostname module."""
1525
1526+ ex_hostname = "cloudinit2"
1527+
1528 def test_hostname(self):
1529 """Test hostname command shows correct output."""
1530 out = self.get_data_file('hostname')
1531- self.assertIn('myhostname', out)
1532+ self.assertIn(self.ex_hostname, out)
1533
1534 # vi: ts=4 expandtab
1535diff --git a/tests/cloud_tests/testcases/modules/set_hostname.yaml b/tests/cloud_tests/testcases/modules/set_hostname.yaml
1536index c96344c..071fb22 100644
1537--- a/tests/cloud_tests/testcases/modules/set_hostname.yaml
1538+++ b/tests/cloud_tests/testcases/modules/set_hostname.yaml
1539@@ -5,7 +5,8 @@ required_features:
1540 - hostname
1541 cloud_config: |
1542 #cloud-config
1543- hostname: myhostname
1544+ hostname: cloudinit2
1545+
1546 collect_scripts:
1547 hosts: |
1548 #!/bin/bash
1549diff --git a/tests/cloud_tests/testcases/modules/set_hostname_fqdn.py b/tests/cloud_tests/testcases/modules/set_hostname_fqdn.py
1550index 398f3d4..eb6f065 100644
1551--- a/tests/cloud_tests/testcases/modules/set_hostname_fqdn.py
1552+++ b/tests/cloud_tests/testcases/modules/set_hostname_fqdn.py
1553@@ -1,26 +1,31 @@
1554 # This file is part of cloud-init. See LICENSE file for license information.
1555
1556 """cloud-init Integration Test Verify Script."""
1557+from tests.cloud_tests.instances.nocloudkvm import CI_DOMAIN
1558 from tests.cloud_tests.testcases import base
1559
1560
1561 class TestHostnameFqdn(base.CloudTestCase):
1562 """Test Hostname module."""
1563
1564+ ex_hostname = "cloudinit1"
1565+ ex_fqdn = "cloudinit2." + CI_DOMAIN
1566+
1567 def test_hostname(self):
1568 """Test hostname output."""
1569 out = self.get_data_file('hostname')
1570- self.assertIn('myhostname', out)
1571+ self.assertIn(self.ex_hostname, out)
1572
1573 def test_hostname_fqdn(self):
1574 """Test hostname fqdn output."""
1575 out = self.get_data_file('fqdn')
1576- self.assertIn('host.myorg.com', out)
1577+ self.assertIn(self.ex_fqdn, out)
1578
1579 def test_hosts(self):
1580 """Test /etc/hosts file."""
1581 out = self.get_data_file('hosts')
1582- self.assertIn('127.0.1.1 host.myorg.com myhostname', out)
1583+ self.assertIn('127.0.1.1 %s %s' % (self.ex_fqdn, self.ex_hostname),
1584+ out)
1585 self.assertIn('127.0.0.1 localhost', out)
1586
1587 # vi: ts=4 expandtab
1588diff --git a/tests/cloud_tests/testcases/modules/set_hostname_fqdn.yaml b/tests/cloud_tests/testcases/modules/set_hostname_fqdn.yaml
1589index daf7593..a85ee79 100644
1590--- a/tests/cloud_tests/testcases/modules/set_hostname_fqdn.yaml
1591+++ b/tests/cloud_tests/testcases/modules/set_hostname_fqdn.yaml
1592@@ -6,8 +6,9 @@ required_features:
1593 cloud_config: |
1594 #cloud-config
1595 manage_etc_hosts: true
1596- hostname: myhostname
1597- fqdn: host.myorg.com
1598+ hostname: cloudinit1
1599+ # this needs changing if CI_DOMAIN were updated.
1600+ fqdn: cloudinit2.i9n.cloud-init.io
1601 collect_scripts:
1602 hosts: |
1603 #!/bin/bash
1604diff --git a/tests/cloud_tests/testcases/modules/set_password_expire.py b/tests/cloud_tests/testcases/modules/set_password_expire.py
1605index a1c3aa0..967aca7 100644
1606--- a/tests/cloud_tests/testcases/modules/set_password_expire.py
1607+++ b/tests/cloud_tests/testcases/modules/set_password_expire.py
1608@@ -18,6 +18,6 @@ class TestPasswordExpire(base.CloudTestCase):
1609 def test_sshd_config(self):
1610 """Test sshd config allows passwords."""
1611 out = self.get_data_file('sshd_config')
1612- self.assertIn('PasswordAuthentication no', out)
1613+ self.assertIn('PasswordAuthentication yes', out)
1614
1615 # vi: ts=4 expandtab
1616diff --git a/tests/cloud_tests/testcases/modules/set_password_expire.yaml b/tests/cloud_tests/testcases/modules/set_password_expire.yaml
1617index 789604b..ba6344b 100644
1618--- a/tests/cloud_tests/testcases/modules/set_password_expire.yaml
1619+++ b/tests/cloud_tests/testcases/modules/set_password_expire.yaml
1620@@ -6,7 +6,9 @@ required_features:
1621 cloud_config: |
1622 #cloud-config
1623 chpasswd: { expire: True }
1624+ ssh_pwauth: yes
1625 users:
1626+ - default
1627 - name: tom
1628 password: $1$xyz$sPMsLNmf66Ohl.ol6JvzE.
1629 lock_passwd: false
1630diff --git a/tests/cloud_tests/testcases/modules/set_password_list.yaml b/tests/cloud_tests/testcases/modules/set_password_list.yaml
1631index a2a89c9..fd3e1e4 100644
1632--- a/tests/cloud_tests/testcases/modules/set_password_list.yaml
1633+++ b/tests/cloud_tests/testcases/modules/set_password_list.yaml
1634@@ -5,6 +5,7 @@ cloud_config: |
1635 #cloud-config
1636 ssh_pwauth: yes
1637 users:
1638+ - default
1639 - name: tom
1640 # md5 gotomgo
1641 passwd: "$1$S7$tT1BEDIYrczeryDQJfdPe0"
1642diff --git a/tests/cloud_tests/testcases/modules/set_password_list_string.yaml b/tests/cloud_tests/testcases/modules/set_password_list_string.yaml
1643index c2a0f63..e9fe54b 100644
1644--- a/tests/cloud_tests/testcases/modules/set_password_list_string.yaml
1645+++ b/tests/cloud_tests/testcases/modules/set_password_list_string.yaml
1646@@ -5,6 +5,7 @@ cloud_config: |
1647 #cloud-config
1648 ssh_pwauth: yes
1649 users:
1650+ - default
1651 - name: tom
1652 # md5 gotomgo
1653 passwd: "$1$S7$tT1BEDIYrczeryDQJfdPe0"
1654diff --git a/tests/cloud_tests/testcases/modules/ssh_auth_key_fingerprints_disable.py b/tests/cloud_tests/testcases/modules/ssh_auth_key_fingerprints_disable.py
1655index 8222321..e7329d4 100644
1656--- a/tests/cloud_tests/testcases/modules/ssh_auth_key_fingerprints_disable.py
1657+++ b/tests/cloud_tests/testcases/modules/ssh_auth_key_fingerprints_disable.py
1658@@ -13,12 +13,4 @@ class TestSshKeyFingerprintsDisable(base.CloudTestCase):
1659 self.assertIn('Skipping module named ssh-authkey-fingerprints, '
1660 'logging of ssh fingerprints disabled', out)
1661
1662- def test_syslog(self):
1663- """Verify output of syslog."""
1664- out = self.get_data_file('syslog')
1665- self.assertNotRegex(out, r'256 SHA256:.*(ECDSA)')
1666- self.assertNotRegex(out, r'256 SHA256:.*(ED25519)')
1667- self.assertNotRegex(out, r'1024 SHA256:.*(DSA)')
1668- self.assertNotRegex(out, r'2048 SHA256:.*(RSA)')
1669-
1670 # vi: ts=4 expandtab
1671diff --git a/tests/cloud_tests/testcases/modules/ssh_auth_key_fingerprints_disable.yaml b/tests/cloud_tests/testcases/modules/ssh_auth_key_fingerprints_disable.yaml
1672index 746653e..d93893e 100644
1673--- a/tests/cloud_tests/testcases/modules/ssh_auth_key_fingerprints_disable.yaml
1674+++ b/tests/cloud_tests/testcases/modules/ssh_auth_key_fingerprints_disable.yaml
1675@@ -5,7 +5,6 @@ required_features:
1676 - syslog
1677 cloud_config: |
1678 #cloud-config
1679- ssh_genkeytypes: []
1680 no_ssh_fingerprints: true
1681 collect_scripts:
1682 syslog: |
1683diff --git a/tests/cloud_tests/testcases/modules/ssh_keys_generate.py b/tests/cloud_tests/testcases/modules/ssh_keys_generate.py
1684index fd6d9ba..b68f556 100644
1685--- a/tests/cloud_tests/testcases/modules/ssh_keys_generate.py
1686+++ b/tests/cloud_tests/testcases/modules/ssh_keys_generate.py
1687@@ -9,11 +9,6 @@ class TestSshKeysGenerate(base.CloudTestCase):
1688
1689 # TODO: Check cloud-init-output for the correct keys being generated
1690
1691- def test_ubuntu_authorized_keys(self):
1692- """Test passed in key is not in list for ubuntu."""
1693- out = self.get_data_file('auth_keys_ubuntu')
1694- self.assertEqual('', out)
1695-
1696 def test_dsa_public(self):
1697 """Test dsa public key not generated."""
1698 out = self.get_data_file('dsa_public')
1699diff --git a/tests/cloud_tests/testcases/modules/ssh_keys_generate.yaml b/tests/cloud_tests/testcases/modules/ssh_keys_generate.yaml
1700index 659fd93..0a7adf6 100644
1701--- a/tests/cloud_tests/testcases/modules/ssh_keys_generate.yaml
1702+++ b/tests/cloud_tests/testcases/modules/ssh_keys_generate.yaml
1703@@ -10,12 +10,6 @@ cloud_config: |
1704 - ed25519
1705 authkey_hash: sha512
1706 collect_scripts:
1707- auth_keys_root: |
1708- #!/bin/bash
1709- cat /root/.ssh/authorized_keys
1710- auth_keys_ubuntu: |
1711- #!/bin/bash
1712- cat /home/ubuntu/ssh/authorized_keys
1713 dsa_public: |
1714 #!/bin/bash
1715 cat /etc/ssh/ssh_host_dsa_key.pub
1716diff --git a/tests/cloud_tests/testcases/modules/ssh_keys_provided.py b/tests/cloud_tests/testcases/modules/ssh_keys_provided.py
1717index 544649d..add3f46 100644
1718--- a/tests/cloud_tests/testcases/modules/ssh_keys_provided.py
1719+++ b/tests/cloud_tests/testcases/modules/ssh_keys_provided.py
1720@@ -7,17 +7,6 @@ from tests.cloud_tests.testcases import base
1721 class TestSshKeysProvided(base.CloudTestCase):
1722 """Test ssh keys module."""
1723
1724- def test_ubuntu_authorized_keys(self):
1725- """Test passed in key is not in list for ubuntu."""
1726- out = self.get_data_file('auth_keys_ubuntu')
1727- self.assertEqual('', out)
1728-
1729- def test_root_authorized_keys(self):
1730- """Test passed in key is in authorized list for root."""
1731- out = self.get_data_file('auth_keys_root')
1732- self.assertIn('lzrkPqONphoZx0LDV86w7RUz1ksDzAdcm0tvmNRFMN1a0frDs50'
1733- '6oA3aWK0oDk4Nmvk8sXGTYYw3iQSkOvDUUlIsqdaO+w==', out)
1734-
1735 def test_dsa_public(self):
1736 """Test dsa public key passed in."""
1737 out = self.get_data_file('dsa_public')
1738diff --git a/tests/cloud_tests/testcases/modules/ssh_keys_provided.yaml b/tests/cloud_tests/testcases/modules/ssh_keys_provided.yaml
1739index 5ceb362..41f6355 100644
1740--- a/tests/cloud_tests/testcases/modules/ssh_keys_provided.yaml
1741+++ b/tests/cloud_tests/testcases/modules/ssh_keys_provided.yaml
1742@@ -71,12 +71,6 @@ cloud_config: |
1743 -----END EC PRIVATE KEY-----
1744 ecdsa_public: ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBFsS5Tvky/IC/dXhE/afxxUG6kdQOvdQJCYGZN42OZqWasYF+L3IG+3/wrV7jOrNrL3AyagHl6+lpPDiSXDMcpQ= root@xenial-lxd
1745 collect_scripts:
1746- auth_keys_root: |
1747- #!/bin/bash
1748- cat /root/.ssh/authorized_keys
1749- auth_keys_ubuntu: |
1750- #!/bin/bash
1751- cat /home/ubuntu/ssh/authorized_keys
1752 dsa_public: |
1753 #!/bin/bash
1754 cat /etc/ssh/ssh_host_dsa_key.pub
1755diff --git a/tests/cloud_tests/util.py b/tests/cloud_tests/util.py
1756index 4357fbb..c5cd697 100644
1757--- a/tests/cloud_tests/util.py
1758+++ b/tests/cloud_tests/util.py
1759@@ -7,6 +7,7 @@ import copy
1760 import glob
1761 import os
1762 import random
1763+import shlex
1764 import shutil
1765 import string
1766 import subprocess
1767@@ -285,20 +286,165 @@ def shell_pack(cmd):
1768 return 'eval set -- "$(echo %s | base64 --decode)" && exec "$@"' % b64
1769
1770
1771+def shell_quote(cmd):
1772+ if isinstance(cmd, (tuple, list)):
1773+ return ' '.join([shlex.quote(x) for x in cmd])
1774+ return shlex.quote(cmd)
1775+
1776+
1777+class TargetBase(object):
1778+ _tmp_count = 0
1779+
1780+ def execute(self, command, stdin=None, env=None,
1781+ rcs=None, description=None):
1782+ """Execute command in instance, recording output, error and exit code.
1783+
1784+ Assumes functional networking and execution as root with the
1785+ target filesystem being available at /.
1786+
1787+ @param command: the command to execute as root inside the image
1788+ if command is a string, then it will be executed as:
1789+ ['sh', '-c', command]
1790+ @param stdin: bytes content for standard in
1791+ @param env: environment variables
1792+ @param rcs: return codes.
1793+ None (default): non-zero exit code will raise exception.
1794+ False: any is allowed (No execption raised).
1795+ list of int: any rc not in the list will raise exception.
1796+ @param description: purpose of command
1797+ @return_value: tuple containing stdout data, stderr data, exit code
1798+ """
1799+ if isinstance(command, str):
1800+ command = ['sh', '-c', command]
1801+
1802+ if rcs is None:
1803+ rcs = (0,)
1804+
1805+ if description:
1806+ LOG.debug('Executing "%s"', description)
1807+ else:
1808+ LOG.debug("Executing command: %s", shell_quote(command))
1809+
1810+ out, err, rc = self._execute(command=command, stdin=stdin, env=env)
1811+
1812+ # False means accept anything.
1813+ if (rcs is False or rc in rcs):
1814+ return out, err, rc
1815+
1816+ raise InTargetExecuteError(out, err, rc, command, description)
1817+
1818+ def _execute(self, command, stdin=None, env=None):
1819+ """Execute command in inside, return stdout, stderr and exit code.
1820+
1821+ Assumes functional networking and execution as root with the
1822+ target filesystem being available at /.
1823+
1824+ @param stdin: bytes content for standard in
1825+ @param env: environment variables
1826+ @return_value: tuple containing stdout data, stderr data, exit code
1827+
1828+ This is intended to be implemented by the Image or Instance.
1829+ Many callers will use the higher level 'execute'."""
1830+ raise NotImplementedError("_execute must be implemented by subclass.")
1831+
1832+ def read_data(self, remote_path, decode=False):
1833+ """Read data from instance filesystem.
1834+
1835+ @param remote_path: path in instance
1836+ @param decode: decode data before returning.
1837+ @return_value: content of remote_path as bytes if 'decode' is False,
1838+ and as string if 'decode' is True.
1839+ """
1840+ # when sh is invoked with '-c', then the first argument is "$0"
1841+ # which is commonly understood as the "program name".
1842+ # 'read_data' is the program name, and 'remote_path' is '$1'
1843+ stdout, stderr, rc = self._execute(
1844+ ["sh", "-c", 'exec cat "$1"', 'read_data', remote_path])
1845+ if rc != 0:
1846+ raise RuntimeError("Failed to read file '%s'" % remote_path)
1847+
1848+ if decode:
1849+ return stdout.decode()
1850+ return stdout
1851+
1852+ def write_data(self, remote_path, data):
1853+ """Write data to instance filesystem.
1854+
1855+ @param remote_path: path in instance
1856+ @param data: data to write in bytes
1857+ """
1858+ # when sh is invoked with '-c', then the first argument is "$0"
1859+ # which is commonly understood as the "program name".
1860+ # 'write_data' is the program name, and 'remote_path' is '$1'
1861+ _, _, rc = self._execute(
1862+ ["sh", "-c", 'exec cat >"$1"', 'write_data', remote_path],
1863+ stdin=data)
1864+
1865+ if rc != 0:
1866+ raise RuntimeError("Failed to write to '%s'" % remote_path)
1867+ return
1868+
1869+ def pull_file(self, remote_path, local_path):
1870+ """Copy file at 'remote_path', from instance to 'local_path'.
1871+
1872+ @param remote_path: path on remote instance
1873+ @param local_path: path on local instance
1874+ """
1875+ with open(local_path, 'wb') as fp:
1876+ fp.write(self.read_data(remote_path))
1877+
1878+ def push_file(self, local_path, remote_path):
1879+ """Copy file at 'local_path' to instance at 'remote_path'.
1880+
1881+ @param local_path: path on local instance
1882+ @param remote_path: path on remote instance"""
1883+ with open(local_path, "rb") as fp:
1884+ self.write_data(remote_path, data=fp.read())
1885+
1886+ def run_script(self, script, rcs=None, description=None):
1887+ """Run script in target and return stdout.
1888+
1889+ @param script: script contents
1890+ @param rcs: allowed return codes from script
1891+ @param description: purpose of script
1892+ @return_value: stdout from script
1893+ """
1894+ # Just write to a file, add execute, run it, then remove it.
1895+ shblob = '; '.join((
1896+ 'set -e',
1897+ 's="$1"',
1898+ 'shift',
1899+ 'cat > "$s"',
1900+ 'trap "rm -f $s" EXIT',
1901+ 'chmod +x "$s"',
1902+ '"$s" "$@"'))
1903+ return self.execute(
1904+ ['sh', '-c', shblob, 'runscript', self.tmpfile()],
1905+ stdin=script, description=description, rcs=rcs)
1906+
1907+ def tmpfile(self):
1908+ """Get a tmp file in the target.
1909+
1910+ @return_value: path to new file in target
1911+ """
1912+ path = "/tmp/%s-%04d" % (type(self).__name__, self._tmp_count)
1913+ self._tmp_count += 1
1914+ return path
1915+
1916+
1917 class InTargetExecuteError(c_util.ProcessExecutionError):
1918 """Error type for in target commands that fail."""
1919
1920- default_desc = 'Unexpected error while running command in target instance'
1921+ default_desc = 'Unexpected error while running command.'
1922
1923- def __init__(self, stdout, stderr, exit_code, cmd, instance,
1924- description=None):
1925+ def __init__(self, stdout, stderr, exit_code, cmd, description=None,
1926+ reason=None):
1927 """Init error and parent error class."""
1928- if isinstance(cmd, (tuple, list)):
1929- cmd = ' '.join(cmd)
1930 super(InTargetExecuteError, self).__init__(
1931- stdout=stdout, stderr=stderr, exit_code=exit_code, cmd=cmd,
1932- reason="Instance: {}".format(instance),
1933- description=description if description else self.default_desc)
1934+ stdout=stdout, stderr=stderr, exit_code=exit_code,
1935+ cmd=shell_quote(cmd),
1936+ description=description if description else self.default_desc,
1937+ reason=reason)
1938
1939
1940 class TempDir(object):
1941diff --git a/tests/unittests/test_data.py b/tests/unittests/test_data.py
1942index 6d621d2..275b16d 100644
1943--- a/tests/unittests/test_data.py
1944+++ b/tests/unittests/test_data.py
1945@@ -18,6 +18,8 @@ from email.mime.application import MIMEApplication
1946 from email.mime.base import MIMEBase
1947 from email.mime.multipart import MIMEMultipart
1948
1949+import httpretty
1950+
1951 from cloudinit import handlers
1952 from cloudinit import helpers as c_helpers
1953 from cloudinit import log
1954@@ -522,6 +524,54 @@ c: 4
1955 self.assertEqual(cfg.get('password'), 'gocubs')
1956 self.assertEqual(cfg.get('locale'), 'chicago')
1957
1958+ @httpretty.activate
1959+ @mock.patch('cloudinit.url_helper.time.sleep')
1960+ def test_include(self, mock_sleep):
1961+ """Test #include."""
1962+ included_url = 'http://hostname/path'
1963+ included_data = '#cloud-config\nincluded: true\n'
1964+ httpretty.register_uri(httpretty.GET, included_url, included_data)
1965+
1966+ blob = '#include\n%s\n' % included_url
1967+
1968+ self.reRoot()
1969+ ci = stages.Init()
1970+ ci.datasource = FakeDataSource(blob)
1971+ ci.fetch()
1972+ ci.consume_data()
1973+ cc_contents = util.load_file(ci.paths.get_ipath("cloud_config"))
1974+ cc = util.load_yaml(cc_contents)
1975+ self.assertTrue(cc.get('included'))
1976+
1977+ @httpretty.activate
1978+ @mock.patch('cloudinit.url_helper.time.sleep')
1979+ def test_include_bad_url(self, mock_sleep):
1980+ """Test #include with a bad URL."""
1981+ bad_url = 'http://bad/forbidden'
1982+ bad_data = '#cloud-config\nbad: true\n'
1983+ httpretty.register_uri(httpretty.GET, bad_url, bad_data, status=403)
1984+
1985+ included_url = 'http://hostname/path'
1986+ included_data = '#cloud-config\nincluded: true\n'
1987+ httpretty.register_uri(httpretty.GET, included_url, included_data)
1988+
1989+ blob = '#include\n%s\n%s' % (bad_url, included_url)
1990+
1991+ self.reRoot()
1992+ ci = stages.Init()
1993+ ci.datasource = FakeDataSource(blob)
1994+ log_file = self.capture_log(logging.WARNING)
1995+ ci.fetch()
1996+ ci.consume_data()
1997+
1998+ self.assertIn("403 Client Error: Forbidden for url: %s" % bad_url,
1999+ log_file.getvalue())
2000+
2001+ cc_contents = util.load_file(ci.paths.get_ipath("cloud_config"))
2002+ cc = util.load_yaml(cc_contents)
2003+ self.assertIsNone(cc.get('bad'))
2004+ self.assertTrue(cc.get('included'))
2005+
2006
2007 class TestUDProcess(helpers.ResourceUsingTestCase):
2008
2009diff --git a/tests/unittests/test_datasource/test_ec2.py b/tests/unittests/test_datasource/test_ec2.py
2010index 6af699a..ba328ee 100644
2011--- a/tests/unittests/test_datasource/test_ec2.py
2012+++ b/tests/unittests/test_datasource/test_ec2.py
2013@@ -307,6 +307,39 @@ class TestEc2(test_helpers.HttprettyTestCase):
2014
2015 @httpretty.activate
2016 @mock.patch('cloudinit.net.dhcp.maybe_perform_dhcp_discovery')
2017+ def test_network_config_cached_property_refreshed_on_upgrade(self, m_dhcp):
2018+ """Refresh the network_config Ec2 cache if network key is absent.
2019+
2020+ This catches an upgrade issue where obj.pkl contained stale metadata
2021+ which lacked newly required network key.
2022+ """
2023+ old_metadata = copy.deepcopy(DEFAULT_METADATA)
2024+ old_metadata.pop('network')
2025+ ds = self._setup_ds(
2026+ platform_data=self.valid_platform_data,
2027+ sys_cfg={'datasource': {'Ec2': {'strict_id': True}}},
2028+ md=old_metadata)
2029+ self.assertTrue(ds.get_data())
2030+ # Provide new revision of metadata that contains network data
2031+ register_mock_metaserver(
2032+ 'http://169.254.169.254/2009-04-04/meta-data/', DEFAULT_METADATA)
2033+ mac1 = '06:17:04:d7:26:09' # Defined in DEFAULT_METADATA
2034+ get_interface_mac_path = (
2035+ 'cloudinit.sources.DataSourceEc2.net.get_interface_mac')
2036+ ds.fallback_nic = 'eth9'
2037+ with mock.patch(get_interface_mac_path) as m_get_interface_mac:
2038+ m_get_interface_mac.return_value = mac1
2039+ ds.network_config # Will re-crawl network metadata
2040+ self.assertIn('Re-crawl of metadata service', self.logs.getvalue())
2041+ expected = {'version': 1, 'config': [
2042+ {'mac_address': '06:17:04:d7:26:09',
2043+ 'name': 'eth9',
2044+ 'subnets': [{'type': 'dhcp4'}, {'type': 'dhcp6'}],
2045+ 'type': 'physical'}]}
2046+ self.assertEqual(expected, ds.network_config)
2047+
2048+ @httpretty.activate
2049+ @mock.patch('cloudinit.net.dhcp.maybe_perform_dhcp_discovery')
2050 def test_valid_platform_with_strict_true(self, m_dhcp):
2051 """Valid platform data should return true with strict_id true."""
2052 ds = self._setup_ds(
2053diff --git a/tests/unittests/test_handler/test_handler_etc_hosts.py b/tests/unittests/test_handler/test_handler_etc_hosts.py
2054new file mode 100644
2055index 0000000..ced05a8
2056--- /dev/null
2057+++ b/tests/unittests/test_handler/test_handler_etc_hosts.py
2058@@ -0,0 +1,69 @@
2059+# This file is part of cloud-init. See LICENSE file for license information.
2060+
2061+from cloudinit.config import cc_update_etc_hosts
2062+
2063+from cloudinit import cloud
2064+from cloudinit import distros
2065+from cloudinit import helpers
2066+from cloudinit import util
2067+
2068+from cloudinit.tests import helpers as t_help
2069+
2070+import logging
2071+import os
2072+import shutil
2073+
2074+LOG = logging.getLogger(__name__)
2075+
2076+
2077+class TestHostsFile(t_help.FilesystemMockingTestCase):
2078+ def setUp(self):
2079+ super(TestHostsFile, self).setUp()
2080+ self.tmp = self.tmp_dir()
2081+
2082+ def _fetch_distro(self, kind):
2083+ cls = distros.fetch(kind)
2084+ paths = helpers.Paths({})
2085+ return cls(kind, {}, paths)
2086+
2087+ def test_write_etc_hosts_suse_localhost(self):
2088+ cfg = {
2089+ 'manage_etc_hosts': 'localhost',
2090+ 'hostname': 'cloud-init.test.us'
2091+ }
2092+ os.makedirs('%s/etc/' % self.tmp)
2093+ hosts_content = '192.168.1.1 blah.blah.us blah\n'
2094+ fout = open('%s/etc/hosts' % self.tmp, 'w')
2095+ fout.write(hosts_content)
2096+ fout.close()
2097+ distro = self._fetch_distro('sles')
2098+ distro.hosts_fn = '%s/etc/hosts' % self.tmp
2099+ paths = helpers.Paths({})
2100+ ds = None
2101+ cc = cloud.Cloud(ds, paths, {}, distro, None)
2102+ self.patchUtils(self.tmp)
2103+ cc_update_etc_hosts.handle('test', cfg, cc, LOG, [])
2104+ contents = util.load_file('%s/etc/hosts' % self.tmp)
2105+ if '127.0.0.1\tcloud-init.test.us\tcloud-init' not in contents:
2106+ self.assertIsNone('No entry for 127.0.0.1 in etc/hosts')
2107+ if '192.168.1.1\tblah.blah.us\tblah' not in contents:
2108+ self.assertIsNone('Default etc/hosts content modified')
2109+
2110+ def test_write_etc_hosts_suse_template(self):
2111+ cfg = {
2112+ 'manage_etc_hosts': 'template',
2113+ 'hostname': 'cloud-init.test.us'
2114+ }
2115+ shutil.copytree('templates', '%s/etc/cloud/templates' % self.tmp)
2116+ distro = self._fetch_distro('sles')
2117+ paths = helpers.Paths({})
2118+ paths.template_tpl = '%s' % self.tmp + '/etc/cloud/templates/%s.tmpl'
2119+ ds = None
2120+ cc = cloud.Cloud(ds, paths, {}, distro, None)
2121+ self.patchUtils(self.tmp)
2122+ cc_update_etc_hosts.handle('test', cfg, cc, LOG, [])
2123+ contents = util.load_file('%s/etc/hosts' % self.tmp)
2124+ if '127.0.0.1 cloud-init.test.us cloud-init' not in contents:
2125+ self.assertIsNone('No entry for 127.0.0.1 in etc/hosts')
2126+ if '::1 cloud-init.test.us cloud-init' not in contents:
2127+ self.assertIsNone('No entry for 127.0.0.1 in etc/hosts')
2128diff --git a/tests/unittests/test_handler/test_handler_ntp.py b/tests/unittests/test_handler/test_handler_ntp.py
2129index 3abe578..28a8455 100644
2130--- a/tests/unittests/test_handler/test_handler_ntp.py
2131+++ b/tests/unittests/test_handler/test_handler_ntp.py
2132@@ -430,5 +430,31 @@ class TestNtp(FilesystemMockingTestCase):
2133 "[Time]\nNTP=192.168.2.1 192.168.2.2 0.mypool.org \n",
2134 content.decode())
2135
2136+ def test_write_ntp_config_template_defaults_pools_empty_lists_sles(self):
2137+ """write_ntp_config_template defaults pools servers upon empty config.
2138+
2139+ When both pools and servers are empty, default NR_POOL_SERVERS get
2140+ configured.
2141+ """
2142+ distro = 'sles'
2143+ mycloud = self._get_cloud(distro)
2144+ ntp_conf = self.tmp_path('ntp.conf', self.new_root) # Doesn't exist
2145+ # Create ntp.conf.tmpl
2146+ with open('{0}.tmpl'.format(ntp_conf), 'wb') as stream:
2147+ stream.write(NTP_TEMPLATE)
2148+ with mock.patch('cloudinit.config.cc_ntp.NTP_CONF', ntp_conf):
2149+ cc_ntp.write_ntp_config_template({}, mycloud, ntp_conf)
2150+ content = util.read_file_or_url('file://' + ntp_conf).contents
2151+ default_pools = [
2152+ "{0}.opensuse.pool.ntp.org".format(x)
2153+ for x in range(0, cc_ntp.NR_POOL_SERVERS)]
2154+ self.assertEqual(
2155+ "servers []\npools {0}\n".format(default_pools),
2156+ content.decode())
2157+ self.assertIn(
2158+ "Adding distro default ntp pool servers: {0}".format(
2159+ ",".join(default_pools)),
2160+ self.logs.getvalue())
2161+
2162
2163 # vi: ts=4 expandtab
2164diff --git a/tests/unittests/test_rh_subscription.py b/tests/unittests/test_rh_subscription.py
2165index e9d5702..2271810 100644
2166--- a/tests/unittests/test_rh_subscription.py
2167+++ b/tests/unittests/test_rh_subscription.py
2168@@ -2,6 +2,7 @@
2169
2170 """Tests for registering RHEL subscription via rh_subscription."""
2171
2172+import copy
2173 import logging
2174
2175 from cloudinit.config import cc_rh_subscription
2176@@ -68,6 +69,20 @@ class GoodTests(TestCase):
2177 self.assertEqual(self.SM.log_success.call_count, 1)
2178 self.assertEqual(self.SM._sub_man_cli.call_count, 2)
2179
2180+ @mock.patch.object(cc_rh_subscription.SubscriptionManager, "_getRepos")
2181+ @mock.patch.object(cc_rh_subscription.SubscriptionManager, "_sub_man_cli")
2182+ def test_update_repos_disable_with_none(self, m_sub_man_cli, m_get_repos):
2183+ cfg = copy.deepcopy(self.config)
2184+ m_get_repos.return_value = ([], ['repo1'])
2185+ m_sub_man_cli.return_value = (b'', b'')
2186+ cfg['rh_subscription'].update(
2187+ {'enable-repo': ['repo1'], 'disable-repo': None})
2188+ mysm = cc_rh_subscription.SubscriptionManager(cfg)
2189+ self.assertEqual(True, mysm.update_repos())
2190+ m_get_repos.assert_called_with()
2191+ self.assertEqual(m_sub_man_cli.call_args_list,
2192+ [mock.call(['repos', '--enable=repo1'])])
2193+
2194 def test_full_registration(self):
2195 '''
2196 Registration with auto-attach, service-level, adding pools,

Subscribers

People subscribed via source and target branches