summaryrefslogtreecommitdiff
path: root/tests/unittests
AgeCommit message (Collapse)Author
2019-03-04net: append type:dhcp[46] only if dhcp[46] is True in v2 netconfigKurt Stieger
When providing netplan configuration to cloud-init, the internal network state would enable DHCP if the 'dhcp' key was present in the source config. In netplan, dhcp[46] is a boolean and the value of the boolean should control whether DHCP is enabled rather than the presence of the key. This issue leaded to inconsistant sysconfig/network-scripts on fedora. 'BOOTPROTO' was always 'dhcp', even if the address config was static. After this change a dhcp subnet is added only if the 'dhcp' setting in source cfg dict is True. LP: #1818032
2019-02-26tests: fix some slow tests and some leaking stateDaniel Watkins
In test_ds_identify, don't mutate otherwise-static test data. When running tests in a random order, this was causing failures due to breaking preconditions for other tests. In tests/helpers, reset logging level in tearDown. Some of the CLI tests set the level of the root logger in a way that isn't correctly reset. For test_poll_imds_re_dhcp_on_timeout and test_dhcp_discovery_run_in_sandbox_warns_invalid_pid, mock out time.sleep; this saves ~11 seconds (or ~40% of previous test time!).
2019-02-25Enable encrypted_data_bag_secret support for ChefEric Williams
Encrypted data bags require a secrets file to be present to decrypt, and the location of the file must be configured the Chef client configuration file, client.rb. This update enables cloud-init's chef module to update that setting in client.rb. LP: #1817082
2019-02-22azure: Filter list of ssh keys pulled from fabricJason Zions (MSFT)
The Azure data source is expected to expose a list of ssh keys for the user-to-be-provisioned in the crawled metadata. When configured to use the __builtin__ agent this list is built by the WALinuxAgentShim. The shim retrieves the full set of certificates and public keys exposed to the VM from the wireserver, extracts any ssh keys it can, and returns that list. This fix reduces that list of ssh keys to just the ones whose fingerprints appear in the "administrative user" section of the ovf-env.xml file. The Azure control plane exposes other ssh keys to the VM for other reasons, but those should not be added to the authorized_keys file for the provisioned user.
2019-02-14EC2: Rewrite network config on AWS Classic instances every bootGuilherme G. Piccoli
AWS EC2 instances' network come in 2 basic flavors: Classic and VPC (Virtual Private Cloud). The former has an interesting behavior of having its MAC address changed whenever the instance is stopped/restarted. This behavior is not observed in VPC instances. In Ubuntu 18.04 (Bionic) the network "management" changed from ENI-style (etc/network/interfaces) to netplan, and when using netplan we observe the following block present in /etc/netplan/50-cloud-init.yaml: match: macaddress: aa:bb:cc:dd:ee:ff Jani Ollikainen noticed in Launchpad bug #1802073 that the EC2 Classic instances were booting without network access in Bionic after stop/restart procedure, due to their MAC address change behavior. It was narrowed down to the netplan MAC match block, that kept the old MAC address after stopping and restarting an instance, since the network configuration writing happens by default only once in EC2 instances, in the first boot. This patch changes the network configuration write to every boot in EC2 Classic instances, by checking against the "vpc-id" metadata information provided only in the VPC instances - if we don't have this metadata value, cloud-init will rewrite the network configuration file in every boot. This was tested in an EC2 Classic instance and proved to fix the issue; unit tests were also added for the new method is_classic_instance(). LP: #1802073 Reported-by: Jani Ollikainen <jani.ollikainen@ik.fi> Suggested-by: Ryan Harper <ryan.harper@canonical.com> Co-developed-by: Chad Smith <chad.smith@canonical.com> Signed-off-by: Guilherme G. Piccoli <gpiccoli@canonical.com>
2019-02-07netplan: Don't render yaml aliases when dumping netplanRyan Harper
Cloud-init rendered netplan with duplicate aliases if a network config included "global" nameserver/search values. Netplan uses can read yaml files which do use aliaes but cloud-init did not render a single yaml dictionary, instead it combined yaml sections into a single document which sometimes resulted in duplicate aliases being present. This branch introduces a yaml SafeDumper class which can set the 'ignore_aliases' attribute. This is not enabled by default but callers to util.yaml_dumps can pass a boolean to toggle this. The netplan render uses noalias=True and the resulting yaml output does not contain any aliases. LP: #1815051
2019-01-30Resolve flake8 comparison and pycodestyle over-ident issuesParide Legovini
Fixes: - flake8: use ==/!= to compare str, bytes, and int literals - pycodestyle: E117 over-indented
2019-01-28sysconfig: On SUSE, use STARTMODE instead of ONBOOTRobert Schweikert
ONBOOT is not recognized on openSUSE and SUSE Linux Enterprise, add the STARTMODE setting LP: #1799540
2019-01-25lxd: install zfs-linux instead of zfs meta packageJohnson Shi
When using the LXD module cloud-init will attempt to install ZFS if it does not exist on the target system. However instead of installing the `zfsutils-linux` package it attempts to install `zfs` resulting in an error. Ubuntu Xenial (16.04) has zfs meta package, but Bionic (18.04) does not. Use the specific base package instead of zfs meta. Co-authored-by: Michael Skalka <michael.skalka@canonical.com> LP: #1799779
2019-01-23net/sysconfig: do not write a resolv.conf file with only the header.Robert Schweikert
Writing the file with no dns information may prevent distro tools from writing a resolv.conf file with dns information obtained from a dhcp server.
2019-01-18net: Make sysconfig renderer compatible with Network Manager.Eduardo Otubo
The 'sysconfig' renderer is activated if, and only if, there's ifup and ifdown commands present in its search dictonary or the network-scripts configuration files are found. This patch adds a check for Network- Manager configuration file as well. This solution is based on the use of the plugin 'ifcfg-rh' present in Network-Manager and is designed to support Fedora 29 or other distributions that also replaced network-scripts by Network-Manager.
2019-01-15net: Wait for dhclient to daemonize before reading lease fileJason Zions
cloud-init uses dhclient to fetch the DHCP lease so it can extract DHCP options. dhclient creates the leasefile, then writes to it; simply waiting for the leasefile to appear creates a race between dhclient and cloud-init. Instead, wait for dhclient to be parented by init. At that point, we know it has written to the leasefile, so it's safe to copy the file and kill the process. cloud-init creates a temporary directory in which to execute dhclient, and deletes that directory after it has killed the process. If cloud-init abandons waiting for dhclient to daemonize, it will still attempt to delete the temporary directory, but will not report an exception should that attempt fail. LP: #1794399
2018-12-20Scaleway: Support ssh keys provided inside an instance tag.PORTE Loïc
The change here will utilize ssh keys found inside an instance's tag. The tag value must start with 'AUTHORIZED_KEY'.
2018-12-20OVF: simplify expected return values of transport functions.Scott Moser
Transport functions (transport_iso9660 and transport_vmware_guestinfo) would return a tuple of 3 values, but only the first was ever used outside of test. The other values (device and filename) were just ignored. This just simplifies the transport functions to now return content (in string format) or None indicating that the transport was not found.
2018-12-20Vmware: Add support for the com.vmware.guestInfo OVF transport.Scott Moser
This adds support for reading OVF information over the 'com.vmware.guestInfo' tranport. The current implementation requires vmware-rpctool be installed in the system. LP: #1807466
2018-12-11net: render 'metric' values in per-subnet routesRyan Harper
It is possible to have a metric value in a per-subnet route. This is currently missing in all renderers. Update each renderer to emit the correct metric value from the config. LP: #1805871
2018-12-06write_files: add support for appending to files.James Baxter
Add 'append: true' to write_files entries to append 'content' to file specified by 'path' key. This modifies the file open mode to append.
2018-12-03dhclient-hook: cleanups, tests and fix a bug on 'down' event.Scott Moser
I noticed a bug in dhclient_hook on the 'down' event, using 'is' operator rather than '==' (if self.net_action is 'down'). This refactors/simplifies the code a bit for easier testing and adds tests. The reason for the rename of 'action' to 'event' is to just be internally consistent. The word and Namespace 'action' is used by cloud-init main, so it was not really usable here. Also adds a main which can easily be debugged with: CI_DHCP_HOOK_DATA_D=./my.d python -m cloudinit.dhclient_hook up eth0
2018-12-03NoCloud: Allow top level 'network' key in network-config.Scott Moser
NoCloud's 'network-config' file was originally expected to contain network configuration without the top level 'network' key. This was because the file was named 'network-config' so specifying 'network' seemed redundant. However, JuJu is currently providing a top level 'network' config when it tries to disable networking ({"network": {"config": "disabled"}). Other users have also been surprised/confused by the fact that a network config in /etc/cloud/cloud.cfg.d/network.cfg differed from what was expected in 'network-config'. LP: #1798117
2018-12-03ovf: Fix ovf network config generation gateway/routesRyan Harper
Move routes under the nic's subnet rather than use top-level ("global") route config ensuring all net renderers will provide the configured route. Also updated cloudinit/cmd/devel/net_convert.py:  - Add input type 'vmware-imc' for OVF customization config files  - Fix bug when output-type was netplan which invoked netplan   generate/apply and attempted to write to   /etc/netplan/50-cloud-init.yaml instead of joining with the   output directory. LP: #1806103
2018-11-29azure: detect vnet migration via netlink media change eventTamilmani Manoharan
Replace Azure pre-provision polling on IMDS with a blocking call which watches for netlink link state change messages. The media change event happens when a pre-provisioned VM has been activated and is connected to the users virtual network and cloud-init can then resume operation to complete image instantiation.
2018-11-28tests: fix incorrect order of mocks in test_handle_zfs_root.Scott Moser
The order of parameters to test_handle_zfs_root did not match the order of the mocks applied. Thanks to Jason Zions for pointing this out.
2018-11-27OVF: identify label iso9660 filesystems with label 'OVF ENV'.Scott Moser
When deploying an OVA, at least some versions of vmware attach a cdrom with an ISO9660 filesystem label of 'OVF ENV'. This was seen on Vmware vCenter Server, 6.0.0, 2776510. In order to accomplish this we had to change the content of the DI_ISO9660_DEVS variable to be comma delimited rather than space delimited.
2018-11-15azure: _poll_imds only retry on 404. Fail on TimeoutChad Smith
Upon URL timeout, _poll_imds is expected to re-dhcp to get updated IP configuration. We don't want to indefinitely retry because the instance likely has invalid IP configuration. LP: #1803598
2018-11-14resizefs: Prefix discovered devpath with '/dev/' when path does not existIgor Galić
In some environments, like FreeBSD, gpart can return the device basename instead of the full path. If this discovered devpath does not exist and is missing the '/dev/' prefix, add that prefix in an attempt to find the device.
2018-11-13azure: retry imds polling on requests.TimeoutChad Smith
There is an infrequent race when the booting instance can hit the IMDS service before it is fully available. This results in a requests.ConnectTimeout being raised. Azure's retry_callback logic now retries on either 404s or Timeouts. LP:1800223
2018-11-12azure: Accept variation in error msg from mount for ntfs volumesJason Zions
If Azure detects an ntfs filesystem type during mount attempt, it should still report the resource device as reformattable. There are slight differences in error message format on RedHat and SuSE. This patch simplifies the expected error match to work on both distributions. LP: #1799338
2018-11-12azure: fix regression introduced when persisting ephemeral dhcp leaseasakkurr
In commitish 9073951 azure datasource tried to leverage stale DHCP information obtained from EphemeralDHCPv4 context manager to report updated provisioning status to the fabric earlier in the boot process. Unfortunately the stale ephemeral network configuration had already been torn down in preparation to bring up IMDS network config so the report attempt failed on timeout. This branch introduces obtain_lease and clean_network public methods on EphemeralDHCPv4 to allow for setup and teardown of ephemeral network configuration without using a context manager. Azure datasource now uses this to persist ephemeral network configuration across multiple contexts during provisioning to avoid multiple DHCP roundtrips.
2018-11-08tests: ec2 mock missing httpretty user-data and instance-identity routesChad Smith
2018-10-31azure: report ready to fabric after reprovision and reduce loggingasakkurr
When reusing a preprovisioned VM, report ready to Azure fabric as soon as we get the reprovision data and the goal state so that we are not delayed by the cloud-init stage switch, saving 2-3 seconds. Also reduce logging when polling IMDS for reprovision data. LP: #1799594
2018-10-30query: better error when missing read permission on instance-dataChad Smith
Emit a permissions error instead of "Missing instance-data.json" when non-root user doesn't have read-permission on /run/cloud-init/instance-data.json
2018-10-17azure: Add apply_network_config option to disable network from IMDSChad Smith
Azure generates network configuration from the IMDS service and removes any preexisting hotplug network scripts which exist in Azure cloud images. Add a datasource configuration option which allows for writing a default network configuration which sets up dhcp on eth0 and leave the hotplug handling to the cloud-image scripts. To disable network-config from Azure IMDS, add the following to /etc/cloud/cloud.cfg.d/99-azure-no-imds-network.cfg: datasource:   Azure:     apply_network_config: False LP: #1798424
2018-10-09instance-data: Add standard keys platform and subplatform. Refactor ec2.Chad Smith
Add the following instance-data.json standardized keys: * v1._beta_keys: List any v1 keys in beta development, e.g. ['subplatform']. * v1.public_ssh_keys: List of any cloud-provided ssh keys for the instance. * v1.platform: String representing the cloud platform api supporting the datasource. For example: 'ec2' for aws, aliyun and brightbox cloud names. * v1.subplatform: String with more details about the source of the metadata consumed. For example, metadata uri, config drive device path or seed directory. To support the new platform and subplatform standardized instance-data, DataSource and its subclasses grew platform and subplatform attributes. The platform attribute defaults to the lowercase string datasource name at self.dsname. This method is overridden in NoCloud, Ec2 and ConfigDrive datasources. The subplatform attribute calls a _get_subplatform method which will return a string containing a simple slug for subplatform type such as metadata, seed-dir or config-drive followed by a detailed uri, device or directory path where the datasource consumed its configuration. As part of this work, DatasourceEC2 methods _get_data and _crawl_metadata have been refactored for a few reasons: - crawl_metadata is now a read-only operation, persisting no attributes on the datasource instance and returns a dictionary of consumed metadata. - crawl_metadata now closely represents the raw stucture of the ec2 metadata consumed, so that end-users can leverage public ec2 metadata documentation where possible. - crawl_metadata adds a '_metadata_api_version' key to the crawled ds.metadata to advertise what version of EC2's api was consumed by cloud-init. - _get_data now does all the processing of crawl_metadata and saves datasource instance attributes userdata_raw, metadata etc. Additional drive-bys: * unit test rework for test_altcloud and test_azure to simplify mocks and make use of existing util and test_helpers functions.
2018-10-09net: ignore nics that have "zero" mac address.Scott Moser
Previously we explicitly excluded mac address '00:00:00:00:00:00'. But then some nics (tunl0 and sit0) ended up having a mac address like '00:00:00:00'. The change here just ignores all 00[:00[:00...]]. LP: #1796917
2018-09-26lxd: adjust to snap installed lxd.Scott Moser
Relax expectation on path to lxc and lxd. The deb path still does install them in /usr/bin/ but that is overly pedantic. Add a 'lxd waitready' (present since lxd 0.5) to wait until lxd is ready before operating on it.
2018-09-26Add support for Infiniband network interfaces (IPoIB).Mark Goddard
OpenStack ironic references Infiniband interfaces via a 6 byte 'MAC address' formed from bytes 13-15 and 18-20 of interface's hardware address. This address is used as the ethernet_mac_address of Infiniband links in network_data.json in configdrives generated by OpenStack nova. We can use this address to map links in network_data.json to their corresponding interface names. When generating interface configuration files, we need to use the interface's full hardware address as the HWADDR, rather than the 6 byte MAC address provided by network_data.json. This change allows IB interfaces to be referenced in this dual mode - by MAC address and hardware address, depending on the context. Support TYPE=InfiniBand for sysconfig configuration of IB interfaces.
2018-09-20Remove dead-code _write_network distro implementations.Scott Moser
Any distro that has a '_write_nework_config' method should no longer get their _write_network called at all. So lets drop that code and raise a RuntimeError any time we got there. Replace the one caller of 'apply_network' (legacy openstack path) with a call to apply_network_config after converting the ENI to network config.
2018-09-18net_util: ensure static configs have netmask in translate_network resultThomas Berger
If a DataSource provides a network configuration in version 2 and runs on a distro which does not have a network renderer class in use, then the conversion of V2 to eni results in static ip configurations with subnet prefix-length (192.168.23.1/24) rather than explicit netmask value. When sending such a config to net_util.translate_network the resulting dictionary is missing the 'netmask' key for static configured addresses breaking network configurations on multiple distributions. This patch detects static ip configurations using prefix-length and converts the format into the previous 'address' and 'netmask' parts to keep compatibility for these distribtuions until they move to the v2 network configuration. LP: #1792454
2018-09-17tests: Add mock for util.get_hostname.Robert Schweikert
At present the host network settings bleed into the test environment causing the test test_handler_apt_source_v3 to fail if the host has a domain setting other then localdomain. LP: #1792799
2018-09-14OpenStack: Support setting mac address on bond.Fabian Wiesel
Fix a bug where setting of mac address on a bond device was ignored when provided in OpenStack network_config.json. LP: #1682064
2018-09-13OpenStack: support reading of newer versions of metdata.Scott Moser
Mark as supported for reading some newer versions of openstack metadata: 2016-06-30 : Newton one 2016-10-06 : Newton two 2017-02-22 : Ocata 2018-08-27 : Rocky
2018-09-12OpenStack: fix bug causing 'latest' version to be used from network.Scott Moser
Cloud-init was reading a list of versions from the OpenStack metadata service (http://169.254.169.254/openstack/) and attempt to select the newest known supported version. The problem was that the list of versions was not being decoded, so we were comparing a list of bytes (found versions) to a list of strings (known versions). LP: #1792157
2018-09-11user-data: jinja template to render instance-data.json in cloud-configChad Smith
Allow users to provide '## template: jinja' as the first line or their #cloud-config or custom script user-data parts. When this header exists, the cloud-config or script will be rendered as a jinja template. All instance metadata keys and values present in /run/cloud-init/instance-data.json will be available as jinja variables for the template. This means any cloud-config module or script can reference any standardized instance data in templates and scripts. Additionally, any standardized instance-data.json keys scoped below a '<v#>' key will be promoted as a top-level key for ease of reference in templates. This means that '{{ local_hostname }}' is the same as using the latest '{{ v#.local_hostname }}'. Since instance-data is written to /run/cloud-init/instance-data.json, make sure it is persisted across reboots when the cached datasource opject is reloaded. LP: #1791781
2018-09-08config: disable ssh access to a configured user accountChad Smith
Cloud config can now disable ssh access to non-root users. When defining the 'users' list in cloud-configuration a boolean 'ssh_redirect_user: true' can be provided to disable ssh logins for that user. Any ssh 'public-keys' defined in cloud meta-data will be added and disabled in .ssh/authorized_keys. Any attempts to ssh as this user using acceptable ssh keys will be presented with a message like the following: Please login as the user "ubuntu" rather than the user "youruser".
2018-09-05tests: Disallow use of util.subp except for where needed.Scott Moser
In many cases, cloud-init uses 'util.subp' to run a subprocess. This is not really desirable in our unit tests as it makes the tests dependent upon existance of those utilities. The change here is to modify the base test case class (CiTestCase) to raise exception any time subp is called. Then, fix all callers. For cases where subp is necessary or actually desired, we can use it via   a.) context hander CiTestCase.allow_subp(value)   b.) class level self.allowed_subp = value Both cases the value is a list of acceptable executable names that will be called (essentially argv[0]). Some cleanups in AltCloud were done as the code was being updated.
2018-09-05sysconfig: refactor sysconfig to accept distro specific templates pathsRyan Harper
Multiple distros use sysconfig format but have different content and paths to certain files. Update distros to specify these template paths in their renderer_configs dictionary.
2018-08-28VMWare: Fix a network config bug in vm with static IPv4 and no gateway.Pengpeng Sun
The issue is when customize a VM with static IPv4 and without gateway, it will still extend route list and will loop a gateways list which is None. This fix is to make sure when no gateway is here, it will not extend route list. LP: #1766538
2018-08-24logging: Add logging config type hyperv for reporting via Azure KVPAndy Liu
Linux guests can provide information to Hyper-V hosts via KVP. KVP allows the guests to provide any string key-value-pairs back to the host's registry. On linux, kvp communication pools are presented as pool files in /var/lib/hyperv/.kvp_pool_#. The following reporting configuration can enable this kvp reporting in addition to default logging if the pool files exist: reporting:     logging:         type: log     telemetry:         type: hyperv
2018-08-17Add datasource Oracle Compute Infrastructure (OCI).Scott Moser
This adds a Oracle specific datasource that functions with OCI. It is a simplified version of the OpenStack metadata server with support for vendor-data. It does not support the OCI-C (classic) platform. Also here is a move of BrokenMetadata to common 'sources' as this was the third occurrence of that class.
2018-08-17azure: allow azure to generate network configuration from IMDS per boot.Chad Smith
Azure datasource now queries IMDS metadata service for network configuration at link local address http://169.254.169.254/metadata/instance?api-version=2017-12-01. The azure metadata service presents a list of macs and allocated ip addresses associated with this instance. Azure will now also regenerate network configuration on every boot because it subscribes to EventType.BOOT maintenance events as well as the 'first boot' EventType.BOOT_NEW_INSTANCE. For testing add azure-imds --kind to cloud-init devel net_convert tool for debugging IMDS metadata. Also refactor _get_data into 3 discrete methods:   - is_platform_viable: check quickly whether the datasource is     potentially compatible with the platform on which is is running   - crawl_metadata: walk all potential metadata candidates, returning a     structured dict of all metadata and userdata. Raise InvalidMetaData on     error.   - _get_data: call crawl_metadata and process results or error. Cache     instance data on class attributes: metadata, userdata_raw etc.