Ejemplo n.º 1
0
void	zbx_on_exit()
{
	zabbix_log(LOG_LEVEL_INFORMATION, "zbx_on_exit()");
#if !defined(_WINDOWS)

	int i = 0;

	if (threads != NULL) {
		for (	i = 1;
			i <= CONFIG_CONFSYNCER_FORKS + CONFIG_DATASENDER_FORKS + CONFIG_POLLER_FORKS
				+ CONFIG_TRAPPERD_FORKS + CONFIG_PINGER_FORKS + CONFIG_HOUSEKEEPER_FORKS
				+ CONFIG_UNREACHABLE_POLLER_FORKS + CONFIG_HTTPPOLLER_FORKS
				+ CONFIG_DISCOVERER_FORKS + CONFIG_DBSYNCER_FORKS + CONFIG_IPMIPOLLER_FORKS; i ++)
		{
			if (threads[i]) {
				kill(threads[i], SIGTERM);
				threads[i] = (ZBX_THREAD_HANDLE)NULL;
			}
		}
		zbx_free(threads);
	}

#endif /* not _WINDOWS */

#ifdef USE_PID_FILE

	daemon_stop();

#endif /* USE_PID_FILE */

	free_metrics();

	zbx_sleep(2); /* wait for all threads closing */

	DBconnect(ZBX_DB_CONNECT_EXIT);
	free_database_cache();
	DBclose();
/*	zbx_mutex_destroy(&node_sync_access);*/

#ifdef HAVE_OPENIPMI
	free_ipmi_handler();
#endif

	zabbix_close_log();

#ifdef  HAVE_SQLITE3
	php_sem_remove(&sqlite_access);
#endif /* HAVE_SQLITE3 */

	zabbix_log(LOG_LEVEL_INFORMATION, "ZABBIX Proxy stopped. ZABBIX %s (revision %s).",
		ZABBIX_VERSION,
		ZABBIX_REVISION);

	exit(SUCCEED);
}
Ejemplo n.º 2
0
void	zbx_on_exit()
{
	zabbix_log(LOG_LEVEL_DEBUG, "zbx_on_exit() called");

	if (NULL != threads)
	{
		int		i;
		sigset_t	set;

		/* ignore SIGCHLD signals in order for zbx_sleep() to work  */
		sigemptyset(&set);
		sigaddset(&set, SIGCHLD);
		sigprocmask(SIG_BLOCK, &set, NULL);

		for (i = 0; i < threads_num; i++)
		{
			if (threads[i])
			{
				kill(threads[i], SIGTERM);
				threads[i] = ZBX_THREAD_HANDLE_NULL;
			}
		}

		zbx_free(threads);
	}

	free_metrics();

	zbx_sleep(2);	/* wait for all child processes to exit */

	DBconnect(ZBX_DB_CONNECT_EXIT);
	free_database_cache();
	free_configuration_cache();
	DBclose();

#ifdef HAVE_OPENIPMI
	free_ipmi_handler();
#endif

#ifdef HAVE_SQLITE3
	zbx_remove_sqlite3_mutex();
#endif

	free_selfmon_collector();

	zabbix_log(LOG_LEVEL_INFORMATION, "Zabbix Proxy stopped. Zabbix %s (revision %s).",
			ZABBIX_VERSION, ZABBIX_REVISION);

	zabbix_close_log();

	exit(SUCCEED);
}
Ejemplo n.º 3
0
void	zbx_on_exit(void)
{
	zabbix_log(LOG_LEVEL_DEBUG, "zbx_on_exit() called");

	if (SUCCEED == DBtxn_ongoing())
		DBrollback();

	if (NULL != threads)
	{
		zbx_threads_wait(threads, threads_num);	/* wait for all child processes to exit */
		zbx_free(threads);
	}
#ifdef HAVE_PTHREAD_PROCESS_SHARED
	zbx_locks_disable();
#endif
	free_metrics();
	zbx_ipc_service_free_env();

	DBconnect(ZBX_DB_CONNECT_EXIT);

	free_database_cache();

	DBclose();

	free_configuration_cache();

	/* free history value cache */
	zbx_vc_destroy();

	zbx_destroy_itservices_lock();

	/* free vmware support */
	if (0 != CONFIG_VMWARE_FORKS)
		zbx_vmware_destroy();

	free_selfmon_collector();

	zbx_uninitialize_events();

	zbx_unload_modules();

	zabbix_log(LOG_LEVEL_INFORMATION, "Zabbix Server stopped. Zabbix %s (revision %s).",
			ZABBIX_VERSION, ZABBIX_REVISION);

	zabbix_close_log();

#if defined(PS_OVERWRITE_ARGV)
	setproctitle_free_env();
#endif

	exit(EXIT_SUCCESS);
}
Ejemplo n.º 4
0
/*********************************************
 DeleteFolder(): Given a folder ID, delete it
 AND recursively delete everything below it!
 This includes upload deletion!
 *********************************************/
void	DeleteFolder	(long FolderId)
{
  void *VDB;
  MyDBaccess(DB,"SELECT folder_pk,parent,name,description,upload_pk FROM folderlist ORDER BY name,parent,folder_pk;");
  VDB = DBmove(DB);
  ListFoldersRecurse(VDB,FolderId,0,-1,1);
  DBclose(VDB);
#if 0
  /** Disabled: Database will take care of this **/
  MyDBaccess(DB,"VACUUM ANALYZE foldercontents;");
  MyDBaccess(DB,"VACUUM ANALYZE folder;");
#endif
} /* DeleteFolder() */
Ejemplo n.º 5
0
/*********************************************
 MyDBaccess(): DBaccess with debugging.
 *********************************************/
int	MyDBaccess	(void *V, char *S)
{
  int rc;
  if (Verbose > 1) printf("%s\n",S);
  rc = DBaccess(V,S);
  if (rc < 0)
	{
	fprintf(stderr,"FATAL: SQL failed: '%s'.\n",SQL);
	DBclose(DB);
	exit(-1);
	}
  return(rc);
} /* MyDBaccess() */
Ejemplo n.º 6
0
/******************************************************************************
 *                                                                            *
 * Function: main_nodewatcher_loop                                            *
 *                                                                            *
 * Purpose: periodically calculates checks sum of config data                 *
 *                                                                            *
 * Parameters:                                                                *
 *                                                                            *
 * Return value:                                                              *
 *                                                                            *
 * Author: Alexei Vladishev                                                   *
 *                                                                            *
 * Comments: never returns                                                    *
 *                                                                            *
 ******************************************************************************/
int main_nodewatcher_loop()
{
    int start, end;
    int	lastrun = 0;

    zabbix_log( LOG_LEVEL_DEBUG, "In main_nodeupdater_loop()");
    for(;;)
    {
        start = time(NULL);

        zbx_setproctitle("connecting to the database");
        zabbix_log( LOG_LEVEL_DEBUG, "Starting sync with nodes");

        DBconnect(ZBX_DB_CONNECT_NORMAL);

#if 0
        if(lastrun + 120 < start)
        {

            DBbegin();
            calculate_checksums();
            compare_checksums();
            update_checksums();

            /* Send configuration changes to required nodes */
            main_nodesender();
            DBcommit();

            lastrun = start;
        }
#endif
        /* Send new events to master node */
        main_eventsender();

        /* Send new history data to master node */
        main_historysender();

        DBclose();

        end = time(NULL);

        if(end-start<10)
        {
            zbx_setproctitle("sender [sleeping for %d seconds]",
                             10-(end-start));
            zabbix_log( LOG_LEVEL_DEBUG, "Sleeping %d seconds",
                        10-(end-start));
            sleep(10-(end-start));
        }
    }
}
Ejemplo n.º 7
0
void	main_housekeeper_loop()
{
	int	d, now;

	set_child_signal_handler();

	for (;;)
	{
		zabbix_log(LOG_LEVEL_WARNING, "Executing housekeeper");
		now = time(NULL);

		zbx_setproctitle("%s [connecting to the database]", get_process_type_string(process_type));

		DBconnect(ZBX_DB_CONNECT_NORMAL);

/* Transaction is not required here. It causes timeouts under MySQL. */
/*		DBbegin();*/

		zbx_setproctitle("%s [removing old history]", get_process_type_string(process_type));

		d = housekeeping_history_and_trends(now);
		zabbix_log(LOG_LEVEL_WARNING, "Deleted %d records from history and trends", d);

		zbx_setproctitle("%s [removing old history]", get_process_type_string(process_type));

		housekeeping_process_log(now);

		zbx_setproctitle("%s [removing old events]", get_process_type_string(process_type));

		housekeeping_events(now);

		zbx_setproctitle("%s [removing old alerts]", get_process_type_string(process_type));

		housekeeping_alerts(now);

		zbx_setproctitle("%s [removing old sessions]", get_process_type_string(process_type));

		housekeeping_sessions(now);

/* Transaction is not required here. It causes timeouts under MySQL. */
/*		DBcommit();*/

/*		zbx_setproctitle("housekeeper [vacuuming database]");*/

/*		DBvacuum();*/

		DBclose();

		zbx_sleep_loop(SEC_PER_HOUR * CONFIG_HOUSEKEEPING_FREQUENCY);
	}
}
Ejemplo n.º 8
0
int main (int argc, char** argv)
{
#ifdef HAVE_MYSQL
	DB_RESULT	result;
	DB_ROW		row;
	zbx_uint64_t	id;
	char*		value;
	hfs_function_value_t fun_val;
	int		index = 0;

	static struct cfg_line cfg[] = {
		{"DBHost",&CONFIG_DBHOST,0,TYPE_STRING,PARM_OPT,0,0},
		{"DBName",&CONFIG_DBNAME,0,TYPE_STRING,PARM_MAND,0,0},
		{"DBUser",&CONFIG_DBUSER,0,TYPE_STRING,PARM_OPT,0,0},
		{"DBPassword",&CONFIG_DBPASSWORD,0,TYPE_STRING,PARM_OPT,0,0},
		{"DBSocket",&CONFIG_DBSOCKET,0,TYPE_STRING,PARM_OPT,0,0},
		{"DBPort",&CONFIG_DBPORT,0,TYPE_INT,PARM_OPT,1024,65535},
		{"ServerHistoryFSPath",&CONFIG_HFS_PATH,0,TYPE_STRING,PARM_OPT,0,0},
		{"ServerSite",&CONFIG_SERVER_SITE,0,TYPE_STRING,PARM_OPT,0,0},	
		{0}
	};

	/* read config file */
	parse_cfg_file ("/etc/zabbix/zabbix_server.conf", cfg);

	/* connect to database */
	DBconnect (ZBX_DB_CONNECT_EXIT);
	/* select all lastvalues from functions */
	result = DBselect ("select functionid, lastvalue from functions");

	/* update them in HFS */
	while (row = DBfetch (result)) {
		ZBX_STR2UINT64 (id, row[0]);
		value = row[1];

		if (HFS_convert_function_str2val (value, &fun_val))
			if (HFS_save_function_value (CONFIG_HFS_PATH, CONFIG_SERVER_SITE, id, &fun_val))
				printf ("Converted item %d of %lld. ID=%lld, val='%s', type=%d\n", index++, result->row_count, id, value, fun_val.type);
			else
				printf ("Item %d save failed. ID=%lld, val=%s\n", index++, id, value);
		else
			printf ("Item %d convert failed. ID=%lld, val=%s\n", index++, id, value);
	}

	DBclose ();
#else
	printf ("This utility have no meaning on ztops\n");
#endif
	return 0;
}
Ejemplo n.º 9
0
void	main_housekeeper_loop(void)
{
    int	now, d_history_and_trends, d_cleanup, d_events, d_sessions, d_services, d_audit;
    double	sec;

    for (;;)
    {
        zabbix_log(LOG_LEVEL_WARNING, "executing housekeeper");
        now = time(NULL);

        zbx_setproctitle("%s [connecting to the database]", get_process_type_string(process_type));
        DBconnect(ZBX_DB_CONNECT_NORMAL);

        DCconfig_get_config_hk(&hk_config);

        zbx_setproctitle("%s [removing old history and trends]", get_process_type_string(process_type));
        sec = zbx_time();
        d_history_and_trends = housekeeping_history_and_trends(now);

        zbx_setproctitle("%s [removing deleted items data]", get_process_type_string(process_type));
        d_cleanup = housekeeping_cleanup();

        zbx_setproctitle("%s [removing old events]", get_process_type_string(process_type));
        d_events = housekeeping_events(now);

        zbx_setproctitle("%s [removing old sessions]", get_process_type_string(process_type));
        d_sessions = housekeeping_sessions(now);

        zbx_setproctitle("%s [removing old service alarms]", get_process_type_string(process_type));
        d_services = housekeeping_services(now);

        zbx_setproctitle("%s [removing old audit log items]", get_process_type_string(process_type));
        d_audit = housekeeping_audit(now);

        sec = zbx_time() - sec;

        zabbix_log(LOG_LEVEL_WARNING, "%s [deleted %d hist/trends, %d items, %d events, %d sessions, %d alarms,"
                   " %d audit items in " ZBX_FS_DBL " sec, idle %d hour(s)]",
                   get_process_type_string(process_type), d_history_and_trends, d_cleanup, d_events,
                   d_sessions, d_services, d_audit, sec, CONFIG_HOUSEKEEPING_FREQUENCY);
        DBclose();

        zbx_setproctitle("%s [deleted %d hist/trends, %d items, %d events, %d sessions, %d alarms, %d audit "
                         "items in " ZBX_FS_DBL " sec, idle %d hour(s)]",
                         get_process_type_string(process_type), d_history_and_trends, d_cleanup, d_events,
                         d_sessions, d_services, d_audit, sec, CONFIG_HOUSEKEEPING_FREQUENCY);

        zbx_sleep_loop(CONFIG_HOUSEKEEPING_FREQUENCY * SEC_PER_HOUR);
    }
}
Ejemplo n.º 10
0
/**************************************************
 LoadAdj(): Given an upload_pk, load the adjacency table.
 This is in the format "every child knows its parent".
 Returns the adjacency tree.
 **************************************************/
void	LoadAdj	(long UploadPk)
{
  long i;
  long Parent,Child;
  void *UDB;

  snprintf(SQL,sizeof(SQL),"SELECT uploadtree_pk,parent FROM uploadtree WHERE upload_fk = %ld AND parent IS NOT NULL ORDER BY parent;",UploadPk);
  DBaccess(DB,SQL);
  TreeSize = DBdatasize(DB);
  if (Verbose) printf("# Upload %ld: %ld items\n",UploadPk,TreeSize);

  UDB=DBmove(DB);
  snprintf(SQL,sizeof(SQL),"SELECT uploadtree_pk,parent FROM uploadtree WHERE upload_fk = %ld AND parent IS NULL;",UploadPk);
  DBaccess(DB,SQL);
  TreeSize += DBdatasize(DB);

  /* Got data! Populate the tree! */
  if (Tree) { free(Tree); }
  if (TreeSize <= 0) { Tree=NULL; return; }
  Tree = (uploadtree *)calloc(TreeSize+1,sizeof(uploadtree));
  for(i=0; i<TreeSize+1; i++)
    {
    Tree[i].UploadtreePk=-1;
    Tree[i].Child=-1;
    Tree[i].Sibling=-1;
    }

  TreeSet=0;
  SetNum=1;

  /* Load the roots */
  for(i=0; i<DBdatasize(DB); i++)
    {
    Child = atol(DBgetvalue(DB,i,0));
    Tree[TreeSet].UploadtreePk = Child;
    TreeSet++;
    }

  /* Load all non-roots */
  for(i=0; i<DBdatasize(UDB); i++)
    {
    Child = atol(DBgetvalue(UDB,i,0));
    Parent = atol(DBgetvalue(UDB,i,1));
    SetParent(Parent,Child);
    }

  /* Free up DB memory */
  DBclose(UDB);
  return;
} /* LoadAdj() */
Ejemplo n.º 11
0
/******************************************************************************
 *                                                                            *
 * Function: main_discoverer_loop                                             *
 *                                                                            *
 * Purpose: periodically try to find new hosts and services                   *
 *                                                                            *
 * Parameters:                                                                *
 *                                                                            *
 * Return value:                                                              *
 *                                                                            *
 * Author: Alexei Vladishev                                                   *
 *                                                                            *
 * Comments: executes once per 30 seconds (hardcoded)                         *
 *                                                                            *
 ******************************************************************************/
void main_discoverer_loop(int num)
{
	int	now;

	DB_RESULT	result;
	DB_ROW		row;
	DB_DRULE	rule;

	zabbix_log( LOG_LEVEL_DEBUG, "In main_discoverer_loop(num:%d)",
		num);

	discoverer_num = num;

	DBconnect(ZBX_DB_CONNECT_NORMAL);

	for(;;)
	{
		zbx_setproctitle("Discoverer finding new hosts and services");
		now=time(NULL);

		result = DBselect("select druleid,iprange,delay,nextcheck,name,status,siteid from drules where status=%d and nextcheck<=%d and " ZBX_SQL_MOD(druleid,%d) "=%d",
			DRULE_STATUS_MONITORED,
			now,
			CONFIG_DISCOVERER_FORKS,
			discoverer_num-1);
		while((row=DBfetch(result)))
		{
			memset(&rule, 0, sizeof(DB_DRULE));

			ZBX_STR2UINT64(rule.druleid,row[0]);
			rule.iprange 		= row[1];
			rule.delay		= atoi(row[2]);
			rule.nextcheck		= atoi(row[3]);
			rule.name		= row[4];
			rule.status		= atoi(row[5]);
			ZBX_STR2UINT64(rule.siteid,row[6]);

			process_rule(&rule);
		}
		DBfree_result(result);

		zbx_setproctitle("Discoverer [sleeping for 30 sec]");

		sleep(30);
	}
	DBclose();
}
Ejemplo n.º 12
0
/*********************************************************
 DBCheckFileExtention(): given a pfile, identify any filenames
 and see if any of them have a known extension based on
 /etc/mime.types.
 Returns the mimetype, or -1 if not found.
 *********************************************************/
int	DBCheckFileExtention	()
{
  int u, Maxu;
  char *Ext;
  int rc;

  if (!FMimetype) return(-1);

  if (Akey >= 0)
    {
    memset(SQL,'\0',sizeof(SQL));
    snprintf(SQL,sizeof(SQL)-1,"SELECT distinct(ufile_name) FROM uploadtree WHERE pfile_fk = %d",Akey);
    if (DBaccess(DB,SQL) < 0)
      {
      printf("ERROR: Unable to query the database.\n");
      printf("LOG: Unable to access database: '%s'\n",SQL);
      fflush(stdout);
      DBclose(DB);
      exit(-1);
      }

    Maxu = DBdatasize(DB);
    for(u=0; u<Maxu; u++)
      {
      Ext = strrchr(DBgetvalue(DB,u,0),'.'); /* find the extention */
      if (Ext)
	{
	Ext++; /* move past period */
	rc = CheckMimeTypes(Ext);
	if (rc >= 0) return(rc);
	}
      }
    } /* if using DB */
  else
    {
    /* using command-line */
    Ext = strrchr(A,'.'); /* find the extention */
    if (Ext)
      {
      Ext++; /* move past period */
      rc = CheckMimeTypes(Ext);
      if (rc >= 0) return(rc);
      }
    }
  return(-1);
} /* DBCheckFileExtention() */
Ejemplo n.º 13
0
Archivo: snmp.c Proyecto: Shmuma/z
int	DBexecute(char *query)
{
	while( mysql_query(&mysql,query) != 0)
	{
		printf("Query::%s\n",query);
		printf("Query failed:%s [%d]\n", mysql_error(&mysql), mysql_errno(&mysql) );

		if( (ER_SERVER_SHUTDOWN   != mysql_errno(&mysql)) && 
            (CR_SERVER_GONE_ERROR != mysql_errno(&mysql)) &&
            (CR_CONNECTION_ERROR  != mysql_errno(&mysql)))
		{
			return -1;
		}

        	DBclose();
        	DBconnect();
	}
}
Ejemplo n.º 14
0
/******************************************************************************
 *                                                                            *
 * Function: main_watchdog_loop                                               *
 *                                                                            *
 * Purpose: periodically checks availability of database and alerts admin if  *
 *          down                                                              *
 *                                                                            *
 * Parameters:                                                                *
 *                                                                            *
 * Return value:                                                              *
 *                                                                            *
 * Author: Alexei Vladishev                                                   *
 *                                                                            *
 * Comments: check database availability every 60 seconds (hardcoded)         *
 *                                                                            *
 ******************************************************************************/
void main_watchdog_loop()
{
	zabbix_log(LOG_LEVEL_WARNING, "In main_watchdog_loop()");

	/* Disable writing to database in zabbix_syslog() */
	CONFIG_ENABLE_LOG = 0;

	DBconnect(ZBX_DB_CONNECT_NORMAL);

	init_config();

	DBclose();

	for (;;) {
		ping_database();

		sleep(60);
	}

	/* We will never reach this point */
}
Ejemplo n.º 15
0
Archivo: trapper.c Proyecto: Shmuma/z
void	child_hist_trapper_main (int i)
{
	int count;
	queue_history_entry_t entry;
	void* history_token;

	zabbix_log( LOG_LEVEL_DEBUG, "In child_trapper_main()");
	zabbix_log( LOG_LEVEL_WARNING, "server #%d started [HistTrapper]", i);

	queue_fd = queue_get_queue_id (i, 1);

	key_values = metric_register ("trapper_history_values",  i);
	key_skipped = metric_register ("trapper_history_skipped_bytes",  i);
	metric_update (key_skipped, mtr_skipped);

	DBconnect(ZBX_DB_CONNECT_NORMAL);

	for (;;) {
		zbx_setproctitle("Trapper waiting for new history data");

		/* First we try to get data from primary queue */
 		count = trapper_dequeue_history (&entry);

		if (count) {
			history_token = NULL;

			mtr_values += entry.count;
			metric_update (key_values, mtr_values);

			for (i = 0; i < entry.count; i++)
				append_history (entry.server, entry.key, entry.items[i].value, entry.items[i].ts, &history_token);
			flush_history (&history_token);
			free (entry.items);
		}
	}

	DBclose();
}
Ejemplo n.º 16
0
/******************************************************************************
 *                                                                            *
 * Function:                                                                  *
 *                                                                            *
 * Purpose:                                                                   *
 *                                                                            *
 * Parameters:                                                                *
 *                                                                            *
 * Return value:                                                              *
 *                                                                            *
 * Comments:                                                                  *
 *                                                                            *
 ******************************************************************************/
static void process_jatrapper(zbx_sock_t * sock)
{
    ja_telegram_object obj;
    char *data;
    const char *__function_name = "process_jatrapper";
    zabbix_log(LOG_LEVEL_DEBUG, "In %s()", __function_name);

    ja_telegram_new(&obj);
    if (ja_telegram_recv(&obj, sock, CONFIG_TIMEOUT) == FAIL)
        goto error;

    data = (char *) json_object_to_json_string(obj.request);
    DBconnect(ZBX_DB_CONNECT_NORMAL);
    if (jatrap_kind(sock, &obj) == SUCCEED) {
        jatraper_reply(sock, &obj);
    } else {
        process_jatrap(sock, data);
    }
    DBclose();

  error:
    ja_telegram_clear(&obj);
}
Ejemplo n.º 17
0
Archivo: db.c Proyecto: phedders/zabbix
void	zbx_db_init(char *host, char *user, char *password, char *dbname, char *dbsocket, int port)
{
#ifdef	HAVE_SQLITE3
	int		ret;
	struct stat	buf;
#endif

#ifdef	HAVE_SQLITE3
	if (0 != stat(dbname, &buf)) {
		zabbix_log(LOG_LEVEL_WARNING, "Cannot open database file \"%s\": %s", dbname, strerror(errno));
		zabbix_log(LOG_LEVEL_WARNING, "Creating database ...");

		ret = sqlite3_open(dbname, &conn);
		if (SQLITE_OK != ret) {
			zabbix_errlog(ERR_Z3002, dbname, 0, sqlite3_errmsg(conn));
			exit(FAIL);
		}

		DBexecute("%s", db_schema);
		DBclose();
	}
#endif
}
Ejemplo n.º 18
0
void	main_housekeeper_loop()
{
	int	now, d_history_and_trends, d_cleanup, d_events, d_alerts, d_sessions;

	for (;;)
	{
		zabbix_log(LOG_LEVEL_WARNING, "executing housekeeper");
		now = time(NULL);

		zbx_setproctitle("%s [connecting to the database]", get_process_type_string(process_type));

		DBconnect(ZBX_DB_CONNECT_NORMAL);

		zbx_setproctitle("%s [removing old history and trends]", get_process_type_string(process_type));
		d_history_and_trends = housekeeping_history_and_trends(now);

		zbx_setproctitle("%s [removing deleted items data]", get_process_type_string(process_type));
		d_cleanup = housekeeping_cleanup();

		zbx_setproctitle("%s [removing old events]", get_process_type_string(process_type));
		d_events = housekeeping_events(now);

		zbx_setproctitle("%s [removing old alerts]", get_process_type_string(process_type));
		d_alerts = housekeeping_alerts(now);

		zbx_setproctitle("%s [removing old sessions]", get_process_type_string(process_type));
		d_sessions = housekeeping_sessions(now);

		zabbix_log(LOG_LEVEL_WARNING, "housekeeper deleted: %d records from history and trends,"
				" %d records of deleted items, %d events, %d alerts, %d sessions",
				d_history_and_trends, d_cleanup, d_events, d_alerts, d_sessions);

		DBclose();

		zbx_sleep_loop(CONFIG_HOUSEKEEPING_FREQUENCY * SEC_PER_HOUR);
	}
}
Ejemplo n.º 19
0
Archivo: trapper.c Proyecto: Shmuma/z
void	child_trapper_main(int i)
{
	int count, history;
	queue_entry_t entry;

	zabbix_log( LOG_LEVEL_DEBUG, "In child_trapper_main()");
	zabbix_log( LOG_LEVEL_WARNING, "server #%d started [Trapper]", i);

	/* initialize queue */
	queue_fd = queue_get_queue_id (i, 0);

	/* initialize metrics */
	key_values = metric_register ("trapper_data_values",  i);
	key_skipped = metric_register ("trapper_data_skipped_bytes",  i);
	metric_update (key_skipped, mtr_skipped);

	DBconnect(ZBX_DB_CONNECT_NORMAL);

	for(;;)
	{
		zbx_setproctitle("Trapper waiting for new queue data");

		/* First we try to get data from primary queue */
		if (trapper_dequeue_request (&entry)) {
			zbx_setproctitle("processing queue data block");

			if (!strcmp (entry.key, "profile"))
				process_profile_value (entry.server, entry.error);
			process_data (0, entry.ts, entry.server, entry.key, entry.value,
				      entry.error, entry.lastlogsize, entry.timestamp,
				      entry.source, entry.severity);
			free (entry.buf);
		}
	}
	DBclose();
}
Ejemplo n.º 20
0
/******************************************************************************
 *                                                                            *
 * Function:                                                                  *
 *                                                                            *
 * Purpose:                                                                   *
 *                                                                            *
 * Parameters:                                                                *
 *                                                                            *
 * Return value:                                                              *
 *                                                                            *
 * Comments:                                                                  *
 *                                                                            *
 ******************************************************************************/
int jarun_icon_extjob_run(const zbx_uint64_t inner_job_id,
                          const zbx_uint64_t inner_jobnet_id,
                          const char *command)
{
    int ret, db_ret;
    pid_t pid;
    char filepath[JA_MAX_STRING_LEN];
    char full_command[JA_MAX_STRING_LEN];
    char jacmd[JA_MAX_STRING_LEN];
    const char *__function_name = "jarun_icon_extjob_run";

    zabbix_log(LOG_LEVEL_DEBUG,
               "In %s() inner_job_id: " ZBX_FS_UI64
               ", command: %s", __function_name, inner_job_id, command);

    ret = SUCCEED;
    zbx_snprintf(filepath, JA_MAX_STRING_LEN, "%s%c%s-" ZBX_FS_UI64,
                 CONFIG_TMPDIR, JA_DLM, progname, inner_job_id);
    zbx_snprintf(full_command, JA_MAX_STRING_LEN, "%s.%s", filepath,
                 JA_EXE);
    zbx_snprintf(jacmd, JA_MAX_STRING_LEN, "%s%c%s", CONFIG_EXTJOB_PATH,
                 JA_DLM, JA_JOBARG_COMMAND);
    if (ja_jobfile_create(filepath, jobext, command) != SUCCEED) {
        return ja_set_runerr(inner_job_id);
    }

    pid = ja_fork();
    if (pid == -1) {
        ja_log("JARUNICONEXTJOB200001", inner_jobnet_id, NULL,
               inner_job_id, __function_name);
        return ja_set_runerr(inner_job_id);
    } else if (pid != 0) {
        waitpid(pid, NULL, WNOHANG);
        db_ret =
            DBexecute
            ("update ja_run_icon_extjob_table set pid = %d where inner_job_id = "
             ZBX_FS_UI64, pid, inner_job_id);
        if (db_ret < ZBX_DB_OK) {
            ja_log("JARUNICONEXTJOB200006", inner_jobnet_id, NULL,
                   inner_job_id, __function_name, pid, inner_job_id);
            return FAIL;
        }
        zabbix_log(LOG_LEVEL_DEBUG,
                   "End of %s() inner_job_id: " ZBX_FS_UI64,
                   __function_name, inner_job_id);
        return SUCCEED;
    }

    DBconnect(ZBX_DB_CONNECT_ONCE);
    if (ja_setenv(inner_job_id) == FAIL) {
        DBclose();
        goto error;
    }
    DBclose();
    execl(jacmd, JA_JOBARG_COMMAND, filepath, full_command, NULL);

  error:
    DBconnect(ZBX_DB_CONNECT_ONCE);
    ja_log("JARUNICONEXTJOB200003", inner_jobnet_id, NULL, inner_job_id,
           __function_name, jacmd, zbx_strerror(errno));
    ja_set_runerr(inner_job_id);
    DBclose();
    exit(0);
}
Ejemplo n.º 21
0
/******************************************************************************
 *                                                                            *
 * Function: change_nodeid                                                    *
 *                                                                            *
 * Purpose: convert database data to new node ID                              *
 *                                                                            *
 * Parameters: old_id - old id, new_id - new node id                          *
 *                                                                            *
 * Return value: SUCCEED - converted successfully                             *
 *               FAIL - an error occurred                                     *
 *                                                                            *
 * Author: Alexei Vladishev                                                   *
 *                                                                            *
 ******************************************************************************/
int	change_nodeid(int old_id, int new_id)
{
	struct conv_t
	{
	        const char	*rel;
        	int		type;
	};

	struct special_conv_t
	{
	        const char	*table_name, *field_name, *type_field_name;
		struct conv_t	convs[32];
	};

	struct special_conv_t	special_convs[] =
	{
		{"sysmaps_elements",	"elementid",	"elementtype",
			{
			{"hosts",	SYSMAP_ELEMENT_TYPE_HOST},
			{"sysmaps",	SYSMAP_ELEMENT_TYPE_MAP},
			{"triggers",	SYSMAP_ELEMENT_TYPE_TRIGGER},
			{"groups",	SYSMAP_ELEMENT_TYPE_HOST_GROUP},
			{"images",	SYSMAP_ELEMENT_TYPE_IMAGE},
			{NULL}
			}
		},
		{"events",		"objectid",	"object",
			{
			{"triggers",	EVENT_OBJECT_TRIGGER},
			{"dhosts",	EVENT_OBJECT_DHOST},
			{"dservices",	EVENT_OBJECT_DSERVICE},
			{NULL}
			}
		},
		{"ids",			"nextid",	NULL,
			{
			{NULL}
			}
		},
		{"node_cksum",		"recordid",	NULL,
			{
			{NULL}
			}
		},
		{"screens_items",	"resourceid",	"resourcetype",
			{
			{"graphs",	SCREEN_RESOURCE_GRAPH},
			{"items",	SCREEN_RESOURCE_SIMPLE_GRAPH},
			{"sysmaps",	SCREEN_RESOURCE_MAP},
			{"items",	SCREEN_RESOURCE_PLAIN_TEXT},
			{"groups",	SCREEN_RESOURCE_HOSTS_INFO},
			{"screens",	SCREEN_RESOURCE_SCREEN},
			{"groups",	SCREEN_RESOURCE_TRIGGERS_OVERVIEW},
			{"groups",	SCREEN_RESOURCE_DATA_OVERVIEW},
			{"groups",	SCREEN_RESOURCE_HOSTGROUP_TRIGGERS},
			{"hosts",	SCREEN_RESOURCE_HOST_TRIGGERS},
			{NULL}
			}
		},
		{"auditlog",	"resourceid",	"resourcetype",
			{
			{"users",		AUDIT_RESOURCE_USER},
/*			{"",			AUDIT_RESOURCE_ZABBIX},*/
			{"config",		AUDIT_RESOURCE_ZABBIX_CONFIG},
			{"media_type",		AUDIT_RESOURCE_MEDIA_TYPE},
			{"hosts",		AUDIT_RESOURCE_HOST},
			{"actions",		AUDIT_RESOURCE_ACTION},
			{"graphs",		AUDIT_RESOURCE_GRAPH},
			{"graphs_items",	AUDIT_RESOURCE_GRAPH_ELEMENT},
/*			{"",			AUDIT_RESOURCE_ESCALATION},
			{"",			AUDIT_RESOURCE_ESCALATION_RULE},
			{"",			AUDIT_RESOURCE_AUTOREGISTRATION},*/
			{"usrgrp",		AUDIT_RESOURCE_USER_GROUP},
			{"applications",	AUDIT_RESOURCE_APPLICATION},
			{"triggers",		AUDIT_RESOURCE_TRIGGER},
			{"groups",		AUDIT_RESOURCE_HOST_GROUP},
			{"items",		AUDIT_RESOURCE_ITEM},
			{"images",		AUDIT_RESOURCE_IMAGE},
			{"valuemaps",		AUDIT_RESOURCE_VALUE_MAP},
			{"services",		AUDIT_RESOURCE_IT_SERVICE},
			{"sysmaps",		AUDIT_RESOURCE_MAP},
			{"screens",		AUDIT_RESOURCE_SCREEN},
/*			{"nodes",		AUDIT_RESOURCE_NODE},*/
/*			{"",			AUDIT_RESOURCE_SCENARIO},*/
			{"drules",		AUDIT_RESOURCE_DISCOVERY_RULE},
			{"slideshows",		AUDIT_RESOURCE_SLIDESHOW},
			{"scripts",		AUDIT_RESOURCE_SCRIPT},
/*			{"",			AUDIT_RESOURCE_PROXY},*/
			{"maintenances",	AUDIT_RESOURCE_MAINTENANCE},
			{"regexps",		AUDIT_RESOURCE_REGEXP},
			{NULL}
			}
		},
		{NULL}
	};

	struct conv_t	condition_convs[] =
	{
		{"groups",	CONDITION_TYPE_HOST_GROUP},
		{"hosts",	CONDITION_TYPE_HOST},
		{"hosts",	CONDITION_TYPE_HOST_TEMPLATE},
		{"hosts",	CONDITION_TYPE_PROXY},
		{"triggers",	CONDITION_TYPE_TRIGGER},
		{"dchecks",	CONDITION_TYPE_DCHECK},
		{"drules",	CONDITION_TYPE_DRULE},
		{NULL},
	};

	int		i, j, s, t, ret = FAIL;
	zbx_uint64_t	prefix;
	const ZBX_TABLE	*r_table;

	if (0 != old_id)
	{
		printf("Conversion from non-zero node ID is not supported.\n");
		return ret;
	}

	if (1 > new_id || new_id > 999)
	{
		printf("Node ID must be in range of 1-999.\n");
		return ret;
	}

	zabbix_set_log_level(LOG_LEVEL_WARNING);

	DBconnect(ZBX_DB_CONNECT_EXIT);

	DBbegin();

	printf("Dropping foreign keys ");
	fflush(stdout);

	for (i = 0; NULL != db_schema_fkeys_drop[i]; i++)
	{
		DBexecute("%s", db_schema_fkeys_drop[i]);
		printf(".");
		fflush(stdout);
	}

	printf(" done.\nConverting tables ");
	fflush(stdout);

	for (i = 0; NULL != tables[i].table; i++)
	{
		printf(".");
		fflush(stdout);

		for (j = 0; NULL != tables[i].fields[j].name; j++)
		{
			for (s = 0; NULL != special_convs[s].table_name; s++)
			{
				if (0 == strcmp(special_convs[s].table_name, tables[i].table) &&
						0 == strcmp(special_convs[s].field_name, tables[i].fields[j].name))
				{
					break;
				}
			}

			if (NULL != special_convs[s].table_name)
			{
				for (t = 0; NULL != special_convs[s].convs[t].rel; t++)
				{
					convert_special_field(old_id, new_id, special_convs[s].table_name,
							special_convs[s].field_name, special_convs[s].type_field_name,
							special_convs[s].convs[t].rel, special_convs[s].convs[t].type);
				}
				continue;
			}

			if (ZBX_TYPE_ID != tables[i].fields[j].type)
				continue;

			/* primary key */
			if (0 == strcmp(tables[i].fields[j].name, tables[i].recid))
			{
				prefix = (zbx_uint64_t)__UINT64_C(100000000000000) * (zbx_uint64_t)new_id;

				if (0 != (tables[i].flags & ZBX_SYNC))
					prefix += (zbx_uint64_t)__UINT64_C(100000000000) * (zbx_uint64_t)new_id;
			}
			/* relations */
			else if (NULL != tables[i].fields[j].fk_table)
			{
				r_table = DBget_table(tables[i].fields[j].fk_table);
				assert(NULL != r_table);

				prefix = (zbx_uint64_t)__UINT64_C(100000000000000)*(zbx_uint64_t)new_id;

				if (0 != (r_table->flags & ZBX_SYNC))
					prefix += (zbx_uint64_t)__UINT64_C(100000000000)*(zbx_uint64_t)new_id;
			}
			/* special processing for table 'profiles' */
			else if (0 == strcmp("profiles", tables[i].table))
			{
				convert_profiles(old_id, new_id, tables[i].fields[j].name);
				continue;
			}
			else
				assert(0);

			DBexecute("update %s set %s=%s+" ZBX_FS_UI64 " where %s>0",
					tables[i].table,
					tables[i].fields[j].name,
					tables[i].fields[j].name,
					prefix,
					tables[i].fields[j].name);
		}
	}

	/* special processing for trigger expressions */
	convert_triggers_expression(old_id, new_id);

	/* special processing for condition values */
	for (i = 0; NULL != condition_convs[i].rel; i++)
		convert_condition_values(old_id, new_id, condition_convs[i].rel, condition_convs[i].type);

	DBexecute("insert into nodes (nodeid,name,ip,nodetype) values (%d,'Local node','127.0.0.1',1)", new_id);

	DBexecute("delete from ids where nodeid=0");

	if (SUCCEED != (ret = DBtxn_status()))
		goto error;

	printf(" done.\nCreating foreign keys ");
	fflush(stdout);

	for (i = 0; NULL != db_schema_fkeys[i]; i++)
	{
		DBexecute("%s", db_schema_fkeys[i]);
		printf(".");
		fflush(stdout);
	}

	ret = DBtxn_status();
error:
	DBcommit();

	DBclose();

	if (SUCCEED != ret)
		printf("Conversion failed.\n");
	else
		printf(" done.\nConversion completed successfully.\n");

	return ret;
}
Ejemplo n.º 22
0
/******************************************************************************
 *                                                                            *
 * Function: main_alerter_loop                                                *
 *                                                                            *
 * Purpose: periodically check table alerts and send notifications if needed  *
 *                                                                            *
 * Parameters:                                                                *
 *                                                                            *
 * Return value:                                                              *
 *                                                                            *
 * Author: Alexei Vladishev                                                   *
 *                                                                            *
 * Comments: never returns                                                    *
 *                                                                            *
 ******************************************************************************/
int main_alerter_loop()
{
	char			error[MAX_STRING_LEN], *error_esc;
	int			res, now;
	struct	sigaction	phan;
	DB_RESULT		result;
	DB_ROW			row;
	DB_ALERT		alert;
	DB_MEDIATYPE		mediatype;

/*	phan.sa_handler = child_signal_handler;*/
        phan.sa_sigaction = child_signal_handler;
	sigemptyset(&phan.sa_mask);
	phan.sa_flags = SA_SIGINFO;
	sigaction(SIGALRM, &phan, NULL);

	zbx_setproctitle("connecting to the database");

	DBconnect(ZBX_DB_CONNECT_NORMAL);

	for (;;) {
		now = time(NULL);

		result = DBselect("select a.alertid,a.mediatypeid,a.sendto,a.subject,a.message,a.status,mt.mediatypeid"
				",mt.type,mt.description,mt.smtp_server,mt.smtp_helo,mt.smtp_email,mt.exec_path"
				",mt.gsm_modem,mt.username,mt.passwd,a.retries from alerts a,media_type mt"
				" where a.status=%d and a.mediatypeid=mt.mediatypeid and a.alerttype=%d" DB_NODE
				" order by a.clock",
				ALERT_STATUS_NOT_SENT,
				ALERT_TYPE_MESSAGE,
				DBnode_local("mt.mediatypeid"));

		while (NULL != (row = DBfetch(result))) {
			res = FAIL;

			ZBX_STR2UINT64(alert.alertid, row[0]);
			alert.mediatypeid	= atoi(row[1]);
			alert.sendto		= row[2];
			alert.subject		= row[3];
			alert.message		= row[4];
			alert.status		= atoi(row[5]);

			ZBX_STR2UINT64(mediatype.mediatypeid, row[6]);
			mediatype.type		= atoi(row[7]);
			mediatype.description	= row[8];
			mediatype.smtp_server	= row[9];
			mediatype.smtp_helo	= row[10];
			mediatype.smtp_email	= row[11];
			mediatype.exec_path	= row[12];

			mediatype.gsm_modem	= row[13];
			mediatype.username	= row[14];
			mediatype.passwd	= row[15];

			alert.retries		= atoi(row[16]);

			*error = '\0';
			res = execute_action(&alert, &mediatype, error, sizeof(error));

			if (res == SUCCEED)
			{
				zabbix_log( LOG_LEVEL_DEBUG, "Alert ID [" ZBX_FS_UI64 "] was sent successfully",
					alert.alertid);
				DBexecute("update alerts set status=%d,error='' where alertid=" ZBX_FS_UI64,
					ALERT_STATUS_SENT,
					alert.alertid);
			}
			else
			{
				zabbix_log( LOG_LEVEL_DEBUG, "Error sending alert ID [" ZBX_FS_UI64 "]",
					alert.alertid);
				zabbix_syslog("Error sending alert ID [" ZBX_FS_UI64 "]",
					alert.alertid);
				error_esc = DBdyn_escape_string_len(error, ALERT_ERROR_LEN);

				alert.retries++;
				if(alert.retries < ALERT_MAX_RETRIES)
				{
					DBexecute("update alerts set retries=%d,error='%s' where alertid=" ZBX_FS_UI64,
						alert.retries,
						error_esc,
						alert.alertid);
				}
				else
				{
					DBexecute("update alerts set status=%d,retries=%d,error='%s' where alertid=" ZBX_FS_UI64,
						ALERT_STATUS_FAILED,
						alert.retries,
						error_esc,
						alert.alertid);
				}

				zbx_free(error_esc);
			}

		}
		DBfree_result(result);

		zbx_setproctitle("sender [sleeping for %d seconds]",
				CONFIG_SENDER_FREQUENCY);

		sleep(CONFIG_SENDER_FREQUENCY);
	}

	/* Never reached */
	DBclose();
}
Ejemplo n.º 23
0
/*********************************************
 DeleteLicense(): Given an upload ID, delete all
 licenses associated with it.
 The DoBegin flag determines whether BEGIN/COMMIT
 should be called.
 Do this if you want to reschedule license analysis.
 *********************************************/
void	DeleteLicense	(long UploadId)
{
  void *VDB;
  char TempTable[256];

  if (Verbose) { printf("Deleting licenses for upload %ld\n",UploadId); }
  DBaccess(DB,"SET statement_timeout = 0;"); /* no timeout */
  MyDBaccess(DB,"BEGIN;");
  memset(TempTable,'\0',sizeof(TempTable));
  snprintf(TempTable,sizeof(TempTable),"DelLic_%ld",UploadId);

  /* Create the temp table */
  if (Verbose) { printf("# Creating temp table: %s\n",TempTable); }
  memset(SQL,'\0',sizeof(SQL));

  /* Get the list of pfiles to process */
  memset(SQL,'\0',sizeof(SQL));
  snprintf(SQL,sizeof(SQL),"SELECT DISTINCT(pfile_fk) FROM uploadtree WHERE upload_fk = '%ld' ;",UploadId);
  MyDBaccess(DB,SQL);
  VDB = DBmove(DB);

  /***********************************************/
  /* delete pfile licenses */
  if (Verbose) { printf("# Deleting licenses\n"); }
      memset(SQL,'\0',sizeof(SQL));
      snprintf(SQL,sizeof(SQL),"DELETE FROM licterm_name WHERE pfile_fk IN (SELECT pfile_fk FROM uploadtree WHERE upload_fk = '%ld');",UploadId);
      MyDBaccess(DB,SQL);

      memset(SQL,'\0',sizeof(SQL));
      snprintf(SQL,sizeof(SQL),"DELETE FROM agent_lic_status WHERE pfile_fk IN (SELECT pfile_fk FROM uploadtree WHERE upload_fk = '%ld');",UploadId);
      MyDBaccess(DB,SQL);

      memset(SQL,'\0',sizeof(SQL));
      snprintf(SQL,sizeof(SQL),"DELETE FROM agent_lic_meta WHERE pfile_fk IN (SELECT pfile_fk FROM uploadtree WHERE upload_fk = '%ld');",UploadId);
      MyDBaccess(DB,SQL);
  ItemsProcessed+=DBdatasize(VDB);
  Heartbeat(ItemsProcessed);

  /***********************************************/
  /* Commit the change! */
  if (Verbose) { printf("# Delete completed\n"); }
  if (Test) MyDBaccess(DB,"ROLLBACK;");
  else
	{
	MyDBaccess(DB,"COMMIT;");
#if 0
	/** Disabled: DB will take care of this **/
	if (Verbose) { printf("# Running vacuum and analyze\n"); }
	MyDBaccess(DB,"VACUUM ANALYZE agent_lic_status;");
	MyDBaccess(DB,"VACUUM ANALYZE agent_lic_meta;");
#endif
	}
  DBaccess(DB,"SET statement_timeout = 120000;");

  DBclose(VDB);
  if (ItemsProcessed > 0)
	{
	/* use heartbeat to say how many are completed */
	raise(SIGALRM);
	}
  if (Verbose) { printf("Deleted licenses for upload %ld\n",UploadId); }
} /* DeleteLicense() */
Ejemplo n.º 24
0
/*********************************************************
 DBCheckMime(): Given a file, check if it has a mime type
 in the DB.  If it does not, then add it.
 Returns DB entry for the mimetype.
 *********************************************************/
void	DBCheckMime	(char *Filename)
{
  char MimeType[MAXCMD];
  char *MagicType;
  int MimeTypeID;
  int i;

  if (Akey >= 0)
    {
    memset(SQL,'\0',sizeof(SQL));
    snprintf(SQL,sizeof(SQL)-1,"SELECT pfile_mimetypefk FROM pfile WHERE pfile_pk = %d AND pfile_mimetypefk is not null;",Akey);
    if (DBaccess(DB,SQL) < 0)
      {
      printf("ERROR: Unable to query the database.\n");
      printf("LOG: Unable to access database: '%s'\n",SQL);
      fflush(stdout);
      DBclose(DB);
      exit(-1);
      }
    if (DBdatasize(DB) > 0)
	{
	return;
	}
    } /* if using DB */

  /* Not in DB, so find out what it is... */
  /* Check using Magic */
  MagicType = (char *)magic_file(MagicCookie,Filename);
  memset(MimeType,'\0',MAXCMD);
  if (MagicType)
      {
      if (Verbose) printf("DEBUG: Found mimetype by magic: '%s'\n",MagicType);
      /* Magic contains additional data after a ';' */
      for(i=0;
	  (i<MAXCMD) && (MagicType[i] != '\0') &&
	  !isspace(MagicType[i]) && !strchr(",;",MagicType[i]);
	  i++)
	{
	MimeType[i] = MagicType[i];
	}
      if (!strchr(MimeType,'/')) { memset(MimeType,'\0',MAXCMD); }
      }

  /* If there is no mimetype, or there is one but it is a default value,
     then determine based on extension */
  if (!strcmp(MimeType,"text/plain") || !strcmp(MimeType,"application/octet-stream") || (MimeType[0]=='\0'))
	{
	/* unknown type... Guess based on file extention */
	MimeTypeID = DBCheckFileExtention();
	/* not known?  */
	if (MimeTypeID < 0) MimeTypeID = GetDefaultMime(MimeType,Filename);
	}
  else
	{
	/* We have a mime-type! Update the database */
	MimeTypeID = DBFindMime(MimeType);
	}

  /* Make sure there is a mime-type */
  if (MimeTypeID < 0)
	{
	/* This should never happen; give it a default. */
	MimeTypeID = DBFindMime("application/octet-stream");
	}

  /* Update pfile record */
  if (Akey >= 0)
    {
    memset(SQL,'\0',sizeof(SQL));
    DBaccess(DB,"BEGIN;");
    snprintf(SQL,sizeof(SQL)-1,"SELECT * FROM pfile WHERE pfile_pk = %d FOR UPDATE;",Akey);
    DBaccess(DB,SQL);
    snprintf(SQL,sizeof(SQL)-1,"UPDATE pfile SET pfile_mimetypefk = %d WHERE pfile_pk = %d;",MimeTypeID,Akey);
    if (DBaccess(DB,SQL) < 0)
      {
      printf("ERROR: Unable to update the database.\n");
      printf("LOG: Unable to update database: '%s'\n",SQL);
      fflush(stdout);
      DBclose(DB);
      exit(-1);
      }
    DBaccess(DB,"COMMIT;");
    }
  else
    {
    /* IF no Akey, then display to stdout */
    int i;
    for(i=0; i < MaxDBMime; i++)
      {
      if (MimeTypeID == atoi(DBgetvalue(DBMime,i,0)))
	{
	printf("%s : mimetype_pk=%d : ",DBgetvalue(DBMime,i,1),MimeTypeID);
	}
      }
    printf("%s\n",Filename);
    }
} /* DBCheckMime() */
Ejemplo n.º 25
0
int	main	(int argc, char *argv[])
{
  int arg;
  char Parm[MAXCMD];
  char *Path;
  int c;
  char *agent_desc = "Determines mimetype for each file";

  /* Init */
  DB = DBopen();
  if (!DB)
  {
	printf("FATAL: Unable to connect to database\n");
	fflush(stdout);
	exit(-1);
  }
  GetAgentKey(DB, basename(argv[0]), 0, SVN_REV, agent_desc);

  FMimetype = fopen("/etc/mime.types","rb");
  if (!FMimetype)
	{
	printf("WARNING: Unable to open /etc/mime.types\n");
	}

  MagicCookie = magic_open(MAGIC_PRESERVE_ATIME|MAGIC_MIME);
  if (MagicCookie == NULL)
	{
	printf("FATAL: Failed to initialize magic cookie\n");
	fflush(stdout);
	DBclose(DB);
	exit(-1);
	}
  if (magic_load(MagicCookie,NULL) != 0)
	{
	printf("FATAL: Failed to load magic file: UnMagic\n");
	fflush(stdout);
	DBclose(DB);
	exit(-1);
	}

  /* Process command-line */
  while((c = getopt(argc,argv,"iv")) != -1)
    {
    switch(c)
	{
	case 'i':
		DBclose(DB);
		return(0);
	case 'v':
		Verbose++;
		break;
	default:
		Usage(argv[0]);
		DBclose(DB);
		exit(-1);
	}
    }

  /* Run from the command-line (for testing) */
  for(arg=optind; arg < argc; arg++)
    {
    Akey = -1;
    memset(A,'\0',sizeof(A));
    strncpy(A,argv[arg],sizeof(A));
    DBCheckMime(A);
    }

  /* Run from scheduler! */
  if (argc == 1)
    {
    signal(SIGALRM,ShowHeartbeat);
    alarm(60);

    printf("OK\n"); /* inform scheduler that we are ready */
    fflush(stdout);
    while(ReadLine(stdin,Parm,MAXCMD) >= 0)
      {
      if (Parm[0] != '\0')
	{
	alarm(0);	/* allow scheduler to know if this hangs */
	SetEnv(Parm); /* set environment (A and Akey globals) */
	/* Process the repository file */
	/** Find the path **/
	Path = RepMkPath("files",A);
	if (Path && RepExist("files",A))
	  {
	  /* Get the mimetype! */
	  DBCheckMime(Path);
	  }
	else
	  {
	  printf("ERROR pfile %d Unable to process.\n",Akey);
	  printf("LOG pfile %d File '%s' not found.\n",Akey,A);
	  fflush(stdout);
	  DBclose(DB);
	  exit(-1);
	  }
	printf("OK\n"); /* inform scheduler that we are ready */
	alarm(60);
	fflush(stdout);
	}
      }
    } /* if run from scheduler */

  /* Clean up */
  if (FMimetype) fclose(FMimetype);
  magic_close(MagicCookie);
  if (DBMime) DBclose(DBMime);
  if (DB) DBclose(DB);
  return(0);
} /* main() */
Ejemplo n.º 26
0
ZBX_THREAD_ENTRY(housekeeper_thread, args)
{
	int	records, start, sleeptime;
	double	sec, time_slept;
	char	sleeptext[25];

	process_type = ((zbx_thread_args_t *)args)->process_type;
	server_num = ((zbx_thread_args_t *)args)->server_num;
	process_num = ((zbx_thread_args_t *)args)->process_num;

	zabbix_log(LOG_LEVEL_INFORMATION, "%s #%d started [%s #%d]", get_daemon_type_string(daemon_type),
			server_num, get_process_type_string(process_type), process_num);

	if (0 == CONFIG_HOUSEKEEPING_FREQUENCY)
	{
		zbx_setproctitle("%s [waiting for user command]", get_process_type_string(process_type));
		zbx_snprintf(sleeptext, sizeof(sleeptext), "waiting for user command");
	}
	else
	{
		sleeptime = HOUSEKEEPER_STARTUP_DELAY * SEC_PER_MIN;
		zbx_setproctitle("%s [startup idle for %d minutes]", get_process_type_string(process_type),
				HOUSEKEEPER_STARTUP_DELAY);
		zbx_snprintf(sleeptext, sizeof(sleeptext), "idle for %d hour(s)", CONFIG_HOUSEKEEPING_FREQUENCY);
	}

	zbx_set_sigusr_handler(zbx_housekeeper_sigusr_handler);

	for (;;)
	{
		sec = zbx_time();

		if (0 == CONFIG_HOUSEKEEPING_FREQUENCY)
			zbx_sleep_forever();
		else
			zbx_sleep_loop(sleeptime);

		time_slept = zbx_time() - sec;

		hk_period = get_housekeeper_period(time_slept);

		start = time(NULL);

		zabbix_log(LOG_LEVEL_WARNING, "executing housekeeper");

		zbx_setproctitle("%s [connecting to the database]", get_process_type_string(process_type));

		DBconnect(ZBX_DB_CONNECT_NORMAL);

		zbx_setproctitle("%s [removing old history]", get_process_type_string(process_type));

		sec = zbx_time();
		records = housekeeping_history(start);
		sec = zbx_time() - sec;

		DBclose();

		zabbix_log(LOG_LEVEL_WARNING, "%s [deleted %d records in " ZBX_FS_DBL " sec, %s]",
				get_process_type_string(process_type), records, sec, sleeptext);

		zbx_setproctitle("%s [deleted %d records in " ZBX_FS_DBL " sec, %s]",
				get_process_type_string(process_type), records, sec, sleeptext);

		if (0 != CONFIG_HOUSEKEEPING_FREQUENCY)
			sleeptime = CONFIG_HOUSEKEEPING_FREQUENCY * SEC_PER_HOUR;
	}
}
Ejemplo n.º 27
0
int	MAIN_ZABBIX_ENTRY(int flags)
{
	zbx_socket_t	listen_sock;
	char		*error = NULL;
	int		i, db_type;

	if (0 != (flags & ZBX_TASK_FLAG_FOREGROUND))
	{
		printf("Starting Zabbix Server. Zabbix %s (revision %s).\nPress Ctrl+C to exit.\n\n",
				ZABBIX_VERSION, ZABBIX_REVISION);
	}

	if (SUCCEED != zbx_locks_create(&error))
	{
		zbx_error("cannot create locks: %s", error);
		zbx_free(error);
		exit(EXIT_FAILURE);
	}

	if (SUCCEED != zabbix_open_log(CONFIG_LOG_TYPE, CONFIG_LOG_LEVEL, CONFIG_LOG_FILE, &error))
	{
		zbx_error("cannot open log: %s", error);
		zbx_free(error);
		exit(EXIT_FAILURE);
	}

#ifdef HAVE_NETSNMP
#	define SNMP_FEATURE_STATUS	"YES"
#else
#	define SNMP_FEATURE_STATUS	" NO"
#endif
#ifdef HAVE_OPENIPMI
#	define IPMI_FEATURE_STATUS	"YES"
#else
#	define IPMI_FEATURE_STATUS	" NO"
#endif
#ifdef HAVE_LIBCURL
#	define LIBCURL_FEATURE_STATUS	"YES"
#else
#	define LIBCURL_FEATURE_STATUS	" NO"
#endif
#if defined(HAVE_LIBCURL) && defined(HAVE_LIBXML2)
#	define VMWARE_FEATURE_STATUS	"YES"
#else
#	define VMWARE_FEATURE_STATUS	" NO"
#endif
#ifdef HAVE_SMTP_AUTHENTICATION
#	define SMTP_AUTH_FEATURE_STATUS	"YES"
#else
#	define SMTP_AUTH_FEATURE_STATUS	" NO"
#endif
#ifdef HAVE_JABBER
#	define JABBER_FEATURE_STATUS	"YES"
#else
#	define JABBER_FEATURE_STATUS	" NO"
#endif
#ifdef HAVE_UNIXODBC
#	define ODBC_FEATURE_STATUS	"YES"
#else
#	define ODBC_FEATURE_STATUS	" NO"
#endif
#ifdef HAVE_SSH2
#	define SSH2_FEATURE_STATUS	"YES"
#else
#	define SSH2_FEATURE_STATUS	" NO"
#endif
#ifdef HAVE_IPV6
#	define IPV6_FEATURE_STATUS	"YES"
#else
#	define IPV6_FEATURE_STATUS	" NO"
#endif
#if defined(HAVE_POLARSSL) || defined(HAVE_GNUTLS) || defined(HAVE_OPENSSL)
#	define TLS_FEATURE_STATUS	"YES"
#else
#	define TLS_FEATURE_STATUS	" NO"
#endif

	zabbix_log(LOG_LEVEL_INFORMATION, "Starting Zabbix Server. Zabbix %s (revision %s).",
			ZABBIX_VERSION, ZABBIX_REVISION);

	zabbix_log(LOG_LEVEL_INFORMATION, "****** Enabled features ******");
	zabbix_log(LOG_LEVEL_INFORMATION, "SNMP monitoring:           " SNMP_FEATURE_STATUS);
	zabbix_log(LOG_LEVEL_INFORMATION, "IPMI monitoring:           " IPMI_FEATURE_STATUS);
	zabbix_log(LOG_LEVEL_INFORMATION, "Web monitoring:            " LIBCURL_FEATURE_STATUS);
	zabbix_log(LOG_LEVEL_INFORMATION, "VMware monitoring:         " VMWARE_FEATURE_STATUS);
	zabbix_log(LOG_LEVEL_INFORMATION, "SMTP authentication:       " SMTP_AUTH_FEATURE_STATUS);
	zabbix_log(LOG_LEVEL_INFORMATION, "Jabber notifications:      " JABBER_FEATURE_STATUS);
	zabbix_log(LOG_LEVEL_INFORMATION, "Ez Texting notifications:  " LIBCURL_FEATURE_STATUS);
	zabbix_log(LOG_LEVEL_INFORMATION, "ODBC:                      " ODBC_FEATURE_STATUS);
	zabbix_log(LOG_LEVEL_INFORMATION, "SSH2 support:              " SSH2_FEATURE_STATUS);
	zabbix_log(LOG_LEVEL_INFORMATION, "IPv6 support:              " IPV6_FEATURE_STATUS);
	zabbix_log(LOG_LEVEL_INFORMATION, "TLS support:               " TLS_FEATURE_STATUS);
	zabbix_log(LOG_LEVEL_INFORMATION, "******************************");

	zabbix_log(LOG_LEVEL_INFORMATION, "using configuration file: %s", CONFIG_FILE);

#if defined(HAVE_POLARSSL) || defined(HAVE_GNUTLS) || defined(HAVE_OPENSSL)
	if (SUCCEED != zbx_coredump_disable())
	{
		zabbix_log(LOG_LEVEL_CRIT, "cannot disable core dump, exiting...");
		exit(EXIT_FAILURE);
	}
#endif
	if (FAIL == zbx_load_modules(CONFIG_LOAD_MODULE_PATH, CONFIG_LOAD_MODULE, CONFIG_TIMEOUT, 1))
	{
		zabbix_log(LOG_LEVEL_CRIT, "loading modules failed, exiting...");
		exit(EXIT_FAILURE);
	}

	zbx_free_config();

	if (SUCCEED != init_database_cache(&error))
	{
		zabbix_log(LOG_LEVEL_CRIT, "cannot initialize database cache: %s", error);
		zbx_free(error);
		exit(EXIT_FAILURE);
	}

	if (SUCCEED != init_configuration_cache(&error))
	{
		zabbix_log(LOG_LEVEL_CRIT, "cannot initialize configuration cache: %s", error);
		zbx_free(error);
		exit(EXIT_FAILURE);
	}

	if (SUCCEED != init_selfmon_collector(&error))
	{
		zabbix_log(LOG_LEVEL_CRIT, "cannot initialize self-monitoring: %s", error);
		zbx_free(error);
		exit(EXIT_FAILURE);
	}

	if (0 != CONFIG_VMWARE_FORKS && SUCCEED != zbx_vmware_init(&error))
	{
		zabbix_log(LOG_LEVEL_CRIT, "cannot initialize VMware cache: %s", error);
		zbx_free(error);
		exit(EXIT_FAILURE);
	}

	if (SUCCEED != zbx_vc_init(&error))
	{
		zabbix_log(LOG_LEVEL_CRIT, "cannot initialize history value cache: %s", error);
		zbx_free(error);
		exit(EXIT_FAILURE);
	}

	if (SUCCEED != zbx_create_itservices_lock(&error))
	{
		zabbix_log(LOG_LEVEL_CRIT, "cannot create IT services lock: %s", error);
		zbx_free(error);
		exit(EXIT_FAILURE);
	}

	if (SUCCEED != zbx_history_init(&error))
	{
		zabbix_log(LOG_LEVEL_CRIT, "cannot initialize history storage: %s", error);
		zbx_free(error);
		exit(EXIT_FAILURE);
	}

	if (FAIL == zbx_export_init(&error))
	{
		zabbix_log(LOG_LEVEL_CRIT, "cannot initialize export: %s", error);
		zbx_free(error);
		exit(EXIT_FAILURE);
	}

	if (ZBX_DB_UNKNOWN == (db_type = zbx_db_get_database_type()))
	{
		zabbix_log(LOG_LEVEL_CRIT, "cannot use database \"%s\": database is not a Zabbix database",
				CONFIG_DBNAME);
		exit(EXIT_FAILURE);
	}
	else if (ZBX_DB_SERVER != db_type)
	{
		zabbix_log(LOG_LEVEL_CRIT, "cannot use database \"%s\": its \"users\" table is empty (is this the"
				" Zabbix proxy database?)", CONFIG_DBNAME);
		exit(EXIT_FAILURE);
	}

	if (SUCCEED != DBcheck_version())
		exit(EXIT_FAILURE);

	DBconnect(ZBX_DB_CONNECT_NORMAL);

	/* make initial configuration sync before worker processes are forked */
	DCsync_configuration(ZBX_DBSYNC_INIT);

	if (SUCCEED != zbx_check_postinit_tasks(&error))
	{
		zabbix_log(LOG_LEVEL_CRIT, "cannot complete post initialization tasks: %s", error);
		zbx_free(error);
		exit(EXIT_FAILURE);
	}

	/* update maintenance states */
	zbx_dc_update_maintenances();

	DBclose();

	zbx_vc_enable();

	threads_num = CONFIG_CONFSYNCER_FORKS + CONFIG_POLLER_FORKS
			+ CONFIG_UNREACHABLE_POLLER_FORKS + CONFIG_TRAPPER_FORKS + CONFIG_PINGER_FORKS
			+ CONFIG_ALERTER_FORKS + CONFIG_HOUSEKEEPER_FORKS + CONFIG_TIMER_FORKS
			+ CONFIG_HTTPPOLLER_FORKS + CONFIG_DISCOVERER_FORKS + CONFIG_HISTSYNCER_FORKS
			+ CONFIG_ESCALATOR_FORKS + CONFIG_IPMIPOLLER_FORKS + CONFIG_JAVAPOLLER_FORKS
			+ CONFIG_SNMPTRAPPER_FORKS + CONFIG_PROXYPOLLER_FORKS + CONFIG_SELFMON_FORKS
			+ CONFIG_VMWARE_FORKS + CONFIG_TASKMANAGER_FORKS + CONFIG_IPMIMANAGER_FORKS
			+ CONFIG_ALERTMANAGER_FORKS + CONFIG_PREPROCMAN_FORKS + CONFIG_PREPROCESSOR_FORKS
			+ CONFIG_LLDMANAGER_FORKS + CONFIG_LLDWORKER_FORKS;
	threads = (pid_t *)zbx_calloc(threads, threads_num, sizeof(pid_t));

	if (0 != CONFIG_TRAPPER_FORKS)
	{
		if (FAIL == zbx_tcp_listen(&listen_sock, CONFIG_LISTEN_IP, (unsigned short)CONFIG_LISTEN_PORT))
		{
			zabbix_log(LOG_LEVEL_CRIT, "listener failed: %s", zbx_socket_strerror());
			exit(EXIT_FAILURE);
		}
	}

#if defined(HAVE_POLARSSL) || defined(HAVE_GNUTLS) || defined(HAVE_OPENSSL)
	zbx_tls_init_parent();
#endif
	zabbix_log(LOG_LEVEL_INFORMATION, "server #0 started [main process]");

	for (i = 0; i < threads_num; i++)
	{
		zbx_thread_args_t	thread_args;
		unsigned char		poller_type;

		if (FAIL == get_process_info_by_thread(i + 1, &thread_args.process_type, &thread_args.process_num))
		{
			THIS_SHOULD_NEVER_HAPPEN;
			exit(EXIT_FAILURE);
		}

		thread_args.server_num = i + 1;
		thread_args.args = NULL;

		switch (thread_args.process_type)
		{
			case ZBX_PROCESS_TYPE_CONFSYNCER:
				zbx_thread_start(dbconfig_thread, &thread_args, &threads[i]);
				break;
			case ZBX_PROCESS_TYPE_POLLER:
				poller_type = ZBX_POLLER_TYPE_NORMAL;
				thread_args.args = &poller_type;
				zbx_thread_start(poller_thread, &thread_args, &threads[i]);
				break;
			case ZBX_PROCESS_TYPE_UNREACHABLE:
				poller_type = ZBX_POLLER_TYPE_UNREACHABLE;
				thread_args.args = &poller_type;
				zbx_thread_start(poller_thread, &thread_args, &threads[i]);
				break;
			case ZBX_PROCESS_TYPE_TRAPPER:
				thread_args.args = &listen_sock;
				zbx_thread_start(trapper_thread, &thread_args, &threads[i]);
				break;
			case ZBX_PROCESS_TYPE_PINGER:
				zbx_thread_start(pinger_thread, &thread_args, &threads[i]);
				break;
			case ZBX_PROCESS_TYPE_ALERTER:
				zbx_thread_start(alerter_thread, &thread_args, &threads[i]);
				break;
			case ZBX_PROCESS_TYPE_HOUSEKEEPER:
				zbx_thread_start(housekeeper_thread, &thread_args, &threads[i]);
				break;
			case ZBX_PROCESS_TYPE_TIMER:
				zbx_thread_start(timer_thread, &thread_args, &threads[i]);
				break;
			case ZBX_PROCESS_TYPE_HTTPPOLLER:
				zbx_thread_start(httppoller_thread, &thread_args, &threads[i]);
				break;
			case ZBX_PROCESS_TYPE_DISCOVERER:
				zbx_thread_start(discoverer_thread, &thread_args, &threads[i]);
				break;
			case ZBX_PROCESS_TYPE_HISTSYNCER:
				zbx_thread_start(dbsyncer_thread, &thread_args, &threads[i]);
				break;
			case ZBX_PROCESS_TYPE_ESCALATOR:
				zbx_thread_start(escalator_thread, &thread_args, &threads[i]);
				break;
			case ZBX_PROCESS_TYPE_JAVAPOLLER:
				poller_type = ZBX_POLLER_TYPE_JAVA;
				thread_args.args = &poller_type;
				zbx_thread_start(poller_thread, &thread_args, &threads[i]);
				break;
			case ZBX_PROCESS_TYPE_SNMPTRAPPER:
				zbx_thread_start(snmptrapper_thread, &thread_args, &threads[i]);
				break;
			case ZBX_PROCESS_TYPE_PROXYPOLLER:
				zbx_thread_start(proxypoller_thread, &thread_args, &threads[i]);
				break;
			case ZBX_PROCESS_TYPE_SELFMON:
				zbx_thread_start(selfmon_thread, &thread_args, &threads[i]);
				break;
			case ZBX_PROCESS_TYPE_VMWARE:
				zbx_thread_start(vmware_thread, &thread_args, &threads[i]);
				break;
			case ZBX_PROCESS_TYPE_TASKMANAGER:
				zbx_thread_start(taskmanager_thread, &thread_args, &threads[i]);
				break;
			case ZBX_PROCESS_TYPE_PREPROCMAN:
				zbx_thread_start(preprocessing_manager_thread, &thread_args, &threads[i]);
				break;
			case ZBX_PROCESS_TYPE_PREPROCESSOR:
				zbx_thread_start(preprocessing_worker_thread, &thread_args, &threads[i]);
				break;
#ifdef HAVE_OPENIPMI
			case ZBX_PROCESS_TYPE_IPMIMANAGER:
				zbx_thread_start(ipmi_manager_thread, &thread_args, &threads[i]);
				break;
			case ZBX_PROCESS_TYPE_IPMIPOLLER:
				zbx_thread_start(ipmi_poller_thread, &thread_args, &threads[i]);
				break;
#endif
			case ZBX_PROCESS_TYPE_ALERTMANAGER:
				zbx_thread_start(alert_manager_thread, &thread_args, &threads[i]);
				break;
			case ZBX_PROCESS_TYPE_LLDMANAGER:
				zbx_thread_start(lld_manager_thread, &thread_args, &threads[i]);
				break;
			case ZBX_PROCESS_TYPE_LLDWORKER:
				zbx_thread_start(lld_worker_thread, &thread_args, &threads[i]);
				break;
		}
	}

	if (SUCCEED == zbx_is_export_enabled())
	{
		zbx_history_export_init("main-process", 0);
		zbx_problems_export_init("main-process", 0);
	}

	while (-1 == wait(&i))	/* wait for any child to exit */
	{
		if (EINTR != errno)
		{
			zabbix_log(LOG_LEVEL_ERR, "failed to wait on child processes: %s", zbx_strerror(errno));
			break;
		}
	}

	/* all exiting child processes should be caught by signal handlers */
	THIS_SHOULD_NEVER_HAPPEN;

	zbx_on_exit();

	return SUCCEED;
}
Ejemplo n.º 28
0
int	DBcheck_version(void)
{
	const char		*__function_name = "DBcheck_version";
	const char		*dbversion_table_name = "dbversion";
	int			db_mandatory, db_optional, required, ret = FAIL, i;
	zbx_db_version_t	*dbversion;
	zbx_dbpatch_t		*patches;

#ifndef HAVE_SQLITE3
	int			total = 0, current = 0, completed, last_completed = -1, optional_num = 0;
#endif
	zabbix_log(LOG_LEVEL_DEBUG, "In %s()", __function_name);

	required = ZBX_FIRST_DB_VERSION;

	/* find out the required version number by getting the last mandatory version */
	/* of the last version patch array                                            */
	for (dbversion = dbversions; NULL != dbversion->patches; dbversion++)
		;

	patches = (--dbversion)->patches;

	for (i = 0; 0 != patches[i].version; i++)
	{
		if (0 != patches[i].mandatory)
			required = patches[i].version;
	}

	DBconnect(ZBX_DB_CONNECT_NORMAL);

	if (SUCCEED != DBtable_exists(dbversion_table_name))
	{
#ifndef HAVE_SQLITE3
		zabbix_log(LOG_LEVEL_DEBUG, "%s() \"%s\" does not exist",
				__function_name, dbversion_table_name);

		if (SUCCEED != DBfield_exists("config", "server_check_interval"))
		{
			zabbix_log(LOG_LEVEL_CRIT, "Cannot upgrade database: the database must"
					" correspond to version 2.0 or later. Exiting ...");
			goto out;
		}

		if (SUCCEED != DBcreate_dbversion_table())
			goto out;
#else
		zabbix_log(LOG_LEVEL_CRIT, "The %s does not match Zabbix database."
				" Current database version (mandatory/optional): UNKNOWN."
				" Required mandatory version: %08d.",
				ZBX_DAEMON_TYPE_SERVER == daemon_type ? "server" : "proxy", required);
		zabbix_log(LOG_LEVEL_CRIT, "Zabbix does not support SQLite3 database upgrade.");

		goto out;
#endif
	}

	DBget_version(&db_mandatory, &db_optional);

#ifndef HAVE_SQLITE3
	for (dbversion = dbversions; NULL != (patches = dbversion->patches); dbversion++)
	{
		for (i = 0; 0 != patches[i].version; i++)
		{
			if (0 != patches[i].mandatory)
				optional_num = 0;
			else
				optional_num++;

			if (db_optional < patches[i].version)
				total++;
		}
	}

	if (required < db_mandatory)
#else
	if (required != db_mandatory)
#endif
	{
		zabbix_log(LOG_LEVEL_CRIT, "The %s does not match Zabbix database."
				" Current database version (mandatory/optional): %08d/%08d."
				" Required mandatory version: %08d.",
				ZBX_DAEMON_TYPE_SERVER == daemon_type ? "server" : "proxy",
				db_mandatory, db_optional, required);
#ifdef HAVE_SQLITE3
		if (required > db_mandatory)
			zabbix_log(LOG_LEVEL_CRIT, "Zabbix does not support SQLite3 database upgrade.");
#endif
		goto out;
	}

	zabbix_log(LOG_LEVEL_INFORMATION, "current database version (mandatory/optional): %08d/%08d",
			db_mandatory, db_optional);
	zabbix_log(LOG_LEVEL_INFORMATION, "required mandatory version: %08d", required);

	ret = SUCCEED;

#ifndef HAVE_SQLITE3
	if (0 == total)
		goto out;

	if (0 != optional_num)
		zabbix_log(LOG_LEVEL_INFORMATION, "optional patches were found");

	zabbix_log(LOG_LEVEL_WARNING, "starting automatic database upgrade");

	for (dbversion = dbversions; NULL != dbversion->patches; dbversion++)
	{
		zbx_dbpatch_t	*patches = dbversion->patches;

		for (i = 0; 0 != patches[i].version; i++)
		{
			if (db_optional >= patches[i].version)
				continue;

			DBbegin();

			/* skipping the duplicated patches */
			if ((0 != patches[i].duplicates && patches[i].duplicates <= db_optional) ||
					SUCCEED == (ret = patches[i].function()))
			{
				ret = DBset_version(patches[i].version, patches[i].mandatory);
			}

			DBend(ret);

			if (SUCCEED != ret)
				break;

			current++;
			completed = (int)(100.0 * current / total);

			if (last_completed != completed)
			{
				zabbix_log(LOG_LEVEL_WARNING, "completed %d%% of database upgrade", completed);
				last_completed = completed;
			}
		}

		if (SUCCEED != ret)
			break;
	}

	if (SUCCEED == ret)
		zabbix_log(LOG_LEVEL_WARNING, "database upgrade fully completed");
	else
		zabbix_log(LOG_LEVEL_CRIT, "database upgrade failed");
#endif	/* not HAVE_SQLITE3 */

out:
	DBclose();

	zabbix_log(LOG_LEVEL_DEBUG, "End of %s():%s", __function_name, zbx_result_string(ret));

	return ret;
}
Ejemplo n.º 29
0
int	MAIN_ZABBIX_ENTRY()
{
	pid_t		pid;
	zbx_sock_t	listen_sock;
	int		i, proxy_num = 0, proxy_count = 0;

	if (NULL == CONFIG_LOG_FILE || '\0' == *CONFIG_LOG_FILE)
		zabbix_open_log(LOG_TYPE_SYSLOG, CONFIG_LOG_LEVEL, NULL);
	else
		zabbix_open_log(LOG_TYPE_FILE, CONFIG_LOG_LEVEL, CONFIG_LOG_FILE);

#ifdef	HAVE_SNMP
#	define SNMP_FEATURE_STATUS 	"YES"
#else
#	define SNMP_FEATURE_STATUS 	" NO"
#endif
#ifdef	HAVE_OPENIPMI
#	define IPMI_FEATURE_STATUS 	"YES"
#else
#	define IPMI_FEATURE_STATUS 	" NO"
#endif
#ifdef	HAVE_LIBCURL
#	define LIBCURL_FEATURE_STATUS	"YES"
#else
#	define LIBCURL_FEATURE_STATUS	" NO"
#endif
#ifdef	HAVE_ODBC
#	define ODBC_FEATURE_STATUS 	"YES"
#else
#	define ODBC_FEATURE_STATUS 	" NO"
#endif
#ifdef	HAVE_SSH2
#	define SSH2_FEATURE_STATUS 	"YES"
#else
#	define SSH2_FEATURE_STATUS 	" NO"
#endif
#ifdef	HAVE_IPV6
#	define IPV6_FEATURE_STATUS 	"YES"
#else
#	define IPV6_FEATURE_STATUS 	" NO"
#endif

	zabbix_log(LOG_LEVEL_INFORMATION, "Starting Zabbix Proxy (%s) [%s]. Zabbix %s (revision %s).",
			ZBX_PROXYMODE_PASSIVE == CONFIG_PROXYMODE ? "passive" : "active",
			CONFIG_HOSTNAME, ZABBIX_VERSION, ZABBIX_REVISION);

	zabbix_log(LOG_LEVEL_INFORMATION, "**** Enabled features ****");
	zabbix_log(LOG_LEVEL_INFORMATION, "SNMP monitoring:       " SNMP_FEATURE_STATUS);
	zabbix_log(LOG_LEVEL_INFORMATION, "IPMI monitoring:       " IPMI_FEATURE_STATUS);
	zabbix_log(LOG_LEVEL_INFORMATION, "WEB monitoring:        " LIBCURL_FEATURE_STATUS);
	zabbix_log(LOG_LEVEL_INFORMATION, "ODBC:                  " ODBC_FEATURE_STATUS);
	zabbix_log(LOG_LEVEL_INFORMATION, "SSH2 support:          " SSH2_FEATURE_STATUS);
	zabbix_log(LOG_LEVEL_INFORMATION, "IPv6 support:          " IPV6_FEATURE_STATUS);
	zabbix_log(LOG_LEVEL_INFORMATION, "**************************");

	DBinit();

	init_database_cache();
	init_configuration_cache();
	init_selfmon_collector();

	DBconnect(ZBX_DB_CONNECT_NORMAL);
	DCsync_configuration();
	DBclose();

	threads_num = CONFIG_CONFSYNCER_FORKS + CONFIG_HEARTBEAT_FORKS + CONFIG_DATASENDER_FORKS
			+ CONFIG_POLLER_FORKS + CONFIG_UNREACHABLE_POLLER_FORKS + CONFIG_TRAPPER_FORKS
			+ CONFIG_PINGER_FORKS + CONFIG_HOUSEKEEPER_FORKS + CONFIG_HTTPPOLLER_FORKS
			+ CONFIG_DISCOVERER_FORKS + CONFIG_HISTSYNCER_FORKS + CONFIG_IPMIPOLLER_FORKS
			+ CONFIG_JAVAPOLLER_FORKS + CONFIG_SNMPTRAPPER_FORKS + CONFIG_SELFMON_FORKS;
	threads = zbx_calloc(threads, threads_num, sizeof(pid_t));

	if (0 < CONFIG_TRAPPER_FORKS)
	{
		if (FAIL == zbx_tcp_listen(&listen_sock, CONFIG_LISTEN_IP, (unsigned short)CONFIG_LISTEN_PORT))
		{
			zabbix_log(LOG_LEVEL_CRIT, "listener failed: %s", zbx_tcp_strerror());
			exit(1);
		}
	}

	for (i = 0; i < threads_num; i++)
	{
		if (0 == (pid = zbx_child_fork()))
		{
			proxy_num = i + 1;	/* child processes are numbered starting from 1 */
			break;
		}
		else
			threads[i] = pid;
	}

	if (0 == proxy_num)
	{
		zabbix_log(LOG_LEVEL_INFORMATION, "proxy #0 started [main process]");

		while (-1 == wait(&i))	/* wait for any child to exit */
		{
			if (EINTR != errno)
			{
				zabbix_log(LOG_LEVEL_ERR, "failed to wait on child processes: %s", zbx_strerror(errno));
				break;
			}
		}

		/* all exiting child processes should be caught by signal handlers */
		THIS_SHOULD_NEVER_HAPPEN;

		zbx_on_exit();
	}
	else if (proxy_num <= (proxy_count += CONFIG_CONFSYNCER_FORKS))
	{
		/* !!! configuration syncer must be proxy #1 - child_signal_handler() uses threads[0] !!! */

		INIT_PROXY(ZBX_PROCESS_TYPE_CONFSYNCER, CONFIG_CONFSYNCER_FORKS);

		main_proxyconfig_loop();
	}
	else if (proxy_num <= (proxy_count += CONFIG_HEARTBEAT_FORKS))
	{
		INIT_PROXY(ZBX_PROCESS_TYPE_HEARTBEAT, CONFIG_HEARTBEAT_FORKS);

		main_heart_loop();
	}
	else if (proxy_num <= (proxy_count += CONFIG_DATASENDER_FORKS))
	{
		INIT_PROXY(ZBX_PROCESS_TYPE_DATASENDER, CONFIG_DATASENDER_FORKS);

		main_datasender_loop();
	}
	else if (proxy_num <= (proxy_count += CONFIG_POLLER_FORKS))
	{
#ifdef HAVE_SNMP
		init_snmp("zabbix_proxy");
#endif

		INIT_PROXY(ZBX_PROCESS_TYPE_POLLER, CONFIG_POLLER_FORKS);

		main_poller_loop(ZBX_POLLER_TYPE_NORMAL);
	}
	else if (proxy_num <= (proxy_count += CONFIG_UNREACHABLE_POLLER_FORKS))
	{
#ifdef HAVE_SNMP
		init_snmp("zabbix_proxy");
#endif

		INIT_PROXY(ZBX_PROCESS_TYPE_UNREACHABLE, CONFIG_UNREACHABLE_POLLER_FORKS);

		main_poller_loop(ZBX_POLLER_TYPE_UNREACHABLE);
	}
	else if (proxy_num <= (proxy_count += CONFIG_TRAPPER_FORKS))
	{
		INIT_PROXY(ZBX_PROCESS_TYPE_TRAPPER, CONFIG_TRAPPER_FORKS);

		main_trapper_loop(&listen_sock);
	}
	else if (proxy_num <= (proxy_count += CONFIG_PINGER_FORKS))
	{
		INIT_PROXY(ZBX_PROCESS_TYPE_PINGER, CONFIG_PINGER_FORKS);

		main_pinger_loop();
	}
	else if (proxy_num <= (proxy_count += CONFIG_HOUSEKEEPER_FORKS))
	{
		INIT_PROXY(ZBX_PROCESS_TYPE_HOUSEKEEPER, CONFIG_HOUSEKEEPER_FORKS);

		main_housekeeper_loop();
	}
	else if (proxy_num <= (proxy_count += CONFIG_HTTPPOLLER_FORKS))
	{
		INIT_PROXY(ZBX_PROCESS_TYPE_HTTPPOLLER, CONFIG_HTTPPOLLER_FORKS);

		main_httppoller_loop();
	}
	else if (proxy_num <= (proxy_count += CONFIG_DISCOVERER_FORKS))
	{
#ifdef HAVE_SNMP
		init_snmp("zabbix_proxy");
#endif

		INIT_PROXY(ZBX_PROCESS_TYPE_DISCOVERER, CONFIG_DISCOVERER_FORKS);

		main_discoverer_loop();
	}
	else if (proxy_num <= (proxy_count += CONFIG_HISTSYNCER_FORKS))
	{
		INIT_PROXY(ZBX_PROCESS_TYPE_HISTSYNCER, CONFIG_HISTSYNCER_FORKS);

		main_dbsyncer_loop();
	}
	else if (proxy_num <= (proxy_count += CONFIG_IPMIPOLLER_FORKS))
	{
		INIT_PROXY(ZBX_PROCESS_TYPE_IPMIPOLLER, CONFIG_IPMIPOLLER_FORKS);

		main_poller_loop(ZBX_POLLER_TYPE_IPMI);
	}
	else if (proxy_num <= (proxy_count += CONFIG_JAVAPOLLER_FORKS))
	{
		INIT_PROXY(ZBX_PROCESS_TYPE_JAVAPOLLER, CONFIG_JAVAPOLLER_FORKS);

		main_poller_loop(ZBX_POLLER_TYPE_JAVA);
	}
	else if (proxy_num <= (proxy_count += CONFIG_SNMPTRAPPER_FORKS))
	{
		INIT_PROXY(ZBX_PROCESS_TYPE_SNMPTRAPPER, CONFIG_SNMPTRAPPER_FORKS);

		main_snmptrapper_loop();
	}
	else if (proxy_num <= (proxy_count += CONFIG_SELFMON_FORKS))
	{
		INIT_PROXY(ZBX_PROCESS_TYPE_SELFMON, CONFIG_SELFMON_FORKS);

		main_selfmon_loop();
	}

	return SUCCEED;
}
Ejemplo n.º 30
0
int	main	(int argc, char *argv[])
{
  char Parm[MAXCMD];
  int c;
  char *agent_desc = "Pulls metadata out of RPM or DEBIAN packages";
  //struct rpmpkginfo *glb_rpmpi;
  //struct debpkginfo *glb_debpi;
  int Agent_pk;

  long upload_pk = 0;           // the upload primary key
  extern int AlarmSecs;
  
  //glb_rpmpi = (struct rpmpkginfo *)malloc(sizeof(struct rpmpkginfo));
  //glb_debpi = (struct debpkginfo *)malloc(sizeof(struct debpkginfo));

  DB = DBopen();
  if (!DB)
  {
    printf("FATAL: Unable to connect to database\n");
    fflush(stdout);
    exit(-1);
  }

  Agent_pk = GetAgentKey(DB, basename(argv[0]), 0, SVN_REV, agent_desc);

  /* Process command-line */
  while((c = getopt(argc,argv,"iv")) != -1)
  {
    switch(c)
	{
	case 'i':
                DBclose(DB);  /* DB was opened above, now close it and exit */
                exit(0);
        case 'v':
                Verbose++;
                break;
	default:
		Usage(argv[0]);
		DBclose(DB);
		exit(-1);
	}
  }

  /* If no args, run from scheduler! */
  if (argc == 1)
  {
    signal(SIGALRM,ShowHeartbeat);
    alarm(AlarmSecs);

    printf("OK\n"); /* inform scheduler that we are ready */
    fflush(stdout);

    while(ReadLine(stdin,Parm,MAXCMD) >= 0)
    {
      if (Verbose) { printf("PKG: pkgagent read %s\n", Parm);}
      fflush(stdout);

      upload_pk = atoi(Parm);
      if (upload_pk ==0) continue;
     
      if(!ProcessUpload(upload_pk)) return -1;
      sleep(15);
      printf("OK\n");
      fflush(stdout);
    }
  }
  else
  {
    /* printf("DEBUG: running in cli mode, processing file(s)\n"); */
    for (; optind < argc; optind++)
    {
       //struct rpmpkginfo *rpmpi;
       //rpmpi = (struct rpmpkginfo *)malloc(sizeof(struct rpmpkginfo));
       //GetMetadata(argv[optind],rpmpi);
       ProcessUpload(atoi(argv[optind]));
    }
  }

  DBclose(DB);
  return(0);
} /* main() */