def _test_get_os_utils(self, mock_load_class, fake_name): os.name = fake_name factory.get_os_utils() if fake_name == 'nt': mock_load_class.assert_called_with( 'cloudbaseinit.osutils.windows.WindowsUtils') elif fake_name == 'posix': mock_load_class.assert_called_with( 'cloudbaseinit.osutils.posix.PosixUtils')
def _test_get_os_utils(self, mock_load_class, fake_name): os.name = fake_name factory.get_os_utils() if fake_name == 'nt': mock_load_class.assert_called_with( 'cloudbaseinit.osutils.windows.WindowsUtils') elif fake_name == 'posix': mock_load_class.assert_called_with( 'cloudbaseinit.osutils.posix.PosixUtils')
def execute(self, service, shared_data): osutils = osutils_factory.get_os_utils() metadata_host_name = service.get_host_name() if not metadata_host_name: LOG.debug('Hostname not found in metadata') return (base.PLUGIN_EXECUTION_DONE, False) metadata_host_name = metadata_host_name.split('.', 1)[0] if (len(metadata_host_name) > NETBIOS_HOST_NAME_MAX_LEN and CONF.netbios_host_name_compatibility): new_host_name = metadata_host_name[:NETBIOS_HOST_NAME_MAX_LEN] LOG.warn('Truncating host name for Netbios compatibility. ' 'Old name: %(metadata_host_name)s, new name: ' '%(new_host_name)s' % {'metadata_host_name': metadata_host_name, 'new_host_name': new_host_name}) else: new_host_name = metadata_host_name new_host_name = re.sub(r'-$', '0', new_host_name) if platform.node().lower() == new_host_name.lower(): LOG.debug("Hostname already set to: %s" % new_host_name) reboot_required = False else: LOG.info("Setting hostname: %s" % new_host_name) osutils.set_host_name(new_host_name) reboot_required = True return (base.PLUGIN_EXECUTION_DONE, reboot_required)
def execute(self, service, shared_data): osutils = osutils_factory.get_os_utils() if not self._check_winrm_service(osutils): return (base.PLUGIN_EXECUTE_ON_NEXT_BOOT, False) winrm_config = winrmconfig.WinRMConfig() winrm_config.set_auth_config(basic=CONF.winrm_enable_basic_auth) cert_manager = x509.CryptoAPICertManager() cert_thumbprint = cert_manager.create_self_signed_cert( self._cert_subject) protocol = winrmconfig.LISTENER_PROTOCOL_HTTPS if winrm_config.get_listener(protocol=protocol): winrm_config.delete_listener(protocol=protocol) winrm_config.create_listener( cert_thumbprint=cert_thumbprint, protocol=protocol) listener_config = winrm_config.get_listener(protocol=protocol) listener_port = listener_config.get("Port") rule_name = "WinRM %s" % protocol osutils.firewall_create_rule(rule_name, listener_port, osutils.PROTOCOL_TCP) return (base.PLUGIN_EXECUTION_DONE, False)
def execute(self, service, shared_data): public_keys = service.get_public_keys() if not public_keys: LOG.debug('Public keys not found in metadata') return (base.PLUGIN_EXECUTION_DONE, False) username = CONF.username osutils = osutils_factory.get_os_utils() user_home = osutils.get_user_home(username) if not user_home: raise exception.CloudbaseInitException("User home directory not found!") LOG.debug("User home: {}".format(user_home)) user_ssh_dir = os.path.join(user_home, '.ssh') if not os.path.exists(user_ssh_dir): os.makedirs(user_ssh_dir) authorized_keys_path = os.path.join(user_ssh_dir, "authorized_keys") LOG.info("Writing SSH public keys in: {}".format(authorized_keys_path)) with open(authorized_keys_path, 'w') as f: for public_key in public_keys: f.write(public_key) # correct permissions osutils.chown(username, username, user_home) return (base.PLUGIN_EXECUTION_DONE, False)
def execute(self, service, shared_data): # TODO(alexpilotti): The username selection logic must be set in the # CreateUserPlugin instead if using CONF.username user_name = shared_data.get(plugin_constant.SHARED_DATA_USERNAME, CONF.username) osutils = osutils_factory.get_os_utils() if osutils.user_exists(user_name): password = self._set_password(service, osutils, user_name, shared_data) if password: LOG.info('Password succesfully updated for user %s' % user_name) # TODO(alexpilotti): encrypt with DPAPI shared_data[plugin_constant.SHARED_DATA_PASSWORD] = password if not service.can_post_password: LOG.info('Cannot set the password in the metadata as it ' 'is not supported by this service') else: self._set_metadata_password(password, service) if service.can_update_password: # If the metadata provider can update the password, the plugin # must run at every boot in order to update the password if # it was changed. return base.PLUGIN_EXECUTE_ON_NEXT_BOOT, False else: return base.PLUGIN_EXECUTION_DONE, False
def process(self, data): """Process the given data received from the cloud-config userdata. It knows to process only lists and dicts. """ if not isinstance(data, (list, dict)): raise exception.CloudbaseInitException( "Can't process the type of data %r" % type(data)) osutils = osutils_factory.get_os_utils() for item in data: if not isinstance(item, dict): continue if not {'name'}.issubset(set(item)): LOG.warning("Missing name key from user information %s", item) continue user_name = item.get('name', None) if not user_name: LOG.warning("Username cannot be empty") continue try: self._create_user(item, osutils) except Exception as ex: LOG.warning( "An error occurred during user '%s' creation: '%s" % (user_name, ex)) return False
def execute(self, service, shared_data): if CONF.ntp_use_dhcp_config: osutils = osutils_factory.get_os_utils() dhcp_hosts = osutils.get_dhcp_hosts_in_use() ntp_option_data = None for (_, dhcp_host) in dhcp_hosts: options_data = dhcp.get_dhcp_options(dhcp_host, [dhcp.OPTION_NTP_SERVERS]) if options_data: ntp_option_data = options_data.get(dhcp.OPTION_NTP_SERVERS) if ntp_option_data: break if not ntp_option_data: LOG.debug("Could not obtain the NTP configuration via DHCP") return (base.PLUGIN_EXECUTE_ON_NEXT_BOOT, False) ntp_hosts = self._unpack_ntp_hosts(ntp_option_data) self.verify_time_service(osutils) osutils.set_ntp_client_config(ntp_hosts) LOG.info('NTP client configured. Server(s): %s' % ntp_hosts) return (base.PLUGIN_EXECUTION_DONE, False)
def execute(self, service, shared_data): public_keys = service.get_public_keys() if not public_keys: LOG.debug('Public keys not found in metadata') return (base.PLUGIN_EXECUTION_DONE, False) username = CONF.username osutils = osutils_factory.get_os_utils() user_home = osutils.get_user_home(username) if not user_home: raise exception.CloudbaseInitException("User profile not found!") LOG.debug("User home: %s" % user_home) user_ssh_dir = os.path.join(user_home, '.ssh') if not os.path.exists(user_ssh_dir): os.makedirs(user_ssh_dir) authorized_keys_path = os.path.join(user_ssh_dir, "authorized_keys") LOG.info("Writing SSH public keys in: %s" % authorized_keys_path) with open(authorized_keys_path, 'w') as f: for public_key in public_keys: f.write(public_key) return (base.PLUGIN_EXECUTION_DONE, False)
def check_metadata_ip_route(metadata_url): ''' Workaround for: https://bugs.launchpad.net/quantum/+bug/1174657 ''' osutils = osutils_factory.get_os_utils() if sys.platform == 'win32' and osutils.check_os_version(6, 0): # 169.254.x.x addresses are not getting routed starting from # Windows Vista / 2008 metadata_netloc = urlparse.urlparse(metadata_url).netloc metadata_host = metadata_netloc.split(':')[0] if metadata_host.startswith("169.254."): if (not osutils.check_static_route_exists(metadata_host) and not check_url(metadata_url)): (interface_index, gateway) = osutils.get_default_gateway() if gateway: try: LOG.debug('Setting gateway for host: %s', metadata_host) osutils.add_static_route(metadata_host, "255.255.255.255", gateway, interface_index, 10) except Exception, ex: # Ignore it LOG.exception(ex)
def _check_existing_route_matches(self, network, netmask, gateway): """Check to make sure a route does not already exist in the ip table""" osutils = osutils_factory.get_os_utils() return len([ r for r in osutils._get_ipv4_routing_table() if r[0] == network and r[1] == netmask and r[2] == gateway ]) > 0
def execute(self, service, shared_data): LOG.debug('OpenMurVDI: executing UserDataAdminPassword Plugin from OpenMurVDI Project') try: user_data = service.get_user_data() except metadata_services_base.NotExistingMetadataException: LOG.info("OpenMurVDI: can't connect to Metadata service") return (base.PLUGIN_EXECUTION_DONE, False) if not user_data: LOG.info("OpenMurVDI: user_data doesn't exist") return (base.PLUGIN_EXECUTION_DONE, False) #user_data = self._check_gzip_compression(user_data) # We have to check the file structure and the password lines = user_data.split('\n') regex = re.compile("password: (.+)$") password = '' for line in lines: mo = regex.match(line) if mo: password = mo.group(1) break # Password contains the password in user_data user_name = CONF.username #LOG.debug("OpenMurVDI: setting password '" + password + "' to user '" + user_name + "'") LOG.debug("OpenMurVDI: setting password from user_data to user '" + user_name + "'") osutils = osutils_factory.get_os_utils() osutils.set_user_password(user_name, password) return (base.PLUGIN_EXECUTION_DONE, False)
def check_metadata_ip_route(metadata_url): #Workaround for: https://bugs.launchpad.net/quantum/+bug/1174657 osutils = osutils_factory.get_os_utils() #TODO: check for FreeBSD if sys.platform == 'win32' and osutils.check_os_version(6, 0): # 169.254.x.x addresses are not getting routed starting from # Windows Vista / 2008 metadata_netloc = parse.urlparse(metadata_url).netloc metadata_host = metadata_netloc.split(':')[0] if metadata_host.startswith("169.254."): if (not osutils.check_static_route_exists(metadata_host) and not check_url(metadata_url)): (interface_index, gateway) = osutils.get_default_gateway() if gateway: try: LOG.debug('Setting gateway for host: %s', metadata_host) osutils.add_static_route(metadata_host, "255.255.255.255", gateway, interface_index, 10) except Exception as ex: # Ignore it LOG.exception(ex)
def execute(self, service, shared_data): user_name = CONF.username shared_data[constants.SHARED_DATA_USERNAME] = user_name osutils = osutils_factory.get_os_utils() password = self._get_password(osutils) if osutils.user_exists(user_name): LOG.info('Setting password for existing user "%s"', user_name) osutils.set_user_password(user_name, password) else: LOG.info('Creating user "%s" and setting password', user_name) self.create_user(user_name, password, osutils) # TODO(alexpilotti): encrypt with DPAPI shared_data[constants.SHARED_DATA_PASSWORD] = password self.post_create_user(user_name, password, osutils) for group_name in CONF.groups: try: osutils.add_user_to_local_group(user_name, group_name) except Exception: LOG.exception('Cannot add user to group "%s"', group_name) return base.PLUGIN_EXECUTION_DONE, False
def execute(self, service, shared_data): reboot_required = False osutils = osutils_factory.get_os_utils() if osutils.is_real_time_clock_utc() != CONF.real_time_clock_utc: osutils.set_real_time_clock_utc(CONF.real_time_clock_utc) LOG.info('RTC set to UTC: %s', CONF.real_time_clock_utc) reboot_required = True if CONF.ntp_enable_service: self.verify_time_service(osutils) LOG.info('NTP client service enabled') if CONF.ntp_use_dhcp_config: dhcp_hosts = osutils.get_dhcp_hosts_in_use() ntp_option_data = None for (_, dhcp_host) in dhcp_hosts: options_data = dhcp.get_dhcp_options(dhcp_host, [dhcp.OPTION_NTP_SERVERS]) if options_data: ntp_option_data = options_data.get(dhcp.OPTION_NTP_SERVERS) if ntp_option_data: break if not ntp_option_data: LOG.debug("Could not obtain the NTP configuration via DHCP") return base.PLUGIN_EXECUTE_ON_NEXT_BOOT, reboot_required ntp_hosts = self._unpack_ntp_hosts(ntp_option_data) osutils.set_ntp_client_config(ntp_hosts) LOG.info('NTP client configured. Server(s): %s' % ntp_hosts) return base.PLUGIN_EXECUTION_DONE, reboot_required
def execute(self, service, shared_data): if CONF.ntp_use_dhcp_config: osutils = osutils_factory.get_os_utils() dhcp_hosts = osutils.get_dhcp_hosts_in_use() ntp_option_data = None for (mac_address, dhcp_host) in dhcp_hosts: options_data = dhcp.get_dhcp_options(dhcp_host, [dhcp.OPTION_NTP_SERVERS]) if options_data: ntp_option_data = options_data.get(dhcp.OPTION_NTP_SERVERS) if ntp_option_data: break if not ntp_option_data: LOG.debug("Could not obtain the NTP configuration via DHCP") return (base.PLUGIN_EXECUTE_ON_NEXT_BOOT, False) # TODO(alexpilotti): support multiple NTP servers ntp_host = socket.inet_ntoa(ntp_option_data[:4]) self._check_w32time_svc_status(osutils) osutils.set_ntp_client_config(ntp_host) LOG.info('NTP client configured. Server: %s' % ntp_host) return (base.PLUGIN_EXECUTION_DONE, False)
def execute(self, service, shared_data): if CONF.ntp_use_dhcp_config: osutils = osutils_factory.get_os_utils() dhcp_hosts = osutils.get_dhcp_hosts_in_use() ntp_option_data = None for (mac_address, dhcp_host) in dhcp_hosts: options_data = dhcp.get_dhcp_options(dhcp_host, [dhcp.OPTION_NTP_SERVERS]) if options_data: ntp_option_data = options_data.get(dhcp.OPTION_NTP_SERVERS) if ntp_option_data: break if not ntp_option_data: LOG.debug("Could not obtain the NTP configuration via DHCP") return (base.PLUGIN_EXECUTE_ON_NEXT_BOOT, False) # TODO(alexpilotti): support multiple NTP servers ntp_host = socket.inet_ntoa(ntp_option_data[:4]) self._check_w32time_svc_status(osutils) osutils.set_ntp_client_config(ntp_host) LOG.info('NTP client configured. Server: %s' % ntp_host) return (base.PLUGIN_EXECUTION_DONE, False)
def execute(self, service, shared_data): osutils = osutils_factory.get_os_utils() metadata_host_name = service.get_host_name() if not metadata_host_name: LOG.debug('Hostname not found in metadata') return (base.PLUGIN_EXECUTION_DONE, False) metadata_host_name = metadata_host_name.split('.', 1)[0] if (len(metadata_host_name) > NETBIOS_HOST_NAME_MAX_LEN and CONF.netbios_host_name_compatibility): new_host_name = metadata_host_name[:NETBIOS_HOST_NAME_MAX_LEN] LOG.warn( 'Truncating host name for Netbios compatibility. ' 'Old name: %(metadata_host_name)s, new name: ' '%(new_host_name)s' % { 'metadata_host_name': metadata_host_name, 'new_host_name': new_host_name }) else: new_host_name = metadata_host_name new_host_name = re.sub(r'-$', '0', new_host_name) if platform.node().lower() == new_host_name.lower(): LOG.debug("Hostname already set to: %s" % new_host_name) reboot_required = False else: LOG.info("Setting hostname: %s" % new_host_name) osutils.set_host_name(new_host_name) reboot_required = True return (base.PLUGIN_EXECUTION_DONE, reboot_required)
def execute(self, service, shared_data): reboot_required = False osutils = osutils_factory.get_os_utils() if osutils.is_real_time_clock_utc() != CONF.real_time_clock_utc: osutils.set_real_time_clock_utc(CONF.real_time_clock_utc) LOG.info('RTC set to UTC: %s', CONF.real_time_clock_utc) reboot_required = True if CONF.ntp_enable_service: self.verify_time_service(osutils) LOG.info('NTP client service enabled') if CONF.ntp_use_dhcp_config: dhcp_hosts = osutils.get_dhcp_hosts_in_use() ntp_option_data = None for (_, _, dhcp_host) in dhcp_hosts: options_data = dhcp.get_dhcp_options(dhcp_host, [dhcp.OPTION_NTP_SERVERS]) if options_data: ntp_option_data = options_data.get(dhcp.OPTION_NTP_SERVERS) if ntp_option_data: break if not ntp_option_data: LOG.debug("Could not obtain the NTP configuration via DHCP") return base.PLUGIN_EXECUTE_ON_NEXT_BOOT, reboot_required ntp_hosts = self._unpack_ntp_hosts(ntp_option_data) osutils.set_ntp_client_config(ntp_hosts) LOG.info('NTP client configured. Server(s): %s' % ntp_hosts) return base.PLUGIN_EXECUTION_DONE, reboot_required
def execute(self, service, shared_data): user_name = CONF.username shared_data[constants.SHARED_DATA_USERNAME] = user_name osutils = osutils_factory.get_os_utils() password = self._get_password(osutils) if osutils.user_exists(user_name): LOG.info('Setting password for existing user "%s"' % user_name) osutils.set_user_password(user_name, password) else: LOG.info('Creating user "%s" and setting password' % user_name) osutils.create_user(user_name, password) # Create a user profile in order for other plugins # to access the user home, etc token = osutils.create_user_logon_session(user_name, password, True) osutils.close_user_logon_session(token) # TODO(alexpilotti): encrypt with DPAPI shared_data[constants.SHARED_DATA_PASSWORD] = password for group_name in CONF.groups: try: osutils.add_user_to_local_group(user_name, group_name) except Exception as ex: LOG.exception(ex) LOG.error('Cannot add user to group "%s"' % group_name) return (base.PLUGIN_EXECUTION_DONE, False)
def execute(self, service, shared_data): user_name = CONF.username shared_data[constants.SHARED_DATA_USERNAME] = user_name osutils = osutils_factory.get_os_utils() password = self._get_password(osutils) if osutils.user_exists(user_name): LOG.info('Setting password for existing user "%s"', user_name) osutils.set_user_password(user_name, password) else: LOG.info('Creating user "%s" and setting password', user_name) self.create_user(user_name, password, osutils) # TODO(alexpilotti): encrypt with DPAPI shared_data[constants.SHARED_DATA_PASSWORD] = password self.post_create_user(user_name, password, osutils) for group_name in CONF.groups: try: osutils.add_user_to_local_group(user_name, group_name) except Exception: LOG.exception('Cannot add user to group "%s"', group_name) return (base.PLUGIN_EXECUTION_DONE, False)
def execute(self, service, shared_data): network_details = service.get_network_details() if not network_details: return (plugin_base.PLUGIN_EXECUTION_DONE, False) address = network_details[0].address netmask = network_details[0].netmask broadcast = network_details[0].broadcast gateway = network_details[0].gateway dnsdomain = None dnsnameservers = network_details[0].dnsnameservers osutils = osutils_factory.get_os_utils() network_adapter_name = CONF.network_adapter if not network_adapter_name: # Get the first available one available_adapters = osutils.get_network_adapters() LOG.debug('available adapters: %s', available_adapters) if not len(available_adapters): raise exception.CloudbaseInitException( "No network adapter available") network_adapter_name = available_adapters[0] LOG.info('Configuring network adapter: \'%s\'' % network_adapter_name) reboot_required = osutils.set_static_network_config( network_adapter_name, address, netmask, broadcast, gateway, dnsdomain, dnsnameservers) return (base.PLUGIN_EXECUTION_DONE, reboot_required)
def execute(self, service, shared_data): # TODO(alexpilotti): The username selection logic must be set in the # CreateUserPlugin instead if using CONF.username user_name = shared_data.get(plugin_constant.SHARED_DATA_USERNAME, CONF.username) osutils = osutils_factory.get_os_utils() if osutils.user_exists(user_name): password = self._set_password(service, osutils, user_name, shared_data) if password: LOG.info('Password succesfully updated for user %s' % user_name) # TODO(alexpilotti): encrypt with DPAPI shared_data[plugin_constant.SHARED_DATA_PASSWORD] = password if not service.can_post_password: LOG.info('Cannot set the password in the metadata as it ' 'is not supported by this service') else: self._set_metadata_password(password, service) if service.can_update_password: # If the metadata provider can update the password, the plugin # must run at every boot in order to update the password if # it was changed. return base.PLUGIN_EXECUTE_ON_NEXT_BOOT, False else: return base.PLUGIN_EXECUTION_DONE, False
def configure_host(self): osutils = osutils_factory.get_os_utils() osutils.wait_for_boot_completion() service = metadata_factory.get_metadata_service() LOG.info('Metadata service loaded: \'%s\'' % service.get_name()) instance_id = service.get_instance_id() LOG.debug('Instance id: %s', instance_id) plugins = plugins_factory.load_plugins() plugins_shared_data = {} reboot_required = False try: for plugin in plugins: if self._check_plugin_os_requirements(osutils, plugin): if self._exec_plugin(osutils, service, plugin, instance_id, plugins_shared_data): reboot_required = True if CONF.allow_reboot: break finally: service.cleanup() if reboot_required and CONF.allow_reboot: try: osutils.reboot() except Exception as ex: LOG.error('reboot failed with error \'%s\'' % ex) elif CONF.stop_service_on_exit: osutils.terminate()
def configure_host(self): osutils = osutils_factory.get_os_utils() osutils.wait_for_boot_completion() service = metadata_factory.get_metadata_service() LOG.info('Metadata service loaded: \'%s\'' % service.get_name()) instance_id = service.get_instance_id() LOG.debug('Instance id: %s', instance_id) plugins = plugins_factory.load_plugins() plugins_shared_data = {} reboot_required = False try: for plugin in plugins: if self._check_plugin_os_requirements(osutils, plugin): if self._exec_plugin(osutils, service, plugin, instance_id, plugins_shared_data): reboot_required = True if CONF.allow_reboot: break finally: service.cleanup() if reboot_required and CONF.allow_reboot: try: osutils.reboot() except Exception as ex: LOG.error('reboot failed with error \'%s\'' % ex) elif CONF.stop_service_on_exit: osutils.terminate()
def execute(self, service, shared_data): network_details = service.get_network_details() if not network_details: return (plugin_base.PLUGIN_EXECUTION_DONE, False) address = network_details[0].address netmask = network_details[0].netmask broadcast = network_details[0].broadcast gateway = network_details[0].gateway dnsdomain = None dnsnameservers = network_details[0].dnsnameservers osutils = osutils_factory.get_os_utils() network_adapter_name = CONF.network_adapter if not network_adapter_name: # Get the first available one available_adapters = osutils.get_network_adapters() LOG.debug('available adapters: %s', available_adapters) if not len(available_adapters): raise exception.CloudbaseInitException( "No network adapter available") network_adapter_name = available_adapters[0] LOG.info('Configuring network adapter: \'%s\'' % network_adapter_name) reboot_required = osutils.set_static_network_config( network_adapter_name, address, netmask, broadcast, gateway, dnsdomain, dnsnameservers) return (base.PLUGIN_EXECUTION_DONE, reboot_required)
def execute(self, service, shared_data): osutils = osutils_factory.get_os_utils() if not self._check_winrm_service(osutils): return (base.PLUGIN_EXECUTE_ON_NEXT_BOOT, False) winrm_config = winrmconfig.WinRMConfig() winrm_config.set_auth_config(basic=CONF.winrm_enable_basic_auth) cert_manager = x509.CryptoAPICertManager() cert_thumbprint = cert_manager.create_self_signed_cert( self._cert_subject) protocol = winrmconfig.LISTENER_PROTOCOL_HTTPS if winrm_config.get_listener(protocol=protocol): winrm_config.delete_listener(protocol=protocol) winrm_config.create_listener(cert_thumbprint=cert_thumbprint, protocol=protocol) listener_config = winrm_config.get_listener(protocol=protocol) listener_port = listener_config.get("Port") rule_name = "WinRM %s" % protocol osutils.firewall_create_rule(rule_name, listener_port, osutils.PROTOCOL_TCP) return (base.PLUGIN_EXECUTION_DONE, False)
def execute(self, service, shared_data): osutils = osutils_factory.get_os_utils() if not self._check_winrm_service(osutils): return base.PLUGIN_EXECUTE_ON_NEXT_BOOT, False listeners_config = self._get_winrm_listeners_config(service) if not listeners_config: LOG.info("No WinRM listener configuration provided") else: with self._check_uac_remote_restrictions(osutils): winrm_config = winrmconfig.WinRMConfig() winrm_config.set_auth_config( basic=CONF.winrm_enable_basic_auth) for listener_config in listeners_config: protocol = listener_config["protocol"].upper() cert_thumb = None if protocol == winrmconfig.LISTENER_PROTOCOL_HTTPS: cert_thumb = listener_config.get( "certificate_thumbprint") if not cert_thumb: cert_thumb = self._create_self_signed_certificate() LOG.info("Configuring WinRM listener for protocol: " "%(protocol)s, certificate thumbprint: " "%(cert_thumb)s", {"protocol": protocol, "cert_thumb": cert_thumb}) self._configure_winrm_listener( osutils, winrm_config, protocol, cert_thumb) return base.PLUGIN_EXECUTION_DONE, False
def _run_slmgr(args): osutils = osutils_factory.get_os_utils() if osutils.check_sysnative_dir_exists(): cscript_dir = osutils.get_sysnative_dir() else: cscript_dir = osutils.get_system32_dir() # Not SYSNATIVE, as it is already executed by a x64 process slmgr_dir = osutils.get_system32_dir() cscript_path = os.path.join(cscript_dir, "cscript.exe") slmgr_path = os.path.join(slmgr_dir, "slmgr.vbs") (out, err, exit_code) = osutils.execute_process( [cscript_path, slmgr_path] + args, shell=False, decode_output=True) if exit_code: raise exception.CloudbaseInitException( 'slmgr.vbs failed with error code %(exit_code)s.\n' 'Output: %(out)s\nError: %(err)s' % { 'exit_code': exit_code, 'out': out, 'err': err }) return out.decode(errors='replace')
def execute(self, service, shared_data): public_keys = service.get_public_keys() if not public_keys: LOG.debug('Public keys not found in metadata') return (base.PLUGIN_EXECUTION_DONE, False) username = CONF.username osutils = osutils_factory.get_os_utils() user_home = osutils.get_user_home(username) if not user_home: raise exception.CloudbaseInitException("User profile not found!") LOG.debug("User home: %s" % user_home) user_ssh_dir = os.path.join(user_home, '.ssh') if not os.path.exists(user_ssh_dir): os.makedirs(user_ssh_dir) authorized_keys_path = os.path.join(user_ssh_dir, "authorized_keys") LOG.info("Writing SSH public keys in: %s" % authorized_keys_path) with open(authorized_keys_path, 'w') as f: for public_key in public_keys: # All public keys are space-stripped. f.write(public_key + "\n") return (base.PLUGIN_EXECUTION_DONE, False)
def execute(self, service, shared_data): osutils = osutils_factory.get_os_utils() if osutils.is_nano_server(): LOG.info("Licensing info and activation are not available on " "Nano Server") else: license_info = self._run_slmgr(osutils, ['/dlv']) LOG.info('Microsoft Windows license info:\n%s' % license_info) reboot_required = False if CONF.activate_windows: if service.get_licensing_info() is not None: licensing_information = service.get_licensing_info() if "kms-server" in licensing_information: LOG.info("Setting KMS server") result = self._run_slmgr( osutils, ["/skms", licensing_information["kms-server"]]) LOG.info("Setting KMS server result:\n%s" % result) if "rearm-instance" in licensing_information: if licensing_information["rearm-instance"]: LOG.info("Rearming license") result = self._run_slmgr(osutils, ["/rearm"]) LOG.info("Rearming result:\n%s" % result) reboot_required = True LOG.info( "Not running the activation anymore, as it will fail after rearming" ) return base.PLUGIN_EXECUTE_ON_NEXT_BOOT, reboot_required LOG.info("Activating Windows") activation_result = self._run_slmgr(osutils, ['/ato']) LOG.debug("Activation result:\n%s" % activation_result) return base.PLUGIN_EXECUTION_DONE, reboot_required
def execute(self, service, shared_data): if CONF.ntp_use_dhcp_config: osutils = osutils_factory.get_os_utils() dhcp_hosts = osutils.get_dhcp_hosts_in_use() ntp_option_data = None for (_, dhcp_host) in dhcp_hosts: options_data = dhcp.get_dhcp_options(dhcp_host, [dhcp.OPTION_NTP_SERVERS]) if options_data: ntp_option_data = options_data.get(dhcp.OPTION_NTP_SERVERS) if ntp_option_data: break if not ntp_option_data: LOG.debug("Could not obtain the NTP configuration via DHCP") return base.PLUGIN_EXECUTE_ON_NEXT_BOOT, False ntp_hosts = self._unpack_ntp_hosts(ntp_option_data) self.verify_time_service(osutils) osutils.set_ntp_client_config(ntp_hosts) LOG.info('NTP client configured. Server(s): %s' % ntp_hosts) return base.PLUGIN_EXECUTION_DONE, False
def __init__(self): super(AzureService, self).__init__(base_url=None) self._enable_retry = True self._goal_state = None self._config_set_drive_path = None self._ovf_env = None self._headers = {"x-ms-guest-agent-name": "cloudbase-init"} self._osutils = osutils_factory.get_os_utils()
def _get_conf_drive_from_vfat(self, target_path): osutils = osutils_factory.get_os_utils() for drive_path in osutils.get_physical_disks(): if vfat.is_vfat_drive(osutils, drive_path): LOG.info('Config Drive found on disk %r', drive_path) os.makedirs(target_path) vfat.copy_from_vfat_drive(osutils, drive_path, target_path) return True
def execute(self, service, shared_data): osutils = osutils_factory.get_os_utils() password = self._get_password(osutils) LOG.info('Scrambling root password') osutils.set_user_password('root', password) return (base.PLUGIN_EXECUTION_DONE, False)
def execute(self, service, shared_data): osutils = osutils_factory.get_os_utils() password = self._get_password(osutils) LOG.info('Scrambling root password') osutils.set_user_password('root', password) return (base.PLUGIN_EXECUTION_DONE, False)
def __init__(self): super(AzureService, self).__init__(base_url=None) self._enable_retry = True self._goal_state = None self._config_set_drive_path = None self._ovf_env = None self._headers = {"x-ms-guest-agent-name": "cloudbase-init"} self._osutils = osutils_factory.get_os_utils()
def _get_conf_drive_from_vfat(self, target_path): osutils = osutils_factory.get_os_utils() for drive_path in osutils.get_physical_disks(): if vfat.is_vfat_drive(osutils, drive_path): LOG.info('Config Drive found on disk %r', drive_path) os.makedirs(target_path) vfat.copy_from_vfat_drive(osutils, drive_path, target_path) return True
def _run_bcdedit(bcdedit_args): args = ["bcdedit.exe"] + bcdedit_args osutils = osutils_factory.get_os_utils() (out, err, ret_val) = osutils.execute_system32_process(args) if ret_val: raise exception.CloudbaseInitException( 'bcdedit failed.\nOutput: %(out)s\nError:' ' %(err)s' % {'out': out, 'err': err})
def execute(self, service, shared_data): user_name, password = self._get_credentials(service, shared_data) certs_data = service.get_client_auth_certs() if not certs_data: LOG.info("WinRM certificate authentication cannot be configured " "as a certificate has not been provided in the metadata") return base.PLUGIN_EXECUTION_DONE, False osutils = osutils_factory.get_os_utils() security_utils = security.WindowsSecurityUtils() # On Windows Vista, 2008, 2008 R2 and 7, changing the configuration of # the winrm service will fail with an "Access is denied" error if the # User Account Control remote restrictions are enabled. # The solution to this issue is to temporarily disable the User Account # Control remote restrictions. # https://support.microsoft.com/kb/951016 disable_uac_remote_restrictions = (osutils.check_os_version(6, 0) and not osutils.check_os_version(6, 2) and security_utils .get_uac_remote_restrictions()) try: if disable_uac_remote_restrictions: LOG.debug("Disabling UAC remote restrictions") security_utils.set_uac_remote_restrictions(enable=False) winrm_config = winrmconfig.WinRMConfig() winrm_config.set_auth_config(certificate=True) for cert_data in certs_data: cert_manager = x509.CryptoAPICertManager() cert_thumprint, cert_upn = cert_manager.import_cert( cert_data, store_name=x509.STORE_NAME_ROOT) if not cert_upn: LOG.error("WinRM certificate authentication cannot be " "configured as the provided certificate lacks a " "subject alt name containing an UPN (OID " "1.3.6.1.4.1.311.20.2.3)") continue if winrm_config.get_cert_mapping(cert_thumprint, cert_upn): winrm_config.delete_cert_mapping(cert_thumprint, cert_upn) LOG.info("Creating WinRM certificate mapping for user " "%(user_name)s with UPN %(cert_upn)s", {'user_name': user_name, 'cert_upn': cert_upn}) winrm_config.create_cert_mapping(cert_thumprint, cert_upn, user_name, password) finally: if disable_uac_remote_restrictions: LOG.debug("Enabling UAC remote restrictions") security_utils.set_uac_remote_restrictions(enable=True) return base.PLUGIN_EXECUTION_DONE, False
def execute(self, service, shared_data): user_name, password = self._get_credentials(service, shared_data) certs_data = service.get_client_auth_certs() if not certs_data: LOG.info("WinRM certificate authentication cannot be configured " "as a certificate has not been provided in the metadata") return base.PLUGIN_EXECUTION_DONE, False osutils = osutils_factory.get_os_utils() security_utils = security.WindowsSecurityUtils() # On Windows Vista, 2008, 2008 R2 and 7, changing the configuration of # the winrm service will fail with an "Access is denied" error if the # User Account Control remote restrictions are enabled. # The solution to this issue is to temporarily disable the User Account # Control remote restrictions. # https://support.microsoft.com/kb/951016 disable_uac_remote_restrictions = (osutils.check_os_version(6, 0) and not osutils.check_os_version(6, 2) and security_utils .get_uac_remote_restrictions()) try: if disable_uac_remote_restrictions: LOG.debug("Disabling UAC remote restrictions") security_utils.set_uac_remote_restrictions(enable=False) winrm_config = winrmconfig.WinRMConfig() winrm_config.set_auth_config(certificate=True) for cert_data in certs_data: cert_manager = x509.CryptoAPICertManager() cert_thumprint, cert_upn = cert_manager.import_cert( cert_data, store_name=x509.STORE_NAME_ROOT) if not cert_upn: LOG.error("WinRM certificate authentication cannot be " "configured as the provided certificate lacks a " "subject alt name containing an UPN (OID " "1.3.6.1.4.1.311.20.2.3)") continue if winrm_config.get_cert_mapping(cert_thumprint, cert_upn): winrm_config.delete_cert_mapping(cert_thumprint, cert_upn) LOG.info("Creating WinRM certificate mapping for user " "%(user_name)s with UPN %(cert_upn)s", {'user_name': user_name, 'cert_upn': cert_upn}) winrm_config.create_cert_mapping(cert_thumprint, cert_upn, user_name, password) finally: if disable_uac_remote_restrictions: LOG.debug("Enabling UAC remote restrictions") security_utils.set_uac_remote_restrictions(enable=True) return base.PLUGIN_EXECUTION_DONE, False
def __init__(self): super(CloudStack, self).__init__( # Note(alexcoman): The base url used by the current metadata # service will be updated later by the `_test_api` method. base_url=None, https_allow_insecure=CONF.cloudstack.https_allow_insecure, https_ca_bundle=CONF.cloudstack.https_ca_bundle) self._osutils = osutils_factory.get_os_utils() self._metadata_host = None
def __init__(self): super(CloudStack, self).__init__( # Note(alexcoman): The base url used by the current metadata # service will be updated later by the `_test_api` method. base_url=None, https_allow_insecure=CONF.cloudstack.https_allow_insecure, https_ca_bundle=CONF.cloudstack.https_ca_bundle) LOG.info('Init CloudStack') self._osutils = osutils_factory.get_os_utils() self._metadata_host = None
def _process_network_details_v2(network_details): osutils = osutils_factory.get_os_utils() NetworkConfigPlugin._process_physical_links(osutils, network_details) NetworkConfigPlugin._process_bond_links(osutils, network_details) NetworkConfigPlugin._process_vlan_links(osutils, network_details) reboot_required = NetworkConfigPlugin._process_networks( osutils, network_details) return plugin_base.PLUGIN_EXECUTION_DONE, reboot_required
def _run_bcdedit(bcdedit_args): args = ["bcdedit.exe"] + bcdedit_args osutils = osutils_factory.get_os_utils() (out, err, ret_val) = osutils.execute_system32_process(args) if ret_val: raise exception.CloudbaseInitException( 'bcdedit failed.\nOutput: %(out)s\nError:' ' %(err)s' % { 'out': out, 'err': err })
def _get_config_drive_cdrom_mount_point(self): osutils = osutils_factory.get_os_utils() for drive in osutils.get_cdrom_drives(): label = osutils.get_volume_label(drive) if label == "config-2" and \ os.path.exists(os.path.join(drive, 'openstack\\latest\\' 'meta_data.json')): return drive return None
def _get_config_drive_cdrom_mount_point(self): osutils = osutils_factory.get_os_utils() for drive in osutils.get_cdrom_drives(): label = osutils.get_volume_label(drive) if label == "config-2" and \ os.path.exists(os.path.join(drive, 'openstack\\latest\\' 'meta_data.json')): return drive return None
def get_volume_activation_product_key(self, license_family, vol_act_type=constant.VOL_ACT_KMS): osutils = osutils_factory.get_os_utils() os_version = osutils.get_os_version() os_major = os_version["major_version"] os_minor = os_version["minor_version"] product_keys_map = productkeys.SKU_TO_PRODUCT_KEY_MAP.get( (os_major, os_minor, vol_act_type), {}) return product_keys_map.get(license_family)
def process(self, data): ntp_servers = [] ntp_servers.extend(data.get('servers', [])) ntp_servers.extend(data.get('pools', [])) if data.get('enabled', True) and ntp_servers: LOG.info("Changing NTP servers to %s." % ntp_servers) osutils = factory.get_os_utils() osutils.set_ntp_client_config(ntp_servers) return False
def execute(self, service, shared_data): osutils = osutils_factory.get_os_utils() metadata_host_name = service.get_host_name() if not metadata_host_name: LOG.debug('Hostname not found in metadata') # In FreeBSD, hostname means FQDN, so no split is needed osutils.set_host_name(metadata_host_name) return (base.PLUGIN_EXECUTION_DONE, False)
def execute(self, service, shared_data): osutils = osutils_factory.get_os_utils() metadata_host_name = service.get_host_name() if not metadata_host_name: LOG.debug('Hostname not found in metadata') # In FreeBSD, hostname means FQDN, so no split is needed osutils.set_host_name(metadata_host_name) return (base.PLUGIN_EXECUTION_DONE, False)
def _process_network_details_v2(network_details): osutils = osutils_factory.get_os_utils() NetworkConfigPlugin._process_physical_links( osutils, network_details) NetworkConfigPlugin._process_bond_links(osutils, network_details) NetworkConfigPlugin._process_vlan_links(osutils, network_details) reboot_required = NetworkConfigPlugin._process_networks( osutils, network_details) return plugin_base.PLUGIN_EXECUTION_DONE, reboot_required
def execute(self, service, shared_data): network_config = service.get_network_config() if not network_config: return (base.PLUGIN_EXECUTION_DONE, False) if 'content_path' not in network_config: return (base.PLUGIN_EXECUTION_DONE, False) content_path = network_config['content_path'] content_name = content_path.rsplit('/', 1)[-1] debian_network_conf = service.get_content(content_name) LOG.debug('network config content:\n%s' % debian_network_conf) # TODO(alexpilotti): implement a proper grammar if debian_network_conf: debian_network_conf = debian_network_conf.decode(encoding='utf-8') m = re.search( r'iface eth0 inet static\s+' r'address\s+(?P<address>[^\s]+)\s+' r'netmask\s+(?P<netmask>[^\s]+)\s+' r'broadcast\s+(?P<broadcast>[^\s]+)\s+' r'gateway\s+(?P<gateway>[^\s]+)\s+' r'dns\-nameservers\s+(?P<dnsnameservers>[^\r\n]+)\s+', debian_network_conf) if not m: raise exception.CloudbaseInitException( "network_config format not recognized") address = m.group('address') netmask = m.group('netmask') broadcast = m.group('broadcast') gateway = m.group('gateway') dnsnameservers = m.group('dnsnameservers').strip().split(' ') osutils = osutils_factory.get_os_utils() network_adapter_name = CONF.network_adapter if not network_adapter_name: # Get the first available one available_adapters = osutils.get_network_adapters() if not len(available_adapters): raise exception.CloudbaseInitException( "No network adapter available") network_adapter_name = available_adapters[0] LOG.info('Configuring network adapter: \'%s\'' % network_adapter_name) reboot_required = osutils.set_static_network_config( network_adapter_name, address, netmask, broadcast, gateway, dnsnameservers) return (base.PLUGIN_EXECUTION_DONE, reboot_required)
def execute(self, service, shared_data): osutils = osutils_factory.get_os_utils() metadata_host_name = service.get_host_name() if not metadata_host_name: LOG.debug("Hostname not found in metadata") return base.PLUGIN_EXECUTION_DONE, False (_, reboot_required) = hostname.set_hostname(osutils, metadata_host_name) return base.PLUGIN_EXECUTION_DONE, reboot_required
def _delete_static_route(self, network): """Delete a route from the operating system.""" try: osutils = osutils_factory.get_os_utils() LOG.debug('Deleting route for network: %s', network) args = ['ROUTE', 'DELETE', network] (out, err, ret_val) = osutils.execute_process(args) if ret_val or err: raise exception.CloudbaseInitException( 'Failed to delete route: %s' % err) except Exception as ex: LOG.exception(ex)
def __init__(self, target_path, cleanup=None): """Instantiate the command. The parameter *target_path* represents the file which will be executed. The optional parameter *cleanup* can be a callable, which will be called after executing a command, no matter if the execution was succesful or not. """ self._target_path = target_path self._cleanup = cleanup self._osutils = osutils_factory.get_os_utils()
def execute(self, service, shared_data): network_config = service.get_network_config() if not network_config: return (base.PLUGIN_EXECUTION_DONE, False) if 'content_path' not in network_config: return (base.PLUGIN_EXECUTION_DONE, False) content_path = network_config['content_path'] content_name = content_path.rsplit('/', 1)[-1] debian_network_conf = service.get_content(content_name) LOG.debug('network config content:\n%s' % debian_network_conf) # TODO(alexpilotti): implement a proper grammar if debian_network_conf: debian_network_conf = debian_network_conf.decode(encoding='utf-8') m = re.search(r'iface eth0 inet static\s+' r'address\s+(?P<address>[^\s]+)\s+' r'netmask\s+(?P<netmask>[^\s]+)\s+' r'broadcast\s+(?P<broadcast>[^\s]+)\s+' r'gateway\s+(?P<gateway>[^\s]+)\s+' r'dns\-nameservers\s+(?P<dnsnameservers>[^\r\n]+)\s+', debian_network_conf) if not m: raise exception.CloudbaseInitException( "network_config format not recognized") address = m.group('address') netmask = m.group('netmask') broadcast = m.group('broadcast') gateway = m.group('gateway') dnsnameservers = m.group('dnsnameservers').strip().split(' ') osutils = osutils_factory.get_os_utils() network_adapter_name = CONF.network_adapter if not network_adapter_name: # Get the first available one available_adapters = osutils.get_network_adapters() if not len(available_adapters): raise exception.CloudbaseInitException( "No network adapter available") network_adapter_name = available_adapters[0] LOG.info('Configuring network adapter: \'%s\'' % network_adapter_name) reboot_required = osutils.set_static_network_config( network_adapter_name, address, netmask, broadcast, gateway, dnsnameservers) return (base.PLUGIN_EXECUTION_DONE, reboot_required)
def execute(self, service, shared_data): osutils = osutils_factory.get_os_utils() license_info = self._run_slmgr(osutils, ['/dlv']) LOG.info('Microsoft Windows license info:\n%s' % license_info) if CONF.activate_windows: LOG.info("Activating Windows") activation_result = self._run_slmgr(osutils, ['/ato']) LOG.debug("Activation result:\n%s" % activation_result) return base.PLUGIN_EXECUTION_DONE, False
def execute(self, service, shared_data): osutils = osutils_factory.get_os_utils() metadata_host_name = service.get_host_name() if not metadata_host_name: LOG.debug('Hostname not found in metadata') return base.PLUGIN_EXECUTION_DONE, False (_, reboot_required) = hostname.set_hostname(osutils, metadata_host_name) return base.PLUGIN_EXECUTION_DONE, reboot_required
def get_volume_activation_product_key(self, license_family, vol_act_type=constant.VOL_ACT_KMS): osutils = osutils_factory.get_os_utils() os_version = osutils.get_os_version() os_major = os_version["major_version"] os_minor = os_version["minor_version"] product_keys_map = productkeys.SKU_TO_PRODUCT_KEY_MAP.get( (os_major, os_minor, vol_act_type), {}) return product_keys_map.get(license_family)