コード例 #1
0
    def resetnetwork(self, name, value):
        ifaces = {}
        xen_macs = utils.list_xenstore_macaddrs()
        for iface in utils.list_hw_interfaces():
            mac = utils.get_hw_addr(iface)
            if not mac or mac not in xen_macs:
                continue
            ifaces[iface] = utils.get_interface(mac)

        # set hostname
        utils.backup_file('/etc/hostname')
        hostname = utils.get_hostname()
        with open('/etc/hostname', 'w') as hostnamefile:
            print(hostname, file=hostnamefile)
        p = Popen(['hostname', hostname], stdout=PIPE, stderr=PIPE, stdin=PIPE)
        out, err = p.communicate()
        if p.returncode != 0:
            return (str(p.returncode), 'Error setting hostname: hostname')

        # setup interface files
        self._setup_loopback()
        for ifname, iface in ifaces.items():
            self._setup_interface(ifname, iface)
            p = Popen(['ifdown', ifname], stdout=PIPE, stderr=PIPE, stdin=PIPE)
            out, err = p.communicate()
            p = Popen(['ifup', ifname], stdout=PIPE, stderr=PIPE, stdin=PIPE)
            out, err = p.communicate()
        if p.returncode != 0:
            return (str(p.returncode), 'Error restarting network')

        return ('0', '')
コード例 #2
0
 def _setup_interface(self, ifname, iface):
     utils.backup_file('/etc/sysconfig/network/ifcfg-{0}'.format(ifname))
     with open('/etc/sysconfig/network/ifcfg-{0}'.format(ifname), 'w') as iffile:
         print('# Label {0}'.format(iface['label']), file=iffile)
         print('BOOTPROTO=static', file=iffile)
         ifnum = None
         for x in iface['ips']:
             if ifnum is None:
                 print('IPADDR={0}'.format(x['ip']), file=iffile)
                 print('NETMASK={0}'.format(x['netmask']), file=iffile)
                 ifnum = 0
             else:
                 print('IPADDR_{0}={1}'.format(ifnum, x['ip']), file=iffile)
                 print('NETMASK_{0}={1}'.format(ifnum, x['netmask']), file=iffile)
                 print('LABEL_{0}={0}'.format(ifnum), file=iffile)
                 ifnum += 1
         if 'ip6s' in iface and iface['ip6s']:
             for x in iface['ip6s']:
                 if ifnum is None:
                     print('IPADDR={0}'.format(x['ip']), file=iffile)
                     print('PREFIXLEN_{0}={1}'.format(ifnum, x['netmask']), file=iffile)
                     ifnum = 0
                 else:
                     print('IPADDR_{0}={1}'.format(ifnum, x['ip']), file=iffile)
                     print('PREFIXLEN_{0}={1}'.format(ifnum, x['netmask']), file=iffile)
                     print('LABEL_{0}={0}'.format(ifnum), file=iffile)
                     ifnum += 1
         print("STARTMODE='auto'", file=iffile)
         print("USERCONTROL='no'", file=iffile)
コード例 #3
0
    def _setup_interface(self, ifname, iface):
        addrs = []
        addrs.extend(['{0}/{1}'.format(x['ip'], utils.netmask_to_prefix(x['netmask'])) for x in iface['ips']])
        if 'ip6s' in iface and iface['ip6s']:
            addrs.extend(['{ip}/{netmask}'.format(**x) for x in iface['ip6s']])
        routes = []
        gateways = []
        if 'gateway' in iface and iface['gateway']:
            gateways.append(iface['gateway'])
        if 'gateway_v6' in iface and iface['gateway_v6']:
            gateways.append(iface['gateway_v6'])
        if 'routes' in iface and iface['routes']:
            for route in iface['routes']:
                route['length'] = utils.netmask_to_prefix(route['netmask'])
                routes.append(route)

        utils.backup_file('/etc/systemd/network/{0}.network'.format(ifname))
        with open('/etc/systemd/network/{0}.network'.format(ifname), 'w') as iffile:
            print('# Label {0}'.format(iface['label']), file=iffile)
            print('[Match]\nName={0}\n'.format(ifname), file=iffile)
            print('[Network]', file=iffile)
            for x in addrs:
                print('Address={0}'.format(x), file=iffile)
            for x in gateways:
                print('Gateway={0}'.format(x), file=iffile)
            if 'dns' in iface and iface['dns']:
                print('DNS={0}'.format(' '.join(iface['dns'])), file=iffile)
            for x in routes:
                print('\n[Route]\nGateway={gateway}\nDestination={route}/{length}'.format(**route), file=iffile)
コード例 #4
0
    def _setup_hostname(self, client):
        """
        hostnamectl is available in some Debian systems and depends on dbus
        """
        hostname = utils.get_hostname(client)
        completed = False
        if os.path.exists('/usr/bin/hostnamectl'):
            utils.backup_file(self.hostname_file)
            p = Popen(['hostnamectl', 'set-hostname', hostname],
                      stdout=PIPE,
                      stderr=PIPE,
                      stdin=PIPE)
            out, err = p.communicate()
            if p.returncode != 0:
                log.error('Error using hostnamectl: {0}'.format(err))
            else:
                # Do not run hostname since it was successful
                completed = True

        if not completed:
            p = Popen(['hostname', hostname],
                      stdout=PIPE,
                      stderr=PIPE,
                      stdin=PIPE)
            out, err = p.communicate()
            if p.returncode != 0:
                log.error('Error using hostname: {0}'.format(err))

        return p.returncode
コード例 #5
0
ファイル: centos.py プロジェクト: theappleman/nova-agent
 def _setup_interface(self, ifname, iface):
     utils.backup_file(
         '/etc/syscfongi/network-scripts/ifcfg-{0}'.format(ifname))
     with open('/etc/sysconfig/network-scripts/ifcfg-{0}'.format(ifname),
               'w') as iffile:
         print('# Label {0}'.format(iface['label']), file=iffile)
         print('BOOTPROTO=static', file=iffile)
         print('DEVICE={0}'.format(ifname), file=iffile)
         for count, x in enumerate(iface['ips']):
             if count == 0:
                 print('IPADDR={0}'.format(x['ip']), file=iffile)
                 print('NETMASK={0}'.format(x['netmask']), file=iffile)
             else:
                 print('IPADDR{0}={1}'.format(count, x['ip']), file=iffile)
                 print('NETMASK{0}={1}'.format(count, x['netmask']),
                       file=iffile)
         if 'gateway' in iface and iface['gateway']:
             print('GATEWAY={0}'.format(iface['gateway']), file=iffile)
         if 'ip6s' in iface and iface['ip6s']:
             print('IPV6INIT=yes', file=iffile)
             for count, x in enumerate(iface['ip6s']):
                 if count == 0:
                     print('IPV6ADDR={ip}/{netmask}'.format(**x),
                           file=iffile)
                 else:
                     print('IPV6ADDR{0}={ip}/{netmask}'.format(count, **x),
                           file=iffile)
             print('IPV6_DEFAULTGW={0}%{1}'.format(iface['gateway_v6'],
                                                   ifname),
                   file=iffile)
         if 'dns' in iface and iface['dns']:
             for count, dns in enumerate(iface['dns']):
                 print("DNS{0}={1}".format(count + 1, dns), file=iffile)
         print('ONBOOT=yes', file=iffile)
         print('NM_CONTROLLED=no', file=iffile)
コード例 #6
0
ファイル: centos.py プロジェクト: oldarmyc/nova-agent
 def _setup_routes(self, ifname, iface):
     route_file = '{0}/{1}-{2}'.format(
         self.netconfig_dir,
         self.route_file_prefix,
         ifname
     )
     utils.backup_file(route_file)
     with open(route_file, 'w') as routefile:
         for count, route in enumerate(iface['routes']):
             routefile.write(
                 'ADDRESS{0}={1}\n'.format(
                     count,
                     route['route']
                 )
             )
             routefile.write(
                 'NETMASK{0}={1}\n'.format(
                     count,
                     route['netmask']
                 )
             )
             routefile.write(
                 'GATEWAY{0}={1}\n'.format(
                     count,
                     route['gateway']
                 )
             )
コード例 #7
0
ファイル: centos.py プロジェクト: gtmanfred/nova-agent
 def _setup_interface(self, ifname, iface):
     utils.backup_file('/etc/syscfongi/network-scripts/ifcfg-{0}'.format(ifname))
     with open('/etc/sysconfig/network-scripts/ifcfg-{0}'.format(ifname), 'w') as iffile:
         print('# Label {0}'.format(iface['label']), file=iffile)
         print('BOOTPROTO=static', file=iffile)
         print('DEVICE={0}'.format(ifname), file=iffile)
         for count, x in enumerate(iface['ips']):
             if count == 0:
                 print('IPADDR={0}'.format(x['ip']), file=iffile)
                 print('NETMASK={0}'.format(x['netmask']), file=iffile)
             else:
                 print('IPADDR{0}={1}'.format(count, x['ip']), file=iffile)
                 print('NETMASK{0}={1}'.format(count, x['netmask']), file=iffile)
         if 'gateway' in iface and iface['gateway']:
             print('GATEWAY={0}'.format(iface['gateway']), file=iffile)
         if 'ip6s' in iface and iface['ip6s']:
             print('IPV6INIT=yes', file=iffile)
             for count, x in enumerate(iface['ip6s']):
                 if count == 0:
                     print('IPV6ADDR={ip}/{netmask}'.format(**x), file=iffile)
                 else:
                     print('IPV6ADDR{0}={ip}/{netmask}'.format(count, **x), file=iffile)
             print('IPV6_DEFAULTGW={0}%{1}'.format(iface['gateway_v6'], ifname), file=iffile)
         if 'dns' in iface and iface['dns']:
             for count, dns in enumerate(iface['dns']):
                 print("DNS{0}={1}".format(count + 1, dns), file=iffile)
         print('ONBOOT=yes', file=iffile)
         print('NM_CONTROLLED=no', file=iffile)
コード例 #8
0
ファイル: __init__.py プロジェクト: survient/nova-agent
    def _setup_hostname(self, client):
        hostname = utils.get_hostname(client)
        completed = False
        if os.path.exists('/usr/bin/hostnamectl'):
            utils.backup_file(self.hostname_file)
            p = Popen(
                ['hostnamectl', 'set-hostname', hostname],
                stdout=PIPE,
                stderr=PIPE,
                stdin=PIPE
            )
            out, err = p.communicate()
            if p.returncode != 0:
                log.error('Error using hostnamectl: {0}'.format(err))
            else:
                # Do not run hostname since hostnamectl was successful
                completed = True

        if not completed:
            log.debug('Falling back to use hostname command')
            p = Popen(
                ['hostname', hostname],
                stdout=PIPE,
                stderr=PIPE,
                stdin=PIPE
            )
            out, err = p.communicate()
            if p.returncode != 0:
                log.error('Error using hostname: {0}'.format(err))
            else:
                log.debug('Writing file {0}'.format(self.hostname_file))
                with open(self.hostname_file, 'w') as host_file:
                    host_file.write(hostname)

        return p.returncode, hostname
コード例 #9
0
 def _setup_loopback(self):
     utils.backup_file('/etc/network/interfaces')
     with open('/etc/network/interfaces', 'w') as iffile:
         print(('# The loopback network interface\n'
                'auto lo\n'
                'iface lo inet loopback\n\n'),
               file=iffile)
コード例 #10
0
ファイル: archlinux.py プロジェクト: gtmanfred/nova-agent
    def resetnetwork(self, name, value):
        ifaces = {}
        xen_macs = utils.list_xenstore_macaddrs()
        for iface in utils.list_hw_interfaces():
            mac = utils.get_hw_addr(iface)
            if not mac or mac not in xen_macs:
                continue
            ifaces[iface] = utils.get_interface(mac)

        # set hostname
        utils.backup_file('/etc/hostname')
        hostname = utils.get_hostname()
        p = Popen(['hostnamectl', 'set-hostname', hostname], stdout=PIPE, stderr=PIPE, stdin=PIPE)
        out, err = p.communicate()
        if p.returncode != 0:
            return (str(p.returncode), 'Error setting hostname')

        # setup interface files
        for ifname, iface in ifaces.items():
            self._setup_interface(ifname, iface)
            p = Popen(['netctl', 'restart', ifname], stdout=PIPE, stderr=PIPE, stdin=PIPE)
            out, err = p.communicate()
            if p.returncode != 0:
                return (str(p.returncode), 'Error restarting network')

        return ('0', '')
コード例 #11
0
ファイル: debian.py プロジェクト: gtmanfred/nova-agent
 def _setup_loopback(self):
     utils.backup_file('/etc/network/interfaces')
     with open('/etc/network/interfaces', 'w') as iffile:
         print((
             '# The loopback network interface\n'
             'auto lo\n'
             'iface lo inet loopback\n\n'
         ), file=iffile)
コード例 #12
0
ファイル: centos.py プロジェクト: gtmanfred/nova-agent
 def _setup_routes(self, ifname, iface):
     utils.backup_file('/etc/syscfongi/network-scripts/route-{0}'.format(ifname))
     with open('/etc/sysconfig/network-scripts/route-{0}'.format(ifname), 'w') as routefile:
         for count, route in enumerate(iface['routes']):
             print((
                 'ADDRESS{0}={route}\n'
                 'NETMASK{0}={netmask}\n'
                 'GATEWAY{0}={gateway}\n'
             ).format(count, **route), file=routefile)
コード例 #13
0
ファイル: tests_utils.py プロジェクト: survient/nova-agent
    def test_rename_interface_file_success(self):
        rename_file = '/tmp/ifcfg-eth0'
        utils.backup_file(rename_file)

        files = glob.glob('/tmp/ifcfg-eth0.*.*.bak')
        self.assertEqual(len(files), 1, 'Did not find any files')
        self.assertIn(
            'ifcfg-eth0', files[0],
            'Did not find the original filename in renamed file path')
コード例 #14
0
ファイル: alpine.py プロジェクト: rcelner/nova-agent
    def resetnetwork(self, name, value, client):
        ifaces = {}
        hostname_return_code, _ = self._setup_hostname(client)
        if hostname_return_code != 0:
            log.error('Error setting hostname on system')

        xen_macs = utils.list_xenstore_macaddrs(client)
        for iface in utils.list_hw_interfaces():
            mac = utils.get_hw_addr(iface)
            if not mac or mac not in xen_macs:
                continue

            ifaces[iface] = utils.get_interface(mac, client)

        # Backup original configuration file
        utils.backup_file(self.netconfig_file)

        # Setup interfaces file
        self._setup_loopback()
        for ifname, iface in ifaces.items():
            self._setup_interfaces(ifname, iface)

        # Loop through the interfaces and restart networking
        for ifname in ifaces.keys():
            p = Popen(['ifdown', ifname], stdout=PIPE, stderr=PIPE, stdin=PIPE)
            out, err = p.communicate()
            if p.returncode != 0:
                return (str(p.returncode),
                        'Error stopping network: {0}'.format(ifname))
            """
            In some cases interfaces may retain old IP addresses especially
            when building from a custom image. To prevent that we will do a
            flush of the interface before bringing it back up.

            Refer to bug:
            https://bugs.launchpad.net/ubuntu/+source/ifupdown/+bug/1584682
            """
            p = Popen(['ip', 'addr', 'flush', 'dev', ifname],
                      stdout=PIPE,
                      stderr=PIPE,
                      stdin=PIPE)
            out, err = p.communicate()
            if p.returncode != 0:
                return (str(p.returncode),
                        'Error flushing network: {0}'.format(ifname))

            # Sleep for one second
            time.sleep(1)
            p = Popen(['ifup', ifname], stdout=PIPE, stderr=PIPE, stdin=PIPE)
            out, err = p.communicate()
            if p.returncode != 0:
                log.error('Error received on network restart: {0}'.format(err))
                return (str(p.returncode),
                        'Error starting network: {0}'.format(ifname))

        return ('0', '')
コード例 #15
0
ファイル: centos.py プロジェクト: theappleman/nova-agent
 def _setup_routes(self, ifname, iface):
     utils.backup_file(
         '/etc/syscfongi/network-scripts/route-{0}'.format(ifname))
     with open('/etc/sysconfig/network-scripts/route-{0}'.format(ifname),
               'w') as routefile:
         for count, route in enumerate(iface['routes']):
             print(('ADDRESS{0}={route}\n'
                    'NETMASK{0}={netmask}\n'
                    'GATEWAY{0}={gateway}\n').format(count, **route),
                   file=routefile)
コード例 #16
0
ファイル: freebsd.py プロジェクト: naterh/nova-agent
 def _setup_dns(self, dns):
     utils.backup_file("/etc/resolvconf/resolv.conf.d/base")
     with open("/etc/resolvconf/resolv.conf.d/base", "w") as iffile:
         for d in dns:
             print("nameserver {0}".format(d), file=iffile)
     if not os.path.exists("/run/resolvconf"):
         os.mkdir("/run/resolvconf")
     shutil.copy("/etc/resolvconf/resolv.conf.d/base", "/run/resolvconf/resolv.conf")
     if not os.path.exists("/etc/resolv.conf") or os.readlink("/etc/resolv.conf") != "/run/resolvconf/resolv.conf":
         os.symlink("/run/resolvconf/resolv.conf", "/etc/resolv.conf")
コード例 #17
0
 def _setup_routes(self, ifname, iface):
     utils.backup_file('/etc/sysconfig/network/ifroute-{0}'.format(ifname))
     with open('/etc/sysconfig/network/ifroute-{0}'.format(ifname), 'w') as routefile:
         print('# Label {0}'.format(iface['label']), file=routefile)
         if 'gateway' in iface and iface['gateway']:
             print('default {0} - -'.format(iface['gateway']), file=routefile)
         if 'gateway_v6' in iface and iface['gateway_v6']:
             print('default {0} - -'.format(iface['gateway_v6']), file=routefile)
         if 'routes' in iface and iface['routes']:
             for route in iface['routes']:
                 print('{route} {gateway} {netmask} {0}'.format(ifname, **route), file=routefile)
コード例 #18
0
ファイル: centos.py プロジェクト: theappleman/nova-agent
    def resetnetwork(self, name, value):
        ifaces = {}
        xen_macs = utils.list_xenstore_macaddrs()
        for iface in utils.list_hw_interfaces():
            mac = utils.get_hw_addr(iface)
            if not mac or mac not in xen_macs:
                continue
            ifaces[iface] = utils.get_interface(mac)

        # set hostname
        utils.backup_file('/etc/sysconfig/network')
        hostname = utils.get_hostname()
        with open('/etc/sysconfig/network', 'w') as netfile:
            print('NETWORKING=yes', file=netfile)
            print('NOZEROCONF=yes', file=netfile)
            print('NETWORKING_IPV6=yes', file=netfile)
            print('HOSTNAME={0}'.format(hostname), file=netfile)
        if os.path.exists('/usr/bin/hostnamectl'):
            utils.backup_file('/etc/hostname')
            p = Popen(['hostnamectl', 'set-hostname', hostname],
                      stdout=PIPE,
                      stderr=PIPE,
                      stdin=PIPE)
            out, err = p.communicate()
            if p.returncode != 0:
                return (str(p.returncode), 'Error setting hostname')
        else:
            p = Popen(['hostname', hostname],
                      stdout=PIPE,
                      stderr=PIPE,
                      stdin=PIPE)
            out, err = p.communicate()
            if p.returncode != 0:
                return (str(p.returncode), 'Error setting hostname')

        # setup interface files
        for ifname, iface in ifaces.items():
            self._setup_interface(ifname, iface)
            if 'routes' in iface:
                self._setup_routes(ifname, iface)
        p = Popen(['service', 'network', 'stop'],
                  stdout=PIPE,
                  stderr=PIPE,
                  stdin=PIPE)
        p = Popen(['service', 'network', 'start'],
                  stdout=PIPE,
                  stderr=PIPE,
                  stdin=PIPE)
        out, err = p.communicate()
        if p.returncode != 0:
            return (str(p.returncode), 'Error restarting network')

        return ('0', '')
コード例 #19
0
 def _setup_dns(self, dns):
     utils.backup_file('/etc/resolvconf/resolv.conf.d/base')
     with open('/etc/resolvconf/resolv.conf.d/base', 'w') as iffile:
         for d in dns:
             print('nameserver {0}'.format(d), file=iffile)
     if not os.path.exists('/run/resolvconf'):
         os.mkdir('/run/resolvconf')
     shutil.copy('/etc/resolvconf/resolv.conf.d/base',
                 '/run/resolvconf/resolv.conf')
     if not os.path.exists('/etc/resolv.conf') or os.readlink(
             '/etc/resolv.conf') != '/run/resolvconf/resolv.conf':
         os.symlink('/run/resolvconf/resolv.conf', '/etc/resolv.conf')
コード例 #20
0
ファイル: centos.py プロジェクト: rmesta/nova-agent
    def _setup_interface(self, ifname, iface):
        interface_file = '{0}/{1}-{2}'.format(self.netconfig_dir,
                                              self.interface_file_prefix,
                                              ifname)
        # Check and see if there are extra arguments in ifcfg file
        extra_args = self._check_for_extra_settings(interface_file)

        # Backup the interface file
        utils.backup_file(interface_file)

        with open(interface_file, 'w') as iffile:
            iffile.write('# Automatically generated, do not edit\n\n')
            iffile.write('# Label {0}\n'.format(iface['label']))
            iffile.write('BOOTPROTO=static\n')
            iffile.write('DEVICE={0}\n'.format(ifname))
            for count, ip_info in enumerate(iface['ips']):
                if count == 0:
                    iffile.write('IPADDR={0}\n'.format(ip_info['ip']))
                    iffile.write('NETMASK={0}\n'.format(ip_info['netmask']))
                else:
                    iffile.write('IPADDR{0}={1}\n'.format(
                        count, ip_info['ip']))
                    iffile.write('NETMASK{0}={1}\n'.format(
                        count, ip_info['netmask']))

            if iface.get('gateway'):
                iffile.write('GATEWAY={0}\n'.format(iface['gateway']))

            if iface.get('ip6s'):
                iffile.write('IPV6INIT=yes\n')
                for count, ip6_info in enumerate(iface['ip6s']):
                    if count == 0:
                        iffile.write('IPV6ADDR={0}/{1}\n'.format(
                            ip6_info['ip'], ip6_info['netmask']))
                    else:
                        iffile.write('IPV6ADDR{0}={1}/{2}\n'.format(
                            count, ip6_info['ip'], ip6_info['netmask']))

                iffile.write('IPV6_DEFAULTGW={0}%{1}\n'.format(
                    iface['gateway_v6'], ifname))

            if iface.get('dns'):
                for count, dns in enumerate(iface['dns']):
                    iffile.write('DNS{0}={1}\n'.format(count + 1, dns))

            iffile.write('ONBOOT=yes\n')
            if not self.use_network_manager:
                iffile.write('NM_CONTROLLED=no\n')

            if len(extra_args) > 0:
                for argument in extra_args:
                    iffile.write('{0}\n'.format(argument))
コード例 #21
0
    def resetnetwork(self, name, value, client):
        ifaces = {}
        hostname_return_code, hostname = self._setup_hostname(client)
        if hostname_return_code != 0:
            return (str(hostname_return_code), 'Error setting hostname')

        xen_macs = utils.list_xenstore_macaddrs(client)
        for iface in utils.list_hw_interfaces():
            mac = utils.get_hw_addr(iface)

            if not mac or mac not in xen_macs:
                continue

            ifaces[iface] = utils.get_interface(mac, client)

        utils.backup_file(self.network_file)
        with open(self.network_file, 'w') as netfile:
            netfile.write('NETWORKING=yes\n')
            netfile.write('NOZEROCONF=yes\n')
            netfile.write('NETWORKING_IPV6=yes\n')
            netfile.write('HOSTNAME={0}\n'.format(hostname))

        # move unused interface files out of the way but back them up
        move_files = utils.get_ifcfg_files_to_remove(
            self.netconfig_dir, '{0}-'.format(self.interface_file_prefix))
        for interface_config in move_files:
            utils.move_file(interface_config)

        # setup interface files
        for ifname, iface in ifaces.items():
            self._setup_interface(ifname, iface)
            if 'routes' in iface:
                self._setup_routes(ifname, iface)

        if os.path.exists('/usr/bin/systemctl'):
            p = Popen(['systemctl', 'restart', 'network.service'],
                      stdout=PIPE,
                      stderr=PIPE,
                      stdin=PIPE)
        else:
            p = Popen(['service', 'network', 'restart'],
                      stdout=PIPE,
                      stderr=PIPE,
                      stdin=PIPE)

        out, err = p.communicate()
        if p.returncode != 0:
            return (str(p.returncode), 'Error restarting network')

        return ('0', '')
コード例 #22
0
ファイル: file_inject.py プロジェクト: survient/nova-agent
def _write_file(filename, data):
    # Get permissions from existing file if it exists
    permission, owner, group = _get_file_permissions(filename)
    dirname = os.path.dirname(filename)
    if not os.path.exists(dirname):
        os.makedirs(dirname)
    """
    Create temporary file in the directory we want to place the file into

    https://docs.python.org/2/library/tempfile.html
    From the documentation: There are no race conditions in the file's
    creation, assuming that the platform properly implements the os.O_EXCL
    flag for os.open(). The file is readable and writable only by the
    creating user ID.
    """
    fd, temp_path = mkstemp(dir=dirname, text=True)

    try:
        """
        Set the ownership for the file. If it fails owner/group will be
        root as that is what nova-agent runs under
        """
        os.fchown(fd, owner, group)
    except Exception:
        pass

    try:
        os.fchmod(fd, permission)
    except Exception:
        # If existing file is not found, then set permissions to default 600
        os.fchmod(fd, stat.S_IRUSR | stat.S_IWUSR)

    # Write data to file after all the permissions are set on the temp file
    try:
        os.write(fd, data)
    except TypeError:
        # Python 3 expects bytes so convert and then write to file
        os.write(fd, encode_to_bytes(data))

    os.close(fd)
    # Check for existence of file and back the original up
    if os.path.exists(filename):
        backup_file(filename)

    # Rename the temp file and put in place
    os.rename(temp_path, filename)
コード例 #23
0
    def _setup_hostname(self, client):
        hostname = utils.get_hostname(client)
        if os.path.exists('/usr/bin/hostnamectl'):
            utils.backup_file(self.hostname_file)
            p = Popen(['hostnamectl', 'set-hostname', hostname],
                      stdout=PIPE,
                      stderr=PIPE,
                      stdin=PIPE)
            out, err = p.communicate()
        else:
            p = Popen(['hostname', hostname],
                      stdout=PIPE,
                      stderr=PIPE,
                      stdin=PIPE)
            out, err = p.communicate()

        return p.returncode, hostname
コード例 #24
0
    def _setup_interface(self, ifname, iface):
        interface_file = '{0}/{1}-{2}'.format(self.netconfig_dir,
                                              self.interface_file_prefix,
                                              ifname)
        utils.backup_file(interface_file)
        with open(interface_file, 'w') as iffile:
            iffile.write('# Automatically generated, do not edit\n\n')
            iffile.write('# Label {0}\n'.format(iface['label']))
            iffile.write('BOOTPROTO=static\n')
            iffile.write('DEVICE={0}\n'.format(ifname))
            for count, ip_info in enumerate(iface['ips']):
                if count == 0:
                    iffile.write('IPADDR={0}\n'.format(ip_info['ip']))
                    iffile.write('NETMASK={0}\n'.format(ip_info['netmask']))
                else:
                    iffile.write('IPADDR{0}={1}\n'.format(
                        count, ip_info['ip']))
                    iffile.write('NETMASK{0}={1}\n'.format(
                        count, ip_info['netmask']))

            if 'gateway' in iface and iface['gateway']:
                iffile.write('GATEWAY={0}\n'.format(iface['gateway']))

            if 'ip6s' in iface and iface['ip6s']:
                iffile.write('IPV6INIT=yes\n')
                for count, ip6_info in enumerate(iface['ip6s']):
                    if count == 0:
                        iffile.write('IPV6ADDR={0}/{1}\n'.format(
                            ip6_info['ip'], ip6_info['netmask']))
                    else:
                        iffile.write('IPV6ADDR{0}={1}/{2}\n'.format(
                            count, ip6_info['ip'], ip6_info['netmask']))

                iffile.write('IPV6_DEFAULTGW={0}%{1}\n'.format(
                    iface['gateway_v6'], ifname))

            if 'dns' in iface and iface['dns']:
                for count, dns in enumerate(iface['dns']):
                    iffile.write('DNS{0}={1}\n'.format(count + 1, dns))

            iffile.write('ONBOOT=yes\n')
            iffile.write('NM_CONTROLLED=no\n')
コード例 #25
0
ファイル: debian.py プロジェクト: nicholaskuechler/nova-agent
    def _setup_hostname(self, client):
        """
        hostnamectl is available in some Debian systems and depends on dbus
        """
        hostname = utils.get_hostname(client)
        if os.path.exists('/usr/bin/hostnamectl'):
            utils.backup_file(self.hostname_file)
            p = Popen(['hostnamectl', 'set-hostname', hostname],
                      stdout=PIPE,
                      stderr=PIPE,
                      stdin=PIPE)
            out, err = p.communicate()
        else:
            p = Popen(['hostname', hostname],
                      stdout=PIPE,
                      stderr=PIPE,
                      stdin=PIPE)
            out, err = p.communicate()

        return p.returncode, hostname
コード例 #26
0
ファイル: centos.py プロジェクト: gtmanfred/nova-agent
    def resetnetwork(self, name, value):
        ifaces = {}
        xen_macs = utils.list_xenstore_macaddrs()
        for iface in utils.list_hw_interfaces():
            mac = utils.get_hw_addr(iface)
            if not mac or mac not in xen_macs:
                continue
            ifaces[iface] = utils.get_interface(mac)

        # set hostname
        utils.backup_file('/etc/sysconfig/network')
        hostname = utils.get_hostname()
        with open('/etc/sysconfig/network', 'w') as netfile:
            print('NETWORKING=yes', file=netfile)
            print('NOZEROCONF=yes', file=netfile)
            print('NETWORKING_IPV6=yes', file=netfile)
            print('HOSTNAME={0}'.format(hostname), file=netfile)
        if os.path.exists('/usr/bin/hostnamectl'):
            utils.backup_file('/etc/hostname')
            p = Popen(['hostnamectl', 'set-hostname', hostname], stdout=PIPE, stderr=PIPE, stdin=PIPE)
            out, err = p.communicate()
            if p.returncode != 0:
                return (str(p.returncode), 'Error setting hostname')
        else:
            p = Popen(['hostname', hostname], stdout=PIPE, stderr=PIPE, stdin=PIPE)
            out, err = p.communicate()
            if p.returncode != 0:
                return (str(p.returncode), 'Error setting hostname')

        # setup interface files
        for ifname, iface in ifaces.items():
            self._setup_interface(ifname, iface)
            if 'routes' in iface:
                self._setup_routes(ifname, iface)
        p = Popen(['service', 'network', 'stop'], stdout=PIPE, stderr=PIPE, stdin=PIPE)
        p = Popen(['service', 'network', 'start'], stdout=PIPE, stderr=PIPE, stdin=PIPE)
        out, err = p.communicate()
        if p.returncode != 0:
            return (str(p.returncode), 'Error restarting network')

        return ('0', '')
コード例 #27
0
 def _setup_interface(self, ifname, iface):
     utils.backup_file('/etc/netctl/{0}'.format(ifname))
     with open('/etc/netctl/{0}'.format(ifname), 'w') as iffile:
         print('# Label {0}'.format(iface['label']), file=iffile)
         print('Connection=ethernet', file=iffile)
         print('Interface={0}'.format(ifname), file=iffile)
         print('IP=static', file=iffile)
         addrs = ['{0}/{1}'.format(x['ip'], x['netmask']) for x in iface['ips']]
         print("Address=('{0}')".format("' '".join(addrs)), file=iffile)
         if 'gateway' in iface and iface['gateway']:
             print('Gateway={0}'.format(iface['gateway']), file=iffile)
         if 'routes' in iface and iface['routes']:
             routes = ['{route}/{netmask} via {gateway}'.format(**x) for x in iface['routes']]
             print("Routes=('{0}')".format("' '".join(routes)), file=iffile)
         if 'ip6s' in iface and iface['ip6s']:
             print('IP6=static', file=iffile)
             addrs6 = ['{0}/{1}'.format(x['ip'], x['netmask']) for x in iface['ip6s']]
             print("Address6=('{0}')".format("' '".join(addrs6)), file=iffile)
             print('Gateway6={0}'.format(iface['gateway_v6']), file=iffile)
         if 'dns' in iface and iface['dns']:
             print("DNS=('{0}')".format("' '".join(iface['dns'])), file=iffile)
コード例 #28
0
ファイル: gentoo.py プロジェクト: gtmanfred/nova-agent
    def resetnetwork(self, name, value):
        ifaces = {}
        xen_macs = utils.list_xenstore_macaddrs()
        for iface in utils.list_hw_interfaces():
            mac = utils.get_hw_addr(iface)
            if not mac or mac not in xen_macs:
                continue
            ifaces[iface] = utils.get_interface(mac)

        # set hostname
        utils.backup_file('/etc/hostname')
        utils.backup_file('/etc/conf.d/hostname')
        hostname = utils.get_hostname()
        with open('/etc/hostname', 'w') as hostnamefile:
            print(hostname, file=hostnamefile)
        with open('/etc/conf.d/hostname', 'w') as hostnamefile:
            print('HOSTNAME={0}'.format(hostname), file=hostnamefile)
        p = Popen(['hostname', hostname], stdout=PIPE, stderr=PIPE, stdin=PIPE)
        out, err = p.communicate()
        if p.returncode != 0:
            return (str(p.returncode), 'Error setting hostname: hostname')

        # setup interface files
        utils.backup_file('/etc/conf.d/net')
        with open('/etc/conf.d/net', 'w') as iffile:
            print('modules="iproute2"', file=iffile)
        for ifname, iface in ifaces.items():
            self._setup_interface(ifname, iface)
            p = Popen(['/etc/init.d/net.{0}'.format(ifname), 'restart'], stdout=PIPE, stderr=PIPE, stdin=PIPE)
            out, err = p.communicate()
            if p.returncode != 0:
                return (str(p.returncode), 'Error restarting network')

        return ('0', '')
コード例 #29
0
 def _setup_dns(self, ifname, iface):
     if 'dns' not in iface:
         return
     newline = 'NETCONFIG_DNS_STATIC_SERVERS="{0}"\n'.format(' '.join(iface['dns']))
     config = '/etc/sysconfig/network/config'
     fh, abs_path = mkstemp()
     nochange = False
     with open(abs_path, 'w') as newfile:
         with open(config) as conffile:
             for line in conffile:
                 if re.search('^NETCONFIG_DNS_STATIC_SERVERS=', line):
                     if line == newline:
                         nochange = True
                         break
                     line = newline
                 newfile.write(line)
     os.close(fh)
     if nochange:
         os.remove(abs_path)
     else:
         utils.backup_file(config)
         os.remove(config)
         move(abs_path, config)
コード例 #30
0
    def resetnetwork(self, name, value):
        ifaces = {}
        xen_macs = utils.list_xenstore_macaddrs()
        for iface in utils.list_hw_interfaces():
            mac = utils.get_hw_addr(iface)
            if not mac or mac not in xen_macs:
                continue
            ifaces[iface] = utils.get_interface(mac)

        # set hostname
        hostname = utils.get_hostname()
        utils.backup_file('/etc/HOSTNAME')
        with open('/etc/HOSTNAME', 'w') as hostfile:
            print(hostname, file=hostfile)
        if os.path.exists('/usr/bin/hostnamectl'):
            utils.backup_file('/etc/hostname')
            p = Popen(['hostnamectl', 'set-hostname', hostname], stdout=PIPE, stderr=PIPE, stdin=PIPE)
            out, err = p.communicate()
            if p.returncode != 0:
                return (str(p.returncode), 'Error setting hostname')
        else:
            p = Popen(['hostname', hostname], stdout=PIPE, stderr=PIPE, stdin=PIPE)
            out, err = p.communicate()
            if p.returncode != 0:
                return (str(p.returncode), 'Error setting hostname')

        # setup interface files
        for ifname, iface in ifaces.items():
            self._setup_interface(ifname, iface)
            self._setup_routes(ifname, iface)
            self._setup_dns(ifname, iface)
        p = Popen(['systemctl', 'restart', 'network.service'], stdout=PIPE, stderr=PIPE, stdin=PIPE)
        out, err = p.communicate()
        if p.returncode != 0:
            return (str(p.returncode), 'Error restarting network')

        return ('0', '')
コード例 #31
0
    def _setup_interface(self, ifname, iface):
        addrs = []
        addrs.extend([
            '{0}/{1}'.format(x['ip'], utils.netmask_to_prefix(x['netmask']))
            for x in iface['ips']
        ])
        if 'ip6s' in iface and iface['ip6s']:
            addrs.extend(['{ip}/{netmask}'.format(**x) for x in iface['ip6s']])
        routes = []
        gateways = []
        if 'gateway' in iface and iface['gateway']:
            gateways.append(iface['gateway'])
        if 'gateway_v6' in iface and iface['gateway_v6']:
            gateways.append(iface['gateway_v6'])
        if 'routes' in iface and iface['routes']:
            for route in iface['routes']:
                route['length'] = utils.netmask_to_prefix(route['netmask'])
                routes.append(route)

        utils.backup_file('/etc/systemd/network/{0}.network'.format(ifname))
        with open('/etc/systemd/network/{0}.network'.format(ifname),
                  'w') as iffile:
            print('# Label {0}'.format(iface['label']), file=iffile)
            print('[Match]\nName={0}\n'.format(ifname), file=iffile)
            print('[Network]', file=iffile)
            for x in addrs:
                print('Address={0}'.format(x), file=iffile)
            for x in gateways:
                print('Gateway={0}'.format(x), file=iffile)
            if 'dns' in iface and iface['dns']:
                print('DNS={0}'.format(' '.join(iface['dns'])), file=iffile)
            for x in routes:
                print(
                    '\n[Route]\nGateway={gateway}\nDestination={route}/{length}'
                    .format(**route),
                    file=iffile)
コード例 #32
0
ファイル: gentoo.py プロジェクト: theappleman/nova-agent
    def resetnetwork(self, name, value):
        ifaces = {}
        xen_macs = utils.list_xenstore_macaddrs()
        for iface in utils.list_hw_interfaces():
            mac = utils.get_hw_addr(iface)
            if not mac or mac not in xen_macs:
                continue
            ifaces[iface] = utils.get_interface(mac)

        # set hostname
        utils.backup_file('/etc/hostname')
        utils.backup_file('/etc/conf.d/hostname')
        hostname = utils.get_hostname()
        with open('/etc/hostname', 'w') as hostnamefile:
            print(hostname, file=hostnamefile)
        with open('/etc/conf.d/hostname', 'w') as hostnamefile:
            print('HOSTNAME={0}'.format(hostname), file=hostnamefile)
        p = Popen(['hostname', hostname], stdout=PIPE, stderr=PIPE, stdin=PIPE)
        out, err = p.communicate()
        if p.returncode != 0:
            return (str(p.returncode), 'Error setting hostname: hostname')

        # setup interface files
        utils.backup_file('/etc/conf.d/net')
        with open('/etc/conf.d/net', 'w') as iffile:
            print('modules="iproute2"', file=iffile)
        for ifname, iface in ifaces.items():
            self._setup_interface(ifname, iface)
            p = Popen(['/etc/init.d/net.{0}'.format(ifname), 'restart'],
                      stdout=PIPE,
                      stderr=PIPE,
                      stdin=PIPE)
            out, err = p.communicate()
            if p.returncode != 0:
                return (str(p.returncode), 'Error restarting network')

        return ('0', '')
コード例 #33
0
 def test_backup_file_failure(self):
     rename_file = '/tmp/ifcfg-eth0'
     os.remove(rename_file)
     utils.backup_file(rename_file)
     assert True, 'Move interface did not generate error'
コード例 #34
0
 def _setup_hostname(self, hostname):
     utils.backup_file('/etc/rc.conf.local')
     with open('/etc/rc.conf.local', 'w') as iffile:
         print('hostname={0}'.format(hostname), file=iffile)
コード例 #35
0
ファイル: freebsd.py プロジェクト: naterh/nova-agent
 def _setup_hostname(self, hostname):
     utils.backup_file("/etc/rc.conf.local")
     with open("/etc/rc.conf.local", "w") as iffile:
         print("hostname={0}".format(hostname), file=iffile)
コード例 #36
0
ファイル: centos.py プロジェクト: oldarmyc/nova-agent
    def resetnetwork(self, name, value, client):
        ifaces = {}
        hostname_return_code, hostname = self._setup_hostname(client)
        if hostname_return_code != 0:
            log.error(
                'Error setting hostname: {0}'.format(hostname_return_code)
            )

        xen_macs = utils.list_xenstore_macaddrs(client)
        for iface in utils.list_hw_interfaces():
            mac = utils.get_hw_addr(iface)

            if not mac or mac not in xen_macs:
                continue

            ifaces[iface] = utils.get_interface(mac, client)

        utils.backup_file(self.network_file)
        with open(self.network_file, 'w') as netfile:
            netfile.write('NETWORKING=yes\n')
            netfile.write('NOZEROCONF=yes\n')
            netfile.write('NETWORKING_IPV6=yes\n')
            netfile.write('HOSTNAME={0}\n'.format(hostname))

        # move unused interface files out of the way but back them up
        move_files = utils.get_ifcfg_files_to_remove(
            self.netconfig_dir,
            '{0}-'.format(self.interface_file_prefix)
        )
        for interface_config in move_files:
            utils.backup_file(interface_config)

        # setup interface files
        for ifname, iface in ifaces.items():
            self._setup_interface(ifname, iface)
            if 'routes' in iface:
                self._setup_routes(ifname, iface)

            """
                Creating servers from custom images may leave IP information
                from the image source. Flush the interface before restart of
                the network to clear out source image IP information
            """
            p = Popen(
                ['ip', 'addr', 'flush', 'dev', ifname],
                stdout=PIPE,
                stderr=PIPE,
                stdin=PIPE
            )
            out, err = p.communicate()
            if p.returncode != 0:
                # Log error and continue to restart network
                log.error('Error flushing interface: {0}'.format(ifname))

        if os.path.exists('/usr/bin/systemctl'):
            p = Popen(
                ['systemctl', 'restart', 'network.service'],
                stdout=PIPE,
                stderr=PIPE,
                stdin=PIPE
            )
        else:
            p = Popen(
                ['service', 'network', 'restart'],
                stdout=PIPE,
                stderr=PIPE,
                stdin=PIPE
            )

        out, err = p.communicate()
        if p.returncode != 0:
            log.error('Error received on network restart: {0}'.format(err))
            return (str(p.returncode), 'Error restarting network')

        return ('0', '')
コード例 #37
0
ファイル: debian.py プロジェクト: nicholaskuechler/nova-agent
 def _setup_loopback(self):
     utils.backup_file(self.netconfig_file)
     with open(self.netconfig_file, 'w') as iffile:
         iffile.write('# The loopback network interface\n')
         iffile.write('auto lo\n')
         iffile.write('iface lo inet loopback\n\n')