Ejemplo n.º 1
0
def view_interface(request):
    return_dict = {}
    try:
        template = 'logged_in_error.html'
        req_ret, err = django_utils.get_request_parameter_values(
            request, ['name'])
        if err:
            raise Exception(err)
        if 'name' not in req_ret:
            raise Exception('Invalid request, please use the menus')

        name = req_ret['name']
        interfaces, err = networking.get_interfaces()
        if err:
            raise Exception(err)
        elif name not in interfaces:
            raise Exception("Specified interface not found")

        if interfaces[name]['vlan']:
            if '.' not in name:
                raise Exception('Invalid VLAN name : %s' % name)
            comps = name.split('.')
            if len(comps) != 2:
                raise Exception('Invalid VLAN name : %s' % name)
            return_dict['parent_nic'] = comps[0]

        return_dict['nic'] = interfaces[name]
        if interfaces[name]['vlan_ids']:
            return_dict['vlans'] = []
            for vlan_id in interfaces[name]['vlan_ids']:
                if '%s.%d' % (name, vlan_id) in interfaces:
                    return_dict['vlans'].append({
                        'name':
                        '%s.%d' % (name, vlan_id),
                        'vlan_id':
                        vlan_id,
                        'info':
                        interfaces['%s.%d' % (name, vlan_id)]
                    })
        return_dict['interfaces'] = interfaces
        return_dict['name'] = name

        template = "view_interface.html"
        return django.shortcuts.render_to_response(
            template,
            return_dict,
            context_instance=django.template.context.RequestContext(request))
    except Exception, e:
        return_dict['base_template'] = "networking_base.html"
        return_dict["page_title"] = 'View network interface details'
        return_dict['tab'] = 'view_interfaces_tab'
        return_dict["error"] = 'Error loading interface details'
        return_dict["error_details"] = str(e)
        return django.shortcuts.render_to_response(
            "logged_in_error.html",
            return_dict,
            context_instance=django.template.context.RequestContext(request))
Ejemplo n.º 2
0
 def __init__(self, *args, **kwargs):
     super(CreateRouteForm, self).__init__(*args, **kwargs)
     ch = []
     interfaces, err = networking.get_interfaces()
     for key, value in interfaces.iteritems():
         # print value['addresses']['AF_INET']
         # check if the interface has an ip address assigned to it ?
         if (value['up_status'] == 'up') and ('AF_INET' in value['addresses']):
             # Just make sure the ip addr is not the localhost address. Just
             # in case.
             if value['addresses']['AF_INET'][0]['addr'] != "127.0.0.1":
                 ch.append((key, key))
     self.fields["interface"] = forms.MultipleChoiceField(
         widget=forms.CheckboxSelectMultiple(), choices=ch)
Ejemplo n.º 3
0
def view_interfaces(request):
    return_dict = {}
    try:
        template = 'logged_in_error.html'
        nics, err = networking.get_interfaces()
        if err:
            raise Exception(err)
        bonds, err = networking.get_bonding_info_all()
        if err:
            raise Exception(err)

        if "ack" in request.GET:
            if request.GET["ack"] == "saved":
                return_dict[
                    'ack_message'] = "Network interface information successfully updated"
            if request.GET["ack"] == "removed_bond":
                return_dict[
                    'ack_message'] = "Network bond successfully removed"
            if request.GET["ack"] == "removed_vlan":
                return_dict['ack_message'] = "VLAN successfully removed"
            if request.GET["ack"] == "created_vlan":
                return_dict['ack_message'] = "VLAN successfully created"
            if request.GET["ack"] == "state_down":
                return_dict[
                    'ack_message'] = "Network interface successfully disabled. The state change may take a couple of seconds to reflect on this page so please refresh it to check the updated status."
            if request.GET["ack"] == "state_up":
                return_dict[
                    'ack_message'] = "Network interface successfully enabled. The state change may take a couple of seconds to reflect on this page so please refresh it to check the updated status."
            if request.GET["ack"] == "created_bond":
                return_dict[
                    'ack_message'] = "Network bond successfully created. Please edit the address information for the bond in order to use it."
        return_dict["nics"] = nics
        return_dict["bonds"] = bonds
        template = "view_interfaces.html"
        return django.shortcuts.render_to_response(
            template,
            return_dict,
            context_instance=django.template.context.RequestContext(request))
    except Exception, e:
        return_dict['base_template'] = "networking_base.html"
        return_dict["page_title"] = 'View network interfaces'
        return_dict['tab'] = 'view_interfaces_tab'
        return_dict["error"] = 'Error loading interfaces'
        return_dict["error_details"] = str(e)
        return django.shortcuts.render_to_response(
            "logged_in_error.html",
            return_dict,
            context_instance=django.template.context.RequestContext(request))
Ejemplo n.º 4
0
def view_bond(request):
    return_dict = {}
    try:
        template = 'logged_in_error.html'
        req_ret, err = django_utils.get_request_parameter_values(
            request, ['name'])
        if err:
            raise Exception(err)
        if 'name' not in req_ret:
            raise Exception('Invalid request, please use the menus')

        name = req_ret['name']

        interfaces, err = networking.get_interfaces()
        if err:
            raise Exception(err)
        elif name not in interfaces:
            raise Exception("Specified interface not found")

        bond, err = networking.get_bonding_info(name)
        if err:
            raise Exception(err)
        if not bond:
            raise Exception("Specified bond not found")

        return_dict['nic'] = interfaces[name]
        return_dict['bond'] = bond
        return_dict['name'] = name

        template = "view_bond.html"
        return django.shortcuts.render_to_response(
            template,
            return_dict,
            context_instance=django.template.context.RequestContext(request))
    except Exception, e:
        return_dict['base_template'] = "networking_base.html"
        return_dict["page_title"] = 'View network bond details'
        return_dict['tab'] = 'view_interfaces_tab'
        return_dict["error"] = 'Error loading network bond details'
        return_dict["error_details"] = str(e)
        return django.shortcuts.render_to_response(
            "logged_in_error.html",
            return_dict,
            context_instance=django.template.context.RequestContext(request))
Ejemplo n.º 5
0
def display_config():

    try:
        hostname = socket.gethostname()
        if hostname:
            print "Hostname : %s" % hostname
        else:
            print "Hostname : Not set"
        print
        interfaces, err = networking.get_interfaces()
        if interfaces:
            for name, interface in interfaces.items():
                if name.startswith('lo'):
                    continue
                print 'Interface : %s. ' % name
                if 'AF_INET' in interface['addresses']:
                    print 'IP Address : %s, Netmask %s. ' % (
                        interface['addresses']['AF_INET'][0]['addr'],
                        interface['addresses']['AF_INET'][0]['netmask']),
                else:
                    print 'No address assigned. ',
                if 'slave_to' in interface:
                    print 'NIC bonded slave to %s.' % interface['slave_to'],
                if 'bonding_master' in interface:
                    print 'NIC bonded master. ',
                    bonding_type, err = networking.get_bonding_type(name)
                    if bonding_type:
                        print 'Bonding type %d. ' % bonding_type
                print 'Carrier status : %s. ' % interface['carrier_status'],
                print 'NIC status : %s. ' % interface['up_status']
                print
        else:
            if err:
                print 'Error retrieving interface information : %s' % err

        dns_list, err = networking.get_name_servers()
        if dns_list:
            print "DNS lookup servers :",
            print ', '.join(dns_list)
            print
    except Exception, e:
        print "Error displaying system configuration : %s" % e
        return -1
Ejemplo n.º 6
0
def get_interface_status():
    """Gets a more concise version of the interface info and status than networking provides."""
    d = {}
    try:
        ifaces, err = networking.get_interfaces()
        if err:
            raise Exception(err)
        # print ifaces
        if ifaces:
            for iface_name, iface in ifaces.items():
                td = {}
                td['hwaddr'] = iface['addresses']['AF_LINK'][0]['addr']
                td['up'] = iface['up_status']
                if 'AF_INET' in iface['addresses'] and iface['addresses'][
                        'AF_INET'] and iface['addresses']['AF_INET'][0]:
                    inet_list = []
                    for inet in iface['addresses']['AF_INET']:
                        inet_dict = {}
                        if 'addr' in inet:
                            inet_dict['address'] = inet['addr']
                        if 'netmask' in inet:
                            inet_dict['netmask'] = inet['netmask']
                        if 'broadcast' in inet:
                            inet_dict['broadcast'] = inet['broadcast']
                        inet_dict['label'] = iface_name
                        inet_list.append(inet_dict)
                    td['inet'] = inet_list
                if 'bonding_master' in iface:
                    td['bonding_master'] = True
                if 'slave_to' in iface:
                    td['slave_to'] = iface['slave_to']
                if 'carrier_status' in iface:
                    td['carrier_status'] = iface['carrier_status']
                if 'bootproto' in iface:
                    td['boot_proto'] = iface['bootproto']
                d[iface_name] = td
    except Exception, e:
        return None, 'Error retrieving interface status : %s' % str(e)
def get_interface_status():
    """Gets a more concise version of the interface info and status than networking provides."""
    d = {}
    try:
        ifaces, err = networking.get_interfaces()
        if err:
            raise Exception(err)
        # print ifaces
        if ifaces:
            for iface_name, iface in ifaces.items():
                td = {}
                td['hwaddr'] = iface['addresses']['AF_LINK'][0]['addr']
                td['up'] = iface['up_status']
                if 'AF_INET' in iface['addresses'] and iface['addresses']['AF_INET'] and iface['addresses']['AF_INET'][0]:
                    inet_list = []
                    for inet in iface['addresses']['AF_INET']:
                        inet_dict = {}
                        if 'addr' in inet:
                            inet_dict['address'] = inet['addr']
                        if 'netmask' in inet:
                            inet_dict['netmask'] = inet['netmask']
                        if 'broadcast' in inet:
                            inet_dict['broadcast'] = inet['broadcast']
                        inet_dict['label'] = iface_name
                        inet_list.append(inet_dict)
                    td['inet'] = inet_list
                if 'bonding_master' in iface:
                    td['bonding_master'] = True
                if 'slave_to' in iface:
                    td['slave_to'] = iface['slave_to']
                if 'carrier_status' in iface:
                    td['carrier_status'] = iface['carrier_status']
                if 'bootproto' in iface:
                    td['boot_proto'] = iface['bootproto']
                d[iface_name] = td
    except Exception, e:
        return None, 'Error retrieving interface status : %s' % str(e)
Ejemplo n.º 8
0
def create_bond():
    try:
        os.system('clear')
        interfaces, err = networking.get_interfaces()
        if err:
            raise Exception(
                'Error retrieving interface information : %s' % err)
        if not interfaces:
            raise Exception('No interfaces detected')

        print '\n\nIntegralSTOR NIC Bonding'
        print '---------------------------------\n\n'
        print 'Available interfaces: \n'

        bm, err = networking.get_bonding_masters()
        if err:
            raise Exception(err)
        bid, err = networking.get_bonding_info_all()
        if err:
            raise Exception(err)

        avail_if = []
        for if_name, iface in interfaces.items():
            if if_name.startswith('lo') or if_name in bm or if_name in bid['by_slave']:
                continue
            print '\t- %s' % if_name
            avail_if.append(if_name)
        print "\n"

        bond_name = None
        is_name = False
        while is_name is False:
            bond_name = raw_input('Provide bond name: ')
            if bond_name in interfaces or bond_name.startswith('lo'):
                print "\t- Can't assign %s, it's been taken already. Please provide another one.\n" % bond_name
            else:
                is_name = True

        print "\n"
        slaves = []
        is_ok = False
        while is_ok is False:
            s = raw_input(
                "\nEnter slaves from the shown interface list, separated by comma. - ").split(",")
            slaves = [inner.strip() for inner in s]
            for slave in slaves:
                if slave not in avail_if:
                    break

            else:
                is_ok = True
                print ("\nSelecetd slaves: %s") % slaves
                confirm = raw_input("\t- Confirm selected slaves (y/n)? ")
                if confirm.lower() in ["n"]:
                    is_ok = False

        print "\n"
        is_ok = False
        while is_ok is False:
            mode = raw_input(
                "Available modes [4]802.3ad, [6]balance-alb] - 4 or 6?: ")
            if mode in ["4", "6"]:
                is_ok = True

        ret, err = networking.create_bond(bond_name, slaves, int(mode))
        if not ret:
            if err:
                raise Exception('Error creating bond: %s' % err)
            else:
                raise Exception("Couldn't create bond")
        if ret:
            print "\nBond created! Configure IP to activate.\n"

    except Exception, e:
        print "Error: %s" % e
        return -1
def configure_networking():

    try:
        os.system('clear')
        change_ip = False
        change_netmask = False
        change_default_gateway = False
        change_bonding_type = False
        change_jumbo_frames = False

        interfaces, err = networking.get_interfaces()
        if err:
            raise Exception(err)

        if 'bond0' not in interfaces.keys():
            if_list = interfaces.keys()
            ret, err = networking.create_bond('bond0', if_list, 6)
            if err:
                raise Exception(err)
            config_changed = True

        ip_info, err = networking.get_ip_info('bond0')
        if err:
            ip_info = None

        '''
    if not ip_info :
      raise Exception("No bonding configured! Incorrect configuration. : %s"%err)
    '''

        config_changed = False
        if ip_info:
            ip = ip_info["ipaddr"]
            str_to_print = 'Enter IP address (currently "%s", press enter to retain current value) : ' % ip
        else:
            ip = None
            str_to_print = "Enter IP address (currently not configured) : "

        valid_input = False
        while not valid_input:
            input = raw_input(str_to_print)
            if input:
                vi, err = networking.validate_ip(input)
                if vi:
                    valid_input = True
                    ip = input
                    change_ip = True
                    config_changed = True
            else:
                if ip:
                    # IP already existed and they are now not changing it so
                    # its ok.
                    valid_input = True
            if not valid_input:
                print "Invalid value. Please try again."
        print

        if ip_info:
            netmask = ip_info["netmask"]
            str_to_print = 'Enter netmask (currently "%s", press enter to retain current value) : ' % netmask
        else:
            netmask = None
            str_to_print = "Enter netmask (currently not set) : "

        valid_input = False
        while not valid_input:
            input = raw_input(str_to_print)
            if input:
                vi, err = networking.validate_netmask(input)
                if vi:
                    valid_input = True
                    netmask = input
                    change_netmask = True
                    config_changed = True
            else:
                if netmask:
                    # IP already existed and they are now not changing it so
                    # its ok.
                    valid_input = True
            if not valid_input:
                print "Invalid value. Please try again."
        print

        default_gateway = None
        if ip_info and "default_gateway" in ip_info:
            default_gateway = ip_info["default_gateway"]
        else:
            default_gateway = None
        if default_gateway:
            str_to_print = 'Enter the default gateway\'s IP address (currently "%s", press enter to retain current value) : ' % default_gateway
        else:
            str_to_print = "Enter the default gateway's IP address (currently not set, press enter to retain current value) : "
        valid_input = False
        while not valid_input:
            input = raw_input(str_to_print)
            if input:
                vi, err = networking.validate_ip(input)
                if vi:
                    valid_input = True
                    default_gateway = input
                    change_default_gateway = True
                    config_changed = True
            else:
                valid_input = True
            if not valid_input:
                print "Invalid value. Please try again."
        print

        hostname = socket.gethostname()
        str_to_print = 'Enter the GRIDCell hostname (currently "%s", press enter to retain current value) : ' % hostname
        valid_input = False
        change_hostname = False
        while not valid_input:
            input = raw_input(str_to_print)
            if input:
                vi, err = networking.validate_hostname(input)
                if vi:
                    valid_input = True
                    hostname = input
                    change_hostname = True
                    config_changed = True
            else:
                valid_input = True
            if not valid_input:
                print "Invalid value. Please try again."
        print

        bonding_type, err = networking.get_bonding_type('bond0')
        print "Ethernet NIC bonding configuration"
        print "----------------------------------"
        print "Ethernet bonding aggregates the bandwidth of all available ethernet ports giving high throughput and failover."
        print "We support two modes. "
        print "The first is LACP (also called 802.3ad) which requires configuration on any switch). The second is balance-alb which does not require switch configuration but may not be supported on all switches. "
        valid_input = False
        while not valid_input:
            print "Valid choices for this selection  are 4 (for 802.3ad or LACP) and 6 (for balance-alb)."
            print
            if bonding_type == -1:
                str_to_print = "Enter bonding mode (currently not configured, press enter to retain current value) : "
            else:
                str_to_print = "Enter bonding mode (currently %s, press enter to retain current value) : " % bonding_type
            input = raw_input(str_to_print)
            if input:
                if input.lower() in ['4', '6']:
                    valid_input = True
                    bonding_type = int(input)
                    change_bonding_type = True
                    config_changed = True
            else:
                valid_input = True
            if not valid_input:
                print "Invalid value. Please try again."
        print

        jfe, err = networking.is_enabled_jumbo_frames('bond0')
        if jfe:
            jumbo_frames = 'y'
            jfe_str = "enabled"
        else:
            jumbo_frames = 'n'
            jfe_str = "disabled"
        print "Jumbo frames support"
        print "--------------------"
        print "Enabling jumbo frames improves network throughput but requires configuration on the switch side."
        print "If you enable it here, please set the MTU size on the switch to 9000"
        valid_input = False
        while not valid_input:
            str_to_print = "Enable jumbo frames (currently %s, press enter to retain current value) (y/n)? : " % jfe_str
            print
            input = raw_input(str_to_print)
            if input:
                if input.lower() in ['y', 'n']:
                    valid_input = True
                    jumbo_frames = input.lower()
                    change_jumbo_frames = True
                    config_changed = True
            else:
                valid_input = True
            if not valid_input:
                print "Invalid value. Please try again."
        print

        print "Final confirmation"
        print "------------------"

        print
        print "The following are the choices that you have made :"
        print "IP address : %s" % ip
        print "Net Mask : %s" % netmask
        print "Hostname : %s" % hostname
        print "Default gateway : %s" % default_gateway
        if bonding_type == 4:
            print "NIC Bonding mode : LACP"
        elif bonding_type == 6:
            print "NIC Bonding mode : balance-alb"
        else:
            print "NIC Bonding mode (unsupported!!) : %d" % bonding_type

        print "Enable jumbo frames : %s" % jumbo_frames

        if not config_changed:
            print
            print
            raw_input(
                'No changes have been made to the configurations. Press enter to return to the main menu.')
            return 0

        str_to_print = 'Commit the above changes? (y/n) :'

        commit = 'n'
        valid_input = False
        while not valid_input:
            input = raw_input(str_to_print)
            if input:
                if input.lower() in ['y', 'n']:
                    valid_input = True
                    commit = input.lower()
            if not valid_input:
                print "Invalid value. Please try again."
        print

        if commit == 'y':
            print "Committing changes!"
        else:
            print "Discarding changes!"

        if commit != 'y':
            return 0

        restart_networking = False
        ip_dict = {}
        errors = []

        if change_ip or change_netmask or change_default_gateway or change_jumbo_frames:
            ip_dict["ip"] = ip
            ip_dict["netmask"] = netmask
            ip_dict["default_gateway"] = default_gateway
            if jumbo_frames == 'y':
                ip_dict["mtu"] = 9000
            else:
                ip_dict["mtu"] = 1500
            rc, err = networking.update_bond_ip(ip_dict)
            if not rc:
                if err:
                    errors.append("Error setting IP configuration : %s" % err)
                else:
                    errors.append("Error setting IP configuration ")
            restart_networking = True

        if change_hostname:
            ret, err = networking.update_hostname(hostname, 'integralstor.lan')
            if err:
                raise Exception(err)
            restart_networking = True

        if change_hostname or change_ip:
            ret, err = networking.update_hosts_file_entry(hostname, ip)
            if err:
                raise Exception(err)

        restart = False
        if restart_networking:
            print
            print
            valid_input = False
            while not valid_input:
                str_to_print = 'Restart network services now (y/n) :'
                print
                input = raw_input(str_to_print)
                if input:
                    if input.lower() in ['y', 'n']:
                        valid_input = True
                        if input.lower() == 'y':
                            restart = True
                if not valid_input:
                    print "Invalid value. Please try again."
            print
        if restart:
            (r, rc), err = command.execute_with_rc('service network restart')
            if err:
                raise Exception(err)
            if rc == 0:
                print "Network service restarted succesfully."
            else:
                print "Error restarting network services."
                raw_input('Press enter to return to the main menu')
                return -1
    except Exception, e:
        print "Error configuring network settings : %s" % e
        return -1
Ejemplo n.º 10
0
def configure_interface():

    try:
        os.system('clear')
        interfaces, err = networking.get_interfaces()
        if err:
            raise Exception(
                'Error retrieving interface information : %s' % err)
        if not interfaces:
            raise Exception('No interfaces detected')
        print
        print
        print 'IntegralSTOR interface configuration'
        print '--------------------------------------------'
        print
        print
        print 'Current network interfaces : '
        print
        for if_name, iface in interfaces.items():
            if if_name.startswith('lo'):
                continue
            print '- %s' % if_name
        print

        valid_input = False
        while not valid_input:
            ifname = raw_input(
                'Enter the name of the interface that you wish to configure : ')
            if ifname not in interfaces or ifname.startswith('lo'):
                print 'Invalid interface name'
            else:
                valid_input = True
        print
        ip_info, err = networking.get_ip_info(ifname)
        '''
    if err:
      raise Exception('Error retrieving interface information : %s'%err)
    '''
        if ip_info:
            ip = ip_info["ipaddr"]
            netmask = ip_info["netmask"]
            if "default_gateway" in ip_info:
                gateway = ip_info["default_gateway"]
            else:
                gateway = None
        else:
            ip = None
            netmask = None
            gateway = None

        old_boot_proto, err = networking.get_interface_bootproto(ifname)
        if err:
            raise Exception(
                'Error retrieving interface information : %s' % err)
            time.sleep(5)

        config_changed = False

        str_to_print = "Configure for DHCP or static addressing (dhcp/static)? : "
        valid_input = False
        while not valid_input:
            input = raw_input(str_to_print)
            if input:
                if input.lower() in ['static', 'dhcp']:
                    valid_input = True
                    boot_proto = input.lower()
                    if boot_proto != old_boot_proto:
                        config_changed = True
            if not valid_input:
                print "Invalid value. Please try again."
        print

        if boot_proto == 'static':
            if ip:
                str_to_print = "Enter IP address (currently %s, press enter to retain current value) : " % ip
            else:
                str_to_print = "Enter IP address (currently not set) : "
            valid_input = False
            while not valid_input:
                input = raw_input(str_to_print)
                if input:
                    ok, err = networking.validate_ip(input)
                    if err:
                        raise Exception('Error validating IP : %s' % err)
                    if ok:
                        valid_input = True
                        ip = input
                        config_changed = True
                elif ip:
                    valid_input = True
                if not valid_input:
                    print "Invalid value. Please try again."
            print

            if netmask:
                str_to_print = "Enter netmask (currently %s, press enter to retain current value) : " % netmask
            else:
                str_to_print = "Enter netmask (currently not set) : "
            valid_input = False
            while not valid_input:
                input = raw_input(str_to_print)
                if input:
                    ok, err = networking.validate_netmask(input)
                    if err:
                        raise Exception('Error validating netmask : %s' % err)
                    if ok:
                        valid_input = True
                        netmask = input
                        config_changed = True
                elif netmask:
                    valid_input = True
            if not valid_input:
                print "Invalid value. Please try again."
            print

            if gateway:
                str_to_print = "Enter gateway (currently %s, press enter to retain current value) : " % gateway
            else:
                str_to_print = "Enter gateway (currently not set) : "
            valid_input = False
            while not valid_input:
                input = raw_input(str_to_print)
                if input:
                    ok, err = networking.validate_ip(input)
                    if err:
                        raise Exception('Error validating gateway : %s' % err)
                    if ok:
                        valid_input = True
                        gateway = input
                        config_changed = True
                elif gateway:
                    valid_input = True
                if not valid_input:
                    print "Invalid value. Please try again."
            print
        if config_changed:
            d = {}
            d['addr_type'] = boot_proto
            if boot_proto == 'static':
                d['ip'] = ip
                d['netmask'] = netmask
                d['default_gateway'] = gateway
            ret, err = networking.update_interface_ip(ifname, d)
            if not ret:
                if err:
                    raise Exception(
                        'Error changing interface address : %s' % err)
                else:
                    raise Exception('Error changing interface address')

            restart = False
            print
            print
            valid_input = False
            while not valid_input:
                str_to_print = 'Restart network services now (y/n) :'
                print
                input = raw_input(str_to_print)
                if input:
                    if input.lower() in ['y', 'n']:
                        valid_input = True
                        if input.lower() == 'y':
                            restart = True
                if not valid_input:
                    print "Invalid value. Please try again."
            print

            if restart:
                ret, err = networking.restart_networking()
                if not ret:
                    if err:
                        raise Exception(err)
                    else:
                        raise Exception("Couldn't restart.")

                use_salt, err = config.use_salt()
                if err:
                    raise Exception(err)
                if use_salt:
                    (r, rc), err = command.execute_with_rc(
                        'service salt-minion restart')
                    if err:
                        raise Exception(err)
                    if rc == 0:
                        print "Salt minion service restarted succesfully."
                    else:
                        print "Error restarting salt minion services."
                        raw_input('Press enter to return to the main menu')
                        return -1
        else:
            print
            print
            raw_input(
                'No changes have been made to the configurations. Press enter to return to the main menu.')
            return 0

    except Exception, e:
        print "Error configuring network settings : %s" % e
        return -1
Ejemplo n.º 11
0
def remove_bond():
    try:
        os.system('clear')
        interfaces, err = networking.get_interfaces()
        if err:
            raise Exception('Error retrieving interface information : %s' %
                            err)
        if not interfaces:
            raise Exception('No interfaces detected')

        print
        print
        print 'IntegralSTOR NIC Bonding'
        print '---------------------------------'
        print
        print
        print 'Active bond(s): \n'

        bm, err = networking.get_bonding_masters()
        if err:
            raise Exception(err)
        bid, err = networking.get_bonding_info_all()
        if err:
            raise Exception(err)

        avail_if = []
        for if_name, iface in interfaces.items():
            if if_name in bm:
                print '\t- %s' % if_name
                avail_if.append(if_name)
        print "\n"
        if not avail_if:
            raise Exception('There is nothing to remove!')

        bond_name = None
        is_name = False
        while is_name is False:
            bond_name = raw_input('To remove a bond, provide its name: ')
            if bond_name not in avail_if:
                print "\t- Can't remove %s, no such bond exists. Please provide another one.\n" % bond_name
            else:
                is_name = True

        ret, err = networking.delete_bond(bond_name)
        if not ret:
            if err:
                raise Exception('Error removing bond: %s' % err)
            else:
                raise Exception("Couldn't remove bond")
        if ret:
            print "\n\tBond removed!\n"

        print
        print 'Regenerating manifest and status.'
        python_scripts_path, err = config.get_python_scripts_path()
        if err:
            raise Exception(err)
        common_python_scripts_path, err = config.get_common_python_scripts_path(
        )
        if err:
            raise Exception(err)
        status_path, err = config.get_system_status_path()
        if err:
            raise Exception(err)

        ret, err = command.get_command_output(
            "python %s/generate_manifest.py %s" %
            (common_python_scripts_path, status_path))
        if err:
            raise Exception(err)
        ret, err = command.get_command_output(
            "python %s/generate_status.py %s" %
            (common_python_scripts_path, status_path))
        if err:
            raise Exception(err)
        print 'Regenerating manifest and status... Done'
        print
    except Exception, e:
        print "Error: %s" % e
        print
        return -1
Ejemplo n.º 12
0
def create_bond(request):
    return_dict = {}
    try:

        interfaces, err = networking.get_interfaces()
        if err:
            raise Exception(err)
        if not interfaces:
            raise Exception(
                "Error loading network interface information : No interfaces found"
            )

        bm, err = networking.get_bonding_masters()
        if err:
            raise Exception(err)
        bid, err = networking.get_bonding_info_all()
        if err:
            raise Exception(err)

        return_dict['interfaces'] = interfaces
        iface_list = []
        existing_bonds = []
        for if_name, iface in interfaces.items():
            if if_name.startswith('lo') or if_name in bid['by_slave']:
                continue
            if if_name in bm:
                existing_bonds.append(if_name)
                continue
            iface_list.append(if_name)

        return_dict['is_iface_avail'] = False
        if iface_list:
            return_dict['is_iface_avail'] = True

        if request.method == "GET":
            form = networking_forms.CreateBondForm(
                interfaces=iface_list, existing_bonds=existing_bonds)
            return_dict['form'] = form
            return django.shortcuts.render_to_response(
                "create_bond.html",
                return_dict,
                context_instance=django.template.context.RequestContext(
                    request))
        else:
            form = networking_forms.CreateBondForm(
                request.POST,
                interfaces=iface_list,
                existing_bonds=existing_bonds)
            return_dict['form'] = form
            if not form.is_valid():
                return django.shortcuts.render_to_response(
                    "create_bond.html",
                    return_dict,
                    context_instance=django.template.context.RequestContext(
                        request))
            cd = form.cleaned_data
            print cd
            result, err = networking.create_bond(cd['name'], cd['slaves'],
                                                 int(cd['mode']))
            if not result:
                if err:
                    raise Exception(err)
                else:
                    raise Exception('Bond creation failed!')
            python_scripts_path, err = config.get_python_scripts_path()
            if err:
                raise Exception(err)
            common_python_scripts_path, err = config.get_common_python_scripts_path(
            )
            if err:
                raise Exception(err)
            status_path, err = config.get_system_status_path()
            if err:
                raise Exception(err)

            ret, err = command.get_command_output(
                "python %s/generate_manifest.py %s" %
                (common_python_scripts_path, status_path))
            if err:
                raise Exception(err)

            ret, err = command.get_command_output(
                "python %s/generate_status.py %s" %
                (common_python_scripts_path, status_path))
            if err:
                raise Exception(err)

            audit_str = "Created a network bond named %s with slaves %s" % (
                cd['name'], ','.join(cd['slaves']))
            audit.audit("create_bond", audit_str, request)
            return django.http.HttpResponseRedirect(
                '/view_interfaces?ack=created_bond')
    except Exception, e:
        return_dict['base_template'] = "networking_base.html"
        return_dict["page_title"] = 'Create a network interface bond'
        return_dict['tab'] = 'view_interfaces_tab'
        return_dict["error"] = 'Error creating a network interface bond'
        return_dict["error_details"] = str(e)
        return django.shortcuts.render_to_response(
            "logged_in_error.html",
            return_dict,
            context_instance=django.template.context.RequestContext(request))
Ejemplo n.º 13
0
def create_vlan(request):
    return_dict = {}
    try:
        req_ret, err = django_utils.get_request_parameter_values(
            request, ['nic'])
        if err:
            raise Exception(err)
        if 'nic' not in req_ret:
            raise Exception('Invalid request, please use the menus')

        interfaces, err = networking.get_interfaces()
        if err:
            raise Exception(err)

        if not interfaces:
            raise Exception(
                "Error loading network interface information : No interfaces found"
            )

        return_dict['interfaces'] = interfaces
        if_list = []
        existing_vlans = []
        for if_name, iface in interfaces.items():
            if '.' in if_name:
                comps = if_name.split('.')
                if len(comps) != 2:
                    raise Exception('Invalid VLAN specification found : %s' %
                                    if_name)
                if int(comps[1]) not in existing_vlans:
                    existing_vlans.append(int(comps[1]))
        if request.method == "GET":
            form = networking_forms.CreateVLANForm(
                existing_vlans=existing_vlans,
                initial={'base_interface': req_ret['nic']})
            return_dict['form'] = form
            return django.shortcuts.render_to_response(
                "create_vlan.html",
                return_dict,
                context_instance=django.template.context.RequestContext(
                    request))
        else:
            form = networking_forms.CreateVLANForm(
                request.POST, existing_vlans=existing_vlans)
            return_dict['form'] = form
            if not form.is_valid():
                return django.shortcuts.render_to_response(
                    "create_vlan.html",
                    return_dict,
                    context_instance=django.template.context.RequestContext(
                        request))
            cd = form.cleaned_data
            # print cd
            result, err = networking.create_vlan(cd['base_interface'],
                                                 cd['vlan_id'])
            if not result:
                if err:
                    raise Exception(err)
                else:
                    raise Exception('VLAN creation failed!')

            result, err = networking.restart_networking()
            if err:
                raise Exception(err)

            audit_str = "Created a network VLAN with id  %d on the base interface %s" % (
                cd['vlan_id'], cd['base_interface'])
            audit.audit("create_vlan", audit_str, request)
            return django.http.HttpResponseRedirect(
                '/view_interfaces?ack=created_vlan')
    except Exception, e:
        return_dict['base_template'] = "networking_base.html"
        return_dict["page_title"] = 'Create a network VLAN'
        return_dict['tab'] = 'view_interfaces_tab'
        return_dict["error"] = 'Error creating a network VLAN'
        return_dict["error_details"] = str(e)
        return django.shortcuts.render_to_response(
            "logged_in_error.html",
            return_dict,
            context_instance=django.template.context.RequestContext(request))
Ejemplo n.º 14
0
def update_interface_address(request):
    return_dict = {}
    try:
        req_ret, err = django_utils.get_request_parameter_values(
            request, ['name'])
        if err:
            raise Exception(err)
        if 'name' not in req_ret:
            raise Exception('Invalid request, please use the menus')

        name = req_ret['name']
        interfaces, err = networking.get_interfaces()
        if err:
            raise Exception(err)
        elif not interfaces or name not in interfaces:
            raise Exception("Specified interface not found")
        return_dict['nic'] = interfaces[name]

        if request.method == "GET":

            initial = {}
            initial['name'] = name
            initial['mtu'] = name
            if 'mtu' in interfaces[name] and interfaces[name]['mtu']:
                initial['mtu'] = interfaces[name]['mtu']
            if 'bootproto' in interfaces[name] and interfaces[name][
                    'bootproto'] == 'dhcp':
                initial['addr_type'] = 'dhcp'
            else:
                initial['addr_type'] = 'static'
                if 'addresses' in interfaces[name] and 'AF_INET' in interfaces[
                        name]['addresses'] and interfaces[name]['addresses'][
                            'AF_INET']:
                    initial['ip'] = interfaces[name]['addresses']['AF_INET'][
                        0]['addr']
                    initial['netmask'] = interfaces[name]['addresses'][
                        'AF_INET'][0]['netmask']
            # print interfaces[name]
            if 'gateways' in interfaces[name] and interfaces[name]['gateways']:
                if interfaces[name]['gateways'][0][2]:
                    initial['default_gateway'] = interfaces[name]['gateways'][
                        0][0]
            # print initial

            form = networking_forms.NICForm(initial=initial)
            return_dict['form'] = form
            return django.shortcuts.render_to_response(
                "update_interface_address.html",
                return_dict,
                context_instance=django.template.context.RequestContext(
                    request))
        else:
            form = networking_forms.NICForm(request.POST)
            return_dict['form'] = form
            if not form.is_valid():
                return django.shortcuts.render_to_response(
                    "update_interface_address.html",
                    return_dict,
                    context_instance=django.template.context.RequestContext(
                        request))
            cd = form.cleaned_data
            result_str = ""
            success = False
            result, err = networking.update_interface_ip(cd['name'], cd)
            if err:
                raise Exception(err)
            result, err = networking.restart_networking()
            if err:
                raise Exception(err)
            ip, err = networking.get_ip_info(
                unicode_utils.convert_unicode_to_string(cd['name']))
            if err:
                raise Exception(err)
            audit_str = 'Changed the address of %s. New values are IP : %s, netmask: %s' % (
                cd['name'], ip['ipaddr'], ip['netmask'])
            if 'default_gateway' in ip:
                audit_str += ', default gateway : %s' % ip['default_gateway']
            audit.audit("edit_interface_address", audit_str, request)
            return django.http.HttpResponseRedirect(
                '/view_interface?name=%s&result=addr_changed' % (name))
    except Exception, e:
        return_dict['base_template'] = "networking_base.html"
        return_dict["page_title"] = 'Modify network interface addressing'
        return_dict['tab'] = 'view_interfaces_tab'
        return_dict["error"] = 'Error modifying network interface addressing'
        return_dict["error_details"] = str(e)
        return django.shortcuts.render_to_response(
            "logged_in_error.html",
            return_dict,
            context_instance=django.template.context.RequestContext(request))