def _get_ad_users_or_groups(type):
  d = load_auth_settings()
  workgroup = d['workgroup']
  if type and type=="users":
    c = command.execute_with_rc("wbinfo -u --domain=%s"%workgroup)
  elif type and type=="groups":
    c = command.execute_with_rc("wbinfo -g --domain=%s"%workgroup)
  else:
    raise Exception("Unknown type specified to retrieve AD users or groups.")

  o = command.get_output_list(c[0])
  #print "wbinfo output = "
  #print o
  e = command.get_error_list(c[0])
  #print "error = "
  #print e
  if c[1] != 0:
    err = ""
    if o:
      err += " ".join(o)
      err += ". "
    if e:
      err += " ".join(e)
    raise Exception("Error getting AD users: %s."%err)
  else:
    return o
예제 #2
0
def ssh_dir_permissions(user='******'):
  try:
    # /bin/su -s /bin/bash -c \"%s\" %s
    uid = pwd.getpwnam(user).pw_uid
    gid = grp.getgrnam("integralstor").gr_gid 
    
    
    path = _get_ssh_dir(user)
    os.chown(path, uid, gid)
    ssh_perm = "/bin/su -s /bin/bash -c 'chmod 700 %s' %s"%(path,user)
    (ret, rc), err = command.execute_with_rc(ssh_perm,True)
    if err:
      raise Exception(err)

    path = _get_authorized_file(user)
    if not os.path.isfile(path):
      with open(path, 'w') as f:
        f.close()

    os.chown(path, uid, gid)
    authorized_key = "/bin/su -s /bin/bash -c 'chmod 640 %s' %s"%(path,user)
    (ret, rc), err = command.execute_with_rc(authorized_key,True)
    if err:
      raise Exception(err)

    path = _get_known_hosts(user)
    if not os.path.isfile(path):
      with open(path, 'w') as f:
        f.close()
    if os.path.isfile(path):
      os.chown(path, uid, gid)
    return True,None
  except Exception,e:
    return False,"Error changing ssh dir permissions: %s"%str(e)
def add_acl(target_name, acl):
  try:
    if not target_name:
      raise Exception('No Target Specified')
    if not acl:
      raise Exception('No ACL specified')

    target, err = get_target(target_name)
    if err:
      raise Exception(err)

    if not target:
      raise Exception('Specified target not found')

    acls = target['acl']

    #First remove ALL from the ACL list
    if acls and 'ALL' in acls:
      cmd = 'tgtadm --lld iscsi --mode target --op unbind --tid %d -I ALL'%target['tid']
      (ret, rc), err = command.execute_with_rc(cmd)
      if err:
        raise Exception(err)
      if rc != 0:
        err = ''
        tl, er = command.get_output_list(ret)
        if er:
          raise Exception(er)
        if tl:
          err = ','.join(tl)
        tl, er = command.get_error_list(ret)
        if er:
          raise Exception(er)
        if tl:
          err = err + ','.join(tl)
        raise Exception('Error removind wildcard ACL : %s'%err)

    cmd = 'tgtadm --lld iscsi --mode target --op bind --tid %d -I %s'%(target['tid'], acl)
    (ret, rc), err = command.execute_with_rc(cmd)
    if err:
      raise Exception(err)
    if rc != 0:
      err = ''
      tl, er = command.get_output_list(ret)
      if er:
        raise Exception(er)
      if tl:
        err = ','.join(tl)
      tl, er = command.get_error_list(ret)
      if er:
        raise Exception(er)
      if tl:
        err = err + ','.join(tl)
      raise Exception(err)
    conf, err = _generate_targets_conf()
    if err:
      raise Exception(err)

  except Exception, e:
    return False, 'Error adding ACL: %s'%str(e)
예제 #4
0
def restart_samba_services():
  try:
    use_salt, err = common.use_salt()
    if err:
      raise Exception(err)
    if use_salt:
      client = salt.client.LocalClient()
      rc = client.cmd('*', 'service.reload', ['smbd'] )
      print rc
      rc = client.cmd('*', 'service.reload', ['winbind'] )
      print rc
      #rc = client.cmd('*', 'service.reload', ['nmbd'] )
      #print rc
    else:
      (ret, rc), err = command.execute_with_rc('service smb reload')
      if err:
        raise Exception(err)
      (ret, rc), err = command.execute_with_rc('service winbind reload')
      if err:
        raise Exception(err)
      if rc != 0:
        err = ''
        tl, er = command.get_output_list(ret)
        if er:
          raise Exception(er)
        if tl:
          err = ','.join(tl)
        tl, er = command.get_error_list(ret)
        if er:
          raise Exception(er)
        if tl:
          err = err + ','.join(tl)
        raise Exception("Return code : %d. Error : %s"%(rc, err))
      (ret, rc), err = command.execute_with_rc('service nmb reload')
      if err:
        raise Exception(err)
      if rc != 0:
        err = ''
        tl, er = command.get_output_list(ret)
        if er:
          raise Exception(er)
        if tl:
          err = ','.join(tl)
        tl, er = command.get_error_list(ret)
        if er:
          raise Exception(er)
        if tl:
          err = err + ','.join(tl)
        raise Exception("Return code : %d. Error : %s"%(rc, err))
  except Exception, e:
    return False, 'Error restarting samba services: %s'%str(e)
예제 #5
0
def remove_acl(target_name, acl):
    try:
        if not target_name:
            raise Exception('No Target Specified')
        if not acl:
            raise Exception('No ACL specified')

        target, err = get_target(target_name)
        if err:
            raise Exception(err)

        if not target:
            raise Exception('Specified target not found')

        acls = target['acl']
        if not acls:
            raise Exception('No ACLs found')

        if acl not in acls:
            raise Exception('Specified ACL not found')

        cmd = 'tgtadm --lld iscsi --mode target --op unbind --tid %d -I %s' % (
            target['tid'], acl)
        (ret, rc), err = command.execute_with_rc(cmd)
        if err:
            raise Exception(err)
        if rc != 0:
            #Could be an initiator name so try this..
            cmd = 'tgtadm --lld iscsi --mode target --op unbind --tid %d --initiator-name %s' % (
                target['tid'], acl)
            ret, rc = command.execute_with_rc(cmd)
            if rc != 0:
                err = ''
                tl, er = command.get_output_list(ret)
                if er:
                    raise Exception(er)
                if tl:
                    err = ','.join(tl)
                tl, er = command.get_error_list(ret)
                if er:
                    raise Exception(er)
                if tl:
                    err = err + ','.join(tl)
                raise Exception(err)
        conf, err = _generate_targets_conf()
        if err:
            raise Exception(err)

    except Exception, e:
        return False, 'Error removing ACL: %s' % str(e)
def remove_acl(target_name, acl):
  try:
    if not target_name:
      raise Exception('No Target Specified')
    if not acl:
      raise Exception('No ACL specified')

    target, err = get_target(target_name)
    if err:
      raise Exception(err)

    if not target:
      raise Exception('Specified target not found')

    acls = target['acl']
    if not acls:
      raise Exception('No ACLs found')

    if acl not in acls:
      raise Exception('Specified ACL not found')


    cmd = 'tgtadm --lld iscsi --mode target --op unbind --tid %d -I %s'%(target['tid'], acl)
    (ret, rc), err = command.execute_with_rc(cmd)
    if err:
      raise Exception(err)
    if rc != 0:
      #Could be an initiator name so try this..
      cmd = 'tgtadm --lld iscsi --mode target --op unbind --tid %d --initiator-name %s'%(target['tid'], acl)
      ret, rc = command.execute_with_rc(cmd)
      if rc != 0:
        err = ''
        tl, er = command.get_output_list(ret)
        if er:
          raise Exception(er)
        if tl:
          err = ','.join(tl)
        tl, er = command.get_error_list(ret)
        if er:
          raise Exception(er)
        if tl:
          err = err + ','.join(tl)
        raise Exception(err)
    conf, err = _generate_targets_conf()
    if err:
      raise Exception(err)

  except Exception, e:
    return False, 'Error removing ACL: %s'%str(e)
예제 #7
0
def create_target(name):
    try:
        targets, err = get_targets()
        if err:
            raise Exception(err)
        highest_tid = 0
        if targets:
            for t in targets:
                if int(t['tid']) > highest_tid:
                    highest_tid = int(t['tid'])
        new_tid = highest_tid + 1
        target_name = 'com.fractalio.integralstor-unicell:%s' % name
        cmd = 'tgtadm --lld iscsi --mode target --op new --tid %d -T %s' % (
            new_tid, target_name)
        (ret, rc), err = command.execute_with_rc(cmd)
        if err:
            raise Exception(err)
        if rc != 0:
            err = ''
            tl, er = command.get_output_list(ret)
            if er:
                raise Exception(er)
            if tl:
                err = ','.join(tl)
            tl, er = command.get_error_list(ret)
            if er:
                raise Exception(er)
            if tl:
                err = err + ','.join(tl)
            raise Exception(err)
        conf, err = _generate_targets_conf()
        if err:
            raise Exception(err)
    except Exception, e:
        return False, 'Error creating target : %s' % str(e)
def delete_target(name):
  try:
    target, err = get_target(name)
    if err:
      raise Exception(err)
    if not target:
      raise Exception('Specified target not found')
    cmd = 'tgtadm --lld iscsi --mode target --op delete --tid %d'%target['tid']
    (ret, rc), err = command.execute_with_rc(cmd)
    if err:
      raise Exception(err)
    if rc != 0:
      err = ''
      tl, er = command.get_output_list(ret)
      if er:
        raise Exception(er)
      if tl:
        err = ','.join(tl)
      tl, er = command.get_error_list(ret)
      if er:
        raise Exception(er)
      if tl:
        err = err + ','.join(tl)
      raise Exception(err)
    conf, err = _generate_targets_conf()
    if err:
      raise Exception(err)
  except Exception, e:
    return False, 'Error deleting target : %s'%str(e)
def create_target(name):
  try:
    targets,err = get_targets()
    if err:
      raise Exception(err)
    highest_tid = 0
    if targets :
      for t in targets:
        if int(t['tid']) > highest_tid:
          highest_tid = int(t['tid'])
    new_tid = highest_tid + 1
    target_name = 'com.fractalio.integralstor_unicell:%s'%name
    cmd = 'tgtadm --lld iscsi --mode target --op new --tid %d -T %s'%(new_tid, target_name)
    (ret, rc), err = command.execute_with_rc(cmd)
    if err:
      raise Exception(err)
    if rc != 0:
      err = ''
      tl, er = command.get_output_list(ret)
      if er:
        raise Exception(er)
      if tl:
        err = ','.join(tl)
      tl, er = command.get_error_list(ret)
      if er:
        raise Exception(er)
      if tl:
        err = err + ','.join(tl)
      raise Exception(err)
    conf, err = _generate_targets_conf()
    if err:
      raise Exception(err)
  except Exception, e:
    return False, 'Error creating target : %s'%str(e)
def _get_service_status(service):
  d = {}
  try:
    (ret, rc), err = command.execute_with_rc('service %s status'%service[0])
    if err:
      raise Exception(err)
    d['status_code'] = rc
    if rc == 0:
      d['status_str'] = 'Running'
    elif rc == 3:
      d['status_str'] = 'Stopped'
    elif rc == 1:
      d['status_str'] = 'Error'
    d['output_str'] = ''
    out, err = command.get_output_list(ret)
    if err:
      raise Exception(err)
    if out:
      d['output_str'] += ','.join(out)
    err, e = command.get_error_list(ret)
    if e:
      raise Exception(e)
    if err:
      d['output_str'] += ','.join(err)
  except Exception, e:
    return None, 'Error retrieving service status : %s'%str(e)
예제 #11
0
def generate_default_primary_named_conf(primary_ip, primary_netmask, secondary_ip, generate_forwarders = False, forwarder_ip = None, generate_zone_file = True):
  rc = 0
  try :
    primary_cidr_netmask, err = get_subnet_in_cidr_format(primary_ip, primary_netmask)
    if err:
      raise Exception(err)

    with open('/etc/named.conf', 'w') as f:
      f.write('// Generated by the IntegralStor script\n')
      f.write("options {\n")
      f.write(" listen-on port 53 { any; };\n")
      f.write(" listen-on-v6 port 53 { ::1; };\n")
      f.write(' directory 	"/var/named";\n')
      f.write(' dump-file 	"/var/named/data/cache_dump.db";\n')
      f.write(' statistics-file "/var/named/data/named_stats.txt";\n')
      f.write(' memstatistics-file "/var/named/data/named_mem_stats.txt";\n')
      f.write(" allow-query     { localhost; any; };\n")
      f.write(" allow-transfer  { localhost; %s; };\n"%secondary_ip)
      if generate_forwarders:
        f.write(" forwarders    { %s; };\n"%forwarder_ip)
        f.write(" recursion yes;\n")
      else:
        f.write(" recursion no;\n")
      f.write("};\n")

      f.write("logging {\n")
      f.write(" channel default_debug {\n")
      f.write('   file "data/named.run";\n')
      f.write("   severity dynamic;\n")
      f.write(" };\n")
      f.write("};\n")


      f.write('zone "." IN {\n')
      f.write(" type hint;\n")
      f.write(' file "named.ca";\n')
      f.write("};\n")

      f.write('zone "integralstor.lan" IN {\n')
      f.write(" type master;\n")
      f.write(' file "integralstor.for";\n')
      f.write(" allow-update { localhost; %s; };\n"%primary_cidr_netmask)
      f.write("};\n")

      f.write('include "/etc/named.rfc1912.zones";\n')
      f.flush()
    f.close()
    if generate_zone_file:
      rc, err = generate_default_zone_file(primary_ip, secondary_ip)
      if err:
        raise Exception(err)
      if not rc :
        raise Exception ('Error generating the default zone file')
    (r, rc), err = command.execute_with_rc('service named reload')
    if err:
      raise Exception(err)
    if rc != 0:
      raise Exception("Error restarting the DNS server")
  except Exception, e:
    return False, "Error generating the master DNS configuration file : %s"%str(e)
예제 #12
0
def get_all_disks_by_name():

    #Returns a list of all disks by name (sda/sbd, etc) in the sytem
    dl = []
    try:
        cmd_dl = "/usr/sbin/smartctl --scan"
        (ret, rc), err = command.execute_with_rc(cmd_dl)
        if err:
            raise Exception(err)
        disk_list, err = command.get_output_list(ret)
        if err:
            raise Exception(err)

        if ret:
            # Regex to capture "/dev/sdX"
            reg_exp_dl = re.compile("(/dev/[a-z]+)")

            for line in disk_list:
                d = {}
                if reg_exp_dl.search(line):
                    result_dl = re.search(r'/dev/sd[a-z]+', line)
                    result_dl1 = re.search(r'/dev/(sd[a-z]+)', line)
                    if result_dl:
                        d["full_path"] = result_dl.group()
                        dname = result_dl1.groups()[0]
                        r = re.match('^sd[a-z]+', dname)
                        d["name"] = r.group()
                        dl.append(d)
        #print "disk list info: ", dl
    except Exception, e:
        return None, "Error retrieving disks by name : %s" % str(e)
예제 #13
0
def delete_target(name):
    try:
        target, err = get_target(name)
        if err:
            raise Exception(err)
        if not target:
            raise Exception('Specified target not found')
        cmd = 'tgtadm --lld iscsi --mode target --op delete --tid %d' % target[
            'tid']
        (ret, rc), err = command.execute_with_rc(cmd)
        if err:
            raise Exception(err)
        if rc != 0:
            err = ''
            tl, er = command.get_output_list(ret)
            if er:
                raise Exception(er)
            if tl:
                err = ','.join(tl)
            tl, er = command.get_error_list(ret)
            if er:
                raise Exception(er)
            if tl:
                err = err + ','.join(tl)
            raise Exception(err)
        conf, err = _generate_targets_conf()
        if err:
            raise Exception(err)
    except Exception, e:
        return False, 'Error deleting target : %s' % str(e)
예제 #14
0
def services_status():
    s = {}
    try:
        platform, err = common.get_platform()
        if err:
            raise Exception(err)
        if platform == 'gridcell':
            #Commenting out ctdb for now as we wont use it for this release!
            #services = ['smb', 'winbind', 'ctdb', 'glusterd']
            services = ['smb', 'winbind', 'glusterd']
            for service_name in services:
                stat, err = command.get_command_output(
                    '/sbin/service %s status' % service_name)
                ret = None
                rc = -1
                tup, err = command.execute_with_rc('/sbin/service %s status' %
                                                   service_name)
                if tup:
                    (ret, rc) = tup
                if err:
                    raise Exception(err)
                if rc == 0:
                    lines, er = command.get_output_list(ret)
                    if er:
                        raise Exception(er)
                    s[service_name] = [0, ','.join(lines)]
                else:
                    err = ''
                    tl, er = command.get_output_list(ret)
                    if er:
                        raise Exception(er)
                    if tl:
                        err = ','.join(tl)
                    tl, er = command.get_error_list(ret)
                    if er:
                        raise Exception(er)
                    if tl:
                        err = err + ','.join(tl)
                    s[service_name] = [-1, err]
        else:
            service_dict, err = services_management.get_sysd_services_status()
            if err:
                raise Exception(err)
            for service_name, service_info in service_dict.items():
                if service_info['info']['status']['status_str'] in [
                        'Failed', 'Unknown State'
                ]:
                    s[service_name] = [
                        -1, service_info['info']['status']['output_str']
                    ]
                else:
                    s[service_name] = [
                        0, service_info['info']['status']['output_str']
                    ]
    except Exception, e:
        return None, 'Error retrieving services status: %s' % str(e)
예제 #15
0
def generate_ssh_key(user='******'):
  try:
    cmd = "ssh-keygen -t rsa -f %s -N ''"%(_get_ssh_dir(user)+"/id_rsa")
    runuser = "******"%s\" %s "%(cmd,user)
    (ret, rc), err = command.execute_with_rc(runuser,True)
    if err:
      raise Exception(err)
    return True,None
  except Exception,e:
    return None,"Error while generating ssh file for user: %s. Error : %s"%(user,str(e))
def mount_and_configure():
    try:
        pog, err = is_part_of_grid()
        if err:
            raise Exception(err)
        if pog:
            admin_vol_name, err = common.get_admin_vol_name()
            if err:
                raise Exception(err)

            # Get the config dir - the mount point.
            config_dir, err = common.get_config_dir()
            if err:
                raise Exception(err)

            ag, err = is_admin_gridcell()
            if err:
                raise Exception(err)

            admin_gridcells, err = get_admin_gridcells()
            if err:
                raise Exception(err)

            mounted, err = is_admin_vol_mounted()
            if not mounted:
                for admin_gridcell in admin_gridcells:
                    reachable, err = networking.can_ping(admin_gridcell)
                    if reachable:
                        (ret, rc), err = command.execute_with_rc(
                            'mount -t glusterfs %s:/%s %s' %
                            (admin_gridcell, admin_vol_name, config_dir))
                        if (not err) and (rc == 0):
                            mounted = True
                            break
                        else:
                            print 'Mount from %s failed.' % admin_gridcell

            if mounted:
                path_dict = {
                    '/etc/krb5.conf': '%s/lock/krb5.conf' % config_dir,
                    '/etc/samba/smb.conf': '%s/lock/smb.conf' % config_dir,
                    '/etc/ctdb/nodes': '%s/lock/smb.conf' % config_dir,
                    '/etc/sysconfig/ctdb': '%s/lock/ctdb' % config_dir
                }
                for link, file in path_dict.items():
                    if os.path.islink(link) or os.path.isfile(link):
                        print link, 'exists so removing'
                        os.remove(link)
                    os.symlink(file, link)
            else:
                raise Exception('Could not mount the admin volume')
    except Exception, e:
        return False, str(e)
예제 #17
0
def delete_route(name,netmask='255.255.255.0'):
  if not name:
    return False,"Interface name missing"
  else:
    if name == 'default':
      cmd = 'route del -net 0.0.0.0 netmask '+netmask
    else: 
      cmd = 'route del -net '+name+' netmask '+netmask
    (ret,rc),err = command.execute_with_rc(cmd)
    if err:
      return False,err
    return (ret,rc),None
예제 #18
0
def generate_default_secondary_named_conf(primary_ip, secondary_netmask, secondary_ip, generate_forwarders = False, forwarder_ip = None):
  try :
    secondary_cidr_netmask, err = get_subnet_in_cidr_format(primary_ip, secondary_netmask)
    if err:
      raise Exception(err)

    with open('/etc/named.conf', 'w') as f:
      f.write('// Generated by the IntegralStor script\n')
      f.write('options {\n')
      f.write('  listen-on port 53 { any; };\n')
      f.write('  listen-on-v6 port 53 { ::1; };\n')
      f.write('  directory 	"/var/named";\n')
      f.write('  dump-file 	"/var/named/data/cache_dump.db";\n')
      f.write('  statistics-file "/var/named/data/named_stats.txt";\n')
      f.write('  memstatistics-file "/var/named/data/named_mem_stats.txt";\n')
      f.write('  allow-query     { localhost; %s; };\n'%secondary_cidr_netmask)
      if generate_forwarders:
        f.write("   forwarders    { %s; };\n"%forwarder_ip)
        f.write('  recursion yes;\n')
      else:
        f.write('  recursion no;\n')
      f.write('};\n')

      f.write('logging {\n')
      f.write('  channel default_debug {\n')
      f.write('    file "data/named.run";\n')
      f.write('    severity dynamic;\n')
      f.write('  };\n')
      f.write('};\n')


      f.write('zone "." IN {\n')
      f.write('  type hint;\n')
      f.write('  file "named.ca";\n')
      f.write('};\n')


      f.write('zone "integralstor.lan" IN {\n')
      f.write('  type slave;\n')
      f.write('  file "slaves/integralstor.for";\n')
      f.write('  masters { %s; };\n'%primary_ip)
      f.write('};\n')
      f.write('include "/etc/named.rfc1912.zones";\n')
      f.flush()
    f.close()
    (r, rc), err = command.execute_with_rc('service named restart')
    if err:
      raise Exception(err)
    if rc != 0:
      raise Exception("Error restarting the DNS server")
  except Exception, e:
    return False, "Error generating the DNS slave configuration file : %s"%e
예제 #19
0
def delete_lun(target_name, backing_store):

    try:

        if not target_name:
            raise ('No target name specified')
        if not backing_store:
            raise ('No backing store path specified')

        target, err = get_target(target_name)
        if err:
            raise Exception(err)
        if not target:
            raise Exception('Specified target not found.')

        luns = target['luns']
        if not luns:
            raise Exception('Specified target does not have any LUNs.')

        lun = None
        for tl in luns:
            if tl['path'] == backing_store:
                lun = tl

        if not lun:
            raise Exception('Specified LUN not found.')

        cmd = 'tgtadm --lld iscsi --mode logicalunit --op delete --tid %d --lun %d' % (
            target['tid'], lun['id'])
        (ret, rc), err = command.execute_with_rc(cmd)
        if err:
            raise Exception(err)
        if rc != 0:
            err = ''
            tl, er = command.get_output_list(ret)
            if er:
                raise Exception(er)
            if tl:
                err = ','.join(tl)
            tl, er = command.get_error_list(ret)
            if er:
                raise Exception(er)
            if tl:
                err = err + ','.join(tl)
            raise Exception(err)
        conf, err = _generate_targets_conf()
        if err:
            raise Exception(err)

    except Exception, e:
        return False, 'Error Deleting Logical Unit: %s' % str(e)
def delete_lun(target_name,backing_store):

  try:

    if not target_name:
      raise ('No target name specified')
    if not backing_store:
      raise ('No backing store path specified')

    target, err = get_target(target_name)
    if err:
      raise Exception(err)
    if not target:
      raise Exception('Specified target not found.')

    luns = target['luns']
    if not luns:
      raise Exception('Specified target does not have any LUNs.')

    lun = None
    for tl in luns:
      if tl['path'] == backing_store:
        lun = tl

    if not lun:
      raise Exception('Specified LUN not found.')
        
    cmd = 'tgtadm --lld iscsi --mode logicalunit --op delete --tid %d --lun %d'%(target['tid'], lun['id'])
    (ret, rc), err = command.execute_with_rc(cmd)
    if err:
      raise Exception(err)
    if rc != 0:
      err = ''
      tl, er = command.get_output_list(ret)
      if er:
        raise Exception(er)
      if tl:
        err = ','.join(tl)
      tl, er = command.get_error_list(ret)
      if er:
        raise Exception(er)
      if tl:
        err = err + ','.join(tl)
      raise Exception(err)
    conf, err = _generate_targets_conf()
    if err:
      raise Exception(err)

  except Exception, e:
    return False, 'Error Deleting Logical Unit: %s'%str(e)
예제 #21
0
def create_lun(target_name, backing_store):
    try:
        if not target_name:
            raise Exception('No Target Specified')
        if not backing_store:
            raise Exception('No backing storage volume specified')

        target, err = get_target(target_name)
        if err:
            raise Exception(err)

        if not target:
            raise Exception('Specified target not found')

        luns = target['luns']
        if not luns:
            raise Exception('Error retrieving LUN list')

        highest_lun_id = 0
        for lun in luns:
            if lun['id'] > highest_lun_id:
                highest_lun_id = lun['id']

        new_lun_id = highest_lun_id + 1

        cmd = 'tgtadm --lld iscsi --mode logicalunit --op new --tid %d --lun %d --backing-store %s' % (
            int(target['tid']), new_lun_id, backing_store)
        (ret, rc), err = command.execute_with_rc(cmd)
        if err:
            raise Exception(err)
        if rc != 0:
            err = ''
            tl, er = command.get_output_list(ret)
            if er:
                raise Exception(er)
            if tl:
                err = ','.join(tl)
            tl, er = command.get_error_list(ret)
            if er:
                raise Exception(er)
            if tl:
                err = err + ','.join(tl)
            raise Exception(err)
        conf, err = _generate_targets_conf()
        if err:
            raise Exception(err)

    except Exception, e:
        return False, 'Error creating LUN : %s' % str(e)
예제 #22
0
def add_route(name,gw,netmask='255.255.255.0',interface=None):
  if not name or not gw:
    return False,"Interface name or gateway missing"
  else:
    if name == 'default':
      cmd = 'route add -net 0.0.0.0 netmask '+netmask+' gw '+gw
    else: 
      cmd = 'route add -net '+name+' netmask '+netmask+' gw '+gw
    if interface:
      cmd = cmd + ' dev '+interface[0]
    print cmd
    (ret,rc),err = command.execute_with_rc(cmd)
    if err:
      return False,err
    return (ret,rc),None
def create_lun(target_name, backing_store):
  try:
    if not target_name:
      raise Exception('No Target Specified')
    if not backing_store:
      raise Exception('No backing storage volume specified')

    target, err = get_target(target_name)
    if err:
      raise Exception(err)

    if not target:
      raise Exception('Specified target not found')

    luns = target['luns']
    if not luns:
      raise Exception('Error retrieving LUN list')

    highest_lun_id = 0
    for lun in luns:
      if lun['id'] > highest_lun_id:
        highest_lun_id = lun['id']

    new_lun_id = highest_lun_id + 1

    cmd = 'tgtadm --lld iscsi --mode logicalunit --op new --tid %d --lun %d --backing-store %s'%(int(target['tid']), new_lun_id, backing_store)
    (ret, rc), err = command.execute_with_rc(cmd)
    if err:
      raise Exception(err)
    if rc != 0:
      err = ''
      tl, er = command.get_output_list(ret)
      if er:
        raise Exception(er)
      if tl:
        err = ','.join(tl)
      tl, er = command.get_error_list(ret)
      if er:
        raise Exception(er)
      if tl:
        err = err + ','.join(tl)
      raise Exception(err)
    conf, err = _generate_targets_conf()
    if err:
      raise Exception(err)

  except Exception, e:
    return False, 'Error creating LUN : %s'%str(e)
def mount_and_configure():
    try:
        pog, err = is_part_of_grid()
        if err:
            raise Exception(err)
        if pog:
            admin_vol_name, err = common.get_admin_vol_name()
            if err:
                raise Exception(err)

            # Get the config dir - the mount point.
            config_dir, err = common.get_config_dir()
            if err:
                raise Exception(err)

            ag, err = is_admin_gridcell()
            if err:
                raise Exception(err)

            admin_gridcells, err = get_admin_gridcells()
            if err:
                raise Exception(err)

            mounted, err = is_admin_vol_mounted()
            if not mounted:
                for admin_gridcell in admin_gridcells:
                    reachable, err = networking.can_ping(admin_gridcell)
                    if reachable:
                        (ret, rc), err = command.execute_with_rc(
                            'mount -t glusterfs %s:/%s %s' % (admin_gridcell, admin_vol_name, config_dir))
                        if (not err) and (rc == 0):
                            mounted = True
                            break
                        else:
                            print 'Mount from %s failed.' % admin_gridcell

            if mounted:
                path_dict = {'/etc/krb5.conf': '%s/lock/krb5.conf' % config_dir, '/etc/samba/smb.conf': '%s/lock/smb.conf' % config_dir,
                             '/etc/ctdb/nodes': '%s/lock/smb.conf' % config_dir, '/etc/sysconfig/ctdb': '%s/lock/ctdb' % config_dir}
                for link, file in path_dict.items():
                    if os.path.islink(link) or os.path.isfile(link):
                        print link, 'exists so removing'
                        os.remove(link)
                    os.symlink(file, link)
            else:
                raise Exception('Could not mount the admin volume')
    except Exception, e:
        return False, str(e)
예제 #25
0
def destroy_ramdisk(path, pool):
    try:
        if not path:
            raise Exception('No RAMDisk path specified')
        res, err = remove_from_ramdisks_config(pool, path)
        if err:
            raise Exception(err)
        if not res:
            raise Exception("Error removing ramdisk info from the conf file")
        cmd = 'umount %s' % path
        lines, err = command.get_command_output(cmd)
        if err:
            raise Exception('Error creating ramdisk : %s' % err)
        (ret, rc), err = command.execute_with_rc(cmd)
        if err:
            raise Exception('Error unmounting ramdisk : %s' % err)
    except Exception, e:
        return False, 'Error destroying ramdisk : %s' % str(e)
예제 #26
0
def delete_local_user(userid):

  error_list = []
  #First check if samba user exists. if so kick out
  ul = get_local_users()
  found = False
  if ul:
    for ud in ul:
      if ud["userid"] == userid:
        found = True
  if not found:
    raise Exception("Error deleting user. The user \"%s\" does not exist. "%userid)

  # Now check if system user exists. If so and is created by integralstor then delete..
  delete_system_user = False
  try:
    d = pwd.getpwnam(userid)
    name = d[4]
    if name.find("integralstor_user") == 0:
      delete_system_user = True
  except KeyError:
    pass

  if delete_system_user:
    '''
    #print "Deleting user %s from the system"%userid
    ret, rc = command.execute_with_rc(r'userdel %s'%userid)
    if rc != 0:
      raise Exception("Error deleting user from the underlying system. Return code : %d. "%rc)
    #print "Deleted user %s from the system"%userid
    '''
    client = salt.client.LocalClient()
    rc = client.cmd('*', 'user.delete', [userid] )
    for hostname, status in rc.items():
      if not status:
        error_list.append("Error deleting the userid on GRIDCell %s"%hostname)

  #print "Deleting user %s from the storage system"%userid
  ret, rc = command.execute_with_rc(r'pdbedit -d 1 -x %s'%userid)
  if rc != 0:
    raise Exception("Error deleting user from the storage system. Return code : %d. "%rc)
  #print "Deleted user %s from the storage system"%userid
  return error_list
예제 #27
0
def get_local_users():
  print "Comes Here"
  ret, rc = command.execute_with_rc("/usr/bin/pdbedit -d 1 -L")
  print ret
  if rc != 0:
    raise "Error retrieving user list. Return code : %d"%rc

  ul = command.get_output_list(ret)
  user_list = []
  for u in ul:
    l = u.split(':')
    if l:
      d = {}
      d["userid"] = l[0]
      if len(l) > 1:
        d["name"] = l[2]
      user_list.append(d)
  print user_list
  return user_list
예제 #28
0
def remove_user_authentication(target_name, username, authentication_type):
    try:
        if not target_name:
            raise "Target Not Specified"
        if not username:
            raise "Username Not Specified"

        target, err = get_target(target_name)
        if err:
            raise Exception(err)
        if not target:
            raise Exception('Specified target not found.')

        cmd = 'tgtadm --lld iscsi --mode account --op unbind --tid %d --user %s' % (
            target['tid'], username)
        if authentication_type == 'outgoing':
            cmd += ' --outgoing'
        (ret, rc), err = command.execute_with_rc(cmd)
        if err:
            raise Exception(err)
        if rc != 0:
            err = ''
            tl, er = command.get_output_list(ret)
            if er:
                raise Exception(er)
            if tl:
                err = ','.join(tl)
            tl, er = command.get_error_list(ret)
            if er:
                raise Exception(er)
            if tl:
                err = err + ','.join(tl)
            raise Exception(err)
        conf, err = _generate_targets_conf()
        if err:
            raise Exception(err)
    except Exception, e:
        return False, 'Error removing user autentication: %s' % str(e)
def remove_user_authentication(target_name, username, authentication_type):
  try:
    if not target_name:
      raise "Target Not Specified"
    if not username:
      raise "Username Not Specified"

    target, err = get_target(target_name)
    if err:
      raise Exception(err)
    if not target:
      raise Exception('Specified target not found.')

    cmd = 'tgtadm --lld iscsi --mode account --op unbind --tid %d --user %s'%(target['tid'], username)
    if authentication_type == 'outgoing':
      cmd += ' --outgoing'
    (ret, rc), err = command.execute_with_rc(cmd)
    if err:
      raise Exception(err)
    if rc != 0:
      err = ''
      tl, er = command.get_output_list(ret)
      if er:
        raise Exception(er)
      if tl:
        err = ','.join(tl)
      tl, er = command.get_error_list(ret)
      if er:
        raise Exception(er)
      if tl:
        err = err + ','.join(tl)
      raise Exception(err)
    conf, err = _generate_targets_conf()
    if err:
      raise Exception(err)
  except Exception, e:
    return False, 'Error removing user autentication: %s'%str(e)
예제 #30
0
def _generate_targets_conf(new_user=None):
    try:
        targets, err = get_targets()
        if err:
            raise Exception(err)
        config_targets, err = _load_targets_conf()
        if err:
            raise Exception(err)

        with open('/tmp/targets.conf', 'w') as f:
            f.write('default-driver iscsi\n')
            for target in targets:
                f.write('\n<target %s>\n' % target['iqn'])
                for lun in target['luns']:
                    if lun['path'] and lun['path'] != 'None':
                        f.write('  backing-store %s\n' % lun['path'])
                for acl in target['acl']:
                    if acl != 'ALL':
                        f.write('  initiator-address %s\n' % acl)
                config_target = None
                #First process new users if any
                if new_user and new_user['iqn'] == target['iqn']:
                    if new_user['type'] == 'incoming':
                        f.write('  incominguser %s %s\n' %
                                (new_user['username'], new_user['pswd']))
                    else:
                        f.write('  outgoinguser %s %s\n' %
                                (new_user['username'], new_user['pswd']))
                for account in target['accounts']:
                    #Now process existing users. Take the list from tgtadm, get pswds from existing config file and write it out again
                    for ct in config_targets:
                        if ct['iqn'] == target['iqn']:
                            config_target = ct
                            break
                    if account['type'] == 'incoming':
                        for ctiu in config_target['incoming_users']:
                            if ctiu['username'] == account['user']:
                                f.write('  incominguser %s %s\n' %
                                        (account['user'], ctiu['pswd']))
                    else:
                        for ctiu in config_target['outgoing_users']:
                            if ctiu['username'] == account['user']:
                                f.write('  outgoinguser %s %s\n' %
                                        (account['user'], ctiu['pswd']))
                f.write('</target>\n\n')
            f.flush()
            f.close()
        shutil.move('/tmp/targets.conf', '/etc/tgt/targets.conf')
        cmd = 'tgt-admin -e'
        (ret, rc), err = command.execute_with_rc(cmd)
        if err:
            raise Exception(err)
        if rc != 0:
            err = ''
            tl, er = command.get_output_list(ret)
            if er:
                raise Exception(er)
            if tl:
                err = ','.join(tl)
            tl, er = command.get_error_list(ret)
            if er:
                raise Exception(er)
            if tl:
                err = err + ','.join(tl)
            raise Exception(err)

    except Exception, e:
        return False, 'Error generating ISCSI config file: %s' % str(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
def display_status():

  try :
    hostname = socket.gethostname()
    use_salt, err = common.use_salt()
    if err:
      raise Exception(err)
    if use_salt:
      print "Salt master service status :",
      (r, rc), err = command.execute_with_rc('service salt-master status')
      if err:
        raise Exception(err)
      l, err = command.get_output_list(r)
      if err:
        raise Exception(err)
      if l:
        print '\n'.join(l)
      else:
        l, err = command.get_error_list(r)
        if err:
          raise Exception(err)
        if l:
          print '\n'.join(l)
      print "Salt minion service status :",
      (r, rc), err = command.execute_with_rc('service salt-minion status')
      if err:
        raise Exception(err)
      l, err = command.get_output_list(r)
      if err:
        raise Exception(err)
      if l:
        print '\n'.join(l)
      else:
        l, err = command.get_error_list(r)
        if err:
          raise Exception(err)
        print l
        if l:
          print '\n'.join(l)
    print "Samba service status :",
    (r, rc), err = command.execute_with_rc('service smb status')
    if err:
      raise Exception(err)
    l, err = command.get_output_list(r)
    if err:
      raise Exception(err)
    if l:
      print '\n'.join(l)
    else:
      l, err = command.get_error_list(r)
      if err:
        raise Exception(err)
      if l:
        print '\n'.join(l)
    print "Winbind service status :",
    (r, rc), err = command.execute_with_rc('service winbind status')
    if err:
      raise Exception(err)
    l, err = command.get_output_list(r)
    if err:
      raise Exception(err)
    if l:
      print '\n'.join(l)
    else:
      l, err = command.get_error_list(r)
      if err:
        raise Exception(err)
      if l:
        print '\n'.join(l)
  except Exception, e:
    print "Error displaying system status : %s"%e
    return -1
예제 #33
0
def process_tasks(node=socket.getfqdn()):
    try:

        db_path, err = common.get_db_path()
        if err:
            raise Exception(err)

        current_user = getpass.getuser()
        now = int(time.time())

        tasks_query = "select * from tasks where node == '" + node + "' and (status == 'error-retrying' or status == 'queued') and (initiate_time <= '%d');" % (
            now)
        print tasks_query
        tasks_to_process, err = db.read_multiple_rows(db_path, tasks_query)
        if err:
            raise Exception(err)
        print tasks_to_process

        if tasks_to_process is not None:

            for task in tasks_to_process:
                #print 'Processing task ', task['task_id']

                if task['last_run_time']:
                    seconds_since_last_run = (now - task['last_run_time'])
                    #retry_interval is in minutes!
                    if seconds_since_last_run < task['retry_interval'] * 60:
                        continue

                #Mark the task as running
                cmd = "update tasks set status = 'running', last_run_time=%d where task_id = '%d'" % (
                    now, task['task_id'])
                status, err = db.execute_iud(db_path, [
                    [cmd],
                ],
                                             get_rowid=True)
                #print status, err
                if err:
                    raise Exception(err)

                audit_str = "%s" % task['description']
                audit.audit("task_start",
                            audit_str,
                            None,
                            system_initiated=True)

                attempts = task['attempts']
                run_as_user_name = task['run_as_user_name']

                #Now process subtasks for the task
                subtasks_query = "select * from subtasks where task_id == '%d' and (status == 'error-retrying' or status == 'queued') order by subtask_id" % task[
                    'task_id']
                subtasks, err = db.read_multiple_rows(db_path, subtasks_query)
                if err:
                    raise Exception(err)

                #Assume task is complete unless proven otherwise
                task_completed = True

                # Iteriate through all the unfinished subtasks related to the task
                for subtask in subtasks:
                    #print 'subtask is ', subtask

                    subtask_id = subtask["subtask_id"]

                    status_update = "update subtasks set status = 'running' where subtask_id = '%d' and status is not 'cancelled'" % subtask_id
                    status, err = db.execute_iud(db_path, [
                        [status_update],
                    ],
                                                 get_rowid=True)
                    if err:
                        task_completed = False
                        break
                    #print subtask['command']
                    #print 'username is ', task['run_as_user_name']

                    #Now actually execute the command
                    #print 'not current user'
                    #This task is not to be meant to be executed by the current user so switch to that user
                    #print 'command is ', row['command']
                    (out, return_code), err = command.execute_with_rc(
                        subtask["command"],
                        shell=True,
                        run_as_user_name=run_as_user_name)
                    #print out, return_code, err

                    if out[0]:
                        output = re.sub("'", "", ''.join(out[0]))
                    else:
                        output = None
                    if out[1]:
                        error = re.sub("'", "", ''.join(out[1]))
                    else:
                        error = None

                    if return_code == 0:
                        # This means the command was successful. So update to completed
                        status_update = "update subtasks set status = 'completed', return_code='%d' where subtask_id = '%d' and status is not 'cancelled';" % (
                            return_code, subtask_id)
                        status, err = db.execute_iud(db_path, [
                            [status_update],
                        ],
                                                     get_rowid=True)
                        if err:
                            task_completed = False
                            break
                        else:
                            continue
                    else:
                        # Subtask command failed
                        if attempts > 1 or attempts == -2:
                            status_update = 'update subtasks set status = "error-retrying", return_code="%d" where subtask_id = "%d" and status is not "cancelled";' % (
                                return_code, subtask_id)
                        elif attempts in [0, 1]:
                            status_update = 'update scheduler_commands set status = "failed", return_code="%d"" where subtask_id = "%d" and status is not "cancelled";' % (
                                return_code, subtask_id)
                        execute, err = db.execute_iud(db_path, [
                            [status_update],
                        ],
                                                      get_rowid=True)
                        task_completed = False
                        break

                if task_completed:
                    status_update = "update tasks set status = 'completed' where task_id = '%d'" % task[
                        'task_id']
                else:
                    if attempts > 1:
                        status_update = "update tasks set status = 'error-retrying', attempts = %d where task_id = '%d' and status is not 'cancelled'" % (
                            attempts - 1, task['task_id'])
                    elif attempts == -2:
                        status_update = "update tasks set status = 'error-retrying', attempts = %d where task_id = '%d' and status is not 'cancelled'" % (
                            -2, task['task_id'])
                    else:
                        status_update = "update tasks set status = 'failed', attempts = '%d' where task_id = '%d' and status is not 'cancelled'" % (
                            0, task['task_id'])
                status, err = db.execute_iud(db_path, [
                    [status_update],
                ],
                                             get_rowid=True)
                if err:
                    raise Exception(err)

                if task_completed:
                    audit.audit("task_complete",
                                audit_str,
                                None,
                                system_initiated=True)
                else:
                    audit.audit("task_fail",
                                audit_str,
                                None,
                                system_initiated=True)

    except Exception as e:
        return False, 'Error processing tasks : %s' % e
    else:
        return True, None
def add_user_authentication(target_name, authentication_type, username,password): 
  try:
    tid = -1
    if not authentication_type:
      raise Exception('No authentication type specified')
    if not target_name:
      raise Exception('No target specified')
    if not username:
      raise Exception('No username specified')
    if not password:
      raise Exception('No password specified')

    target, err = get_target(target_name)
    if err:
      raise Exception(err)
    if not target:
      raise Exception('Specified target not found.')

    cmd1 = 'tgtadm --lld iscsi --mode account --op new --user %s --password %s'%(username, password)
    (ret, rc), err = command.execute_with_rc(cmd1)
    if err:
      raise Exception(err)
    if rc != 0:
      err = ''
      tl, er = command.get_output_list(ret)
      if er:
        raise Exception(er)
      if tl:
        err = ','.join(tl)
      tl, er = command.get_error_list(ret)
      if er:
        raise Exception(er)
      if tl:
        err = err + ','.join(tl)
      raise Exception(err)


    cmd2 = 'tgtadm --lld iscsi --mode account --op bind --tid %d --user %s'%(target['tid'], username)
    if authentication_type == 'outgoing':
      cmd2 += ' --outgoing'

    (ret, rc), err = command.execute_with_rc(cmd2)
    if err:
      raise Exception(err)
    if rc != 0:
      err = ''
      tl, er = command.get_output_list(ret)
      if er:
        raise Exception(er)
      if tl:
        err = ','.join(tl)
      tl, er = command.get_error_list(ret)
      if er:
        raise Exception(er)
      if tl:
        err = err + ','.join(tl)
      raise Exception(err)
    new_user_dict = {}
    new_user_dict['iqn'] = target['iqn']
    new_user_dict['username'] = username
    new_user_dict['type'] = authentication_type
    new_user_dict['pswd'] = password
    conf, err = _generate_targets_conf(new_user_dict)
    if err:
      raise Exception(err)

  except Exception, e:
    return False, 'Error Adding User: %s'%str(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"]
            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
예제 #36
0
def add_user_authentication(target_name, authentication_type, username,
                            password):
    try:
        tid = -1
        if not authentication_type:
            raise Exception('No authentication type specified')
        if not target_name:
            raise Exception('No target specified')
        if not username:
            raise Exception('No username specified')
        if not password:
            raise Exception('No password specified')

        target, err = get_target(target_name)
        if err:
            raise Exception(err)
        if not target:
            raise Exception('Specified target not found.')

        cmd1 = 'tgtadm --lld iscsi --mode account --op new --user %s --password %s' % (
            username, password)
        (ret, rc), err = command.execute_with_rc(cmd1)
        if err:
            raise Exception(err)
        if rc != 0:
            err = ''
            tl, er = command.get_output_list(ret)
            if er:
                raise Exception(er)
            if tl:
                err = ','.join(tl)
            tl, er = command.get_error_list(ret)
            if er:
                raise Exception(er)
            if tl:
                err = err + ','.join(tl)
            raise Exception(err)

        cmd2 = 'tgtadm --lld iscsi --mode account --op bind --tid %d --user %s' % (
            target['tid'], username)
        if authentication_type == 'outgoing':
            cmd2 += ' --outgoing'

        (ret, rc), err = command.execute_with_rc(cmd2)
        if err:
            raise Exception(err)
        if rc != 0:
            err = ''
            tl, er = command.get_output_list(ret)
            if er:
                raise Exception(er)
            if tl:
                err = ','.join(tl)
            tl, er = command.get_error_list(ret)
            if er:
                raise Exception(er)
            if tl:
                err = err + ','.join(tl)
            raise Exception(err)
        new_user_dict = {}
        new_user_dict['iqn'] = target['iqn']
        new_user_dict['username'] = username
        new_user_dict['type'] = authentication_type
        new_user_dict['pswd'] = password
        conf, err = _generate_targets_conf(new_user_dict)
        if err:
            raise Exception(err)

    except Exception, e:
        return False, 'Error Adding User: %s' % str(e)
예제 #37
0
def add_acl(target_name, acl):
    try:
        if not target_name:
            raise Exception('No Target Specified')
        if not acl:
            raise Exception('No ACL specified')

        target, err = get_target(target_name)
        if err:
            raise Exception(err)

        if not target:
            raise Exception('Specified target not found')

        acls = target['acl']

        #First remove ALL from the ACL list
        if acls and 'ALL' in acls:
            cmd = 'tgtadm --lld iscsi --mode target --op unbind --tid %d -I ALL' % target[
                'tid']
            (ret, rc), err = command.execute_with_rc(cmd)
            if err:
                raise Exception(err)
            if rc != 0:
                err = ''
                tl, er = command.get_output_list(ret)
                if er:
                    raise Exception(er)
                if tl:
                    err = ','.join(tl)
                tl, er = command.get_error_list(ret)
                if er:
                    raise Exception(er)
                if tl:
                    err = err + ','.join(tl)
                raise Exception('Error removind wildcard ACL : %s' % err)

        cmd = 'tgtadm --lld iscsi --mode target --op bind --tid %d -I %s' % (
            target['tid'], acl)
        (ret, rc), err = command.execute_with_rc(cmd)
        if err:
            raise Exception(err)
        if rc != 0:
            err = ''
            tl, er = command.get_output_list(ret)
            if er:
                raise Exception(er)
            if tl:
                err = ','.join(tl)
            tl, er = command.get_error_list(ret)
            if er:
                raise Exception(er)
            if tl:
                err = err + ','.join(tl)
            raise Exception(err)
        conf, err = _generate_targets_conf()
        if err:
            raise Exception(err)

    except Exception, e:
        return False, 'Error adding ACL: %s' % str(e)
def _generate_targets_conf(new_user = None):
  try:
    targets, err = get_targets()
    if err:
      raise Exception(err)
    config_targets, err = _load_targets_conf()
    if err:
      raise Exception(err)

    with open('/tmp/targets.conf','w') as f:
      f.write('default-driver iscsi\n')
      for target in targets:
        f.write('\n<target %s>\n'%target['iqn'])
        for lun in target['luns']:
          if lun['path'] and lun['path'] != 'None':
            f.write('  backing-store %s\n'%lun['path'])
        for acl in target['acl']:
          if acl != 'ALL':
            f.write('  initiator-address %s\n'%acl)
        config_target = None            
        #First process new users if any
        if new_user and new_user['iqn'] == target['iqn']:
          if new_user['type'] == 'incoming':
            f.write('  incominguser %s %s\n'%(new_user['username'], new_user['pswd']))
          else:
            f.write('  outgoinguser %s %s\n'%(new_user['username'], new_user['pswd']))
        for account in target['accounts']:
          #Now process existing users. Take the list from tgtadm, get pswds from existing config file and write it out again
          for ct in config_targets:
            if ct['iqn'] == target['iqn']:
              config_target = ct
              break
          if account['type'] == 'incoming':
            for ctiu in config_target['incoming_users']:
              if ctiu['username'] == account['user']:
                f.write('  incominguser %s %s\n'%(account['user'], ctiu['pswd']))
          else:
            for ctiu in config_target['outgoing_users']:
              if ctiu['username'] == account['user']:
                f.write('  outgoinguser %s %s\n'%(account['user'], ctiu['pswd']))
        f.write('</target>\n\n')
      f.flush()
      f.close()
    shutil.move('/tmp/targets.conf', '/etc/tgt/targets.conf')
    cmd = 'tgt-admin -e'
    (ret, rc), err = command.execute_with_rc(cmd)
    if err:
      raise Exception(err)
    if rc != 0:
      err = ''
      tl, er = command.get_output_list(ret)
      if er:
        raise Exception(er)
      if tl:
        err = ','.join(tl)
      tl, er = command.get_error_list(ret)
      if er:
        raise Exception(er)
      if tl:
        err = err + ','.join(tl)
      raise Exception(err)
            
  except Exception, e:
    return False, 'Error generating ISCSI config file: %s'%str(e)
def display_status():

    try:
        hostname = socket.gethostname()
        use_salt, err = common.use_salt()
        if err:
            raise Exception(err)
        if use_salt:
            print "Salt master service status :",
            (r,
             rc), err = command.execute_with_rc('service salt-master status')
            if err:
                raise Exception(err)
            l, err = command.get_output_list(r)
            if err:
                raise Exception(err)
            if l:
                print '\n'.join(l)
            else:
                l, err = command.get_error_list(r)
                if err:
                    raise Exception(err)
                if l:
                    print '\n'.join(l)
            print "Salt minion service status :",
            (r,
             rc), err = command.execute_with_rc('service salt-minion status')
            if err:
                raise Exception(err)
            l, err = command.get_output_list(r)
            if err:
                raise Exception(err)
            if l:
                print '\n'.join(l)
            else:
                l, err = command.get_error_list(r)
                if err:
                    raise Exception(err)
                print l
                if l:
                    print '\n'.join(l)
        print "Samba service status :",
        (r, rc), err = command.execute_with_rc('service smb status')
        if err:
            raise Exception(err)
        l, err = command.get_output_list(r)
        if err:
            raise Exception(err)
        if l:
            print '\n'.join(l)
        else:
            l, err = command.get_error_list(r)
            if err:
                raise Exception(err)
            if l:
                print '\n'.join(l)
        print "Winbind service status :",
        (r, rc), err = command.execute_with_rc('service winbind status')
        if err:
            raise Exception(err)
        l, err = command.get_output_list(r)
        if err:
            raise Exception(err)
        if l:
            print '\n'.join(l)
        else:
            l, err = command.get_error_list(r)
            if err:
                raise Exception(err)
            if l:
                print '\n'.join(l)
    except Exception, e:
        print "Error displaying system status : %s" % e
        return -1