Exemple #1
0
int my_redel(const char *org_name, const char *tmp_name, myf MyFlags)
{
  int error=1;
  DBUG_ENTER("my_redel");
  DBUG_PRINT("my",("org_name: '%s' tmp_name: '%s'  MyFlags: %d",
		   org_name,tmp_name,MyFlags));

  if (my_copystat(org_name,tmp_name,MyFlags) < 0)
    goto end;
  if (MyFlags & MY_REDEL_MAKE_BACKUP)
  {
    char name_buff[FN_REFLEN+20];    
    char ext[20];
    ext[0]='-';
    get_date(ext+1,2+4,(time_t) 0);
    strmov(strend(ext),REDEL_EXT);
    if (my_rename(org_name, fn_format(name_buff, org_name, "", ext, 2),
		  MyFlags))
      goto end;
  }
  else if (my_delete(org_name,MyFlags))
      goto end;
  if (my_rename(tmp_name,org_name,MyFlags))
    goto end;

  error=0;
end:
  DBUG_RETURN(error);
} /* my_redel */
int my_rename_with_symlink(const char *from, const char *to, myf MyFlags)
{
#ifndef HAVE_READLINK
  return my_rename(from, to, MyFlags);
#else
  char link_name[FN_REFLEN], tmp_name[FN_REFLEN];
  int was_symlink= (!my_disable_symlinks &&
            !my_readlink(link_name, from, MYF(0)));
  int result=0;
  int name_is_different;
  DBUG_ENTER("my_rename_with_symlink");

  if (!was_symlink)
    DBUG_RETURN(my_rename(from, to, MyFlags));

  /* Change filename that symlink pointed to */
  strmov(tmp_name, to);
  fn_same(tmp_name,link_name,1);        /* Copy dir */
  name_is_different= strcmp(link_name, tmp_name);
  if (name_is_different && !access(tmp_name, F_OK))
  {
    my_errno= EEXIST;
    if (MyFlags & MY_WME)
      my_error(EE_CANTCREATEFILE, MYF(0), tmp_name, EEXIST);
    DBUG_RETURN(1);
  }

  /* Create new symlink */
  if (my_symlink(tmp_name, to, MyFlags))
    DBUG_RETURN(1);

  /*
    Rename symlinked file if the base name didn't change.
    This can happen if you use this function where 'from' and 'to' has
    the same basename and different directories.
   */

  if (name_is_different && my_rename(link_name, tmp_name, MyFlags))
  {
    int save_errno=my_errno;
    my_delete(to, MyFlags);            /* Remove created symlink */
    my_errno=save_errno;
    DBUG_RETURN(1);
  }

  /* Remove original symlink */
  if (my_delete(from, MyFlags))
  {
    int save_errno=my_errno;
    /* Remove created link */
    my_delete(to, MyFlags);
    /* Rename file back */
    if (strcmp(link_name, tmp_name))
      (void) my_rename(tmp_name, link_name, MyFlags);
    my_errno=save_errno;
    result= 1;
  }
  DBUG_RETURN(result);
#endif /* HAVE_READLINK */
}
Exemple #3
0
int my_redel(const char *org_name, const char *tmp_name,
             time_t backup_time_stamp, myf MyFlags)
{
  int error=1;
  DBUG_ENTER("my_redel");
  DBUG_PRINT("my",("org_name: '%s' tmp_name: '%s'  MyFlags: %lu",
		   org_name,tmp_name,MyFlags));

  if (!my_disable_copystat_in_redel &&
      my_copystat(org_name,tmp_name,MyFlags) < 0)
    goto end;
  if (MyFlags & MY_REDEL_MAKE_BACKUP)
  {
    char name_buff[FN_REFLEN + MY_BACKUP_NAME_EXTRA_LENGTH];    
    my_create_backup_name(name_buff, org_name, backup_time_stamp);
    if (my_rename(org_name, name_buff, MyFlags))
      goto end;
  }
  else if (my_delete(org_name, MyFlags))
      goto end;
  if (my_rename(tmp_name,org_name,MyFlags))
    goto end;

  error=0;
end:
  DBUG_RETURN(error);
} /* my_redel */
Exemple #4
0
static int do_rotate(LOGGER_HANDLE *log)
{
  char namebuf[FN_REFLEN];
  int result;
  unsigned int i;
  char *buf_old, *buf_new, *tmp;

  if (log->rotations == 0)
    return 0;

  memcpy(namebuf, log->path, log->path_len);

  buf_new= logname(log, namebuf, log->rotations);
  buf_old= log->path;
  for (i=log->rotations-1; i>0; i--)
  {
    logname(log, buf_old, i);
    if (!access(buf_old, F_OK) &&
        (result= my_rename(buf_old, buf_new, MYF(0))))
      goto exit;
    tmp= buf_old;
    buf_old= buf_new;
    buf_new= tmp;
  }
  if ((result= my_close(log->file, MYF(0))))
    goto exit;
  namebuf[log->path_len]= 0;
  result= my_rename(namebuf, logname(log, log->path, 1), MYF(0));
  log->file= my_open(namebuf, LOG_FLAGS, MYF(0));
exit:
  errno= my_errno;
  return log->file < 0 || result;
}
Exemple #5
0
void rename_test(){
    int fd;
    show_file_list();
    char filename[40];
    char changename[40];
    printf("\n");
    if(my_rename("/usr/data/data1/file1", "/usr/data/data1/file1_1") != OK){
        printf("rename error!!\n");
        return;
    }
    show_file_list();
    printf("\n");

    if(my_mkdir("usr/data/manyfile") != OK){
        printf("mkdir error!!\n");
        return;
    }
    show_file_list();
    printf("\n");

    int i = 35;
    memset(filename, 0, 40);
    memset(changename, 0, 40);
    strcpy(filename, "usr/data/manyfile/file");
    strcpy(changename, "usr/data/manyfile/file");
    int length = strlen(filename);
    for(; i < 65; ++i){
        filename[length] = (char)i;
        if(fd = my_create(filename) < 0){
            my_close(fd);
            printf("create file error when i = %d\n", i);
            return;
        }
        my_close(fd);
    }
        show_file_list();
        printf("\n");

    /* int i = 30; */
    /* changename[length] = (char)70; */
    /* printf("changename is %s, length is %d\n",changename, length); */
    /* printf("filename is %s, length is %d\n",filename, length); */
    /* exit(0); */
    for( i = 35; i < 65; ++i){
        filename[length] = (char)i;
        changename[length] = (char)(100 - i);
        if(my_rename(filename, changename) != OK){
            printf("rename error when i = %d!!\n", i);
            return;
        }
    }
        show_file_list();
        printf("\n");
}
Exemple #6
0
/* gets called every X seconds by an event in the scheduling queue */
void npcdmod_file_roller() {
	char temp_buffer[1024];
	char spool_file[1024];
	int result = 0;
	time_t current_time;

	time(&current_time);

	sprintf(spool_file, "%s%s.%d", spool_dir, perfdata_spool_filename, current_time);
	spool_file[sizeof(spool_file) - 1] = '\x0';

	/* close actual file */
	fclose(fp);

	/* move the original file */
	result = my_rename(perfdata_file, spool_file);

	/* open a new file */
	if ((fp = fopen(perfdata_file, "a")) == NULL) {
		snprintf(temp_buffer, sizeof(temp_buffer) - 1,
				"npcdmod: Could not reopen file. %s", strerror(errno),
				NSLOG_INFO_MESSAGE);
		temp_buffer[sizeof(temp_buffer) - 1] = '\x0';
		write_to_all_logs(temp_buffer, NSLOG_INFO_MESSAGE);
	}

	return;
}
Exemple #7
0
int 
mi_rename(const char *old_name, const char *new_name)
{
	char		from      [FN_REFLEN], to[FN_REFLEN];
#ifdef USE_RAID
	uint		raid_type = 0, raid_chunks = 0;
#endif
	DBUG_ENTER("mi_rename");

#ifdef EXTRA_DEBUG
	check_table_is_closed(old_name, "rename old_table");
	check_table_is_closed(new_name, "rename new table2");
#endif
#ifdef USE_RAID
	{
		MI_INFO        *info;
		if (!(info = mi_open(old_name, O_RDONLY, 0)))
			DBUG_RETURN(my_errno);
		raid_type = info->s->base.raid_type;
		raid_chunks = info->s->base.raid_chunks;
		mi_close(info);
	}
#ifdef EXTRA_DEBUG
	check_table_is_closed(old_name, "rename raidcheck");
#endif
#endif				/* USE_RAID */

	fn_format(from, old_name, "", MI_NAME_IEXT, 4);
	fn_format(to, new_name, "", MI_NAME_IEXT, 4);
	if (my_rename(from, to, MYF(MY_WME)))
		DBUG_RETURN(my_errno);
	fn_format(from, old_name, "", MI_NAME_DEXT, 4);
	fn_format(to, new_name, "", MI_NAME_DEXT, 4);
#ifdef USE_RAID
	if (raid_type)
		DBUG_RETURN(my_raid_rename(from, to, raid_chunks, MYF(MY_WME)) ? my_errno :
			    0);
#endif
	DBUG_RETURN(my_rename(from, to, MYF(MY_WME)) ? my_errno : 0);
}
/* write to the debug log */
int log_debug_info(int level, int verbosity, const char *fmt, ...) {
    va_list ap;
    char *tmppath = NULL;
    struct timeval current_time;

    if(!(debug_level == DEBUGL_ALL || (level & debug_level)))
        return OK;

    if(verbosity > debug_verbosity)
        return OK;

    if(debug_file_fp == NULL)
        return ERROR;

    /* write the timestamp */
    gettimeofday(&current_time, NULL);
    fprintf(debug_file_fp, "[%lu.%06lu] [%03d.%d] [pid=%lu] ", current_time.tv_sec, current_time.tv_usec, level, verbosity, (unsigned long)getpid());

    /* write the data */
    va_start(ap, fmt);
    vfprintf(debug_file_fp, fmt, ap);
    va_end(ap);

    /* flush, so we don't have problems tailing or when fork()ing */
    fflush(debug_file_fp);

    /* if file has grown beyond max, rotate it */
    if((unsigned long)ftell(debug_file_fp) > max_debug_file_size && max_debug_file_size > 0L) {

        /* close the file */
        close_debug_log();

        /* rotate the log file */
        asprintf(&tmppath, "%s.old", debug_file);
        if(tmppath) {

            /* unlink the old debug file */
            unlink(tmppath);

            /* rotate the debug file */
            my_rename(debug_file, tmppath);

            /* free memory */
            my_free(tmppath);
        }

        /* open a new file */
        open_debug_log();
    }

    return OK;
}
Exemple #9
0
/** Move a check result temporary file to the queue directory.
 *
 * This is a modified copy of a Nagios 3.x function. The difference is this 
 * version doesn't set umask due to race conditions with nagios core code.
 *
 * @param[in] resfile - the result file to be moved.
 */
static void nagios3xMoveCheckResultToQueue(char * resfile)
{
   char * outfile;
   int ret = -1;

   // a nagios 3x global variable
   extern char * check_result_path;

   // create a safe temp file
   // path length + 'cXXXXXX' (7) + '/' (1) + '.ok' (3) + null (1)
   if ((outfile = (char *)xmalloc(strlen(check_result_path) 
         + 7 + 1 + 3 + 1)) != 0)
   {
      int fd;
      //int oldmask = umask(077);

      sprintf(outfile, "%s/cXXXXXX", check_result_path);
      if ((fd = mkstemp(outfile)) > 0)
      {
#ifdef __CYGWIN__
         // Cygwin cannot rename open files - gives Permission Denied
         close(fd);
#endif

         // move the original file using a nagios core function
         ret = my_rename(resfile, outfile);

#ifndef __CYGWIN__
         // close the file
         close(fd);
#endif

         // create an ok-to-go indicator file
         strcat(outfile, ".ok");
         if ((fd = open(outfile, O_CREAT|O_WRONLY|O_TRUNC, S_IRUSR|S_IWUSR)) > 0)
            close(fd);

      }

      //umask(oldmask);

      xfree(outfile);
   }

   // delete the original file if allocation failed or it couldn't be moved
   if (ret != 0)
      unlink(resfile);
}
Exemple #10
0
/* hard links are also tested a bunch in test_rename */
void test_link(char *workdir) {
    char file1[1024], file2[1024], file3[1024];
    struct stat sb;

    printf("Testing link\n");

    sprintf(file1, "%s/original", workdir);
    sprintf(file2, "%s/link", workdir);

    my_create(file1);
    my_stat(file1, &sb);
    my_link(file1, file2);
    verify_inum(file2, &sb);
    my_unlink(file2);
    verify_inum(file1, &sb);

    /* Test deletion of the original file after a hard link has been
       created */
    my_link(file1, file2);
    my_unlink(file1);
    verify_inum(file2, &sb);
    /* Make sure the original file really isn't accessible */
    verify_no_exist(file1);
    my_unlink(file2);
    verify_no_exist(file2);

    /* Try renaming a hard link */
    my_create(file1);
    my_stat(file1, &sb);
    my_link(file1, file2);
    sprintf(file3, "%s/file3", workdir);
    my_rename(file2, file3);
    verify_inum(file3, &sb);
    verify_no_exist(file2);

    my_unlink(file3);
    verify_no_exist(file3);

    my_unlink(file1);

}
/* rotates the main log file */
int rotate_log_file(time_t rotation_time) {
    char *temp_buffer = NULL;
    char method_string[16] = "";
    char *log_archive = NULL;
    struct tm *t, tm_s;
    int rename_result = 0;
    int stat_result = -1;
    struct stat log_file_stat;
    struct stat archive_stat;
    int archive_stat_result;

    if(log_rotation_method == LOG_ROTATION_NONE) {
        return OK;
    }
    else if(log_rotation_method == LOG_ROTATION_HOURLY)
        strcpy(method_string, "HOURLY");
    else if(log_rotation_method == LOG_ROTATION_DAILY)
        strcpy(method_string, "DAILY");
    else if(log_rotation_method == LOG_ROTATION_WEEKLY)
        strcpy(method_string, "WEEKLY");
    else if(log_rotation_method == LOG_ROTATION_MONTHLY)
        strcpy(method_string, "MONTHLY");
    else
        return ERROR;

    /* update the last log rotation time and status log */
    last_log_rotation = time(NULL);
    update_program_status(FALSE);

    t = localtime_r(&rotation_time, &tm_s);

    stat_result = stat(log_file, &log_file_stat);

    close_log_file();

    /* get the archived filename to use */
    asprintf(&log_archive, "%s%snagios-%02d-%02d-%d-%02d.log", log_archive_path, (log_archive_path[strlen(log_archive_path) - 1] == '/') ? "" : "/", t->tm_mon + 1, t->tm_mday, t->tm_year + 1900, t->tm_hour);

    /* HACK: If the archive exists, don't overwrite it. This is a hack
    	because the real problem is that some log rotations are executed
    	early and as a result the next log rotatation is scheduled for
    	the same time as the one that ran early */
    archive_stat_result = stat(log_archive, &archive_stat);
    if((0 == archive_stat_result) ||
            ((-1 == archive_stat_result) && (ENOENT != errno))) {
        return OK;
    }

    /* rotate the log file */
    rename_result = my_rename(log_file, log_archive);
    log_fp = open_log_file();
    if (log_fp == NULL)
        return ERROR;

    if(rename_result) {
        my_free(log_archive);
        return ERROR;
    }

    /* record the log rotation after it has been done... */
    asprintf(&temp_buffer, "LOG ROTATION: %s\n", method_string);
    write_to_all_logs_with_timestamp(temp_buffer, NSLOG_PROCESS_INFO, &rotation_time);
    my_free(temp_buffer);

    /* record log file version format */
    write_log_file_info(&rotation_time);

    if(stat_result == 0) {
        chmod(log_file, log_file_stat.st_mode);
        chown(log_file, log_file_stat.st_uid, log_file_stat.st_gid);
    }

    /* log current host and service state if activated */
    if(log_current_states==TRUE) {
        log_host_states(CURRENT_STATES, &rotation_time);
        log_service_states(CURRENT_STATES, &rotation_time);
    }

    /* free memory */
    my_free(log_archive);

    return OK;
}
Exemple #12
0
int main(int argc, char** argv) {
    NDB_INIT(argv[0]);

    load_defaults("my",load_default_groups,&argc,&argv);
    int ho_error;
#ifndef DBUG_OFF
    opt_debug= "d:t:O,/tmp/ndb_mgm.trace";
#endif
    if ((ho_error=handle_options(&argc, &argv, my_long_options,
                                 ndb_std_get_one_option)))
        exit(ho_error);

    char buf[MAXHOSTNAMELEN+10];
    if(argc == 1) {
        BaseString::snprintf(buf, sizeof(buf), "%s",  argv[0]);
        opt_connect_str= buf;
    } else if (argc >= 2) {
        BaseString::snprintf(buf, sizeof(buf), "%s:%s",  argv[0], argv[1]);
        opt_connect_str= buf;
    }

    if (!isatty(0) || opt_execute_str)
    {
        prompt= 0;
    }

    signal(SIGPIPE, handler);
    com = new Ndb_mgmclient(opt_connect_str,1);
    int ret= 0;
    BaseString histfile;
    if (!opt_execute_str)
    {
#ifdef HAVE_READLINE
        char *histfile_env= getenv("NDB_MGM_HISTFILE");
        if (histfile_env)
            histfile.assign(histfile_env,strlen(histfile_env));
        else if(getenv("HOME"))
        {
            histfile.assign(getenv("HOME"),strlen(getenv("HOME")));
            histfile.append("/.ndb_mgm_history");
        }
        if (histfile.length())
            read_history(histfile.c_str());
#endif

        ndbout << "-- NDB Cluster -- Management Client --" << endl;
        while(read_and_execute(_try_reconnect));

#ifdef HAVE_READLINE
        if (histfile.length())
        {
            BaseString histfile_tmp;
            histfile_tmp.assign(histfile);
            histfile_tmp.append(".TMP");
            if(!write_history(histfile_tmp.c_str()))
                my_rename(histfile_tmp.c_str(), histfile.c_str(), MYF(MY_WME));
        }
#endif
    }
    else
    {
        com->execute(opt_execute_str,_try_reconnect, 0, &ret);
    }
    delete com;

    ndb_end(opt_endinfo ? MY_CHECK_ERROR | MY_GIVE_INFO : 0);
    return ret;
}
Exemple #13
0
/* rotates the main log file */
int rotate_log_file(time_t rotation_time){
	char *temp_buffer=NULL;
	char method_string[16]="";
	char *log_archive=NULL;
	struct tm *t;
	int rename_result=0;
	int stat_result=-1;
	struct stat log_file_stat;

	if(log_rotation_method==LOG_ROTATION_NONE){
		return OK;
	        }
	else if(log_rotation_method==LOG_ROTATION_HOURLY)
		strcpy(method_string,"HOURLY");
	else if(log_rotation_method==LOG_ROTATION_DAILY)
		strcpy(method_string,"DAILY");
	else if(log_rotation_method==LOG_ROTATION_WEEKLY)
		strcpy(method_string,"WEEKLY");
	else if(log_rotation_method==LOG_ROTATION_MONTHLY)
		strcpy(method_string,"MONTHLY");
	else
		return ERROR;

	/* update the last log rotation time and status log */
	last_log_rotation=time(NULL);
	update_program_status(FALSE);

	t=localtime(&rotation_time);

	stat_result = stat(log_file, &log_file_stat);

	/* get the archived filename to use */
	asprintf(&log_archive,"%s%snagios-%02d-%02d-%d-%02d.log",log_archive_path,(log_archive_path[strlen(log_archive_path)-1]=='/')?"":"/",t->tm_mon+1,t->tm_mday,t->tm_year+1900,t->tm_hour);

	/* rotate the log file */
	rename_result=my_rename(log_file,log_archive);

	if(rename_result){
		my_free(log_archive);
		return ERROR;
	        }

#ifdef USE_EVENT_BROKER
	/* REMOVED - log rotation events are already handled by NEBTYPE_TIMEDEVENT_EXECUTE... */
	/* send data to the event broker */
        /*
	broker_log_data(NEBTYPE_LOG_ROTATION,NEBFLAG_NONE,NEBATTR_NONE,log_archive,log_rotation_method,0,NULL);
	*/
#endif

	/* record the log rotation after it has been done... */
	asprintf(&temp_buffer,"LOG ROTATION: %s\n",method_string);
	write_to_all_logs_with_timestamp(temp_buffer,NSLOG_PROCESS_INFO,&rotation_time);
	my_free(temp_buffer);

	/* record log file version format */
	write_log_file_info(&rotation_time);

	if(stat_result==0){
		chmod(log_file, log_file_stat.st_mode);
		chown(log_file, log_file_stat.st_uid, log_file_stat.st_gid);
		}

	/* log current host and service state */
	log_host_states(CURRENT_STATES,&rotation_time);
	log_service_states(CURRENT_STATES,&rotation_time);

	/* free memory */
	my_free(log_archive);

	return OK;
        }
Exemple #14
0
/* write to the debug log */
int log_debug_info(int level, int verbosity, const char *fmt, ...) {
	va_list ap;
	char *temp_path = NULL;
	struct timeval current_time;

	/* ignore if logging is not appropriate */
	if (log_level(level, verbosity) != TRUE)
		return OK;

	if (debug_file_fp == NULL)
		return ERROR;

	/*
	 * lock it so concurrent threads don't stomp on each other's
	 * writings. We maintain the lock until we've (optionally)
	 * renamed the file.
	 * If soft_lock() fails we return early.
	 */
	if (soft_lock(&debug_fp_lock) < 0)
		return ERROR;

	/* write the timestamp */
	gettimeofday(&current_time, NULL);
	fprintf(debug_file_fp, "[%lu.%06lu] [%03d.%d] [pid=%lu] ", current_time.tv_sec, current_time.tv_usec, level, verbosity, (unsigned long)getpid());

	/* write the data */
	va_start(ap, fmt);
	vfprintf(debug_file_fp, fmt, ap);
	va_end(ap);

	/* flush, so we don't have problems tailing or when fork()ing */
	fflush(debug_file_fp);

	/* if file has grown beyond max, rotate it */
	if ((unsigned long)ftell(debug_file_fp) > max_debug_file_size && max_debug_file_size > 0L) {

		/* close the file */
		close_debug_log();

		/* rotate the log file */
		asprintf(&temp_path, "%s.old", debug_file);
		if (temp_path) {

			/* unlink the old debug file */
			unlink(temp_path);

			/* rotate the debug file */
			my_rename(debug_file, temp_path);

			/* free memory */
			my_free(temp_path);
		}

		/* open a new file */
		open_debug_log();
	}

	pthread_mutex_unlock(&debug_fp_lock);

	return OK;
}
Exemple #15
0
int main(int argc, char** argv){
  NDB_INIT(argv[0]);

  ndb_opt_set_usage_funcs(short_usage_sub, usage);
  load_defaults("my",load_default_groups,&argc,&argv);
  int ho_error;
#ifndef DBUG_OFF
  opt_debug= "d:t:O,/tmp/ndb_mgm.trace";
#endif
  if ((ho_error=handle_options(&argc, &argv, my_long_options,
			       ndb_std_get_one_option)))
    exit(ho_error);

  BaseString connect_str(opt_ndb_connectstring);
  if(argc == 1) {
    connect_str.assfmt("%s", argv[0]);
  } else if (argc >= 2) {
    connect_str.assfmt("%s:%s", argv[0], argv[1]);
  }

  if (!isatty(0) || opt_execute_str)
  {
    prompt= 0;
  }

  com = new Ndb_mgmclient(connect_str.c_str(), opt_verbose);
  int ret= 0;
  BaseString histfile;
  if (!opt_execute_str)
  {
#ifdef HAVE_READLINE
    char *histfile_env= getenv("NDB_MGM_HISTFILE");
    if (histfile_env)
      histfile.assign(histfile_env,strlen(histfile_env));
    else if(getenv("HOME"))
    {
      histfile.assign(getenv("HOME"),strlen(getenv("HOME")));
      histfile.append("/.ndb_mgm_history");
    }
    if (histfile.length())
      read_history(histfile.c_str());
#endif

    ndbout << "-- NDB Cluster -- Management Client --" << endl;
    while(read_and_execute(opt_try_reconnect))
      ;

#ifdef HAVE_READLINE
    if (histfile.length())
    {
      BaseString histfile_tmp;
      histfile_tmp.assign(histfile);
      histfile_tmp.append(".TMP");
      if(!write_history(histfile_tmp.c_str()))
        my_rename(histfile_tmp.c_str(), histfile.c_str(), MYF(MY_WME));
    }
#endif
  }
  else
  {
    com->execute(opt_execute_str, opt_try_reconnect, 0, &ret);
  }
  delete com;

  ndb_end(opt_ndb_endinfo ? MY_CHECK_ERROR | MY_GIVE_INFO : 0);

  // Don't allow negative return code
  if (ret < 0)
    ret = 255;
  return ret;
}
Exemple #16
0
void test_rename(char *workdir) {
    char file1[1024], file2[1024], link[1024],
         subdir[1024], newdir[1024];
    struct stat sb1, sb2;
    int fd;

    printf("testing rename\n");

    sprintf(file1, "%s/file1", workdir);
    sprintf(file2, "%s/file2", workdir);

    /* test stat first.. since we need it to test rename */
    my_stat(file1, &sb1);

    /* Not much to look at, really..  how about making sure that
       the modification time of the file is not in the future.
       allow ten seconds of slack */
    if (sb1.st_mtime > time(NULL) + 10) {
        printf("Modification time of %s is in the future!\n",
               file1);
        exit(1);
    }

    my_rename(file1, file2);

    /* try repeat */
    if (!rename(file1, file2)) {
        printf("repeat rename(%s,%s) worked.. but it shouldn't have\n",
               file1, file2);
        exit(1);
    }


    /* inode number of file2 should be the same as it was for file1 */
    verify_inum(file2, &sb1);


    /* rename back */
    my_rename(file2, file1);

    verify_inum(file1, &sb1);

    /* Make a subdir, which will be renamed */
    sprintf(subdir, "%s/rename_this_dir", workdir);

    my_mkdir(subdir);
    my_stat(subdir, &sb2);

    /* Test moving a file into a subdir */
    sprintf(file2, "%s/file1", subdir);
    my_rename(file1, file2);
    verify_inum(file2, &sb1);

    /* Add in a hard link to spice things up */
    sprintf(link, "%s/link", subdir);
    my_link(file2, link);

    sprintf(newdir, "%s/newdirname", workdir);
    my_rename(subdir, newdir);
    verify_inum(newdir, &sb2);
    sprintf(file2, "%s/file1", newdir);
    verify_inum(file2, &sb1);
    sprintf(link, "%s/newdirname/link", workdir);
    verify_inum(link, &sb1);

    /* Test moving up in the tree */
    my_rename(file2,file1);
    verify_inum(file1, &sb1);

    my_unlink(link);

    my_rmdir(newdir);

}
Exemple #17
0
/* write all status data to file */
int xsddefault_save_status_data(void) {
	char *temp_file = NULL;
	customvariablesmember *temp_customvariablesmember = NULL;
	host *temp_host = NULL;
	service *temp_service = NULL;
	contact *temp_contact = NULL;
	comment *temp_comment = NULL;
	scheduled_downtime *temp_downtime = NULL;
	time_t current_time;
	int fd = 0;
	FILE *fp = NULL;
	int result = OK;

	log_debug_info(DEBUGL_FUNCTIONS, 0, "save_status_data()\n");

	/* users may not want us to write status data */
	if(!xsddefault_status_log || !strcmp(xsddefault_status_log, "/dev/null"))
		return OK;

	/* open a safe temp file for output */
	if(xsddefault_temp_file == NULL)
		return ERROR;
	asprintf(&temp_file, "%sXXXXXX", xsddefault_temp_file);
	if(temp_file == NULL)
		return ERROR;

	log_debug_info(DEBUGL_STATUSDATA, 2, "Writing status data to temp file '%s'\n", temp_file);

	if((fd = mkstemp(temp_file)) == -1) {

		/* log an error */
		logit(NSLOG_RUNTIME_ERROR, TRUE, "Error: Unable to create temp file '%s' for writing status data: %s\n", temp_file, strerror(errno));

		/* free memory */
		my_free(temp_file);

		return ERROR;
		}
	fp = (FILE *)fdopen(fd, "w");
	if(fp == NULL) {

		close(fd);
		unlink(temp_file);

		/* log an error */
		logit(NSLOG_RUNTIME_ERROR, TRUE, "Error: Unable to open temp file '%s' for writing status data: %s\n", temp_file, strerror(errno));

		/* free memory */
		my_free(temp_file);

		return ERROR;
		}

	/* generate check statistics */
	generate_check_stats();

	/* write version info to status file */
	fprintf(fp, "########################################\n");
	fprintf(fp, "#          NAGIOS STATUS FILE\n");
	fprintf(fp, "#\n");
	fprintf(fp, "# THIS FILE IS AUTOMATICALLY GENERATED\n");
	fprintf(fp, "# BY NAGIOS.  DO NOT MODIFY THIS FILE!\n");
	fprintf(fp, "########################################\n\n");

	time(&current_time);

	/* write file info */
	fprintf(fp, "info {\n");
	fprintf(fp, "\tcreated=%lu\n", current_time);
	fprintf(fp, "\tversion=%s\n", PROGRAM_VERSION);
	fprintf(fp, "\tlast_update_check=%lu\n", last_update_check);
	fprintf(fp, "\tupdate_available=%d\n", update_available);
	fprintf(fp, "\tlast_version=%s\n", (last_program_version == NULL) ? "" : last_program_version);
	fprintf(fp, "\tnew_version=%s\n", (new_program_version == NULL) ? "" : new_program_version);
	fprintf(fp, "\t}\n\n");

	/* save program status data */
	fprintf(fp, "programstatus {\n");
	fprintf(fp, "\tmodified_host_attributes=%lu\n", modified_host_process_attributes);
	fprintf(fp, "\tmodified_service_attributes=%lu\n", modified_service_process_attributes);
	fprintf(fp, "\tnagios_pid=%d\n", nagios_pid);
	fprintf(fp, "\tdaemon_mode=%d\n", daemon_mode);
	fprintf(fp, "\tprogram_start=%lu\n", program_start);
	fprintf(fp, "\tlast_log_rotation=%lu\n", last_log_rotation);
	fprintf(fp, "\tenable_notifications=%d\n", enable_notifications);
	fprintf(fp, "\tactive_service_checks_enabled=%d\n", execute_service_checks);
	fprintf(fp, "\tpassive_service_checks_enabled=%d\n", accept_passive_service_checks);
	fprintf(fp, "\tactive_host_checks_enabled=%d\n", execute_host_checks);
	fprintf(fp, "\tpassive_host_checks_enabled=%d\n", accept_passive_host_checks);
	fprintf(fp, "\tenable_event_handlers=%d\n", enable_event_handlers);
	fprintf(fp, "\tobsess_over_services=%d\n", obsess_over_services);
	fprintf(fp, "\tobsess_over_hosts=%d\n", obsess_over_hosts);
	fprintf(fp, "\tcheck_service_freshness=%d\n", check_service_freshness);
	fprintf(fp, "\tcheck_host_freshness=%d\n", check_host_freshness);
	fprintf(fp, "\tenable_flap_detection=%d\n", enable_flap_detection);
	fprintf(fp, "\tprocess_performance_data=%d\n", process_performance_data);
	fprintf(fp, "\tglobal_host_event_handler=%s\n", (global_host_event_handler == NULL) ? "" : global_host_event_handler);
	fprintf(fp, "\tglobal_service_event_handler=%s\n", (global_service_event_handler == NULL) ? "" : global_service_event_handler);
	fprintf(fp, "\tnext_comment_id=%lu\n", next_comment_id);
	fprintf(fp, "\tnext_downtime_id=%lu\n", next_downtime_id);
	fprintf(fp, "\tnext_event_id=%lu\n", next_event_id);
	fprintf(fp, "\tnext_problem_id=%lu\n", next_problem_id);
	fprintf(fp, "\tnext_notification_id=%lu\n", next_notification_id);
	fprintf(fp, "\tactive_scheduled_host_check_stats=%d,%d,%d\n", check_statistics[ACTIVE_SCHEDULED_HOST_CHECK_STATS].minute_stats[0], check_statistics[ACTIVE_SCHEDULED_HOST_CHECK_STATS].minute_stats[1], check_statistics[ACTIVE_SCHEDULED_HOST_CHECK_STATS].minute_stats[2]);
	fprintf(fp, "\tactive_ondemand_host_check_stats=%d,%d,%d\n", check_statistics[ACTIVE_ONDEMAND_HOST_CHECK_STATS].minute_stats[0], check_statistics[ACTIVE_ONDEMAND_HOST_CHECK_STATS].minute_stats[1], check_statistics[ACTIVE_ONDEMAND_HOST_CHECK_STATS].minute_stats[2]);
	fprintf(fp, "\tpassive_host_check_stats=%d,%d,%d\n", check_statistics[PASSIVE_HOST_CHECK_STATS].minute_stats[0], check_statistics[PASSIVE_HOST_CHECK_STATS].minute_stats[1], check_statistics[PASSIVE_HOST_CHECK_STATS].minute_stats[2]);
	fprintf(fp, "\tactive_scheduled_service_check_stats=%d,%d,%d\n", check_statistics[ACTIVE_SCHEDULED_SERVICE_CHECK_STATS].minute_stats[0], check_statistics[ACTIVE_SCHEDULED_SERVICE_CHECK_STATS].minute_stats[1], check_statistics[ACTIVE_SCHEDULED_SERVICE_CHECK_STATS].minute_stats[2]);
	fprintf(fp, "\tactive_ondemand_service_check_stats=%d,%d,%d\n", check_statistics[ACTIVE_ONDEMAND_SERVICE_CHECK_STATS].minute_stats[0], check_statistics[ACTIVE_ONDEMAND_SERVICE_CHECK_STATS].minute_stats[1], check_statistics[ACTIVE_ONDEMAND_SERVICE_CHECK_STATS].minute_stats[2]);
	fprintf(fp, "\tpassive_service_check_stats=%d,%d,%d\n", check_statistics[PASSIVE_SERVICE_CHECK_STATS].minute_stats[0], check_statistics[PASSIVE_SERVICE_CHECK_STATS].minute_stats[1], check_statistics[PASSIVE_SERVICE_CHECK_STATS].minute_stats[2]);
	fprintf(fp, "\tcached_host_check_stats=%d,%d,%d\n", check_statistics[ACTIVE_CACHED_HOST_CHECK_STATS].minute_stats[0], check_statistics[ACTIVE_CACHED_HOST_CHECK_STATS].minute_stats[1], check_statistics[ACTIVE_CACHED_HOST_CHECK_STATS].minute_stats[2]);
	fprintf(fp, "\tcached_service_check_stats=%d,%d,%d\n", check_statistics[ACTIVE_CACHED_SERVICE_CHECK_STATS].minute_stats[0], check_statistics[ACTIVE_CACHED_SERVICE_CHECK_STATS].minute_stats[1], check_statistics[ACTIVE_CACHED_SERVICE_CHECK_STATS].minute_stats[2]);
	fprintf(fp, "\texternal_command_stats=%d,%d,%d\n", check_statistics[EXTERNAL_COMMAND_STATS].minute_stats[0], check_statistics[EXTERNAL_COMMAND_STATS].minute_stats[1], check_statistics[EXTERNAL_COMMAND_STATS].minute_stats[2]);

	fprintf(fp, "\tparallel_host_check_stats=%d,%d,%d\n", check_statistics[PARALLEL_HOST_CHECK_STATS].minute_stats[0], check_statistics[PARALLEL_HOST_CHECK_STATS].minute_stats[1], check_statistics[PARALLEL_HOST_CHECK_STATS].minute_stats[2]);
	fprintf(fp, "\tserial_host_check_stats=%d,%d,%d\n", check_statistics[SERIAL_HOST_CHECK_STATS].minute_stats[0], check_statistics[SERIAL_HOST_CHECK_STATS].minute_stats[1], check_statistics[SERIAL_HOST_CHECK_STATS].minute_stats[2]);
	fprintf(fp, "\t}\n\n");


	/* save host status data */
	for(temp_host = host_list; temp_host != NULL; temp_host = temp_host->next) {

		fprintf(fp, "hoststatus {\n");
		fprintf(fp, "\thost_name=%s\n", temp_host->name);

		fprintf(fp, "\tmodified_attributes=%lu\n", temp_host->modified_attributes);
		fprintf(fp, "\tcheck_command=%s\n", (temp_host->check_command == NULL) ? "" : temp_host->check_command);
		fprintf(fp, "\tcheck_period=%s\n", (temp_host->check_period == NULL) ? "" : temp_host->check_period);
		fprintf(fp, "\tnotification_period=%s\n", (temp_host->notification_period == NULL) ? "" : temp_host->notification_period);
		fprintf(fp, "\tcheck_interval=%f\n", temp_host->check_interval);
		fprintf(fp, "\tretry_interval=%f\n", temp_host->retry_interval);
		fprintf(fp, "\tevent_handler=%s\n", (temp_host->event_handler == NULL) ? "" : temp_host->event_handler);

		fprintf(fp, "\thas_been_checked=%d\n", temp_host->has_been_checked);
		fprintf(fp, "\tshould_be_scheduled=%d\n", temp_host->should_be_scheduled);
		fprintf(fp, "\tcheck_execution_time=%.3f\n", temp_host->execution_time);
		fprintf(fp, "\tcheck_latency=%.3f\n", temp_host->latency);
		fprintf(fp, "\tcheck_type=%d\n", temp_host->check_type);
		fprintf(fp, "\tcurrent_state=%d\n", temp_host->current_state);
		fprintf(fp, "\tlast_hard_state=%d\n", temp_host->last_hard_state);
		fprintf(fp, "\tlast_event_id=%lu\n", temp_host->last_event_id);
		fprintf(fp, "\tcurrent_event_id=%lu\n", temp_host->current_event_id);
		fprintf(fp, "\tcurrent_problem_id=%lu\n", temp_host->current_problem_id);
		fprintf(fp, "\tlast_problem_id=%lu\n", temp_host->last_problem_id);
		fprintf(fp, "\tplugin_output=%s\n", (temp_host->plugin_output == NULL) ? "" : temp_host->plugin_output);
		fprintf(fp, "\tlong_plugin_output=%s\n", (temp_host->long_plugin_output == NULL) ? "" : temp_host->long_plugin_output);
		fprintf(fp, "\tperformance_data=%s\n", (temp_host->perf_data == NULL) ? "" : temp_host->perf_data);
		fprintf(fp, "\tlast_check=%lu\n", temp_host->last_check);
		fprintf(fp, "\tnext_check=%lu\n", temp_host->next_check);
		fprintf(fp, "\tcheck_options=%d\n", temp_host->check_options);
		fprintf(fp, "\tcurrent_attempt=%d\n", temp_host->current_attempt);
		fprintf(fp, "\tmax_attempts=%d\n", temp_host->max_attempts);
		fprintf(fp, "\tstate_type=%d\n", temp_host->state_type);
		fprintf(fp, "\tlast_state_change=%lu\n", temp_host->last_state_change);
		fprintf(fp, "\tlast_hard_state_change=%lu\n", temp_host->last_hard_state_change);
		fprintf(fp, "\tlast_time_up=%lu\n", temp_host->last_time_up);
		fprintf(fp, "\tlast_time_down=%lu\n", temp_host->last_time_down);
		fprintf(fp, "\tlast_time_unreachable=%lu\n", temp_host->last_time_unreachable);
		fprintf(fp, "\tlast_notification=%lu\n", temp_host->last_notification);
		fprintf(fp, "\tnext_notification=%lu\n", temp_host->next_notification);
		fprintf(fp, "\tno_more_notifications=%d\n", temp_host->no_more_notifications);
		fprintf(fp, "\tcurrent_notification_number=%d\n", temp_host->current_notification_number);
		fprintf(fp, "\tcurrent_notification_id=%lu\n", temp_host->current_notification_id);
		fprintf(fp, "\tnotifications_enabled=%d\n", temp_host->notifications_enabled);
		fprintf(fp, "\tproblem_has_been_acknowledged=%d\n", temp_host->problem_has_been_acknowledged);
		fprintf(fp, "\tacknowledgement_type=%d\n", temp_host->acknowledgement_type);
		fprintf(fp, "\tactive_checks_enabled=%d\n", temp_host->checks_enabled);
		fprintf(fp, "\tpassive_checks_enabled=%d\n", temp_host->accept_passive_checks);
		fprintf(fp, "\tevent_handler_enabled=%d\n", temp_host->event_handler_enabled);
		fprintf(fp, "\tflap_detection_enabled=%d\n", temp_host->flap_detection_enabled);
		fprintf(fp, "\tprocess_performance_data=%d\n", temp_host->process_performance_data);
		fprintf(fp, "\tobsess=%d\n", temp_host->obsess);
		fprintf(fp, "\tlast_update=%lu\n", current_time);
		fprintf(fp, "\tis_flapping=%d\n", temp_host->is_flapping);
		fprintf(fp, "\tpercent_state_change=%.2f\n", temp_host->percent_state_change);
		fprintf(fp, "\tscheduled_downtime_depth=%d\n", temp_host->scheduled_downtime_depth);
		/* custom variables */
		for(temp_customvariablesmember = temp_host->custom_variables; temp_customvariablesmember != NULL; temp_customvariablesmember = temp_customvariablesmember->next) {
			if(temp_customvariablesmember->variable_name)
				fprintf(fp, "\t_%s=%d;%s\n", temp_customvariablesmember->variable_name, temp_customvariablesmember->has_been_modified, (temp_customvariablesmember->variable_value == NULL) ? "" : temp_customvariablesmember->variable_value);
			}
		fprintf(fp, "\t}\n\n");
		}

	/* save service status data */
	for(temp_service = service_list; temp_service != NULL; temp_service = temp_service->next) {

		fprintf(fp, "servicestatus {\n");
		fprintf(fp, "\thost_name=%s\n", temp_service->host_name);

		fprintf(fp, "\tservice_description=%s\n", temp_service->description);
		fprintf(fp, "\tmodified_attributes=%lu\n", temp_service->modified_attributes);
		fprintf(fp, "\tcheck_command=%s\n", (temp_service->check_command == NULL) ? "" : temp_service->check_command);
		fprintf(fp, "\tcheck_period=%s\n", (temp_service->check_period == NULL) ? "" : temp_service->check_period);
		fprintf(fp, "\tnotification_period=%s\n", (temp_service->notification_period == NULL) ? "" : temp_service->notification_period);
		fprintf(fp, "\tcheck_interval=%f\n", temp_service->check_interval);
		fprintf(fp, "\tretry_interval=%f\n", temp_service->retry_interval);
		fprintf(fp, "\tevent_handler=%s\n", (temp_service->event_handler == NULL) ? "" : temp_service->event_handler);

		fprintf(fp, "\thas_been_checked=%d\n", temp_service->has_been_checked);
		fprintf(fp, "\tshould_be_scheduled=%d\n", temp_service->should_be_scheduled);
		fprintf(fp, "\tcheck_execution_time=%.3f\n", temp_service->execution_time);
		fprintf(fp, "\tcheck_latency=%.3f\n", temp_service->latency);
		fprintf(fp, "\tcheck_type=%d\n", temp_service->check_type);
		fprintf(fp, "\tcurrent_state=%d\n", temp_service->current_state);
		fprintf(fp, "\tlast_hard_state=%d\n", temp_service->last_hard_state);
		fprintf(fp, "\tlast_event_id=%lu\n", temp_service->last_event_id);
		fprintf(fp, "\tcurrent_event_id=%lu\n", temp_service->current_event_id);
		fprintf(fp, "\tcurrent_problem_id=%lu\n", temp_service->current_problem_id);
		fprintf(fp, "\tlast_problem_id=%lu\n", temp_service->last_problem_id);
		fprintf(fp, "\tcurrent_attempt=%d\n", temp_service->current_attempt);
		fprintf(fp, "\tmax_attempts=%d\n", temp_service->max_attempts);
		fprintf(fp, "\tstate_type=%d\n", temp_service->state_type);
		fprintf(fp, "\tlast_state_change=%lu\n", temp_service->last_state_change);
		fprintf(fp, "\tlast_hard_state_change=%lu\n", temp_service->last_hard_state_change);
		fprintf(fp, "\tlast_time_ok=%lu\n", temp_service->last_time_ok);
		fprintf(fp, "\tlast_time_warning=%lu\n", temp_service->last_time_warning);
		fprintf(fp, "\tlast_time_unknown=%lu\n", temp_service->last_time_unknown);
		fprintf(fp, "\tlast_time_critical=%lu\n", temp_service->last_time_critical);
		fprintf(fp, "\tplugin_output=%s\n", (temp_service->plugin_output == NULL) ? "" : temp_service->plugin_output);
		fprintf(fp, "\tlong_plugin_output=%s\n", (temp_service->long_plugin_output == NULL) ? "" : temp_service->long_plugin_output);
		fprintf(fp, "\tperformance_data=%s\n", (temp_service->perf_data == NULL) ? "" : temp_service->perf_data);
		fprintf(fp, "\tlast_check=%lu\n", temp_service->last_check);
		fprintf(fp, "\tnext_check=%lu\n", temp_service->next_check);
		fprintf(fp, "\tcheck_options=%d\n", temp_service->check_options);
		fprintf(fp, "\tcurrent_notification_number=%d\n", temp_service->current_notification_number);
		fprintf(fp, "\tcurrent_notification_id=%lu\n", temp_service->current_notification_id);
		fprintf(fp, "\tlast_notification=%lu\n", temp_service->last_notification);
		fprintf(fp, "\tnext_notification=%lu\n", temp_service->next_notification);
		fprintf(fp, "\tno_more_notifications=%d\n", temp_service->no_more_notifications);
		fprintf(fp, "\tnotifications_enabled=%d\n", temp_service->notifications_enabled);
		fprintf(fp, "\tactive_checks_enabled=%d\n", temp_service->checks_enabled);
		fprintf(fp, "\tpassive_checks_enabled=%d\n", temp_service->accept_passive_checks);
		fprintf(fp, "\tevent_handler_enabled=%d\n", temp_service->event_handler_enabled);
		fprintf(fp, "\tproblem_has_been_acknowledged=%d\n", temp_service->problem_has_been_acknowledged);
		fprintf(fp, "\tacknowledgement_type=%d\n", temp_service->acknowledgement_type);
		fprintf(fp, "\tflap_detection_enabled=%d\n", temp_service->flap_detection_enabled);
		fprintf(fp, "\tprocess_performance_data=%d\n", temp_service->process_performance_data);
		fprintf(fp, "\tobsess=%d\n", temp_service->obsess);
		fprintf(fp, "\tlast_update=%lu\n", current_time);
		fprintf(fp, "\tis_flapping=%d\n", temp_service->is_flapping);
		fprintf(fp, "\tpercent_state_change=%.2f\n", temp_service->percent_state_change);
		fprintf(fp, "\tscheduled_downtime_depth=%d\n", temp_service->scheduled_downtime_depth);
		/* custom variables */
		for(temp_customvariablesmember = temp_service->custom_variables; temp_customvariablesmember != NULL; temp_customvariablesmember = temp_customvariablesmember->next) {
			if(temp_customvariablesmember->variable_name)
				fprintf(fp, "\t_%s=%d;%s\n", temp_customvariablesmember->variable_name, temp_customvariablesmember->has_been_modified, (temp_customvariablesmember->variable_value == NULL) ? "" : temp_customvariablesmember->variable_value);
			}
		fprintf(fp, "\t}\n\n");
		}

	/* save contact status data */
	for(temp_contact = contact_list; temp_contact != NULL; temp_contact = temp_contact->next) {

		fprintf(fp, "contactstatus {\n");
		fprintf(fp, "\tcontact_name=%s\n", temp_contact->name);

		fprintf(fp, "\tmodified_attributes=%lu\n", temp_contact->modified_attributes);
		fprintf(fp, "\tmodified_host_attributes=%lu\n", temp_contact->modified_host_attributes);
		fprintf(fp, "\tmodified_service_attributes=%lu\n", temp_contact->modified_service_attributes);
		fprintf(fp, "\thost_notification_period=%s\n", (temp_contact->host_notification_period == NULL) ? "" : temp_contact->host_notification_period);
		fprintf(fp, "\tservice_notification_period=%s\n", (temp_contact->service_notification_period == NULL) ? "" : temp_contact->service_notification_period);

		fprintf(fp, "\tlast_host_notification=%lu\n", temp_contact->last_host_notification);
		fprintf(fp, "\tlast_service_notification=%lu\n", temp_contact->last_service_notification);
		fprintf(fp, "\thost_notifications_enabled=%d\n", temp_contact->host_notifications_enabled);
		fprintf(fp, "\tservice_notifications_enabled=%d\n", temp_contact->service_notifications_enabled);
		/* custom variables */
		for(temp_customvariablesmember = temp_contact->custom_variables; temp_customvariablesmember != NULL; temp_customvariablesmember = temp_customvariablesmember->next) {
			if(temp_customvariablesmember->variable_name)
				fprintf(fp, "\t_%s=%d;%s\n", temp_customvariablesmember->variable_name, temp_customvariablesmember->has_been_modified, (temp_customvariablesmember->variable_value == NULL) ? "" : temp_customvariablesmember->variable_value);
			}
		fprintf(fp, "\t}\n\n");
		}

	/* save all comments */
	for(temp_comment = comment_list; temp_comment != NULL; temp_comment = temp_comment->next) {

		if(temp_comment->comment_type == HOST_COMMENT)
			fprintf(fp, "hostcomment {\n");
		else
			fprintf(fp, "servicecomment {\n");
		fprintf(fp, "\thost_name=%s\n", temp_comment->host_name);
		if(temp_comment->comment_type == SERVICE_COMMENT)
			fprintf(fp, "\tservice_description=%s\n", temp_comment->service_description);
		fprintf(fp, "\tentry_type=%d\n", temp_comment->entry_type);
		fprintf(fp, "\tcomment_id=%lu\n", temp_comment->comment_id);
		fprintf(fp, "\tsource=%d\n", temp_comment->source);
		fprintf(fp, "\tpersistent=%d\n", temp_comment->persistent);
		fprintf(fp, "\tentry_time=%lu\n", temp_comment->entry_time);
		fprintf(fp, "\texpires=%d\n", temp_comment->expires);
		fprintf(fp, "\texpire_time=%lu\n", temp_comment->expire_time);
		fprintf(fp, "\tauthor=%s\n", temp_comment->author);
		fprintf(fp, "\tcomment_data=%s\n", temp_comment->comment_data);
		fprintf(fp, "\t}\n\n");
		}

	/* save all downtime */
	for(temp_downtime = scheduled_downtime_list; temp_downtime != NULL; temp_downtime = temp_downtime->next) {

		if(temp_downtime->type == HOST_DOWNTIME)
			fprintf(fp, "hostdowntime {\n");
		else
			fprintf(fp, "servicedowntime {\n");
		fprintf(fp, "\thost_name=%s\n", temp_downtime->host_name);
		if(temp_downtime->type == SERVICE_DOWNTIME)
			fprintf(fp, "\tservice_description=%s\n", temp_downtime->service_description);
		fprintf(fp, "\tdowntime_id=%lu\n", temp_downtime->downtime_id);
		fprintf(fp, "\tcomment_id=%lu\n", temp_downtime->comment_id);
		fprintf(fp, "\tentry_time=%lu\n", temp_downtime->entry_time);
		fprintf(fp, "\tstart_time=%lu\n", temp_downtime->start_time);
		fprintf(fp, "\tflex_downtime_start=%lu\n", temp_downtime->flex_downtime_start);
		fprintf(fp, "\tend_time=%lu\n", temp_downtime->end_time);
		fprintf(fp, "\ttriggered_by=%lu\n", temp_downtime->triggered_by);
		fprintf(fp, "\tfixed=%d\n", temp_downtime->fixed);
		fprintf(fp, "\tduration=%lu\n", temp_downtime->duration);
		fprintf(fp, "\tis_in_effect=%d\n", temp_downtime->is_in_effect);
		fprintf(fp, "\tauthor=%s\n", temp_downtime->author);
		fprintf(fp, "\tcomment=%s\n", temp_downtime->comment);
		fprintf(fp, "\t}\n\n");
		}


	/* reset file permissions */
	fchmod(fd, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH);

	/* flush the file to disk */
	fflush(fp);

	/* fsync the file so that it is completely written out before moving it */
	fsync(fd);

	/* close the temp file */
	result = fclose(fp);

	/* save/close was successful */
	if(result == 0) {

		result = OK;

		/* move the temp file to the status log (overwrite the old status log) */
		if(my_rename(temp_file, xsddefault_status_log)) {
			unlink(temp_file);
			logit(NSLOG_RUNTIME_ERROR, TRUE, "Error: Unable to update status data file '%s': %s", xsddefault_status_log, strerror(errno));
			result = ERROR;
			}
		}

	/* a problem occurred saving the file */
	else {

		result = ERROR;

		/* remove temp file and log an error */
		unlink(temp_file);
		logit(NSLOG_RUNTIME_ERROR, TRUE, "Error: Unable to save status file: %s", strerror(errno));
		}

	/* free memory */
	my_free(temp_file);

	return result;
	}
Exemple #18
0
/* rotates the main log file */
int rotate_log_file(time_t rotation_time) {
	char *temp_buffer = NULL;
	char method_string[16] = "";
	char *log_archive = NULL;
	struct tm *t, tm_s;
	int rename_result = 0;
	int stat_result = -1;
	struct stat log_file_stat;

	if (log_rotation_method == LOG_ROTATION_NONE) {
		return OK;
	} else if (log_rotation_method == LOG_ROTATION_HOURLY)
		strcpy(method_string, "HOURLY");
	else if (log_rotation_method == LOG_ROTATION_DAILY)
		strcpy(method_string, "DAILY");
	else if (log_rotation_method == LOG_ROTATION_WEEKLY)
		strcpy(method_string, "WEEKLY");
	else if (log_rotation_method == LOG_ROTATION_MONTHLY)
		strcpy(method_string, "MONTHLY");
	else
		return ERROR;

	/* update the last log rotation time and status log */
	last_log_rotation = time(NULL);
	update_program_status(FALSE);

	t = localtime_r(&rotation_time, &tm_s);

	stat_result = stat(log_file, &log_file_stat);

	close_log_file();

	/* get the archived filename to use */
	dummy = asprintf(&log_archive, "%s%sicinga-%02d-%02d-%d-%02d.log", log_archive_path, (log_archive_path[strlen(log_archive_path)-1] == '/') ? "" : "/", t->tm_mon + 1, t->tm_mday, t->tm_year + 1900, t->tm_hour);

	/* rotate the log file */
	rename_result = my_rename(log_file, log_archive);

	log_fp = open_log_file();

	if (rename_result) {
		my_free(log_archive);
		return ERROR;
	}

	/* record the log rotation after it has been done... */
	dummy = asprintf(&temp_buffer, "LOG ROTATION: %s\n", method_string);
	write_to_all_logs_with_timestamp(temp_buffer, NSLOG_PROCESS_INFO, &rotation_time);
	my_free(temp_buffer);

	/* record log file version format */
	write_log_file_info(&rotation_time);

	if (stat_result == 0) {
		chmod(log_file, log_file_stat.st_mode);
		dummy = chown(log_file, log_file_stat.st_uid, log_file_stat.st_gid);
	}

	/* log current host and service state if activated*/
	if (log_current_states == TRUE) {
		log_host_states(CURRENT_STATES, &rotation_time);
		log_service_states(CURRENT_STATES, &rotation_time);
	}

	/* free memory */
	my_free(log_archive);

	return OK;
}