pg_autovacuum.c 48.4 KB
Newer Older
1 2 3
/* pg_autovacuum.c
 * All the code for the pg_autovacuum program
 * (c) 2003 Matthew T. O'Connor
4
 * Revisions by Christopher B. Browne, Liberty RMS
5
 * Win32 Service code added by Dave Page
6
 *
7
 * $PostgreSQL: pgsql/contrib/pg_autovacuum/pg_autovacuum.c,v 1.27 2004/12/02 22:48:10 momjian Exp $
8 9
 */

10
#include "postgres_fe.h"
11

12 13 14 15 16 17
#include <unistd.h>
#ifdef HAVE_GETOPT_H
#include <getopt.h>
#endif
#include <time.h>
#include <sys/time.h>
18 19
#ifdef WIN32
#include <windows.h>
20 21 22
#endif

#include "pg_autovacuum.h"
23

24
#ifdef WIN32
25 26 27 28 29 30 31
unsigned int sleep();

SERVICE_STATUS ServiceStatus;
SERVICE_STATUS_HANDLE hStatus;
int			appMode = 0;
#endif

32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
/* define atooid */
#define atooid(x)  ((Oid) strtoul((x), NULL, 10))


static cmd_args *args;
static FILE	   *LOGOUTPUT;
static char		logbuffer[4096];


/* The main program loop function */
static int	VacuumLoop(int argc, char **argv);

/* Functions for dealing with command line arguements */
static cmd_args *get_cmd_args(int argc, char *argv[]);
static void print_cmd_args(void);
static void free_cmd_args(void);
static void usage(void);

/* Functions for managing database lists */
static Dllist *init_db_list(void);
static db_info *init_dbinfo(char *dbname, Oid oid, long age);
static void update_db_list(Dllist *db_list);
static void remove_db_from_list(Dlelem *db_to_remove);
static void print_db_info(db_info * dbi, int print_table_list);
static void print_db_list(Dllist *db_list, int print_table_lists);
static int	xid_wraparound_check(db_info * dbi);
static void free_db_list(Dllist *db_list);

/* Functions for managing table lists */
static tbl_info *init_table_info(PGresult *conn, int row, db_info * dbi);
static void update_table_list(db_info * dbi);
static void remove_table_from_list(Dlelem *tbl_to_remove);
static void print_table_list(Dllist *tbl_node);
static void print_table_info(tbl_info * tbl);
static void update_table_thresholds(db_info * dbi, tbl_info * tbl, int vacuum_type);
static void free_tbl_list(Dllist *tbl_list);

/* A few database helper functions */
static int	check_stats_enabled(db_info * dbi);
static PGconn *db_connect(db_info * dbi);
static void db_disconnect(db_info * dbi);
static PGresult *send_query(const char *query, db_info * dbi);

/* Other Generally needed Functions */
#ifndef WIN32
static void daemonize(void);
#endif
static void log_entry(const char *logentry, int level);

#ifdef WIN32
/* Windows Service related functions */
static void ControlHandler(DWORD request);
static int	InstallService();
static int	RemoveService();
#endif

88

89
static void
90
log_entry(const char *logentry, int level)
91
{
92 93
	/*
	 * Note: Under Windows we dump the log entries to the normal
94 95
	 * stderr/logfile as well, otherwise it can be a pain to debug 
	 * service install failures etc.
96 97
	 */

Bruce Momjian's avatar
Bruce Momjian committed
98 99
	time_t		curtime;
	struct tm  *loctime;
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
	char		timebuffer[128],
				slevel[10];


#ifdef WIN32
	static HANDLE evtHandle = INVALID_HANDLE_VALUE;
	static int	last_level;
	WORD		elevel;
#endif

	switch (level)
	{
		case LVL_DEBUG:
			sprintf(slevel, "DEBUG:   ");
			break;

		case LVL_INFO:
			sprintf(slevel, "INFO:    ");
			break;

		case LVL_WARNING:
			sprintf(slevel, "WARNING: ");
			break;

		case LVL_ERROR:
			sprintf(slevel, "ERROR:   ");
			break;

		case LVL_EXTRA:
			sprintf(slevel, "         ");
			break;

		default:
			sprintf(slevel, "         ");
			break;
	}
Bruce Momjian's avatar
Bruce Momjian committed
136 137 138

	curtime = time(NULL);
	loctime = localtime(&curtime);
139
	strftime(timebuffer, sizeof(timebuffer), "%Y-%m-%d %H:%M:%S %Z", loctime);
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
	fprintf(LOGOUTPUT, "[%s] %s%s\n", timebuffer, slevel, logentry);

#ifdef WIN32

	/* Restore the previous level if this is extra info */
	if (level == LVL_EXTRA)
		level = last_level;
	last_level = level;

	switch (level)
	{
		case LVL_DEBUG:
			elevel = EVENTLOG_INFORMATION_TYPE;
			break;

		case LVL_INFO:
			elevel = EVENTLOG_SUCCESS;
			break;

		case LVL_WARNING:
			elevel = EVENTLOG_WARNING_TYPE;
			break;

		case LVL_ERROR:
			elevel = EVENTLOG_ERROR_TYPE;
			break;

		default:
			elevel = EVENTLOG_SUCCESS;
			break;
	}

	if (evtHandle == INVALID_HANDLE_VALUE)
	{
		evtHandle = RegisterEventSource(NULL, "PostgreSQL Auto Vacuum");
		if (evtHandle == NULL)
		{
			evtHandle = INVALID_HANDLE_VALUE;
			return;
		}
	}

182
	ReportEvent(evtHandle, elevel, 0, 0, NULL, 1, 0, &logentry, NULL);
183
#endif
184 185
}

186 187 188 189 190 191 192
/*
 * Function used to detach the pg_autovacuum daemon from the tty and go into
 * the background.
 *
 * This code is mostly ripped directly from pm_dameonize in postmaster.c with
 * unneeded code removed.
 */
193
#ifndef WIN32
194
static void
195
daemonize(void)
196
{
Bruce Momjian's avatar
Bruce Momjian committed
197 198 199 200 201
	pid_t		pid;

	pid = fork();
	if (pid == (pid_t) -1)
	{
202
		log_entry("cannot disassociate from controlling TTY", LVL_ERROR);
Bruce Momjian's avatar
Bruce Momjian committed
203 204 205 206 207 208 209 210
		fflush(LOGOUTPUT);
		_exit(1);
	}
	else if (pid)
	{							/* parent */
		/* Parent should just exit, without doing any atexit cleanup */
		_exit(0);
	}
211

212 213 214
/* GH: If there's no setsid(), we hopefully don't need silent mode.
 * Until there's a better solution.  */
#ifdef HAVE_SETSID
Bruce Momjian's avatar
Bruce Momjian committed
215 216
	if (setsid() < 0)
	{
217
		log_entry("cannot disassociate from controlling TTY", LVL_ERROR);
Bruce Momjian's avatar
Bruce Momjian committed
218 219 220
		fflush(LOGOUTPUT);
		_exit(1);
	}
221
#endif
222

223
}
224
#endif   /* WIN32 */
225 226

/* Create and return tbl_info struct with initialized to values from row or res */
227
static tbl_info *
Bruce Momjian's avatar
Bruce Momjian committed
228
init_table_info(PGresult *res, int row, db_info * dbi)
229
{
Bruce Momjian's avatar
Bruce Momjian committed
230 231 232 233
	tbl_info   *new_tbl = (tbl_info *) malloc(sizeof(tbl_info));

	if (!new_tbl)
	{
234
		log_entry("init_table_info: Cannot get memory", LVL_ERROR);
Bruce Momjian's avatar
Bruce Momjian committed
235 236 237 238
		fflush(LOGOUTPUT);
		return NULL;
	}

239
	if (res == NULL)
Bruce Momjian's avatar
Bruce Momjian committed
240 241 242 243 244 245 246 247
		return NULL;

	new_tbl->dbi = dbi;			/* set pointer to db */

	new_tbl->schema_name = (char *)
		malloc(strlen(PQgetvalue(res, row, PQfnumber(res, "schemaname"))) + 1);
	if (!new_tbl->schema_name)
	{
248
		log_entry("init_table_info: malloc failed on new_tbl->schema_name", LVL_ERROR);
Bruce Momjian's avatar
Bruce Momjian committed
249 250 251 252 253 254 255 256
		fflush(LOGOUTPUT);
		return NULL;
	}
	strcpy(new_tbl->schema_name,
		   PQgetvalue(res, row, PQfnumber(res, "schemaname")));

	new_tbl->table_name = (char *)
		malloc(strlen(PQgetvalue(res, row, PQfnumber(res, "relname"))) +
257
			   strlen(new_tbl->schema_name) + 6);
Bruce Momjian's avatar
Bruce Momjian committed
258 259
	if (!new_tbl->table_name)
	{
260
		log_entry("init_table_info: malloc failed on new_tbl->table_name", LVL_ERROR);
Bruce Momjian's avatar
Bruce Momjian committed
261 262 263
		fflush(LOGOUTPUT);
		return NULL;
	}
264

265 266 267 268
	/*
	 * Put both the schema and table name in quotes so that we can work
	 * with mixed case table names
	 */
269 270 271
	strcpy(new_tbl->table_name, "\"");
	strcat(new_tbl->table_name, new_tbl->schema_name);
	strcat(new_tbl->table_name, "\".\"");
Bruce Momjian's avatar
Bruce Momjian committed
272
	strcat(new_tbl->table_name, PQgetvalue(res, row, PQfnumber(res, "relname")));
273
	strcat(new_tbl->table_name, "\"");
Bruce Momjian's avatar
Bruce Momjian committed
274 275 276

	new_tbl->CountAtLastAnalyze =
		(atol(PQgetvalue(res, row, PQfnumber(res, "n_tup_ins"))) +
277 278
		 atol(PQgetvalue(res, row, PQfnumber(res, "n_tup_upd"))) +
		 atol(PQgetvalue(res, row, PQfnumber(res, "n_tup_del"))));
Bruce Momjian's avatar
Bruce Momjian committed
279 280 281 282 283 284 285
	new_tbl->curr_analyze_count = new_tbl->CountAtLastAnalyze;

	new_tbl->CountAtLastVacuum =
		(atol(PQgetvalue(res, row, PQfnumber(res, "n_tup_del"))) +
		 atol(PQgetvalue(res, row, PQfnumber(res, "n_tup_upd"))));
	new_tbl->curr_vacuum_count = new_tbl->CountAtLastVacuum;

286 287 288
	new_tbl->relid = atooid(PQgetvalue(res, row, PQfnumber(res, "oid")));
	new_tbl->reltuples = atof(PQgetvalue(res, row, PQfnumber(res, "reltuples")));
	new_tbl->relpages = atooid(PQgetvalue(res, row, PQfnumber(res, "relpages")));
Bruce Momjian's avatar
Bruce Momjian committed
289

290
	if (strcmp("t", PQgetvalue(res, row, PQfnumber(res, "relisshared"))))
291
		new_tbl->relisshared = 0;
292
	else
293
		new_tbl->relisshared = 1;
294

Bruce Momjian's avatar
Bruce Momjian committed
295 296 297 298 299 300 301 302 303
	new_tbl->analyze_threshold =
		args->analyze_base_threshold + args->analyze_scaling_factor * new_tbl->reltuples;
	new_tbl->vacuum_threshold =
		args->vacuum_base_threshold + args->vacuum_scaling_factor * new_tbl->reltuples;

	if (args->debug >= 2)
		print_table_info(new_tbl);

	return new_tbl;
304 305 306
}

/* Set thresholds = base_value + scaling_factor * reltuples
307
   Should be called after a vacuum since vacuum updates values in pg_class */
308
static void
Bruce Momjian's avatar
Bruce Momjian committed
309
update_table_thresholds(db_info * dbi, tbl_info * tbl, int vacuum_type)
310
{
Bruce Momjian's avatar
Bruce Momjian committed
311 312 313 314
	PGresult   *res = NULL;
	int			disconnect = 0;
	char		query[128];

315
	if (dbi->conn == NULL)
Bruce Momjian's avatar
Bruce Momjian committed
316 317 318 319 320
	{
		dbi->conn = db_connect(dbi);
		disconnect = 1;
	}

321
	if (dbi->conn != NULL)
Bruce Momjian's avatar
Bruce Momjian committed
322
	{
323
		snprintf(query, sizeof(query), PAGES_QUERY, tbl->relid);
Bruce Momjian's avatar
Bruce Momjian committed
324
		res = send_query(query, dbi);
325
		if (res != NULL)
Bruce Momjian's avatar
Bruce Momjian committed
326 327
		{
			tbl->reltuples =
328 329
				atof(PQgetvalue(res, 0, PQfnumber(res, "reltuples")));
			tbl->relpages = atooid(PQgetvalue(res, 0, PQfnumber(res, "relpages")));
Bruce Momjian's avatar
Bruce Momjian committed
330 331 332 333 334

			/*
			 * update vacuum thresholds only of we just did a vacuum
			 * analyze
			 */
335
			if (vacuum_type == VACUUM_ANALYZE)
Bruce Momjian's avatar
Bruce Momjian committed
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363
			{
				tbl->vacuum_threshold =
					(args->vacuum_base_threshold + args->vacuum_scaling_factor * tbl->reltuples);
				tbl->CountAtLastVacuum = tbl->curr_vacuum_count;
			}

			/* update analyze thresholds */
			tbl->analyze_threshold =
				(args->analyze_base_threshold + args->analyze_scaling_factor * tbl->reltuples);
			tbl->CountAtLastAnalyze = tbl->curr_analyze_count;

			PQclear(res);

			/*
			 * If the stats collector is reporting fewer updates then we
			 * have on record then the stats were probably reset, so we
			 * need to reset also
			 */
			if ((tbl->curr_analyze_count < tbl->CountAtLastAnalyze) ||
				(tbl->curr_vacuum_count < tbl->CountAtLastVacuum))
			{
				tbl->CountAtLastAnalyze = tbl->curr_analyze_count;
				tbl->CountAtLastVacuum = tbl->curr_vacuum_count;
			}
		}
	}
	if (disconnect)
		db_disconnect(dbi);
364 365
}

366
static void
Bruce Momjian's avatar
Bruce Momjian committed
367
update_table_list(db_info * dbi)
368
{
Bruce Momjian's avatar
Bruce Momjian committed
369 370 371 372 373 374 375 376
	int			disconnect = 0;
	PGresult   *res = NULL;
	tbl_info   *tbl = NULL;
	Dlelem	   *tbl_elem = DLGetHead(dbi->table_list);
	int			i = 0,
				t = 0,
				found_match = 0;

377
	if (dbi->conn == NULL)
Bruce Momjian's avatar
Bruce Momjian committed
378 379 380 381 382
	{
		dbi->conn = db_connect(dbi);
		disconnect = 1;
	}

383
	if (dbi->conn != NULL)
Bruce Momjian's avatar
Bruce Momjian committed
384 385 386 387 388 389
	{
		/*
		 * Get a result set that has all the information we will need to
		 * both remove tables from the list that no longer exist and add
		 * tables to the list that are new
		 */
390
		res = send_query((char *) TABLE_STATS_QUERY, dbi);
391
		if (res != NULL)
Bruce Momjian's avatar
Bruce Momjian committed
392
		{
393
			t = PQntuples(res);
Bruce Momjian's avatar
Bruce Momjian committed
394

395
			/*
Bruce Momjian's avatar
Bruce Momjian committed
396 397 398 399
			 * First: use the tbl_list as the outer loop and the result
			 * set as the inner loop, this will determine what tables
			 * should be removed
			 */
400
			while (tbl_elem != NULL)
Bruce Momjian's avatar
Bruce Momjian committed
401 402
			{
				tbl = ((tbl_info *) DLE_VAL(tbl_elem));
403
				found_match = 0;
Bruce Momjian's avatar
Bruce Momjian committed
404

405
				for (i = 0; i < t; i++)
Bruce Momjian's avatar
Bruce Momjian committed
406 407
				{				/* loop through result set looking for a
								 * match */
408 409 410 411 412
					if (tbl->relid == atooid(PQgetvalue(res, i, PQfnumber(res, "oid"))))
					{
						found_match = 1;
						break;
					}
Bruce Momjian's avatar
Bruce Momjian committed
413
				}
414
				if (found_match == 0)
Bruce Momjian's avatar
Bruce Momjian committed
415 416
				{				/* then we didn't find this tbl_elem in
								 * the result set */
417
					Dlelem	   *elem_to_remove = tbl_elem;
Bruce Momjian's avatar
Bruce Momjian committed
418

419 420 421 422 423
					tbl_elem = DLGetSucc(tbl_elem);
					remove_table_from_list(elem_to_remove);
				}
				else
					tbl_elem = DLGetSucc(tbl_elem);
Bruce Momjian's avatar
Bruce Momjian committed
424 425 426
			}					/* Done removing dropped tables from the
								 * table_list */

427
			/*
Bruce Momjian's avatar
Bruce Momjian committed
428 429 430
			 * Then loop use result set as outer loop and tbl_list as the
			 * inner loop to determine what tables are new
			 */
431
			for (i = 0; i < t; i++)
Bruce Momjian's avatar
Bruce Momjian committed
432
			{
433 434 435
				tbl_elem = DLGetHead(dbi->table_list);
				found_match = 0;
				while (tbl_elem != NULL)
Bruce Momjian's avatar
Bruce Momjian committed
436
				{
437 438 439 440 441 442 443
					tbl = ((tbl_info *) DLE_VAL(tbl_elem));
					if (tbl->relid == atooid(PQgetvalue(res, i, PQfnumber(res, "oid"))))
					{
						found_match = 1;
						break;
					}
					tbl_elem = DLGetSucc(tbl_elem);
Bruce Momjian's avatar
Bruce Momjian committed
444
				}
Bruce Momjian's avatar
Bruce Momjian committed
445 446
				if (found_match == 0)	/* then we didn't find this result
										 * now in the tbl_list */
447 448 449 450 451 452
				{
					DLAddTail(dbi->table_list, DLNewElem(init_table_info(res, i, dbi)));
					if (args->debug >= 1)
					{
						sprintf(logbuffer, "added table: %s.%s", dbi->dbname,
								((tbl_info *) DLE_VAL(DLGetTail(dbi->table_list)))->table_name);
453
						log_entry(logbuffer, LVL_DEBUG);
454 455
					}
				}
Bruce Momjian's avatar
Bruce Momjian committed
456
			}					/* end of for loop that adds tables */
457
		}
Bruce Momjian's avatar
Bruce Momjian committed
458 459 460 461 462 463 464 465
		fflush(LOGOUTPUT);
		PQclear(res);
		res = NULL;
		if (args->debug >= 3)
			print_table_list(dbi->table_list);
		if (disconnect)
			db_disconnect(dbi);
	}
466 467 468
}

/* Free memory, and remove the node from the list */
469
static void
Bruce Momjian's avatar
Bruce Momjian committed
470
remove_table_from_list(Dlelem *tbl_to_remove)
471
{
Bruce Momjian's avatar
Bruce Momjian committed
472 473 474 475 476
	tbl_info   *tbl = ((tbl_info *) DLE_VAL(tbl_to_remove));

	if (args->debug >= 1)
	{
		sprintf(logbuffer, "Removing table: %s from list.", tbl->table_name);
477
		log_entry(logbuffer, LVL_DEBUG);
Bruce Momjian's avatar
Bruce Momjian committed
478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497
		fflush(LOGOUTPUT);
	}
	DLRemove(tbl_to_remove);

	if (tbl->schema_name)
	{
		free(tbl->schema_name);
		tbl->schema_name = NULL;
	}
	if (tbl->table_name)
	{
		free(tbl->table_name);
		tbl->table_name = NULL;
	}
	if (tbl)
	{
		free(tbl);
		tbl = NULL;
	}
	DLFreeElem(tbl_to_remove);
498 499 500
}

/* Free the entire table list */
501
static void
Bruce Momjian's avatar
Bruce Momjian committed
502
free_tbl_list(Dllist *tbl_list)
503
{
Bruce Momjian's avatar
Bruce Momjian committed
504 505 506
	Dlelem	   *tbl_elem = DLGetHead(tbl_list);
	Dlelem	   *tbl_elem_to_remove = NULL;

507
	while (tbl_elem != NULL)
Bruce Momjian's avatar
Bruce Momjian committed
508 509 510 511 512 513
	{
		tbl_elem_to_remove = tbl_elem;
		tbl_elem = DLGetSucc(tbl_elem);
		remove_table_from_list(tbl_elem_to_remove);
	}
	DLFreeList(tbl_list);
514 515
}

516
static void
Bruce Momjian's avatar
Bruce Momjian committed
517
print_table_list(Dllist *table_list)
518
{
Bruce Momjian's avatar
Bruce Momjian committed
519 520
	Dlelem	   *table_elem = DLGetHead(table_list);

521
	while (table_elem != NULL)
Bruce Momjian's avatar
Bruce Momjian committed
522 523 524 525
	{
		print_table_info(((tbl_info *) DLE_VAL(table_elem)));
		table_elem = DLGetSucc(table_elem);
	}
526 527
}

528
static void
Bruce Momjian's avatar
Bruce Momjian committed
529
print_table_info(tbl_info * tbl)
530
{
531
	sprintf(logbuffer, "  table name: %s.%s", tbl->dbi->dbname, tbl->table_name);
532
	log_entry(logbuffer, LVL_INFO);
533
	sprintf(logbuffer, "     relid: %u;   relisshared: %d", tbl->relid, tbl->relisshared);
534
	log_entry(logbuffer, LVL_INFO);
535
	sprintf(logbuffer, "     reltuples: %f;  relpages: %u", tbl->reltuples, tbl->relpages);
536
	log_entry(logbuffer, LVL_INFO);
537
	sprintf(logbuffer, "     curr_analyze_count: %li; curr_vacuum_count: %li",
Bruce Momjian's avatar
Bruce Momjian committed
538
			tbl->curr_analyze_count, tbl->curr_vacuum_count);
539
	log_entry(logbuffer, LVL_INFO);
540
	sprintf(logbuffer, "     last_analyze_count: %li; last_vacuum_count: %li",
Bruce Momjian's avatar
Bruce Momjian committed
541
			tbl->CountAtLastAnalyze, tbl->CountAtLastVacuum);
542
	log_entry(logbuffer, LVL_INFO);
543
	sprintf(logbuffer, "     analyze_threshold: %li; vacuum_threshold: %li",
Bruce Momjian's avatar
Bruce Momjian committed
544
			tbl->analyze_threshold, tbl->vacuum_threshold);
545
	log_entry(logbuffer, LVL_INFO);
Bruce Momjian's avatar
Bruce Momjian committed
546
	fflush(LOGOUTPUT);
547 548 549 550 551 552 553
}

/* End of table Management Functions */

/* Beginning of DB Management Functions */

/* init_db_list() creates the db_list and initalizes template1 */
554
static Dllist *
555
init_db_list(void)
556
{
Bruce Momjian's avatar
Bruce Momjian committed
557 558 559 560 561
	Dllist	   *db_list = DLNewList();
	db_info    *dbs = NULL;
	PGresult   *res = NULL;

	DLAddHead(db_list, DLNewElem(init_dbinfo((char *) "template1", 0, 0)));
562
	if (DLGetHead(db_list) == NULL)
Bruce Momjian's avatar
Bruce Momjian committed
563
	{							/* Make sure init_dbinfo was successful */
564
		log_entry("init_db_list(): Error creating db_list for db: template1.", LVL_ERROR);
Bruce Momjian's avatar
Bruce Momjian committed
565 566 567 568 569 570 571 572 573 574 575
		fflush(LOGOUTPUT);
		return NULL;
	}

	/*
	 * We do this just so we can set the proper oid for the template1
	 * database
	 */
	dbs = ((db_info *) DLE_VAL(DLGetHead(db_list)));
	dbs->conn = db_connect(dbs);

576
	if (dbs->conn != NULL)
Bruce Momjian's avatar
Bruce Momjian committed
577 578
	{
		res = send_query(FROZENOID_QUERY, dbs);
579 580 581 582 583 584
		if (res != NULL)
		{
			dbs->oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "oid")));
			dbs->age = atol(PQgetvalue(res, 0, PQfnumber(res, "age")));
			if (res)
				PQclear(res);
Bruce Momjian's avatar
Bruce Momjian committed
585

586 587 588 589 590
			if (args->debug >= 2)
				print_db_list(db_list, 0);
		}
		else
			return NULL;
Bruce Momjian's avatar
Bruce Momjian committed
591 592
	}
	return db_list;
593 594 595
}

/* Simple function to create an instance of the dbinfo struct
Bruce Momjian's avatar
Bruce Momjian committed
596
	Initalizes all the pointers and connects to the database  */
597
static db_info *
598
init_dbinfo(char *dbname, Oid oid, long age)
599
{
Bruce Momjian's avatar
Bruce Momjian committed
600 601 602 603 604 605 606
	db_info    *newdbinfo = (db_info *) malloc(sizeof(db_info));

	newdbinfo->analyze_threshold = args->vacuum_base_threshold;
	newdbinfo->vacuum_threshold = args->analyze_base_threshold;
	newdbinfo->dbname = (char *) malloc(strlen(dbname) + 1);
	strcpy(newdbinfo->dbname, dbname);
	newdbinfo->username = NULL;
607
	if (args->user != NULL)
Bruce Momjian's avatar
Bruce Momjian committed
608 609 610 611 612
	{
		newdbinfo->username = (char *) malloc(strlen(args->user) + 1);
		strcpy(newdbinfo->username, args->user);
	}
	newdbinfo->password = NULL;
613
	if (args->password != NULL)
Bruce Momjian's avatar
Bruce Momjian committed
614 615 616 617 618 619 620 621 622 623 624 625 626
	{
		newdbinfo->password = (char *) malloc(strlen(args->password) + 1);
		strcpy(newdbinfo->password, args->password);
	}
	newdbinfo->oid = oid;
	newdbinfo->age = age;
	newdbinfo->table_list = DLNewList();
	newdbinfo->conn = NULL;

	if (args->debug >= 2)
		print_table_list(newdbinfo->table_list);

	return newdbinfo;
627 628 629
}

/* Function adds and removes databases from the db_list as appropriate */
630
static void
Bruce Momjian's avatar
Bruce Momjian committed
631
update_db_list(Dllist *db_list)
632
{
Bruce Momjian's avatar
Bruce Momjian committed
633 634 635 636 637 638 639 640 641 642 643
	int			disconnect = 0;
	PGresult   *res = NULL;
	Dlelem	   *db_elem = DLGetHead(db_list);
	db_info    *dbi = NULL;
	db_info    *dbi_template1 = DLE_VAL(db_elem);
	int			i = 0,
				t = 0,
				found_match = 0;

	if (args->debug >= 2)
	{
644
		log_entry("updating the database list", LVL_DEBUG);
Bruce Momjian's avatar
Bruce Momjian committed
645 646 647
		fflush(LOGOUTPUT);
	}

648
	if (dbi_template1->conn == NULL)
Bruce Momjian's avatar
Bruce Momjian committed
649 650 651 652 653
	{
		dbi_template1->conn = db_connect(dbi_template1);
		disconnect = 1;
	}

654
	if (dbi_template1->conn != NULL)
Bruce Momjian's avatar
Bruce Momjian committed
655 656 657 658 659 660 661
	{
		/*
		 * Get a result set that has all the information we will need to
		 * both remove databasews from the list that no longer exist and
		 * add databases to the list that are new
		 */
		res = send_query(FROZENOID_QUERY2, dbi_template1);
662
		if (res != NULL)
Bruce Momjian's avatar
Bruce Momjian committed
663
		{
664
			t = PQntuples(res);
Bruce Momjian's avatar
Bruce Momjian committed
665

666
			/*
Bruce Momjian's avatar
Bruce Momjian committed
667 668 669 670
			 * First: use the db_list as the outer loop and the result set
			 * as the inner loop, this will determine what databases
			 * should be removed
			 */
671
			while (db_elem != NULL)
Bruce Momjian's avatar
Bruce Momjian committed
672 673
			{
				dbi = ((db_info *) DLE_VAL(db_elem));
674
				found_match = 0;
Bruce Momjian's avatar
Bruce Momjian committed
675

676
				for (i = 0; i < t; i++)
Bruce Momjian's avatar
Bruce Momjian committed
677 678
				{				/* loop through result set looking for a
								 * match */
679 680 681
					if (dbi->oid == atooid(PQgetvalue(res, i, PQfnumber(res, "oid"))))
					{
						found_match = 1;
Bruce Momjian's avatar
Bruce Momjian committed
682

683
						/*
Bruce Momjian's avatar
Bruce Momjian committed
684 685 686
						 * update the dbi->age so that we ensure
						 * xid_wraparound won't happen
						 */
687 688 689
						dbi->age = atol(PQgetvalue(res, i, PQfnumber(res, "age")));
						break;
					}
Bruce Momjian's avatar
Bruce Momjian committed
690
				}
691
				if (found_match == 0)
Bruce Momjian's avatar
Bruce Momjian committed
692 693
				{				/* then we didn't find this db_elem in the
								 * result set */
694
					Dlelem	   *elem_to_remove = db_elem;
Bruce Momjian's avatar
Bruce Momjian committed
695

696 697 698 699 700
					db_elem = DLGetSucc(db_elem);
					remove_db_from_list(elem_to_remove);
				}
				else
					db_elem = DLGetSucc(db_elem);
Bruce Momjian's avatar
Bruce Momjian committed
701 702 703
			}					/* Done removing dropped databases from
								 * the table_list */

704
			/*
Bruce Momjian's avatar
Bruce Momjian committed
705 706 707
			 * Then loop use result set as outer loop and db_list as the
			 * inner loop to determine what databases are new
			 */
708
			for (i = 0; i < t; i++)
Bruce Momjian's avatar
Bruce Momjian committed
709
			{
710 711 712
				db_elem = DLGetHead(db_list);
				found_match = 0;
				while (db_elem != NULL)
Bruce Momjian's avatar
Bruce Momjian committed
713
				{
714 715 716 717 718 719 720
					dbi = ((db_info *) DLE_VAL(db_elem));
					if (dbi->oid == atooid(PQgetvalue(res, i, PQfnumber(res, "oid"))))
					{
						found_match = 1;
						break;
					}
					db_elem = DLGetSucc(db_elem);
Bruce Momjian's avatar
Bruce Momjian committed
721
				}
Bruce Momjian's avatar
Bruce Momjian committed
722 723
				if (found_match == 0)	/* then we didn't find this result
										 * now in the tbl_list */
724 725
				{
					DLAddTail(db_list, DLNewElem(init_dbinfo
Bruce Momjian's avatar
Bruce Momjian committed
726 727 728
						  (PQgetvalue(res, i, PQfnumber(res, "datname")),
					   atooid(PQgetvalue(res, i, PQfnumber(res, "oid"))),
					  atol(PQgetvalue(res, i, PQfnumber(res, "age"))))));
729 730 731
					if (args->debug >= 1)
					{
						sprintf(logbuffer, "added database: %s", ((db_info *) DLE_VAL(DLGetTail(db_list)))->dbname);
732
						log_entry(logbuffer, LVL_DEBUG);
733 734
					}
				}
Bruce Momjian's avatar
Bruce Momjian committed
735
			}					/* end of for loop that adds tables */
736
		}
Bruce Momjian's avatar
Bruce Momjian committed
737 738 739 740 741 742 743 744
		fflush(LOGOUTPUT);
		PQclear(res);
		res = NULL;
		if (args->debug >= 3)
			print_db_list(db_list, 0);
		if (disconnect)
			db_disconnect(dbi_template1);
	}
745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760
}

/* xid_wraparound_check

From the docs:

With the standard freezing policy, the age column will start at one billion for a
freshly-vacuumed database. When the age approaches two billion, the database must
be vacuumed again to avoid risk of wraparound failures. Recommended practice is
to vacuum each database at least once every half-a-billion (500 million) transactions,
so as to provide plenty of safety margin.

So we do a full database vacuum if age > 1.5billion
return 0 if nothing happened,
return 1 if the database needed a database wide vacuum
*/
761
static int
Bruce Momjian's avatar
Bruce Momjian committed
762
xid_wraparound_check(db_info * dbi)
763
{
Bruce Momjian's avatar
Bruce Momjian committed
764 765 766 767 768 769
	/*
	 * FIXME: should probably do something better here so that we don't
	 * vacuum all the databases on the server at the same time.  We have
	 * 500million xacts to work with so we should be able to spread the
	 * load of full database vacuums a bit
	 */
Bruce Momjian's avatar
Bruce Momjian committed
770
	if (dbi->age > 1500000000)
Bruce Momjian's avatar
Bruce Momjian committed
771 772 773
	{
		PGresult   *res = NULL;

774
		res = send_query("VACUUM", dbi);
Bruce Momjian's avatar
Bruce Momjian committed
775
		/* FIXME: Perhaps should add a check for PQ_COMMAND_OK */
776 777
		if (res != NULL)
			PQclear(res);
Bruce Momjian's avatar
Bruce Momjian committed
778 779 780
		return 1;
	}
	return 0;
781 782 783
}

/* Close DB connection, free memory, and remove the node from the list */
784
static void
Bruce Momjian's avatar
Bruce Momjian committed
785
remove_db_from_list(Dlelem *db_to_remove)
786
{
Bruce Momjian's avatar
Bruce Momjian committed
787 788 789 790 791
	db_info    *dbi = ((db_info *) DLE_VAL(db_to_remove));

	if (args->debug >= 1)
	{
		sprintf(logbuffer, "Removing db: %s from list.", dbi->dbname);
792
		log_entry(logbuffer, LVL_DEBUG);
Bruce Momjian's avatar
Bruce Momjian committed
793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823
		fflush(LOGOUTPUT);
	}
	DLRemove(db_to_remove);
	if (dbi->conn)
		db_disconnect(dbi);
	if (dbi->dbname)
	{
		free(dbi->dbname);
		dbi->dbname = NULL;
	}
	if (dbi->username)
	{
		free(dbi->username);
		dbi->username = NULL;
	}
	if (dbi->password)
	{
		free(dbi->password);
		dbi->password = NULL;
	}
	if (dbi->table_list)
	{
		free_tbl_list(dbi->table_list);
		dbi->table_list = NULL;
	}
	if (dbi)
	{
		free(dbi);
		dbi = NULL;
	}
	DLFreeElem(db_to_remove);
824 825 826 827
}

/* Function is called before program exit to free all memory
		mostly it's just to keep valgrind happy */
828
static void
Bruce Momjian's avatar
Bruce Momjian committed
829
free_db_list(Dllist *db_list)
830
{
Bruce Momjian's avatar
Bruce Momjian committed
831 832 833
	Dlelem	   *db_elem = DLGetHead(db_list);
	Dlelem	   *db_elem_to_remove = NULL;

834
	while (db_elem != NULL)
Bruce Momjian's avatar
Bruce Momjian committed
835 836 837 838 839 840 841
	{
		db_elem_to_remove = db_elem;
		db_elem = DLGetSucc(db_elem);
		remove_db_from_list(db_elem_to_remove);
		db_elem_to_remove = NULL;
	}
	DLFreeList(db_list);
842 843
}

844
static void
Bruce Momjian's avatar
Bruce Momjian committed
845
print_db_list(Dllist *db_list, int print_table_lists)
846
{
Bruce Momjian's avatar
Bruce Momjian committed
847 848
	Dlelem	   *db_elem = DLGetHead(db_list);

849
	while (db_elem != NULL)
Bruce Momjian's avatar
Bruce Momjian committed
850 851 852 853
	{
		print_db_info(((db_info *) DLE_VAL(db_elem)), print_table_lists);
		db_elem = DLGetSucc(db_elem);
	}
854 855
}

856
static void
Bruce Momjian's avatar
Bruce Momjian committed
857
print_db_info(db_info * dbi, int print_tbl_list)
858
{
859
	sprintf(logbuffer, "dbname: %s", (dbi->dbname) ? dbi->dbname : "(null)");
860
	log_entry(logbuffer, LVL_INFO);
Bruce Momjian's avatar
Bruce Momjian committed
861

862
	sprintf(logbuffer, "  oid: %u", dbi->oid);
863
	log_entry(logbuffer, LVL_INFO);
Bruce Momjian's avatar
Bruce Momjian committed
864

865
	sprintf(logbuffer, "  username: %s", (dbi->username) ? dbi->username : "(null)");
866
	log_entry(logbuffer, LVL_INFO);
Bruce Momjian's avatar
Bruce Momjian committed
867

868
	sprintf(logbuffer, "  password: %s", (dbi->password) ? dbi->password : "(null)");
869
	log_entry(logbuffer, LVL_INFO);
Bruce Momjian's avatar
Bruce Momjian committed
870

871
	if (dbi->conn != NULL)
872
		log_entry("  conn is valid, (connected)", LVL_INFO);
Bruce Momjian's avatar
Bruce Momjian committed
873
	else
874
		log_entry("  conn is null, (not connected)", LVL_INFO);
Bruce Momjian's avatar
Bruce Momjian committed
875

876
	sprintf(logbuffer, "  default_analyze_threshold: %li", dbi->analyze_threshold);
877
	log_entry(logbuffer, LVL_INFO);
Bruce Momjian's avatar
Bruce Momjian committed
878

879
	sprintf(logbuffer, "  default_vacuum_threshold: %li", dbi->vacuum_threshold);
880
	log_entry(logbuffer, LVL_INFO);
Bruce Momjian's avatar
Bruce Momjian committed
881

Bruce Momjian's avatar
Bruce Momjian committed
882
	fflush(LOGOUTPUT);
883
	if (print_tbl_list > 0)
Bruce Momjian's avatar
Bruce Momjian committed
884
		print_table_list(dbi->table_list);
885 886 887 888
}

/* End of DB List Management Function */

889
/* Beginning of misc Functions */
890

891
/* Perhaps add some test to this function to make sure that the stats we need are available */
892
static PGconn *
Bruce Momjian's avatar
Bruce Momjian committed
893
db_connect(db_info * dbi)
894
{
Bruce Momjian's avatar
Bruce Momjian committed
895 896 897 898
	PGconn	   *db_conn =
	PQsetdbLogin(args->host, args->port, NULL, NULL, dbi->dbname,
				 dbi->username, dbi->password);

899
	if (PQstatus(db_conn) != CONNECTION_OK)
Bruce Momjian's avatar
Bruce Momjian committed
900 901 902
	{
		sprintf(logbuffer, "Failed connection to database %s with error: %s.",
				dbi->dbname, PQerrorMessage(db_conn));
903
		log_entry(logbuffer, LVL_ERROR);
Bruce Momjian's avatar
Bruce Momjian committed
904 905 906 907
		fflush(LOGOUTPUT);
		PQfinish(db_conn);
		db_conn = NULL;
	}
908
		
Bruce Momjian's avatar
Bruce Momjian committed
909 910
	return db_conn;
}	/* end of db_connect() */
911

912
static void
Bruce Momjian's avatar
Bruce Momjian committed
913
db_disconnect(db_info * dbi)
914
{
915
	if (dbi->conn != NULL)
Bruce Momjian's avatar
Bruce Momjian committed
916 917 918 919
	{
		PQfinish(dbi->conn);
		dbi->conn = NULL;
	}
920 921
}

922
static int
Bruce Momjian's avatar
Bruce Momjian committed
923
check_stats_enabled(db_info * dbi)
924
{
925
	PGresult   *res;
Bruce Momjian's avatar
Bruce Momjian committed
926 927
	int			ret = 0;

928
	res = send_query("SHOW stats_row_level", dbi);
929
	if (res != NULL)
930 931 932 933
	{
		ret = strcmp("on", PQgetvalue(res, 0, PQfnumber(res, "stats_row_level")));
		PQclear(res);
	}
Bruce Momjian's avatar
Bruce Momjian committed
934
	return ret;
935 936
}

937
static PGresult *
Bruce Momjian's avatar
Bruce Momjian committed
938
send_query(const char *query, db_info * dbi)
939
{
Bruce Momjian's avatar
Bruce Momjian committed
940 941
	PGresult   *res;

942
	if (dbi->conn == NULL)
Bruce Momjian's avatar
Bruce Momjian committed
943 944
		return NULL;

945
	if (args->debug >= 4)
946
		log_entry(query, LVL_DEBUG);
947

Bruce Momjian's avatar
Bruce Momjian committed
948 949 950 951 952 953 954
	res = PQexec(dbi->conn, query);

	if (!res)
	{
		sprintf(logbuffer,
		   "Fatal error occured while sending query (%s) to database %s",
				query, dbi->dbname);
955
		log_entry(logbuffer, LVL_ERROR);
Bruce Momjian's avatar
Bruce Momjian committed
956
		sprintf(logbuffer, "The error is [%s]", PQresultErrorMessage(res));
957
		log_entry(logbuffer, LVL_EXTRA);
Bruce Momjian's avatar
Bruce Momjian committed
958 959 960
		fflush(LOGOUTPUT);
		return NULL;
	}
961 962
	if (PQresultStatus(res) != PGRES_TUPLES_OK &&
		PQresultStatus(res) != PGRES_COMMAND_OK)
Bruce Momjian's avatar
Bruce Momjian committed
963 964 965 966
	{
		sprintf(logbuffer,
		  "Can not refresh statistics information from the database %s.",
				dbi->dbname);
967
		log_entry(logbuffer, LVL_ERROR);
Bruce Momjian's avatar
Bruce Momjian committed
968
		sprintf(logbuffer, "The error is [%s]", PQresultErrorMessage(res));
969
		log_entry(logbuffer, LVL_EXTRA);
Bruce Momjian's avatar
Bruce Momjian committed
970 971 972 973 974 975
		fflush(LOGOUTPUT);
		PQclear(res);
		return NULL;
	}
	return res;
}	/* End of send_query() */
976

977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045
/*
 * Perform either a vacuum or a vacuum analyze
 */
static void
perform_maintenance_command(db_info * dbi, tbl_info * tbl, int operation)
{
	char		buf[256];
	
	/* 
	 * Set the vacuum_cost variables if supplied on command line
	 */	
	if (args->av_vacuum_cost_delay != -1)
	{	
		snprintf(buf, sizeof(buf), "set vacuum_cost_delay = %d",
				 args->av_vacuum_cost_delay);
		send_query(buf, dbi);
	}
	if (args->av_vacuum_cost_page_hit != -1)
	{	
		snprintf(buf, sizeof(buf), "set vacuum_cost_page_hit = %d",
				 args->av_vacuum_cost_page_hit);
		send_query(buf, dbi);
	}
	if (args->av_vacuum_cost_page_miss != -1)
	{	
		snprintf(buf, sizeof(buf), "set vacuum_cost_page_miss = %d",
				 args->av_vacuum_cost_page_miss);
		send_query(buf, dbi);
	}
	if (args->av_vacuum_cost_page_dirty != -1)
	{	
		snprintf(buf, sizeof(buf), "set vacuum_cost_page_dirty = %d",
				 args->av_vacuum_cost_page_dirty);
		send_query(buf, dbi);
	}
	if (args->av_vacuum_cost_limit != -1)
	{	
		snprintf(buf, sizeof(buf), "set vacuum_cost_limit = %d",
				 args->av_vacuum_cost_limit);
		send_query(buf, dbi);
	}
	
	/*
	 * if ((relisshared = t and database != template1) or 
	 * if operation = ANALYZE_ONLY) 
	 * then only do an analyze
	 */
	if ((tbl->relisshared > 0 && strcmp("template1", dbi->dbname) != 0) ||
		(operation == ANALYZE_ONLY))
		snprintf(buf, sizeof(buf), "ANALYZE %s", tbl->table_name);
	else if (operation == VACUUM_ANALYZE)
		snprintf(buf, sizeof(buf), "VACUUM ANALYZE %s", tbl->table_name);
	else
		return;
			
	if (args->debug >= 1)
	{
		sprintf(logbuffer, "Performing: %s", buf);
		log_entry(logbuffer, LVL_DEBUG);
		fflush(LOGOUTPUT);
	}
	
	send_query(buf, dbi);

	update_table_thresholds(dbi, tbl, operation);

	if (args->debug >= 2)
		print_table_info(tbl);
}
1046

1047
static void
1048
free_cmd_args(void)
1049
{
1050
	if (args != NULL)
Bruce Momjian's avatar
Bruce Momjian committed
1051
	{
1052
		if (args->user != NULL)
Bruce Momjian's avatar
Bruce Momjian committed
1053
			free(args->user);
1054
		if (args->password != NULL)
Bruce Momjian's avatar
Bruce Momjian committed
1055 1056 1057
			free(args->password);
		free(args);
	}
1058 1059
}

1060
static cmd_args *
Bruce Momjian's avatar
Bruce Momjian committed
1061
get_cmd_args(int argc, char *argv[])
1062
{
Bruce Momjian's avatar
Bruce Momjian committed
1063 1064 1065 1066 1067 1068 1069 1070 1071 1072
	int			c;

	args = (cmd_args *) malloc(sizeof(cmd_args));
	args->sleep_base_value = SLEEPBASEVALUE;
	args->sleep_scaling_factor = SLEEPSCALINGFACTOR;
	args->vacuum_base_threshold = VACBASETHRESHOLD;
	args->vacuum_scaling_factor = VACSCALINGFACTOR;
	args->analyze_base_threshold = -1;
	args->analyze_scaling_factor = -1;
	args->debug = AUTOVACUUM_DEBUG;
1073
#ifndef WIN32
Bruce Momjian's avatar
Bruce Momjian committed
1074
	args->daemonize = 0;
1075 1076 1077 1078 1079 1080
#else
	args->install_as_service = 0;
	args->remove_as_service = 0;
	args->service_user = 0;
	args->service_password = 0;
#endif
1081 1082 1083 1084 1085
	args->user = 0;
	args->password = 0;
	args->host = 0;
	args->logfile = 0;
	args->port = 0;
Bruce Momjian's avatar
Bruce Momjian committed
1086

1087 1088 1089 1090 1091 1092 1093 1094 1095
	/*
	 * Cost-Based Vacuum Delay Settings for pg_autovacuum 
	 */
	args->av_vacuum_cost_delay = -1;
	args->av_vacuum_cost_page_hit = -1;
	args->av_vacuum_cost_page_miss = -1;
	args->av_vacuum_cost_page_dirty = -1;
	args->av_vacuum_cost_limit = -1;

Bruce Momjian's avatar
Bruce Momjian committed
1096 1097 1098 1099
	/*
	 * Fixme: Should add some sanity checking such as positive integer
	 * values etc
	 */
1100
#ifndef WIN32
1101
	while ((c = getopt(argc, argv, "s:S:v:V:a:A:d:U:P:H:L:p:hDc:C:m:n:l:")) != -1)
1102
#else
1103
	while ((c = getopt(argc, argv, "s:S:v:V:a:A:d:U:P:H:L:p:hIRN:W:E:c:C:m:n:l:")) != -1)
1104
#endif
Bruce Momjian's avatar
Bruce Momjian committed
1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125
	{
		switch (c)
		{
			case 's':
				args->sleep_base_value = atoi(optarg);
				break;
			case 'S':
				args->sleep_scaling_factor = atof(optarg);
				break;
			case 'v':
				args->vacuum_base_threshold = atoi(optarg);
				break;
			case 'V':
				args->vacuum_scaling_factor = atof(optarg);
				break;
			case 'a':
				args->analyze_base_threshold = atoi(optarg);
				break;
			case 'A':
				args->analyze_scaling_factor = atof(optarg);
				break;
1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137
			case 'c':
				args->av_vacuum_cost_delay = atoi(optarg);
				break;
			case 'C':
				args->av_vacuum_cost_page_hit = atoi(optarg);
				break;
			case 'm':
				args->av_vacuum_cost_page_miss = atoi(optarg);
				break;
			case 'n':
				args->av_vacuum_cost_page_dirty = atoi(optarg);
				break;
1138
			case 'l':
1139 1140
				args->av_vacuum_cost_limit = atoi(optarg);
				break;
1141
#ifndef WIN32
Bruce Momjian's avatar
Bruce Momjian committed
1142 1143 1144
			case 'D':
				args->daemonize++;
				break;
1145
#endif
Bruce Momjian's avatar
Bruce Momjian committed
1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166
			case 'd':
				args->debug = atoi(optarg);
				break;
			case 'U':
				args->user = optarg;
				break;
			case 'P':
				args->password = optarg;
				break;
			case 'H':
				args->host = optarg;
				break;
			case 'L':
				args->logfile = optarg;
				break;
			case 'p':
				args->port = optarg;
				break;
			case 'h':
				usage();
				exit(0);
1167
#ifdef WIN32
1168 1169 1170
			case 'E':
				args->service_dependencies = optarg;
				break;
1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183
			case 'I':
				args->install_as_service++;
				break;
			case 'R':
				args->remove_as_service++;
				break;
			case 'N':
				args->service_user = optarg;
				break;
			case 'W':
				args->service_password = optarg;
				break;
#endif
Bruce Momjian's avatar
Bruce Momjian committed
1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199
			default:

				/*
				 * It's here that we know that things are invalid... It is
				 * not forcibly an error to call usage
				 */
				fprintf(stderr, "Error: Invalid Command Line Options.\n");
				usage();
				exit(1);
				break;
		}

		/*
		 * if values for insert thresholds are not specified, then they
		 * default to 1/2 of the delete values
		 */
1200
		if (args->analyze_base_threshold == -1)
Bruce Momjian's avatar
Bruce Momjian committed
1201
			args->analyze_base_threshold = args->vacuum_base_threshold / 2;
1202
		if (args->analyze_scaling_factor == -1)
Bruce Momjian's avatar
Bruce Momjian committed
1203 1204 1205
			args->analyze_scaling_factor = args->vacuum_scaling_factor / 2;
	}
	return args;
1206 1207
}

1208
static void
1209
usage(void)
1210
{
Bruce Momjian's avatar
Bruce Momjian committed
1211 1212 1213 1214
	int			i = 0;
	float		f = 0;

	fprintf(stderr, "usage: pg_autovacuum \n");
1215
#ifndef WIN32
Bruce Momjian's avatar
Bruce Momjian committed
1216
	fprintf(stderr, "   [-D] Daemonize (Detach from tty and run in the background)\n");
1217 1218 1219 1220 1221
#else
	fprintf(stderr, "   [-I] Install as a Windows service\n");
	fprintf(stderr, "   [-R] Remove as a Windows service (all other options will be ignored)\n");
	fprintf(stderr, "   [-N] Username to run service as (only useful when installing as a Windows service)\n");
	fprintf(stderr, "   [-W] Password to run service with (only useful when installing as a Windows service)\n");
1222
	fprintf(stderr, "   [-E] Dependent service that must start before this service (only useful when installing as a Windows service)\n");
1223
#endif
Bruce Momjian's avatar
Bruce Momjian committed
1224
	i = AUTOVACUUM_DEBUG;
1225
	fprintf(stderr, "   [-d] debug (debug level=0,1,2,3; default=%d)\n", i);
Bruce Momjian's avatar
Bruce Momjian committed
1226 1227

	i = SLEEPBASEVALUE;
1228
	fprintf(stderr, "   [-s] sleep base value (default=%d)\n", i);
Bruce Momjian's avatar
Bruce Momjian committed
1229 1230 1231 1232
	f = SLEEPSCALINGFACTOR;
	fprintf(stderr, "   [-S] sleep scaling factor (default=%f)\n", f);

	i = VACBASETHRESHOLD;
1233
	fprintf(stderr, "   [-v] vacuum base threshold (default=%d)\n", i);
Bruce Momjian's avatar
Bruce Momjian committed
1234 1235 1236
	f = VACSCALINGFACTOR;
	fprintf(stderr, "   [-V] vacuum scaling factor (default=%f)\n", f);
	i = i / 2;
1237
	fprintf(stderr, "   [-a] analyze base threshold (default=%d)\n", i);
Bruce Momjian's avatar
Bruce Momjian committed
1238 1239 1240 1241 1242
	f = f / 2;
	fprintf(stderr, "   [-A] analyze scaling factor (default=%f)\n", f);

	fprintf(stderr, "   [-L] logfile (default=none)\n");

1243 1244 1245 1246
	fprintf(stderr, "   [-c] vacuum_cost_delay (default=none)\n");
	fprintf(stderr, "   [-C] vacuum_cost_page_hit (default=none)\n");
	fprintf(stderr, "   [-m] vacuum_cost_page_miss (default=none)\n");
	fprintf(stderr, "   [-n] vacuum_cost_page_dirty (default=none)\n");
1247
	fprintf(stderr, "   [-l] vacuum_cost_limit (default=none)\n");
1248
	
Bruce Momjian's avatar
Bruce Momjian committed
1249 1250 1251 1252 1253 1254
	fprintf(stderr, "   [-U] username (libpq default)\n");
	fprintf(stderr, "   [-P] password (libpq default)\n");
	fprintf(stderr, "   [-H] host (libpq default)\n");
	fprintf(stderr, "   [-p] port (libpq default)\n");

	fprintf(stderr, "   [-h] help (Show this output)\n");
1255 1256
}

1257
static void
1258
print_cmd_args(void)
1259
{
Bruce Momjian's avatar
Bruce Momjian committed
1260
	sprintf(logbuffer, "Printing command_args");
1261
	log_entry(logbuffer, LVL_INFO);
Bruce Momjian's avatar
Bruce Momjian committed
1262
	sprintf(logbuffer, "  args->host=%s", (args->host) ? args->host : "(null)");
1263
	log_entry(logbuffer, LVL_INFO);
Bruce Momjian's avatar
Bruce Momjian committed
1264
	sprintf(logbuffer, "  args->port=%s", (args->port) ? args->port : "(null)");
1265
	log_entry(logbuffer, LVL_INFO);
1266
	sprintf(logbuffer, "  args->username=%s", (args->user) ? args->user : "(null)");
1267
	log_entry(logbuffer, LVL_INFO);
Bruce Momjian's avatar
Bruce Momjian committed
1268
	sprintf(logbuffer, "  args->password=%s", (args->password) ? args->password : "(null)");
1269
	log_entry(logbuffer, LVL_INFO);
Bruce Momjian's avatar
Bruce Momjian committed
1270
	sprintf(logbuffer, "  args->logfile=%s", (args->logfile) ? args->logfile : "(null)");
1271 1272
	log_entry(logbuffer, LVL_INFO);
#ifndef WIN32
1273
	sprintf(logbuffer, "  args->daemonize=%d", args->daemonize);
1274 1275
	log_entry(logbuffer, LVL_INFO);
#else
1276
	sprintf(logbuffer, "  args->install_as_service=%d", args->install_as_service);
1277
	log_entry(logbuffer, LVL_INFO);
1278
	sprintf(logbuffer, "  args->remove_as_service=%d", args->remove_as_service);
1279
	log_entry(logbuffer, LVL_INFO);
1280 1281
	sprintf(logbuffer, "  args->service_dependencies=%s", (args->service_dependencies) ? args->service_dependencies : "(null)");
	log_entry(logbuffer, LVL_INFO);
1282 1283 1284 1285 1286
	sprintf(logbuffer, "  args->service_user=%s", (args->service_user) ? args->service_user : "(null)");
	log_entry(logbuffer, LVL_INFO);
	sprintf(logbuffer, "  args->service_password=%s", (args->service_password) ? args->service_password : "(null)");
	log_entry(logbuffer, LVL_INFO);
#endif
Bruce Momjian's avatar
Bruce Momjian committed
1287

1288
	sprintf(logbuffer, "  args->sleep_base_value=%d", args->sleep_base_value);
1289
	log_entry(logbuffer, LVL_INFO);
Bruce Momjian's avatar
Bruce Momjian committed
1290
	sprintf(logbuffer, "  args->sleep_scaling_factor=%f", args->sleep_scaling_factor);
1291
	log_entry(logbuffer, LVL_INFO);
1292
	sprintf(logbuffer, "  args->vacuum_base_threshold=%d", args->vacuum_base_threshold);
1293
	log_entry(logbuffer, LVL_INFO);
Bruce Momjian's avatar
Bruce Momjian committed
1294
	sprintf(logbuffer, "  args->vacuum_scaling_factor=%f", args->vacuum_scaling_factor);
1295
	log_entry(logbuffer, LVL_INFO);
1296
	sprintf(logbuffer, "  args->analyze_base_threshold=%d", args->analyze_base_threshold);
1297
	log_entry(logbuffer, LVL_INFO);
Bruce Momjian's avatar
Bruce Momjian committed
1298
	sprintf(logbuffer, "  args->analyze_scaling_factor=%f", args->analyze_scaling_factor);
1299
	log_entry(logbuffer, LVL_INFO);
1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327
	
	if (args->av_vacuum_cost_delay != -1)
		sprintf(logbuffer, "  args->av_vacuum_cost_delay=%d", args->av_vacuum_cost_delay);
	else 
		sprintf(logbuffer, "  args->av_vacuum_cost_delay=(default)");
	log_entry(logbuffer, LVL_INFO);
	if (args->av_vacuum_cost_page_hit != -1)
		sprintf(logbuffer, "  args->av_vacuum_cost_page_hit=%d", args->av_vacuum_cost_page_hit);
	else
		sprintf(logbuffer, "  args->av_vacuum_cost_page_hit=(default)");
	log_entry(logbuffer, LVL_INFO);
	if (args->av_vacuum_cost_page_miss != -1)
		sprintf(logbuffer, "  args->av_vacuum_cost_page_miss=%d", args->av_vacuum_cost_page_miss);
	else
		sprintf(logbuffer, "  args->av_vacuum_cost_page_miss=(default)");
	log_entry(logbuffer, LVL_INFO);
	if (args->av_vacuum_cost_page_dirty != -1)
		sprintf(logbuffer, "  args->av_vacuum_cost_page_dirty=%d", args->av_vacuum_cost_page_dirty);
	else
		sprintf(logbuffer, "  args->av_vacuum_cost_page_dirty=(default)");
	log_entry(logbuffer, LVL_INFO);
	if (args->av_vacuum_cost_limit != -1)
		sprintf(logbuffer, "  args->av_vacuum_cost_limit=%d", args->av_vacuum_cost_limit);
	else
		sprintf(logbuffer, "  args->av_vacuum_cost_limit=(default)");
	log_entry(logbuffer, LVL_INFO);
	
	sprintf(logbuffer, "  args->debug=%d", args->debug);
1328
	log_entry(logbuffer, LVL_INFO);
Bruce Momjian's avatar
Bruce Momjian committed
1329 1330

	fflush(LOGOUTPUT);
1331 1332
}

1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393
#ifdef WIN32

/* Handle control requests from the Service Control Manager */
static void
ControlHandler(DWORD request)
{
	switch (request)
	{
		case SERVICE_CONTROL_STOP:
		case SERVICE_CONTROL_SHUTDOWN:
			log_entry("pg_autovacuum service stopping...", LVL_INFO);
			fflush(LOGOUTPUT);
			ServiceStatus.dwWin32ExitCode = 0;
			ServiceStatus.dwCurrentState = SERVICE_STOPPED;
			SetServiceStatus(hStatus, &ServiceStatus);
			return;

		default:
			break;
	}

	/* Report current status */
	SetServiceStatus(hStatus, &ServiceStatus);

	return;
}

/* Register with the Service Control Manager */
static int
InstallService()
{
	SC_HANDLE	schService = NULL;
	SC_HANDLE	schSCManager = NULL;
	char		szFilename[MAX_PATH],
				szKey[MAX_PATH],
				szCommand[MAX_PATH + 1024],
				szMsgDLL[MAX_PATH];
	HKEY		hk = NULL;
	DWORD		dwData = 0;

	/*
	 * Register the service with the SCM
	 */
	GetModuleFileName(NULL, szFilename, MAX_PATH);

	/* Open the Service Control Manager on the local computer. */
	schSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
	if (!schSCManager)
		return -1;

	schService = CreateService(
							   schSCManager,	/* SCManager database */
							   TEXT("pg_autovacuum"),	/* Name of service */
							   TEXT("PostgreSQL Auto Vacuum"),	/* Name to display */
							   SERVICE_ALL_ACCESS,		/* Desired access */
							   SERVICE_WIN32_OWN_PROCESS,		/* Service type */
							   SERVICE_AUTO_START,		/* Start type */
							   SERVICE_ERROR_NORMAL,	/* Error control type */
							   szFilename,		/* Service binary */
							   NULL,	/* No load ordering group */
							   NULL,	/* No tag identifier */
1394
							   args->service_dependencies,	/* Dependencies */
1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414
							   args->service_user,		/* Service account */
							   args->service_password); /* Account password */

	if (!schService)
		return -2;

	/*
	 * Rewrite the command line for the service
	 */
	sprintf(szKey, "SYSTEM\\CurrentControlSet\\Services\\pg_autovacuum");
	if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, szKey, 0, KEY_ALL_ACCESS, &hk))
		return -3;

	/* Build the command line */
	sprintf(szCommand, "\"%s\"", szFilename);
	if (args->host)
		sprintf(szCommand, "%s -H %s", szCommand, args->host);
	if (args->port)
		sprintf(szCommand, "%s -p %s", szCommand, args->port);
	if (args->user)
1415
		sprintf(szCommand, "%s -U \"%s\"", szCommand, args->user);
1416
	if (args->password)
1417
		sprintf(szCommand, "%s -P \"%s\"", szCommand, args->password);
1418
	if (args->logfile)
1419
		sprintf(szCommand, "%s -L \"%s\"", szCommand, args->logfile);
1420
	if (args->sleep_base_value != (int) SLEEPBASEVALUE)
1421
		sprintf(szCommand, "%s -s %d", szCommand, args->sleep_base_value);
1422 1423 1424
	if (args->sleep_scaling_factor != (float) SLEEPSCALINGFACTOR)
		sprintf(szCommand, "%s -S %f", szCommand, args->sleep_scaling_factor);
	if (args->vacuum_base_threshold != (int) VACBASETHRESHOLD)
1425
		sprintf(szCommand, "%s -v %d", szCommand, args->vacuum_base_threshold);
1426 1427 1428
	if (args->vacuum_scaling_factor != (float) VACSCALINGFACTOR)
		sprintf(szCommand, "%s -V %f", szCommand, args->vacuum_scaling_factor);
	if (args->analyze_base_threshold != (int) (VACBASETHRESHOLD / 2))
1429
		sprintf(szCommand, "%s -a %d", szCommand, args->analyze_base_threshold);
1430 1431 1432
	if (args->analyze_scaling_factor != (float) (VACSCALINGFACTOR / 2))
		sprintf(szCommand, "%s -A %f", szCommand, args->analyze_scaling_factor);
	if (args->debug != (int) AUTOVACUUM_DEBUG)
1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444
		sprintf(szCommand, "%s -d %d", szCommand, args->debug);
	if (args->av_vacuum_cost_delay != -1)
		sprintf(szCommand, "%s -d %d", szCommand, args->av_vacuum_cost_delay);
	if (args->av_vacuum_cost_page_hit != -1)
		sprintf(szCommand, "%s -d %d", szCommand, args->av_vacuum_cost_page_hit);
	if (args->av_vacuum_cost_page_miss != -1)
		sprintf(szCommand, "%s -d %d", szCommand, args->av_vacuum_cost_page_miss);
	if (args->av_vacuum_cost_page_dirty != -1)
		sprintf(szCommand, "%s -d %d", szCommand, args->av_vacuum_cost_page_dirty);
	if (args->av_vacuum_cost_limit != -1)
		sprintf(szCommand, "%s -d %d", szCommand, args->av_vacuum_cost_limit);		
		
1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456
	/* And write the new value */
	if (RegSetValueEx(hk, "ImagePath", 0, REG_EXPAND_SZ, (LPBYTE) szCommand, (DWORD) strlen(szCommand) + 1))
		return -4;
	RegCloseKey(hk);

	/*
	 * Set the Event source for the application log
	 */
	sprintf(szKey, "SYSTEM\\CurrentControlSet\\Services\\EventLog\\Application\\PostgreSQL Auto Vacuum");
	if (RegCreateKeyEx(HKEY_LOCAL_MACHINE, szKey, 0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hk, NULL))
		return -5;

1457 1458 1459
	/* TODO Try to find pgevent.dll, rather than hope it's in the path. ! */
	/* Message DLL */
	sprintf(szMsgDLL, "pgevent.dll");
1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508
	if (RegSetValueEx(hk, "EventMessageFile", 0, REG_EXPAND_SZ, (LPBYTE) szMsgDLL, (DWORD) strlen(szMsgDLL) + 1))
		return -6;

	/* Set the event types supported */
	dwData = EVENTLOG_ERROR_TYPE | EVENTLOG_WARNING_TYPE | EVENTLOG_INFORMATION_TYPE | EVENTLOG_SUCCESS;
	if (RegSetValueEx(hk, "TypesSupported", 0, REG_DWORD, (LPBYTE) & dwData, sizeof(DWORD)))
		return -9;

	RegCloseKey(hk);
	return 0;
}

/* Unregister from the Service Control Manager */
static int
RemoveService()
{
	SC_HANDLE	schService = NULL;
	SC_HANDLE	schSCManager = NULL;
	char		szKey[MAX_PATH];
	HKEY		hk = NULL;

	/* Open the SCM */
	schSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
	if (!schSCManager)
		return -1;

	/* Open the service */
	schService = OpenService(schSCManager, TEXT("pg_autovacuum"), SC_MANAGER_ALL_ACCESS);
	if (!schService)
		return -2;

	/* Now delete the service */
	if (!DeleteService(schService))
		return -3;

	/*
	 * Remove the Event source from the application log
	 */
	sprintf(szKey, "SYSTEM\\CurrentControlSet\\Services\\EventLog\\Application");
	if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, szKey, 0, KEY_ALL_ACCESS, &hk))
		return -4;
	if (RegDeleteKey(hk, "PostgreSQL Auto Vacuum"))
		return -5;

	return 0;
}
#endif   /* WIN32 */

static
1509
int
1510
VacuumLoop(int argc, char **argv)
1511
{
Bruce Momjian's avatar
Bruce Momjian committed
1512 1513 1514
	int			j = 0,
				loops = 0;

1515
	/* int numInserts, numDeletes, */
Bruce Momjian's avatar
Bruce Momjian committed
1516 1517 1518 1519 1520 1521 1522
	int			sleep_secs;
	Dllist	   *db_list;
	Dlelem	   *db_elem,
			   *tbl_elem;
	db_info    *dbs;
	tbl_info   *tbl;
	PGresult   *res = NULL;
1523
	double		diff;
1524

Bruce Momjian's avatar
Bruce Momjian committed
1525 1526 1527
	struct timeval now,
				then;

1528
#ifdef WIN32
Bruce Momjian's avatar
Bruce Momjian committed
1529

1530 1531 1532 1533
	if (appMode)
		log_entry("pg_autovacuum starting in Windows Application mode", LVL_INFO);
	else
		log_entry("pg_autovacuum starting in Windows Service mode", LVL_INFO);
Bruce Momjian's avatar
Bruce Momjian committed
1534

1535 1536 1537 1538 1539 1540 1541 1542 1543
	ServiceStatus.dwServiceType = SERVICE_WIN32;
	ServiceStatus.dwCurrentState = SERVICE_START_PENDING;
	ServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
	ServiceStatus.dwWin32ExitCode = 0;
	ServiceStatus.dwServiceSpecificExitCode = 0;
	ServiceStatus.dwCheckPoint = 0;
	ServiceStatus.dwWaitHint = 0;

	if (!appMode)
Bruce Momjian's avatar
Bruce Momjian committed
1544
	{
1545 1546 1547
		hStatus = RegisterServiceCtrlHandler("pg_autovacuum", (LPHANDLER_FUNCTION) ControlHandler);
		if (hStatus == (SERVICE_STATUS_HANDLE) 0)
			return -1;
Bruce Momjian's avatar
Bruce Momjian committed
1548
	}
1549
#endif   /* WIN32 */
Bruce Momjian's avatar
Bruce Momjian committed
1550 1551 1552

	/* Init the db list with template1 */
	db_list = init_db_list();
1553
	if (db_list == NULL)
Bruce Momjian's avatar
Bruce Momjian committed
1554
		return 1;
Bruce Momjian's avatar
Bruce Momjian committed
1555

1556
	if (check_stats_enabled(((db_info *) DLE_VAL(DLGetHead(db_list)))) != 0)
Bruce Momjian's avatar
Bruce Momjian committed
1557
	{
1558 1559
		log_entry("GUC variable stats_row_level must be enabled.", LVL_ERROR);
		log_entry("       Please fix the problems and try again.", LVL_EXTRA);
Bruce Momjian's avatar
Bruce Momjian committed
1560 1561 1562 1563 1564 1565 1566
		fflush(LOGOUTPUT);

		exit(1);
	}

	gettimeofday(&then, 0);		/* for use later to caluculate sleep time */

1567
#ifndef WIN32
Bruce Momjian's avatar
Bruce Momjian committed
1568
	while (1)
1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579
#else
	/* We can now report the running status to SCM. */
	ServiceStatus.dwCurrentState = SERVICE_RUNNING;
	if (!appMode)
		SetServiceStatus(hStatus, &ServiceStatus);

	while (ServiceStatus.dwCurrentState == SERVICE_RUNNING)
#endif
	{
		/* Main Loop */

Bruce Momjian's avatar
Bruce Momjian committed
1580 1581 1582 1583 1584
		db_elem = DLGetHead(db_list);	/* Reset cur_db_node to the
										 * beginning of the db_list */

		dbs = ((db_info *) DLE_VAL(db_elem));	/* get pointer to cur_db's
												 * db_info struct */
1585
		if (dbs->conn == NULL)
Bruce Momjian's avatar
Bruce Momjian committed
1586 1587
		{
			dbs->conn = db_connect(dbs);
1588
			if (dbs->conn == NULL)
Bruce Momjian's avatar
Bruce Momjian committed
1589 1590
			{					/* Serious problem: We can't connect to
								 * template1 */
1591
				log_entry("Cannot connect to template1, exiting.", LVL_ERROR);
Bruce Momjian's avatar
Bruce Momjian committed
1592 1593
				fflush(LOGOUTPUT);
				fclose(LOGOUTPUT);
1594 1595 1596 1597 1598 1599 1600
#ifdef WIN32
				ServiceStatus.dwCurrentState = SERVICE_STOPPED;
				ServiceStatus.dwWin32ExitCode = ERROR_SERVICE_SPECIFIC_ERROR;
				ServiceStatus.dwServiceSpecificExitCode = -1;
				if (!appMode)
					SetServiceStatus(hStatus, &ServiceStatus);
#endif
Bruce Momjian's avatar
Bruce Momjian committed
1601 1602 1603 1604
				exit(1);
			}
		}

1605
		if (loops % UPDATE_INTERVAL == 0)		/* Update the list if it's
Bruce Momjian's avatar
Bruce Momjian committed
1606 1607 1608 1609
												 * time */
			update_db_list(db_list);	/* Add and remove databases from
										 * the list */

1610
		while (db_elem != NULL)
Bruce Momjian's avatar
Bruce Momjian committed
1611 1612 1613 1614
		{						/* Loop through databases in list */
			dbs = ((db_info *) DLE_VAL(db_elem));		/* get pointer to
														 * cur_db's db_info
														 * struct */
1615
			if (dbs->conn == NULL)
Bruce Momjian's avatar
Bruce Momjian committed
1616 1617
				dbs->conn = db_connect(dbs);

1618
			if (dbs->conn != NULL)
Bruce Momjian's avatar
Bruce Momjian committed
1619
			{
1620
				if (loops % UPDATE_INTERVAL == 0)		/* Update the list if
Bruce Momjian's avatar
Bruce Momjian committed
1621 1622 1623 1624
														 * it's time */
					update_table_list(dbs);		/* Add and remove tables
												 * from the list */

1625
				if (xid_wraparound_check(dbs) == 0)
Bruce Momjian's avatar
Bruce Momjian committed
1626
				{
1627 1628 1629
					res = send_query(TABLE_STATS_QUERY, dbs);	/* Get an updated
																 * snapshot of this dbs
																 * table stats */
1630 1631 1632
					if (res != NULL)
					{
						for (j = 0; j < PQntuples(res); j++)
Bruce Momjian's avatar
Bruce Momjian committed
1633 1634 1635
						{		/* loop through result set */
							tbl_elem = DLGetHead(dbs->table_list);		/* Reset tbl_elem to top
																		 * of dbs->table_list */
1636
							while (tbl_elem != NULL)
Bruce Momjian's avatar
Bruce Momjian committed
1637 1638 1639
							{	/* Loop through tables in list */
								tbl = ((tbl_info *) DLE_VAL(tbl_elem)); /* set tbl_info =
																		 * current_table */
1640
								if (tbl->relid == atooid(PQgetvalue(res, j, PQfnumber(res, "oid"))))
Bruce Momjian's avatar
Bruce Momjian committed
1641
								{
1642 1643
									tbl->curr_analyze_count =
										(atol(PQgetvalue(res, j, PQfnumber(res, "n_tup_ins"))) +
Bruce Momjian's avatar
Bruce Momjian committed
1644 1645
										 atol(PQgetvalue(res, j, PQfnumber(res, "n_tup_upd"))) +
										 atol(PQgetvalue(res, j, PQfnumber(res, "n_tup_del"))));
1646 1647
									tbl->curr_vacuum_count =
										(atol(PQgetvalue(res, j, PQfnumber(res, "n_tup_del"))) +
Bruce Momjian's avatar
Bruce Momjian committed
1648 1649
										 atol(PQgetvalue(res, j, PQfnumber(res, "n_tup_upd"))));

1650
									/*
Bruce Momjian's avatar
Bruce Momjian committed
1651 1652 1653 1654 1655 1656 1657 1658 1659
									 * Check numDeletes to see if we need
									 * to vacuum, if so: Run vacuum
									 * analyze (adding analyze is small so
									 * we might as well) Update table
									 * thresholds and related information
									 * if numDeletes is not big enough for
									 * vacuum then check numInserts for
									 * analyze
									 */
1660
									if (tbl->curr_vacuum_count - tbl->CountAtLastVacuum >= tbl->vacuum_threshold)
1661
										perform_maintenance_command(dbs, tbl, VACUUM_ANALYZE);
1662
									else if (tbl->curr_analyze_count - tbl->CountAtLastAnalyze >= tbl->analyze_threshold)
1663 1664 1665
										perform_maintenance_command(dbs, tbl, ANALYZE_ONLY);

									break;		/* We found a match, no need to keep looping. */
Bruce Momjian's avatar
Bruce Momjian committed
1666
								}
Bruce Momjian's avatar
Bruce Momjian committed
1667

1668
								/*
Bruce Momjian's avatar
Bruce Momjian committed
1669 1670 1671
								 * Advance the table pointers for the next
								 * loop
								 */
1672
								tbl_elem = DLGetSucc(tbl_elem);
Bruce Momjian's avatar
Bruce Momjian committed
1673 1674 1675

							}	/* end for table while loop */
						}		/* end for j loop (tuples in PGresult) */
1676
					}			/* end if (res != NULL) */
1677
				}				/* close of if (xid_wraparound_check()) */
Bruce Momjian's avatar
Bruce Momjian committed
1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688
				/* Done working on this db, Clean up, then advance cur_db */
				PQclear(res);
				res = NULL;
				db_disconnect(dbs);
			}
			db_elem = DLGetSucc(db_elem);		/* move on to next DB
												 * regardless */
		}						/* end of db_list while loop */

		/* Figure out how long to sleep etc ... */
		gettimeofday(&now, 0);
1689
		diff = (int) (now.tv_sec - then.tv_sec) * 1000000.0 + (int) (now.tv_usec - then.tv_usec);
Bruce Momjian's avatar
Bruce Momjian committed
1690

1691
		sleep_secs = args->sleep_base_value + args->sleep_scaling_factor * diff / 1000000.0;
Bruce Momjian's avatar
Bruce Momjian committed
1692 1693 1694 1695
		loops++;
		if (args->debug >= 2)
		{
			sprintf(logbuffer,
1696
			 "%d All DBs checked in: %.0f usec, will sleep for %d secs.",
Bruce Momjian's avatar
Bruce Momjian committed
1697
					loops, diff, sleep_secs);
1698
			log_entry(logbuffer, LVL_DEBUG);
1699
			fflush(LOGOUTPUT);
Bruce Momjian's avatar
Bruce Momjian committed
1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713
		}

		sleep(sleep_secs);		/* Larger Pause between outer loops */

		gettimeofday(&then, 0); /* Reset time counter */

	}							/* end of while loop */

	/*
	 * program is exiting, this should never run, but is here to make
	 * compiler / valgrind happy
	 */
	free_db_list(db_list);
	free_cmd_args();
1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807
	return 0;
}

/* Beginning of AutoVacuum Main Program */
int
main(int argc, char *argv[])
{

#ifdef WIN32
	LPVOID		lpMsgBuf;
	SERVICE_TABLE_ENTRY ServiceTable[2];
#endif

	args = get_cmd_args(argc, argv);	/* Get Command Line Args and put
										 * them in the args struct */
#ifndef WIN32
	/* Dameonize if requested */
	if (args->daemonize == 1)
		daemonize();
#endif

	if (args->logfile)
	{
		LOGOUTPUT = fopen(args->logfile, "a");
		if (!LOGOUTPUT)
		{
			fprintf(stderr, "Could not open log file - [%s]\n", args->logfile);
			exit(-1);
		}
	}
	else
		LOGOUTPUT = stderr;
	if (args->debug >= 2)
		print_cmd_args();

#ifdef WIN32
	/* Install as a Windows service if required */
	if (args->install_as_service)
	{
		if (InstallService() != 0)
		{
			FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) & lpMsgBuf, 0, NULL);
			sprintf(logbuffer, "%s", (char *) lpMsgBuf);
			log_entry(logbuffer, LVL_ERROR);
			fflush(LOGOUTPUT);
			exit(-1);
		}
		else
		{
			log_entry("Successfully installed Windows service", LVL_INFO);
			fflush(LOGOUTPUT);
			exit(0);
		}
	}

	/* Remove as a Windows service if required */
	if (args->remove_as_service)
	{
		if (RemoveService() != 0)
		{
			FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) & lpMsgBuf, 0, NULL);
			sprintf(logbuffer, "%s", (char *) lpMsgBuf);
			log_entry(logbuffer, LVL_ERROR);
			fflush(LOGOUTPUT);
			exit(-1);
		}
		else
		{
			log_entry("Successfully removed Windows service", LVL_INFO);
			fflush(LOGOUTPUT);
			exit(0);
		}
	}

	/* Normal service startup */
	ServiceTable[0].lpServiceName = "pg_autovacuum";
	ServiceTable[0].lpServiceProc = (LPSERVICE_MAIN_FUNCTION) VacuumLoop;

	ServiceTable[1].lpServiceName = NULL;
	ServiceTable[1].lpServiceProc = NULL;

	/* Start the control dispatcher thread for our service */
	if (!StartServiceCtrlDispatcher(ServiceTable))
	{
		appMode = 1;
		VacuumLoop(0, NULL);
	}

#else							/* Unix */

	/* Call the main program loop. */
	VacuumLoop(0, NULL);
#endif   /* WIN32 */

Bruce Momjian's avatar
Bruce Momjian committed
1808
	return EXIT_SUCCESS;
1809
}