Example #1
0
def update_admin_password(request):
    """ Used to change a user's password for the management utility"""

    try:
        return_dict = {}

        if request.user and request.user.is_authenticated():
            if request.method == 'POST':
                iv_logging.debug("Admin password change posted")
                # user has submitted the password info
                form = admin_forms.ChangeAdminPasswordForm(request.POST)
                if form.is_valid():
                    cd = form.cleaned_data
                    oldPasswd = cd['oldPasswd']
                    newPasswd1 = cd['newPasswd1']
                    newPasswd2 = cd['newPasswd2']
                    # Checking for old password is done in the form itself
                    if request.user.check_password(oldPasswd):
                        if newPasswd1 == newPasswd2:
                            # all systems go so now change password
                            request.user.set_password(newPasswd1)
                            request.user.save()
                            return_dict[
                                'ack_message'] = 'Password changed sucessful.'
                            iv_logging.info(
                                "Admin password change request successful.")
                            audit_str = "Changed admin password"
                            audit.audit("modify_admin_password", audit_str,
                                        request)
                        else:
                            return_dict['error'] = 'New passwords do not match'
                # else invalid form or error so existing form data to return_dict and
                # fall through to redisplay the form
                if 'success' not in return_dict:
                    return_dict['form'] = form
                    iv_logging.info("Admin password change request failed.")
            else:
                form = admin_forms.ChangeAdminPasswordForm()
                return_dict['form'] = form

            return django.shortcuts.render_to_response(
                'update_admin_password_form.html',
                return_dict,
                context_instance=django.template.context.RequestContext(
                    request))
        else:
            # User not authenticated so return a login screen
            return django.http.HttpResponseRedirect('/login/')
    except Exception, e:
        return_dict['base_template'] = "admin_base.html"
        return_dict["page_title"] = 'Change admininistrator password'
        return_dict['tab'] = 'change_admin_pswd_tab'
        return_dict["error"] = 'Error changing administrator password'
        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 configure_ntp_settings(request):

  return_dict = {}
  try:
    if request.method=="GET":
      ntp_servers, err = ntp.get_ntp_servers()
      if err:
        raise Exception(err)
      if not ntp_servers:
        form = common_forms.ConfigureNTPForm()
      else:
        form = common_forms.ConfigureNTPForm(initial={'server_list': ','.join(ntp_servers)})
      url = "edit_ntp_settings.html"
    else:
      form = common_forms.ConfigureNTPForm(request.POST)
      if form.is_valid():
        iv_logging.debug("Got valid request to change NTP settings")
        cd = form.cleaned_data
        si, err = system_info.load_system_config()
        if err:
          raise Exception(err)
        server_list = cd["server_list"]
        if ',' in server_list:
          slist = server_list.split(',')
        else:
          slist = server_list.split(' ')
        with open('/tmp/ntp.conf', 'w') as temp:
          #First create the ntp.conf file for the primary and secondary nodes
          temp.write("driftfile /var/lib/ntp/drift\n")
          temp.write("restrict default kod nomodify notrap nopeer noquery\n")
          temp.write("restrict -6 default kod nomodify notrap nopeer noquery\n")
          temp.write("logfile /var/log/ntp.log\n")
          temp.write("\n")
          for server in slist:
            temp.write("server %s iburst\n"%server)
          temp.flush()
          temp.close()
        shutil.move('/tmp/ntp.conf', '/etc/ntp.conf')
        #ret, err = ntp.restart_ntp_service()
        ret, err = services_management.change_service_status('ntpd', 'restart')
        if err:
          raise Exception(err)
        return django.http.HttpResponseRedirect("/view_ntp_settings?ack=saved")
      else:
        #invalid form
        iv_logging.debug("Got invalid request to change NTP settings")
        url = "edit_ntp_settings.html"
    return_dict["form"] = form
    return django.shortcuts.render_to_response(url, return_dict, context_instance = django.template.context.RequestContext(request))
  except Exception, e:
    return_dict['base_template'] = "system_base.html"
    return_dict["page_title"] = 'Modify NTP notifications settings'
    return_dict['tab'] = 'ntp_settings_tab'
    return_dict["error"] = 'Error modifying NTP notifications settings'
    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 configure_ntp_settings(request):

  return_dict = {}
  try:
    if request.method=="GET":
      ntp_servers, err = ntp.get_ntp_servers()
      if err:
        raise Exception(err)
      if not ntp_servers:
        form = common_forms.ConfigureNTPForm()
      else:
        form = common_forms.ConfigureNTPForm(initial={'server_list': ','.join(ntp_servers)})
      url = "edit_ntp_settings.html"
    else:
      form = common_forms.ConfigureNTPForm(request.POST)
      if form.is_valid():
        iv_logging.debug("Got valid request to change NTP settings")
        cd = form.cleaned_data
        si, err = system_info.load_system_config()
        if err:
          raise Exception(err)
        server_list = cd["server_list"]
        if ',' in server_list:
          slist = server_list.split(',')
        else:
          slist = server_list.split(' ')
        with open('/tmp/ntp.conf', 'w') as temp:
          #First create the ntp.conf file for the primary and secondary nodes
          temp.write("driftfile /var/lib/ntp/drift\n")
          temp.write("restrict default kod nomodify notrap nopeer noquery\n")
          temp.write("restrict -6 default kod nomodify notrap nopeer noquery\n")
          temp.write("logfile /var/log/ntp.log\n")
          temp.write("\n")
          for server in slist:
            temp.write("server %s iburst\n"%server)
          temp.flush()
          temp.close()
        shutil.move('/tmp/ntp.conf', '/etc/ntp.conf')
        ret, err = ntp.restart_ntp_service()
        if err:
          raise Exception(err)
        return django.http.HttpResponseRedirect("/show/ntp_settings?saved=1")
      else:
        #invalid form
        iv_logging.debug("Got invalid request to change NTP settings")
        url = "edit_ntp_settings.html"
    return_dict["form"] = form
    return django.shortcuts.render_to_response(url, return_dict, context_instance = django.template.context.RequestContext(request))
  except Exception, e:
    return_dict['base_template'] = "system_base.html"
    return_dict["page_title"] = 'Modify email notifications settings'
    return_dict['tab'] = 'email_tab'
    return_dict["error"] = 'Error modifying email notifications settings'
    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 login(request):
  """ Used to login a user into the management utility"""

  return_dict = {}
  authSucceeded = False

  if request.method == 'POST':
    iv_logging.info("Login request posted")
    # Someone is submitting info so check it
    form = admin_forms.LoginForm(request.POST)
    if form.is_valid():
      # submitted form is valid so now try to authenticate
      # if not valid then fall out to end of function and return form to user
      # with existing data
      cd = form.cleaned_data
      username = cd['username']
      password = cd['password']
      # Try to authenticate
      user = django.contrib.auth.authenticate(username=username, password=password)
      if user is not None and user.is_active:
        # Clear the session if the user has been logged in anywhere else.
        sessions = Session.objects.all()
        for s in sessions:
          if s.get_decoded() and (s.get_decoded()['_auth_user_id'] == user.id):
            s.delete()
        # authentication succeeded! Login and send to home screen
        django.contrib.auth.login(request, user)
        iv_logging.info("Login request from user '%s' succeeded"%username)
        authSucceeded = True
      else:
        iv_logging.info("Login request from user '%s' failed"%username)
        return_dict['invalidUser'] = True
    else:
      #Invalid form
      iv_logging.debug("Invalid login information posted")
  else:
    # GET request so create a new form and send back to user
    form = admin_forms.LoginForm()
    # Clear the session if the user has been logged in anywhere else.
    sessions = Session.objects.all()
    for s in sessions:
      if s.get_decoded() is not None and s.get_decoded().get('_auth_user_id') is not None:
        return_dict['session_active'] = True

  return_dict['form'] = form

  if authSucceeded:
    return django.http.HttpResponseRedirect('/show/dashboard/')

  # For all other cases, return to login screen with return_dict 
  # appropriately populated
  return django.shortcuts.render_to_response('login_form.html', return_dict, context_instance = django.template.context.RequestContext(request))
def update_ntp_settings(request):

    return_dict = {}
    try:
        if request.method == "GET":
            ntp_servers, err = ntp.get_ntp_servers()
            if err:
                raise Exception(err)
            if not ntp_servers:
                form = system_forms.ConfigureNTPForm()
            else:
                form = system_forms.ConfigureNTPForm(
                    initial={'server_list': ','.join(ntp_servers)})
            url = "update_ntp_settings.html"
        else:
            form = system_forms.ConfigureNTPForm(request.POST)
            if form.is_valid():
                iv_logging.debug("Got valid request to change NTP settings")
                cd = form.cleaned_data
                server_list = cd["server_list"]
                if ',' in server_list:
                    slist = server_list.split(',')
                else:
                    slist = server_list.split(' ')
                ret, err = ntp.update_integralstor_ntp_servers(slist)
                # print ret, err
                if err:
                    raise Exception(err)
                audit_str = "Modified NTP servers to %s" % server_list
                audit.audit("update_ntp_servers", audit_str, request)
                return django.http.HttpResponseRedirect(
                    "/system/view_ntp_settings?ack=saved")
            else:
                # invalid form
                iv_logging.debug("Got invalid request to change NTP settings")
                url = "update_ntp_settings.html"
        return_dict["form"] = form
        return django.shortcuts.render_to_response(
            url,
            return_dict,
            context_instance=django.template.context.RequestContext(request))
    except Exception, e:
        return_dict['base_template'] = "system_base.html"
        return_dict["page_title"] = 'Modify NTP notifications settings'
        return_dict['tab'] = 'ntp_settings_tab'
        return_dict["error"] = 'Error modifying NTP notifications settings'
        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))
Example #6
0
def edit_integral_view_log_level(request):

  return_dict = {}
  try:
    if request.method == 'POST':
      iv_logging.debug("Trying to change Integral View Log settings")
      form = log_management_forms.IntegralViewLoggingForm(request.POST)
      if form.is_valid():
        iv_logging.debug("Trying to change Integral View Log settings - form valid")
        cd = form.cleaned_data
        log_level = int(cd['log_level'])
        iv_logging.debug("Trying to change Integral View Log settings - log level is %d"%log_level)
        ret, err = iv_logging.set_log_level(log_level)
        if err:
          raise Exception(err)
        iv_logging.debug("Trying to change Integral View Log settings - changed log level")
        return django.http.HttpResponseRedirect("/show/integral_view_log_level?saved=1")
    else:
      init = {}
      init['log_level'] = iv_logging.get_log_level()
      form = log_management_forms.IntegralViewLoggingForm(initial=init)
      return_dict['form'] = form
      return django.shortcuts.render_to_response('edit_integral_view_log_level.html', return_dict, context_instance=django.template.context.RequestContext(request))
  except Exception, e:
    return_dict['base_template'] = "logging_base.html"
    return_dict["page_title"] = 'Modify IntegralView log level'
    return_dict['tab'] = 'view_current_audit_tab'
    return_dict["error"] = 'Error modifying IntegralView log level'
    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 update_admin_password(request):
    """ Used to change a user's password for the management utility"""

    try:
        return_dict = {}

        if request.user and request.user.is_authenticated():
            if request.method == 'POST':
                iv_logging.debug("Admin password change posted")
                # user has submitted the password info
                form = admin_forms.ChangeAdminPasswordForm(request.POST)
                if form.is_valid():
                    cd = form.cleaned_data
                    oldPasswd = cd['oldPasswd']
                    newPasswd1 = cd['newPasswd1']
                    newPasswd2 = cd['newPasswd2']
                    # Checking for old password is done in the form itself
                    if request.user.check_password(oldPasswd):
                        if newPasswd1 == newPasswd2:
                            # all systems go so now change password
                            request.user.set_password(newPasswd1)
                            request.user.save()
                            return_dict['ack_message'] = 'Password changed sucessful.'
                            iv_logging.info(
                                "Admin password change request successful.")
                            audit_str = "Changed admin password"
                            audit.audit("modify_admin_password",
                                        audit_str, request)
                        else:
                            return_dict['error'] = 'New passwords do not match'
                # else invalid form or error so existing form data to return_dict and
                # fall through to redisplay the form
                if 'success' not in return_dict:
                    return_dict['form'] = form
                    iv_logging.info("Admin password change request failed.")
            else:
                form = admin_forms.ChangeAdminPasswordForm()
                return_dict['form'] = form

            return django.shortcuts.render_to_response('update_admin_password_form.html', return_dict, context_instance=django.template.context.RequestContext(request))
        else:
            # User not authenticated so return a login screen
            return django.http.HttpResponseRedirect('/login/')
    except Exception, e:
        return_dict['base_template'] = "system_base.html"
        return_dict["page_title"] = 'Change admininistrator password'
        return_dict['tab'] = 'system_info_tab'
        return_dict["error"] = 'Error changing administrator password'
        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 edit_integral_view_log_level(request):

  return_dict = {}
  try:
    if request.method == 'POST':
      iv_logging.debug("Trying to change Integral View Log settings")
      form = log_management_forms.IntegralViewLoggingForm(request.POST)
      if form.is_valid():
        iv_logging.debug("Trying to change Integral View Log settings - form valid")
        cd = form.cleaned_data
        log_level = int(cd['log_level'])
        iv_logging.debug("Trying to change Integral View Log settings - log level is %d"%log_level)
        ret, err = iv_logging.set_log_level(log_level)
        if err:
          raise Exception(err)
        iv_logging.debug("Trying to change Integral View Log settings - changed log level")
        return django.http.HttpResponseRedirect("/show/integral_view_log_level?saved=1")
    else:
      init = {}
      init['log_level'] = iv_logging.get_log_level()
      form = log_management_forms.IntegralViewLoggingForm(initial=init)
      return_dict['form'] = form
      return django.shortcuts.render_to_response('edit_integral_view_log_level.html', return_dict, context_instance=django.template.context.RequestContext(request))
  except Exception, e:
    return_dict['base_template'] = "logging_base.html"
    return_dict["page_title"] = 'Modify IntegralView log level'
    return_dict['tab'] = 'view_current_audit_tab'
    return_dict["error"] = 'Error modifying IntegralView log level'
    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 configure_email_settings(request):

  return_dict = {}
  url = "edit_email_settings.html"
  if request.method=="GET":
    d = mail.load_email_settings()
    if not d:
      form = admin_forms.ConfigureEmailForm()
    else:
      if d["tls"]:
        d["tls"] = True
      else:
        d["tls"] = False
      if d["email_alerts"]:
        d["email_alerts"] = True
      else:
        d["email_alerts"] = False
      form = admin_forms.ConfigureEmailForm(initial = {'email_server':d["server"], 'email_server_port':d["port"], 'tls':d["tls"], 'username':d["username"], 'email_alerts':d["email_alerts"], 'rcpt_list':d["rcpt_list"]})
  else:
    form = admin_forms.ConfigureEmailForm(request.POST)
    if form.is_valid():
      cd = form.cleaned_data
      d = {}
      if "email_alerts" in cd:
        d["email_alerts"] = cd["email_alerts"]
      else:
        d["email_alerts"] = False
      d["server"] = cd["email_server"]
      d["port"] = cd["email_server_port"]
      d["username"] = cd["username"]
      d["pswd"] = cd["pswd"]
      d["rcpt_list"] = cd["rcpt_list"]
      if "tls" in cd:
        d["tls"] = cd["tls"]
      else:
        d["tls"] = False
      #print "Saving : "
      #print d
      try:
        mail.save_email_settings(d)
      except Exception, e:
        iv_logging.debug("Exception when trying to save email settings : %s"%e)
        return django.http.HttpResponseRedirect("/show/email_settings?not_saved=1&err=%s"%str(e))

      ret = mail.send_mail(cd["email_server"], cd["email_server_port"], cd["username"], cd["pswd"], cd["tls"], cd["rcpt_list"], "Test email from FractalView", "This is a test email sent by the Fractal View system in order to confirm that your email settings are working correctly.")
      if ret:
        return django.http.HttpResponseRedirect("/show/email_settings?saved=1&err=%s"%ret)
      else:
        return django.http.HttpResponseRedirect("/show/email_settings?saved=1")
def update_ntp_settings(request):

    return_dict = {}
    try:
        if request.method == "GET":
            ntp_servers, err = ntp.get_ntp_servers()
            if err:
                raise Exception(err)
            if not ntp_servers:
                form = system_forms.ConfigureNTPForm()
            else:
                form = system_forms.ConfigureNTPForm(
                    initial={'server_list': ','.join(ntp_servers)})
            url = "update_ntp_settings.html"
        else:
            form = system_forms.ConfigureNTPForm(request.POST)
            if form.is_valid():
                iv_logging.debug("Got valid request to change NTP settings")
                cd = form.cleaned_data
                server_list = cd["server_list"]
                if ',' in server_list:
                    slist = server_list.split(',')
                else:
                    slist = server_list.split(' ')
                ret, err = ntp.update_integralstor_ntp_servers(slist)
                # print ret, err
                if err:
                    raise Exception(err)
                audit_str = "Modified NTP servers to %s" % server_list
                audit.audit("update_ntp_servers",
                            audit_str, request)
                return django.http.HttpResponseRedirect("/system/view_ntp_settings?ack=saved")
            else:
                # invalid form
                iv_logging.debug("Got invalid request to change NTP settings")
                url = "update_ntp_settings.html"
        return_dict["form"] = form
        return django.shortcuts.render_to_response(url, return_dict, context_instance=django.template.context.RequestContext(request))
    except Exception, e:
        return_dict['base_template'] = "system_base.html"
        return_dict["page_title"] = 'Modify NTP notifications settings'
        return_dict['tab'] = 'ntp_settings_tab'
        return_dict["error"] = 'Error modifying NTP notifications settings'
        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 change_admin_password(request):
  """ Used to change a user's password for the management utility"""

  return_dict = {}

  if request.user and request.user.is_authenticated():
    if request.method == 'POST':
      iv_logging.debug("Admin password change posted")
      #user has submitted the password info
      form = admin_forms.ChangeAdminPasswordForm(request.POST)
      if form.is_valid():
        cd = form.cleaned_data
        oldPasswd = cd['oldPasswd']
        newPasswd1 = cd['newPasswd1']
        newPasswd2 = cd['newPasswd2']
        #Checking for old password is done in the form itself
        if request.user.check_password(oldPasswd):
          if newPasswd1 == newPasswd2:
            # all systems go so now change password
            request.user.set_password(newPasswd1);
            request.user.save()
            return_dict['success'] = True
            iv_logging.info("Admin password change request successful.")
            audit_str = "Changed admin password"
            audit.audit("modify_admin_password", audit_str, request.META["REMOTE_ADDR"])
          else:
	          return_dict['error'] = 'New passwords do not match'
      # else invalid form or error so existing form data to return_dict and 
      # fall through to redisplay the form
      if 'success' not in return_dict:
        return_dict['form'] = form
        iv_logging.info("Admin password change request failed.")
    else:
      form = admin_forms.ChangeAdminPasswordForm()
      return_dict['form'] = form

    return django.shortcuts.render_to_response('change_admin_password_form.html', return_dict, context_instance = django.template.context.RequestContext(request))
  else:
    #User not authenticated so return a login screen
    return django.http.HttpResponseRedirect('/login/')
def edit_integral_view_log_level(request):

  return_dict = {}
  try:
    if request.method == 'POST':
      iv_logging.debug("Trying to change Integral View Log settings")
      form = log_management_forms.IntegralViewLoggingForm(request.POST)
      if form.is_valid():
        iv_logging.debug("Trying to change Integral View Log settings - form valid")
        cd = form.cleaned_data
        log_level = int(cd['log_level'])
        iv_logging.debug("Trying to change Integral View Log settings - log level is %d"%log_level)
        try:
          iv_logging.set_log_level(log_level)
        except Exception, e:
          return_dict['error'] = 'Error setting log level : %s'%e
          return django.shortcuts.render_to_response('logged_in_error.html', return_dict, context_instance=django.template.context.RequestContext(request))
        iv_logging.debug("Trying to change Integral View Log settings - changed log level")
        return django.http.HttpResponseRedirect("/show/integral_view_log_level?saved=1")
    else:
Example #13
0
def download_sys_log(request):
    """ Download the system log of the type specified in sys_log_type POST param for the node specified in the hostname POST parameter. 
    This calls the /sys_log via an http request on that node to get the info"""

    return_dict = {}
    try:
        gluster_lck, err = lock.get_lock('gluster_commands')
        if err:
            raise Exception(err)

        if not gluster_lck:
            raise Exception(
                'This action cannot be performed as an underlying storage command is being run. Please retry this operation after a few seconds.'
            )
        return_dict['base_template'] = "log_base.html"
        return_dict["page_title"] = 'Download system logs'
        return_dict['tab'] = 'download_system_logs_tab'
        return_dict["error"] = 'Error downloading system logs'
        si, err = system_info.load_system_config()
        if err:
            raise Exception(err)
        if not si:
            raise Exception('Could not load system configuration')
        form = log_management_forms.SystemLogsForm(request.POST or None,
                                                   system_config=si)

        if request.method == 'POST':
            if form.is_valid():
                cd = form.cleaned_data
                sys_log_type = cd['sys_log_type']
                hostname = cd["hostname"]

                iv_logging.debug(
                    "Got sys log download request for type %s hostname %s" %
                    (sys_log_type, hostname))

                #fn = {'boot':'/var/log/boot.log', 'dmesg':'/var/log/dmesg', 'message':'/var/log/messages', 'smb':'/var/log/smblog.vfs', 'winbind':'/var/log/samba/log.winbindd','ctdb':'/var/log/log.ctdb'}
                #dn = {'boot':'boot.log', 'dmesg':'dmesg', 'message':'messages','smb':'samba_logs','winbind':'winbind_logs','ctdb':'ctdb_logs'}
                fn = {
                    'boot': '/var/log/boot.log',
                    'dmesg': '/var/log/dmesg',
                    'message': '/var/log/messages',
                    'smb': '/var/log/smblog.vfs',
                    'winbind': '/var/log/samba/log.winbindd'
                }
                dn = {
                    'boot': 'boot.log',
                    'dmesg': 'dmesg',
                    'message': 'messages',
                    'smb': 'samba_logs',
                    'winbind': 'winbind_logs'
                }

                file_name = fn[sys_log_type]
                display_name = dn[sys_log_type]

                client = salt.client.LocalClient()

                ret = client.cmd('%s' % (hostname), 'cp.push', [file_name])
                print ret

                zf_name = '%s.zip' % display_name

                try:
                    zf = zipfile.ZipFile(zf_name, 'w')
                    zf.write("/var/cache/salt/master/minions/%s/files/%s" %
                             (hostname, file_name),
                             arcname=display_name)
                    zf.close()
                except Exception as e:
                    raise Exception("Error compressing remote log file : %s" %
                                    str(e))

                response = django.http.HttpResponse()
                response[
                    'Content-disposition'] = 'attachment; filename=%s.zip' % (
                        display_name)
                response['Content-type'] = 'application/x-compressed'
                with open(zf_name, 'rb') as f:
                    byte = f.read(1)
                    while byte:
                        response.write(byte)
                        byte = f.read(1)
                response.flush()

                return response

        # either a get or an invalid form so send back form
        return_dict['form'] = form
        return django.shortcuts.render_to_response(
            'download_sys_log_form.html',
            return_dict,
            context_instance=django.template.context.RequestContext(request))
    except Exception, e:
        s = str(e)
        if "Another transaction is in progress".lower() in s.lower():
            return_dict[
                "error"] = "An underlying storage operation has locked a volume so we are unable to process this request. Please try after a couple of seconds"
        else:
            return_dict[
                "error"] = "An error occurred when processing your request : %s" % s
        return django.shortcuts.render_to_response(
            "logged_in_error.html",
            return_dict,
            context_instance=django.template.context.RequestContext(request))
def create_volume_conf(request):
    """ Used to confirm volume creation parameters"""

    return_dict = {}
    try:
        gluster_lck, err = lock.get_lock('gluster_commands')
        if err:
            raise Exception(err)

        if not gluster_lck:
            raise Exception(
                'This action cannot be performed as an underlying storage command is being run. Please retry this operation after a few seconds.')

        return_dict['base_template'] = "volume_base.html"
        return_dict["page_title"] = 'Create a volume - confirmation'
        return_dict['tab'] = 'view_volumes_tab'
        return_dict["error"] = 'Error getting information for creating a volume'

        si, err = system_info.load_system_config()
        if err:
            raise Exception(err)
        if not si:
            raise Exception('Could not load system information')

        form = integral_view.forms.volume_creation_forms.VolOndiskStorageForm(
            request.POST or None)

        if form.is_valid():
            cd = form.cleaned_data
            vol_type = cd['vol_type']
            vol_name = cd['vol_name']
            ondisk_storage = cd['ondisk_storage']
            vol_access = cd['vol_access']
            repl_count = 2
            if vol_type == "replicated":
                # repl_count = int(cd["repl_count"])
                # Hardcoded to 2 for now till we resolve the hot spare issue
                repl_count = 2
            transport = "TCP"

            iv_logging.info("create volume initiated for vol_type %s, vol_name %s, ondisk_storage %s, vol_access %s" % (
                vol_type, vol_name, ondisk_storage, vol_access))
            d, err = gluster_volumes.build_create_volume_command(
                vol_name, vol_type, ondisk_storage, repl_count, transport, si)
            if err:
                raise Exception(err)
            if d and "error" in d:
                return_dict["error"] = "Error creating the volume : %s" % d["error"]
                return django.shortcuts.render_to_response('logged_in_error.html', return_dict, context_instance=django.template.context.RequestContext(request))

            node_list_str = ('<ul>')
            for n in d["node_list"]:
                node_list_str += '<li>'
                for i in n:
                    node_list_str += str(i)
                    node_list_str += ', '
                node_list_str += '</li>'
            node_list_str += '</ul>'

            iv_logging.debug("create vol node list %s" % node_list_str)
            return_dict['cmd'] = d['cmd']
            return_dict['dataset_list'] = d['dataset_list']
            return_dict['node_list_str'] = node_list_str
            return_dict['vol_type'] = vol_type
            return_dict['vol_name'] = vol_name
            return_dict['vol_access'] = vol_access
            return_dict['ondisk_storage'] = ondisk_storage
            if vol_type == "replicated":
                return_dict['repl_count'] = str(repl_count)

        else:
            # Invalid form
            url = 'vol_create_wiz_vol_type.html'
            return_dict['form'] = form
            return django.shortcuts.render_to_response(url, return_dict, context_instance=django.template.context.RequestContext(request))

        if settings.APP_DEBUG:
            return_dict['app_debug'] = True

        return_dict['form'] = form
        return django.shortcuts.render_to_response('vol_create_wiz_confirm.html', return_dict, context_instance=django.template.context.RequestContext(request))
    except Exception, e:
        s = str(e)
        if "Another transaction is in progress".lower() in s.lower():
            return_dict["error_details"] = "An underlying storage operation has locked a volume so we are unable to process this request. Please try after a couple of seconds"
        else:
            return_dict["error_details"] = "An error occurred when processing your request : %s" % s
        return django.shortcuts.render_to_response("logged_in_error.html", return_dict, context_instance=django.template.context.RequestContext(request))
Example #15
0
def login(request):
    """ Used to login a user into the management utility"""
    try:
        return_dict = {}
        authSucceeded = False

        if request.method == 'POST':
            iv_logging.info("Login request posted")
            # Someone is submitting info so check it
            form = admin_forms.LoginForm(request.POST)
            if form.is_valid():
                # submitted form is valid so now try to authenticate
                # if not valid then fall out to end of function and return form to user
                # with existing data
                cd = form.cleaned_data
                username = cd['username']
                password = cd['password']
                # Try to authenticate
                user = django.contrib.auth.authenticate(username=username,
                                                        password=password)
                if user is not None and user.is_active:
                    '''
                    #Uncomment if we want to kick out an already logged in user.
                    # Clear the session if the user has been logged in anywhere else.
                    sessions = Session.objects.all()
                    for s in sessions:
                      if s.get_decoded() and (int(s.get_decoded()['_auth_user_id']) == user.id):
                        s.delete()
                    '''
                    # authentication succeeded! Login and send to home screen
                    django.contrib.auth.login(request, user)
                    iv_logging.info("Login request from user '%s' succeeded" %
                                    username)
                    authSucceeded = True
                else:
                    iv_logging.info("Login request from user '%s' failed" %
                                    username)
                    return_dict['invalidUser'] = True
            else:
                # Invalid form
                iv_logging.debug("Invalid login information posted")
        else:
            # GET request so create a new form and send back to user
            form = admin_forms.LoginForm()
            # Clear the session if the user has been logged in anywhere else.
            sessions = Session.objects.all()
            for s in sessions:
                if s.get_decoded() is not None and s.get_decoded().get(
                        '_auth_user_id') is not None:
                    return_dict['session_active'] = True

        return_dict['form'] = form

        if authSucceeded:
            return django.http.HttpResponseRedirect(
                '/view_dashboard/sys_health')

        # For all other cases, return to login screen with return_dict
        # appropriately populated
        return django.shortcuts.render_to_response(
            'login_form.html',
            return_dict,
            context_instance=django.template.context.RequestContext(request))
    except Exception, e:
        s = str(e)
        return_dict[
            "error"] = "An error occurred when processing your request : %s" % s
        return django.shortcuts.render_to_response(
            'logged_in_error.html',
            return_dict,
            context_instance=django.template.context.RequestContext(request))
Example #16
0
def create_volume_conf(request):
    """ Used to confirm volume creation parameters"""

    return_dict = {}
    try:
        gluster_lck, err = lock.get_lock('gluster_commands')
        if err:
            raise Exception(err)

        if not gluster_lck:
            raise Exception(
                'This action cannot be performed as an underlying storage command is being run. Please retry this operation after a few seconds.'
            )

        return_dict['base_template'] = "volume_base.html"
        return_dict["page_title"] = 'Create a volume - confirmation'
        return_dict['tab'] = 'view_volumes_tab'
        return_dict[
            "error"] = 'Error getting information for creating a volume'

        si, err = system_info.load_system_config()
        if err:
            raise Exception(err)
        if not si:
            raise Exception('Could not load system information')

        form = integral_view.forms.volume_creation_forms.VolOndiskStorageForm(
            request.POST or None)

        if form.is_valid():
            cd = form.cleaned_data
            vol_type = cd['vol_type']
            vol_name = cd['vol_name']
            ondisk_storage = cd['ondisk_storage']
            vol_access = cd['vol_access']
            repl_count = 2
            if vol_type == "replicated":
                # repl_count = int(cd["repl_count"])
                # Hardcoded to 2 for now till we resolve the hot spare issue
                repl_count = 2
            transport = "TCP"

            iv_logging.info(
                "create volume initiated for vol_type %s, vol_name %s, ondisk_storage %s, vol_access %s"
                % (vol_type, vol_name, ondisk_storage, vol_access))
            d, err = gluster_volumes.build_create_volume_command(
                vol_name, vol_type, ondisk_storage, repl_count, transport, si)
            if err:
                raise Exception(err)
            if d and "error" in d:
                return_dict[
                    "error"] = "Error creating the volume : %s" % d["error"]
                return django.shortcuts.render_to_response(
                    'logged_in_error.html',
                    return_dict,
                    context_instance=django.template.context.RequestContext(
                        request))

            node_list_str = ('<ul>')
            for n in d["node_list"]:
                node_list_str += '<li>'
                for i in n:
                    node_list_str += str(i)
                    node_list_str += ', '
                node_list_str += '</li>'
            node_list_str += '</ul>'

            iv_logging.debug("create vol node list %s" % node_list_str)
            return_dict['cmd'] = d['cmd']
            return_dict['dataset_list'] = d['dataset_list']
            return_dict['node_list_str'] = node_list_str
            return_dict['vol_type'] = vol_type
            return_dict['vol_name'] = vol_name
            return_dict['vol_access'] = vol_access
            return_dict['ondisk_storage'] = ondisk_storage
            if vol_type == "replicated":
                return_dict['repl_count'] = str(repl_count)

        else:
            # Invalid form
            url = 'vol_create_wiz_vol_type.html'
            return_dict['form'] = form
            return django.shortcuts.render_to_response(
                url,
                return_dict,
                context_instance=django.template.context.RequestContext(
                    request))

        if settings.APP_DEBUG:
            return_dict['app_debug'] = True

        return_dict['form'] = form
        return django.shortcuts.render_to_response(
            'vol_create_wiz_confirm.html',
            return_dict,
            context_instance=django.template.context.RequestContext(request))
    except Exception, e:
        s = str(e)
        if "Another transaction is in progress".lower() in s.lower():
            return_dict[
                "error_details"] = "An underlying storage operation has locked a volume so we are unable to process this request. Please try after a couple of seconds"
        else:
            return_dict[
                "error_details"] = "An error occurred when processing your request : %s" % s
        return django.shortcuts.render_to_response(
            "logged_in_error.html",
            return_dict,
            context_instance=django.template.context.RequestContext(request))
Example #17
0
def configure_ntp_settings(request):

  return_dict = {}
  try:
    if request.method=="GET":
      ntp_servers = ntp.get_ntp_servers()
      if not ntp_servers:
        form = common_forms.ConfigureNTPForm()
      else:
        form = common_forms.ConfigureNTPForm(initial={'server_list': ','.join(ntp_servers)})
      url = "edit_ntp_settings.html"
    else:
      form = common_forms.ConfigureNTPForm(request.POST)
      if form.is_valid():
        iv_logging.debug("Got valid request to change NTP settings")
        cd = form.cleaned_data
        si = system_info.load_system_config()
        server_list = cd["server_list"]
        if ',' in server_list:
          slist = server_list.split(',')
        else:
          slist = server_list.split(' ')
        try:
          primary_server = "primary.fractalio.lan"
          secondary_server = "secondary.fractalio.lan"
          #First create the ntp.conf file for the primary and secondary nodes
          temp = tempfile.NamedTemporaryFile(mode="w")
          temp.write("driftfile /var/lib/ntp/drift\n")
          temp.write("restrict default kod nomodify notrap nopeer noquery\n")
          temp.write("restrict -6 default kod nomodify notrap nopeer noquery\n")
          temp.write("includefile /etc/ntp/crypto/pw\n")
          temp.write("keys /etc/ntp/keys\n")
          temp.write("\n")
          for server in slist:
            temp.write("server %s iburst\n"%server)
          temp.flush()
          shutil.move(temp.name, "%s/ntp/primary_ntp.conf"%fractalio.common.get_admin_vol_mountpoint())
          #client = salt.client.LocalClient()
          #client.cmd('roles:master', 'cp.get_file', ["salt://tmp/%s"%os.path.basename(temp.name), '%s/ntp.conf'%fractalio.common.get_ntp_conf_path()], expr_form='grain')
          #client.cmd('roles:master', 'cmd.run_all', ["service ntpd restart"], expr_form='grain')
          #shutil.copyfile(temp.name, '%s/ntp.conf'%settings.NTP_CONF_PATH)
          temp1 = tempfile.NamedTemporaryFile(mode="w")
          temp1.write("server %s iburst\n"%primary_server)
          temp1.write("server %s iburst\n"%secondary_server)
          for s in si.keys():
            temp1.write("peer %s iburst\n"%s)
          temp1.write("server 127.127.1.0\n")
          temp1.write("fudge 127.127.1.0 stratum 10\n")
          temp1.flush()
          shutil.move(temp1.name, "%s/ntp/secondary_ntp.conf"%fractalio.common.get_admin_vol_mountpoint())
          #client.cmd('role:secondary', 'cp.get_file', ["salt://tmp/%s"%os.path.basename(temp1.name), '%s/ntp.conf'%fractalio.common.get_ntp_conf_path()], expr_form='grain')
          #client.cmd('role:secondary', 'cmd.run_all', ["service ntpd restart"], expr_form='grain')
          #shutil.copyfile(temp.name, '/tmp/ntp.conf')
  
          '''
          lines = ntp.get_non_server_lines()
          if lines:
            for line in lines:
              temp.write("%s\n"%line)
          '''
          #ntp.restart_ntp_service()
        except Exception, e:
          return_dict["error"] = "Error updating NTP information : %s"%e
          return django.shortcuts.render_to_response("logged_in_error.html", return_dict, context_instance = django.template.context.RequestContext(request))
        else:
          return django.http.HttpResponseRedirect("/show/ntp_settings?saved=1")
      else:
Example #18
0
          else:
            d["tls"] = False
          if d["email_alerts"]:
            d["email_alerts"] = True
          else:
            d["email_alerts"] = False
          return_dict["email_settings"] = d
        if "saved" in request.REQUEST:
          return_dict["saved"] = request.REQUEST["saved"]
        if "not_saved" in request.REQUEST:
          return_dict["not_saved"] = request.REQUEST["not_saved"]
        if "err" in request.REQUEST:
          return_dict["err"] = request.REQUEST["err"]
        template = "view_email_settings.html"
      except Exception, e:
        iv_logging.debug("error loading email settings %s"%e)
        return_dict["error"] = str(e)

    elif page == "audit_trail":

      al = None
      try:
        al = audit.get_lines()
      except Exception, e:
        return_dict["error"] = str(e)
      else:
        template = "view_audit_trail.html"
        return_dict["audit_list"] = al

    elif page == "node_status":
      
def download_sys_log(request):
  """ Download the system log of the type specified in sys_log_type POST param for the node specified in the hostname POST parameter. 
  This calls the /sys_log via an http request on that node to get the info"""

  return_dict = {}
  try:
    scl, err = system_info.load_system_config()
    if err:
      raise Exception(err)
    form = log_management_forms.SystemLogsForm(request.POST or None, system_config_list = scl)
  
    if request.method == 'POST':
      if form.is_valid():
        cd = form.cleaned_data
        sys_log_type = cd['sys_log_type']
        hostname = cd["hostname"]
  
        iv_logging.debug("Got sys log download request for type %s hostname %s"%(sys_log_type, hostname))
  
        fn = {'boot':'/var/log/boot.log', 'dmesg':'/var/log/dmesg', 'message':'/var/log/messages', 'smb':'/var/log/smblog.vfs', 'winbind':'/var/log/samba/log.winbindd','ctdb':'/var/log/log.ctdb'}
        dn = {'boot':'boot.log', 'dmesg':'dmesg', 'message':'messages','smb':'samba_logs','winbind':'winbind_logs','ctdb':'ctdb_logs'}
  
        file_name = fn[sys_log_type]
        display_name = dn[sys_log_type]
  
        import os

        use_salt, err = common.use_salt()
        if err:
          raise Exception(err)
        if use_salt:
          import salt.client
          client = salt.client.LocalClient()
          ret = client.cmd('%s'%(hostname),'cp.push',[file_name])
  
        # This has been maintained for reference purposes.
        # dt = datetime.datetime.now()
        # dt_str = dt.strftime("%d%m%Y%H%M%S")
  
        # lfn = "/tmp/%s_%s"%(sys_log_type, dt_str)
        # cmd = "/opt/fractal/bin/client %s get_file %s %s"%(hostname, file_name, lfn)
        # print "command is "+cmd
  
        # try :
        #   ret, rc = command.execute_with_rc(cmd)
        # except Exception, e:
        #   return_dict["error"] = "Error retrieving remote log file : %s"%e
        #   return django.shortcuts.render_to_response('logged_in_error.html', return_dict, context_instance = django.template.context.RequestContext(request))
  
        # if rc != 0 :
        #   return_dict["error"] = "Error retrieving remote log file. Retrieval returned an error code of %d"%rc
        #   return django.shortcuts.render_to_response('logged_in_error.html', return_dict, context_instance = django.template.context.RequestContext(request))
  
        zf_name = '%s.zip'%display_name
  
        try:
          zf = zipfile.ZipFile(zf_name, 'w')
          if use_salt:
            zf.write("/var/cache/salt/master/minions/%s/files/%s"%(hostname,file_name), arcname = display_name)
          else:
            zf.write(file_name, arcname = display_name)
          zf.close()
        except Exception as e:
          raise Exception("Error compressing remote log file : %s"%str(e))
  
        try:
          response = django.http.HttpResponse()
          response['Content-disposition'] = 'attachment; filename=%s.zip'%(display_name)
          response['Content-type'] = 'application/x-compressed'
          with open(zf_name, 'rb') as f:
            byte = f.read(1)
            while byte:
              response.write(byte)
              byte = f.read(1)
          response.flush()
        except Exception as e:
          return None
  
        return response
  
    # either a get or an invalid form so send back form
    return_dict['form'] = form
    return django.shortcuts.render_to_response('download_sys_log_form.html', return_dict, context_instance=django.template.context.RequestContext(request))
  except Exception, e:
    return_dict['base_template'] = "logging_base.html"
    return_dict["page_title"] = 'Download system logs'
    return_dict['tab'] = 'download_system_logs_tab'
    return_dict["error"] = 'Error downloading system logs'
    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))
Example #20
0
def download_vol_log(request):
    """ Used to download the volume log of a particular volume whose name is in the vol_name post parameter"""

    return_dict = {}
    try:
        gluster_lck, err = lock.get_lock('gluster_commands')
        if err:
            raise Exception(err)

        if not gluster_lck:
            raise Exception(
                'This action cannot be performed as an underlying storage command is being run. Please retry this operation after a few seconds.'
            )

        return_dict['base_template'] = 'log_base.html'
        return_dict["page_title"] = 'Download volume logs'
        return_dict['tab'] = 'volume_log_download_tab'
        return_dict["error"] = 'Error downloading volume logs'

        vil, err = gluster_volumes.get_basic_volume_info_all()
        if err:
            raise Exception(err)
        if not vil:
            raise Exception('No volumes detected')

        l = []
        for v in vil:
            l.append(v["name"])

        if request.method == 'POST':
            form = volume_management_forms.VolumeNameForm(request.POST,
                                                          vol_list=l)
            if form.is_valid():
                cd = form.cleaned_data
                vol_name = cd['vol_name']
                iv_logging.debug("Got volume log download request for %s" %
                                 vol_name)
                file_name = None
                v, err = gluster_volumes.get_basic_volume_info(vol_name)
                if err:
                    raise Exception(err)
                if not v:
                    raise Exception("Could not retrieve volume info")
                brick = v["bricks"][0][0]
                if not brick:
                    raise Exception(
                        "Could not retrieve volume log location - no brick")
                l = brick.split(':')
                if not l:
                    raise Exception(
                        "Could not retrieve volume log location - malformed brick 1"
                    )
                l1 = l[1].split('/')
                if not l1:
                    raise Exception(
                        "Could not retrieve volume log location - malformed brick 2"
                    )
                file_name = '/var/log/glusterfs/bricks/%s-%s-%s.log' % (
                    l1[1], l1[2], vol_name)

                display_name = 'integralstor_gridcell-%s.log' % vol_name

                # Formulate the zip file name
                zf_name = '/tmp/integralstor_gridcell_volume_%s_log' % vol_name
                dt = datetime.datetime.now()
                dt_str = dt.strftime("%d%m%Y%H%M%S")
                zf_name = zf_name + dt_str + ".zip"

                try:
                    zf = zipfile.ZipFile(zf_name, 'w')
                    zf.write(file_name, arcname=display_name)
                    zf.write('/var/log/glusterfs/cli.log', arcname='cli.log')
                    zf.write('/var/log/glusterfs/cmd_history.log',
                             arcname='cmd_history.log')
                    zf.write(
                        '/var/log/glusterfs/etc-glusterfs-glusterd.vol.log',
                        arcname='etc-glusterfs-glusterd.vol.log')
                    zf.write('/var/log/glusterfs/', arcname='')
                    zf.write('/var/log/glusterfs/', arcname='')
                    zf.close()
                except Exception as e:
                    raise Exception("Error generating zip file : %s" % str(e))

                response = django.http.HttpResponse()
                response[
                    'Content-disposition'] = 'attachment; filename=integralstor_gridcell_volume_%s_log_%s.zip' % (
                        vol_name, dt_str)
                response['Content-type'] = 'application/x-compressed'
                try:
                    with open(zf_name, 'rb') as f:
                        byte = f.read(1)
                        while byte:
                            response.write(byte)
                            byte = f.read(1)
                    response.flush()
                except Exception as e:
                    raise Exception("Error compressing remote log file : %s" %
                                    str(e))
                return response

        else:
            form = volume_management_forms.VolumeNameForm(vol_list=l)
        # either a get or an invalid form so send back form
        return_dict['form'] = form
        return_dict['op'] = 'download_log'
        return django.shortcuts.render_to_response(
            'download_vol_log_form.html',
            return_dict,
            context_instance=django.template.context.RequestContext(request))
    except Exception, e:
        s = str(e)
        if "Another transaction is in progress".lower() in s.lower():
            return_dict[
                "error"] = "An underlying storage operation has locked a volume so we are unable to process this request. Please try after a couple of seconds"
        else:
            return_dict[
                "error"] = "An error occurred when processing your request : %s" % s
        return django.shortcuts.render_to_response(
            "logged_in_error.html",
            return_dict,
            context_instance=django.template.context.RequestContext(request))
def download_vol_log(request):
    """ Used to download the volume log of a particular volume whose name is in the vol_name post parameter"""

    return_dict = {}
    try:
        gluster_lck, err = lock.get_lock('gluster_commands')
        if err:
            raise Exception(err)

        if not gluster_lck:
            raise Exception(
                'This action cannot be performed as an underlying storage command is being run. Please retry this operation after a few seconds.')

        return_dict['base_template'] = 'log_base.html'
        return_dict["page_title"] = 'Download volume logs'
        return_dict['tab'] = 'volume_log_download_tab'
        return_dict["error"] = 'Error downloading volume logs'

        vil, err = gluster_volumes.get_basic_volume_info_all()
        if err:
            raise Exception(err)
        if not vil:
            raise Exception('No volumes detected')

        l = []
        for v in vil:
            l.append(v["name"])

        if request.method == 'POST':
            form = volume_management_forms.VolumeNameForm(
                request.POST, vol_list=l)
            if form.is_valid():
                cd = form.cleaned_data
                vol_name = cd['vol_name']
                iv_logging.debug(
                    "Got volume log download request for %s" % vol_name)
                file_name = None
                v, err = gluster_volumes.get_basic_volume_info(vol_name)
                if err:
                    raise Exception(err)
                if not v:
                    raise Exception("Could not retrieve volume info")
                brick = v["bricks"][0][0]
                if not brick:
                    raise Exception(
                        "Could not retrieve volume log location - no brick")
                l = brick.split(':')
                if not l:
                    raise Exception(
                        "Could not retrieve volume log location - malformed brick 1")
                l1 = l[1].split('/')
                if not l1:
                    raise Exception(
                        "Could not retrieve volume log location - malformed brick 2")
                file_name = '/var/log/glusterfs/bricks/%s-%s-%s.log' % (
                    l1[1], l1[2], vol_name)

                display_name = 'integralstor_gridcell-%s.log' % vol_name

                # Formulate the zip file name
                zf_name = '/tmp/integralstor_gridcell_volume_%s_log' % vol_name
                dt = datetime.datetime.now()
                dt_str = dt.strftime("%d%m%Y%H%M%S")
                zf_name = zf_name + dt_str + ".zip"

                try:
                    zf = zipfile.ZipFile(zf_name, 'w')
                    zf.write(file_name, arcname=display_name)
                    zf.write('/var/log/glusterfs/cli.log', arcname='cli.log')
                    zf.write('/var/log/glusterfs/cmd_history.log',
                             arcname='cmd_history.log')
                    zf.write('/var/log/glusterfs/etc-glusterfs-glusterd.vol.log',
                             arcname='etc-glusterfs-glusterd.vol.log')
                    zf.write('/var/log/glusterfs/', arcname='')
                    zf.write('/var/log/glusterfs/', arcname='')
                    zf.close()
                except Exception as e:
                    raise Exception("Error generating zip file : %s" % str(e))

                response = django.http.HttpResponse()
                response['Content-disposition'] = 'attachment; filename=integralstor_gridcell_volume_%s_log_%s.zip' % (
                    vol_name, dt_str)
                response['Content-type'] = 'application/x-compressed'
                try:
                    with open(zf_name, 'rb') as f:
                        byte = f.read(1)
                        while byte:
                            response.write(byte)
                            byte = f.read(1)
                    response.flush()
                except Exception as e:
                    raise Exception(
                        "Error compressing remote log file : %s" % str(e))
                return response

        else:
            form = volume_management_forms.VolumeNameForm(vol_list=l)
        # either a get or an invalid form so send back form
        return_dict['form'] = form
        return_dict['op'] = 'download_log'
        return django.shortcuts.render_to_response('download_vol_log_form.html', return_dict, context_instance=django.template.context.RequestContext(request))
    except Exception, e:
        s = str(e)
        if "Another transaction is in progress".lower() in s.lower():
            return_dict["error"] = "An underlying storage operation has locked a volume so we are unable to process this request. Please try after a couple of seconds"
        else:
            return_dict["error"] = "An error occurred when processing your request : %s" % s
        return django.shortcuts.render_to_response("logged_in_error.html", return_dict, context_instance=django.template.context.RequestContext(request))
def download_sys_log(request):
    """ Download the system log of the type specified in sys_log_type POST param for the node specified in the hostname POST parameter. 
    This calls the /sys_log via an http request on that node to get the info"""

    return_dict = {}
    try:
        gluster_lck, err = lock.get_lock('gluster_commands')
        if err:
            raise Exception(err)

        if not gluster_lck:
            raise Exception(
                'This action cannot be performed as an underlying storage command is being run. Please retry this operation after a few seconds.')
        return_dict['base_template'] = "log_base.html"
        return_dict["page_title"] = 'Download system logs'
        return_dict['tab'] = 'download_system_logs_tab'
        return_dict["error"] = 'Error downloading system logs'
        si, err = system_info.load_system_config()
        if err:
            raise Exception(err)
        if not si:
            raise Exception('Could not load system configuration')
        form = log_management_forms.SystemLogsForm(
            request.POST or None, system_config=si)

        if request.method == 'POST':
            if form.is_valid():
                cd = form.cleaned_data
                sys_log_type = cd['sys_log_type']
                hostname = cd["hostname"]

                iv_logging.debug("Got sys log download request for type %s hostname %s" % (
                    sys_log_type, hostname))

                #fn = {'boot':'/var/log/boot.log', 'dmesg':'/var/log/dmesg', 'message':'/var/log/messages', 'smb':'/var/log/smblog.vfs', 'winbind':'/var/log/samba/log.winbindd','ctdb':'/var/log/log.ctdb'}
                #dn = {'boot':'boot.log', 'dmesg':'dmesg', 'message':'messages','smb':'samba_logs','winbind':'winbind_logs','ctdb':'ctdb_logs'}
                fn = {'boot': '/var/log/boot.log', 'dmesg': '/var/log/dmesg', 'message': '/var/log/messages',
                      'smb': '/var/log/smblog.vfs', 'winbind': '/var/log/samba/log.winbindd'}
                dn = {'boot': 'boot.log', 'dmesg': 'dmesg', 'message': 'messages',
                      'smb': 'samba_logs', 'winbind': 'winbind_logs'}

                file_name = fn[sys_log_type]
                display_name = dn[sys_log_type]

                client = salt.client.LocalClient()

                ret = client.cmd('%s' % (hostname), 'cp.push', [file_name])
                print ret

                zf_name = '%s.zip' % display_name

                try:
                    zf = zipfile.ZipFile(zf_name, 'w')
                    zf.write("/var/cache/salt/master/minions/%s/files/%s" %
                             (hostname, file_name), arcname=display_name)
                    zf.close()
                except Exception as e:
                    raise Exception(
                        "Error compressing remote log file : %s" % str(e))

                response = django.http.HttpResponse()
                response['Content-disposition'] = 'attachment; filename=%s.zip' % (
                    display_name)
                response['Content-type'] = 'application/x-compressed'
                with open(zf_name, 'rb') as f:
                    byte = f.read(1)
                    while byte:
                        response.write(byte)
                        byte = f.read(1)
                response.flush()

                return response

        # either a get or an invalid form so send back form
        return_dict['form'] = form
        return django.shortcuts.render_to_response('download_sys_log_form.html', return_dict, context_instance=django.template.context.RequestContext(request))
    except Exception, e:
        s = str(e)
        if "Another transaction is in progress".lower() in s.lower():
            return_dict["error"] = "An underlying storage operation has locked a volume so we are unable to process this request. Please try after a couple of seconds"
        else:
            return_dict["error"] = "An error occurred when processing your request : %s" % s
        return django.shortcuts.render_to_response("logged_in_error.html", return_dict, context_instance=django.template.context.RequestContext(request))