Beispiel #1
0
def edit_interface_address(request):
    return_dict = {}
    try:
        if 'name' not in request.REQUEST:
            raise Exception(
                "Interface name not specified. Please use the menus.")

        name = request.REQUEST["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(
                "edit_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(
                    "edit_interface_address.html",
                    return_dict,
                    context_instance=django.template.context.RequestContext(
                        request))
            cd = form.cleaned_data
            result_str = ""
            success = False
            result, err = networking.set_interface_ip_info(cd['name'], cd)
            if err:
                raise Exception(err)
            result, err = networking.restart_networking()
            if err:
                raise Exception(err)
            ip, err = networking.get_ip_info(
                common.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.META)
            return django.http.HttpResponseRedirect(
                '/view_nic?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))
Beispiel #2
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
        if_list = []
        existing_bonds = []
        for if_name, iface in interfaces.items():
            ret, err = networking.get_ip_info(if_name)
            if ret:
                continue
            if if_name.startswith('lo') or if_name in bid['by_slave']:
                continue
            if if_name in bm:
                existing_bonds.append(if_name)
                continue
            if_list.append(if_name)

        if request.method == "GET":
            form = networking_forms.CreateBondForm(
                interfaces=if_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=if_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 = common.get_python_scripts_path()
            if err:
                raise Exception(err)
            common_python_scripts_path, err = common.get_common_python_scripts_path(
            )
            if err:
                raise Exception(err)
            status_path, err = common.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.META)
            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))
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 Unicell 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():
            ret, err = networking.get_ip_info(if_name)
            if ret:
                continue
            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!\n"

    except Exception, e:
        print "Error: %s" % e
        return -1
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 Unicell 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.set_interface_ip_info(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 = common.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
def save_samba_server_settings(request):

  return_dict = {}
  try:
    if request.method != "POST":
      return_dict["error"] = "Invalid access method. Please try again using the menus"
      return django.shortcuts.render_to_response('logged_in_error.html', return_dict, context_instance=django.template.context.RequestContext(request))
  
    if "security" not in request.POST:
      return_dict["error"] = "Invalid security specification. Please try again using the menus"
      return django.shortcuts.render_to_response('logged_in_error.html', return_dict, context_instance=django.template.context.RequestContext(request))
  
    if request.POST["security"] == "ads":
      form = samba_shares_forms.AuthADSettingsForm(request.POST)
    elif request.POST["security"] == "users":
      form = samba_shares_forms.AuthUsersSettingsForm(request.POST)
    else:
      return_dict["error"] = "Invalid security specification. Please try again using the menus"
      return django.shortcuts.render_to_response('logged_in_error.html', return_dict, context_instance=django.template.context.RequestContext(request))
  
    return_dict["form"] = form
    return_dict["action"] = "edit"
  
    if form.is_valid():
      cd = form.cleaned_data
  
      try :
        samba_settings.save_auth_settings(cd)
        #print '1'

        ipinfo = networking.get_ip_info('bond0')
        if cd["security"] == "ads":
          # We now need to add the AD server as the forwarder in our DNS config on the primary...
          nsl = networking.get_name_servers()
          if not nsl:
            raise Exception("Could not detect the IP addresses of the primary and secondary GRIDCells")
          rc = networking.generate_default_primary_named_conf(nsl[0], ipinfo['netmask'], nsl[1], True, cd['password_server_ip'], False)
          if rc != 0:
            raise Exception("Error updating the DNS configuration on the primary GRIDCell")

          # ... and on the secondary
          client = salt.client.LocalClient()
          r2 = client.cmd('roles:secondary', 'cmd.run_all', ['python /opt/fractalio/scripts/python/create_secondary_named_config.py %s %s %s %s'%(nsl[0], nsl[1], ipinfo['netmask'], cd['password_server_ip'])], expr_form='grain')
          if r2:
            for node, ret in r2.items():
              if ret["retcode"] != 0:
                raise Exception("Error updating the DNS configuration on the primary GRIDCell")

        #print '2'
      except Exception, e:
        return_dict["error"] = "Error saving authentication settings - %s" %e
      if not "error" in return_dict and cd["security"] == "ads":
        try :
          samba_settings.generate_krb5_conf()
          #print '3'
        except Exception, e:
          return_dict["error"] = "Error generating kerberos config file - %s" %e
      if not "error" in return_dict:
        try :
          samba_settings.generate_smb_conf()
          #print '4'
        except Exception, e:
          return_dict["error"] = "Error generating file share authentication config file- %s" %e
def save_samba_server_settings(request):

    return_dict = {}
    try:
        if request.method != "POST":
            return_dict[
                "error"] = "Invalid access method. Please try again using the menus"
            return django.shortcuts.render_to_response(
                'logged_in_error.html',
                return_dict,
                context_instance=django.template.context.RequestContext(
                    request))

        if "security" not in request.POST:
            return_dict[
                "error"] = "Invalid security specification. Please try again using the menus"
            return django.shortcuts.render_to_response(
                'logged_in_error.html',
                return_dict,
                context_instance=django.template.context.RequestContext(
                    request))

        if request.POST["security"] == "ads":
            form = samba_shares_forms.AuthADSettingsForm(request.POST)
        elif request.POST["security"] == "users":
            form = samba_shares_forms.AuthUsersSettingsForm(request.POST)
        else:
            return_dict[
                "error"] = "Invalid security specification. Please try again using the menus"
            return django.shortcuts.render_to_response(
                'logged_in_error.html',
                return_dict,
                context_instance=django.template.context.RequestContext(
                    request))

        return_dict["form"] = form
        return_dict["action"] = "edit"

        if form.is_valid():
            cd = form.cleaned_data

            try:
                samba_settings.save_auth_settings(cd)
                #print '1'

                ipinfo = networking.get_ip_info('bond0')
                if cd["security"] == "ads":
                    # We now need to add the AD server as the forwarder in our DNS config on the primary...
                    nsl = networking.get_name_servers()
                    if not nsl:
                        raise Exception(
                            "Could not detect the IP addresses of the primary and secondary GRIDCells"
                        )
                    rc = networking.generate_default_primary_named_conf(
                        nsl[0], ipinfo['netmask'], nsl[1], True,
                        cd['password_server_ip'], False)
                    if rc != 0:
                        raise Exception(
                            "Error updating the DNS configuration on the primary GRIDCell"
                        )

                    # ... and on the secondary
                    client = salt.client.LocalClient()
                    r2 = client.cmd(
                        'roles:secondary',
                        'cmd.run_all', [
                            'python /opt/fractalio/scripts/python/create_secondary_named_config.py %s %s %s %s'
                            % (nsl[0], nsl[1], ipinfo['netmask'],
                               cd['password_server_ip'])
                        ],
                        expr_form='grain')
                    if r2:
                        for node, ret in r2.items():
                            if ret["retcode"] != 0:
                                raise Exception(
                                    "Error updating the DNS configuration on the primary GRIDCell"
                                )

                #print '2'
            except Exception, e:
                return_dict[
                    "error"] = "Error saving authentication settings - %s" % e
            if not "error" in return_dict and cd["security"] == "ads":
                try:
                    samba_settings.generate_krb5_conf()
                    #print '3'
                except Exception, e:
                    return_dict[
                        "error"] = "Error generating kerberos config file - %s" % e
            if not "error" in return_dict:
                try:
                    samba_settings.generate_smb_conf()
                    #print '4'
                except Exception, e:
                    return_dict[
                        "error"] = "Error generating file share authentication config file- %s" % e
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 Unicell 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"]
    else:
      ip = None
      netmask = None
    #print ip_info
    old_boot_proto, err = networking.get_interface_bootproto(ifname)
    if err:
      raise Exception('Error retrieving interface information : %s'%err)
    



    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 config_changed:
      d = {}
      d['addr_type'] = boot_proto
      if boot_proto == 'static':
        d['ip'] = ip
        d['netmask'] = netmask
      ret, err = networking.set_interface_ip_info(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:
        (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
        use_salt, err = common.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