tracker-main.c 33.8 KB
Newer Older
1
/*
2
 * Copyright (C) 2008, Nokia <ivan.frade@nokia.com>
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA  02110-1301, USA.
 */

20
#include "config-miners.h"
21
22
23
24
25
26
27
28

#include <string.h>
#include <stdlib.h>
#include <locale.h>
#include <errno.h>
#include <sys/types.h>
#include <unistd.h>

29
30
31
32
#ifdef HAVE_MALLOC_TRIM
#include <malloc.h>
#endif

33
#include <glib.h>
34
#include <glib-unix.h>
35
36
37
#include <glib-object.h>
#include <glib/gi18n.h>

38
#include <libtracker-miners-common/tracker-common.h>
39
#include <libtracker-sparql/tracker-sparql.h>
40
#include <libtracker-miner/tracker-miner.h>
41

42
#include "tracker-config.h"
43
#include "tracker-miner-files.h"
44

Martyn Russell's avatar
Martyn Russell committed
45
#define ABOUT	  \
46
47
	"Tracker " PACKAGE_VERSION "\n"

Martyn Russell's avatar
Martyn Russell committed
48
#define LICENSE	  \
49
	"This program is free software and comes without any warranty.\n" \
Martyn Russell's avatar
Martyn Russell committed
50
51
52
	"It is licensed under version 2 or later of the General Public " \
	"License which can be viewed at:\n" \
	"\n" \
53
54
	"  http://www.gnu.org/licenses/gpl.txt\n"

55
56
#define SECONDS_PER_DAY 60 * 60 * 24

57
58
#define DBUS_NAME_SUFFIX "Tracker3.Miner.Files"
#define DBUS_PATH "/org/freedesktop/Tracker3/Miner/Files"
59
#define LOCALE_FILENAME "locale-for-miner-apps.txt"
60

61
static GMainLoop *main_loop;
62
63
static GDBusProxy *index_proxy;
static GPtrArray *proxy_folders;
64
static guint cleanup_id;
65

66
static gint initial_sleep = -1;
67
static gboolean no_daemon;
68
69
static gchar *eligible;
static gboolean version;
70
static guint miners_timeout_id = 0;
71
static gboolean do_crawling = FALSE;
72
static gchar *domain_ontology_name = NULL;
73
static gboolean dry_run = FALSE;
74

75
76
77
static gboolean slept = TRUE;
static gboolean graphs_ready = FALSE;

78
static GOptionEntry entries[] = {
79
80
81
	{ "initial-sleep", 's', 0,
	  G_OPTION_ARG_INT, &initial_sleep,
	  N_("Initial sleep time in seconds, "
82
	     "0->1000 (default=15)"),
83
	  NULL },
84
85
86
87
	{ "no-daemon", 'n', 0,
	  G_OPTION_ARG_NONE, &no_daemon,
	  N_("Runs until all configured locations are indexed and then exits"),
	  NULL },
88
89
90
91
	{ "eligible", 'e', 0,
	  G_OPTION_ARG_FILENAME, &eligible,
	  N_("Checks if FILE is eligible for being mined based on configuration"),
	  N_("FILE") },
92
93
	{ "domain-ontology", 'd', 0,
	  G_OPTION_ARG_STRING, &domain_ontology_name,
94
	  N_("Runs for a specific domain ontology"),
95
	  NULL },
96
97
98
99
	{ "dry-run", 'r', 0,
	  G_OPTION_ARG_NONE, &dry_run,
	  N_("Avoids changes in the filesystem"),
	  NULL },
100
101
102
103
	{ "version", 'V', 0,
	  G_OPTION_ARG_NONE, &version,
	  N_("Displays version information"),
	  NULL },
104
105
106
107
	{ NULL }
};

static void
108
log_option_values (TrackerConfig *config)
109
{
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
#ifdef G_ENABLE_DEBUG
	if (TRACKER_DEBUG_CHECK (CONFIG)) {
		g_message ("General options:");
		g_message ("  Initial Sleep  ........................  %d",
		           tracker_config_get_initial_sleep (config));

		g_message ("Indexer options:");
		g_message ("  Throttle level  .......................  %d",
		           tracker_config_get_throttle (config));
		g_message ("  Indexing while on battery  ............  %s (first time only = %s)",
		           tracker_config_get_index_on_battery (config) ? "yes" : "no",
		           tracker_config_get_index_on_battery_first_time (config) ? "yes" : "no");

		if (tracker_config_get_low_disk_space_limit (config) == -1) {
			g_message ("  Low disk space limit  .................  Disabled");
		} else {
			g_message ("  Low disk space limit  .................  %d%%",
			           tracker_config_get_low_disk_space_limit (config));
		}
129
	}
130
#endif
131
132
}

133
134
135
136
137
138
139
static void
miner_reset_applications (TrackerMiner *miner)
{
	const gchar *sparql;
	GError *error = NULL;

	sparql =
140
		"DELETE { ?icon a rdfs:Resource } "
141
142
143
144
		"WHERE { ?app a nfo:SoftwareApplication; nfo:softwareIcon ?icon }; "
		"DELETE { ?app tracker:extractorHash ?h } "
		"WHERE { ?app a nfo:SoftwareApplication ; "
		"             tracker:extractorHash ?h } ";
145
146
147
148

	/* Execute a sync update, we don't want the apps miner to start before
	 * we finish this. */
	tracker_sparql_connection_update (tracker_miner_get_connection (miner),
149
	                                  sparql,
150
151
152
153
154
155
156
157
158
159
	                                  NULL, &error);

	if (error) {
		/* Some error happened performing the query, not good */
		g_critical ("Couldn't reset indexed applications: %s",
		            error ? error->message : "unknown error");
		g_error_free (error);
	}
}

160
161
162
163
164
165
static GFile *
get_cache_dir (TrackerDomainOntology *domain_ontology)
{
	GFile *cache;

	cache = tracker_domain_ontology_get_cache (domain_ontology);
166
	return g_file_get_child (cache, "files");
167
168
}

169
static void
170
save_current_locale (TrackerDomainOntology *domain_ontology)
171
172
173
{
	GError *error = NULL;
	gchar *locale = tracker_locale_get (TRACKER_LOCALE_LANGUAGE);
174
175
176
177
178
179
	GFile *cache = get_cache_dir (domain_ontology);
	gchar *cache_path = g_file_get_path (cache);
	gchar *locale_file;

	locale_file = g_build_filename (cache_path, LOCALE_FILENAME, NULL);
	g_free (cache_path);
180

181
182
	TRACKER_NOTE (CONFIG, g_message ("Saving locale used to index applications"));
	TRACKER_NOTE (CONFIG, g_message ("  Creating locale file '%s'", locale_file));
183
184
185
186
187
188
189
190
191
192
193

	if (locale == NULL) {
		locale = g_strdup ("");
	}

	if (!g_file_set_contents (locale_file, locale, -1, &error)) {
		g_message ("  Could not set file contents, %s",
		           error ? error->message : "no error given");
		g_clear_error (&error);
	}

194
	g_object_unref (cache);
195
196
197
198
199
	g_free (locale);
	g_free (locale_file);
}

static gboolean
200
201
detect_locale_changed (TrackerMiner          *miner,
		       TrackerDomainOntology *domain_ontology)
202
{
203
204
	GFile *cache;
	gchar *cache_path;
205
206
207
208
209
	gchar *locale_file;
	gchar *previous_locale = NULL;
	gchar *current_locale;
	gboolean changed;

210
211
212
	cache = get_cache_dir (domain_ontology);
	cache_path = g_file_get_path (cache);
	locale_file = g_build_filename (cache_path, LOCALE_FILENAME, NULL);
213
	g_object_unref (cache);
214
	g_free (cache_path);
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232

	if (G_LIKELY (g_file_test (locale_file, G_FILE_TEST_EXISTS))) {
		gchar *contents;

		/* Check locale is correct */
		if (G_LIKELY (g_file_get_contents (locale_file, &contents, NULL, NULL))) {
			if (contents &&
			    contents[0] == '\0') {
				g_critical ("  Empty locale file found at '%s'", locale_file);
				g_free (contents);
			} else {
				/* Re-use contents */
				previous_locale = contents;
			}
		} else {
			g_critical ("  Could not get content of file '%s'", locale_file);
		}
	} else {
233
		TRACKER_NOTE (CONFIG, g_message ("  Could not find locale file:'%s'", locale_file));
234
235
236
237
238
239
240
241
242
	}

	g_free (locale_file);

	current_locale = tracker_locale_get (TRACKER_LOCALE_LANGUAGE);

	/* Note that having both to NULL is actually valid, they would default
	 * to the unicode collation without locale-specific stuff. */
	if (g_strcmp0 (previous_locale, current_locale) != 0) {
243
244
		TRACKER_NOTE (CONFIG, g_message ("Locale change detected from '%s' to '%s'...",
		                      previous_locale, current_locale));
245
246
		changed = TRUE;
	} else {
247
		TRACKER_NOTE (CONFIG, g_message ("Current and previous locales match: '%s'", previous_locale));
248
249
250
251
252
253
254
		changed = FALSE;
	}

	g_free (current_locale);
	g_free (previous_locale);

	if (changed) {
255
		TRACKER_NOTE (CONFIG, g_message ("Resetting nfo:Software due to locale change..."));
256
257
258
259
260
261
		miner_reset_applications (miner);
	}

	return changed;
}

262
263
static gboolean
signal_handler (gpointer user_data)
264
{
265
266
	int signo = GPOINTER_TO_INT (user_data);

267
268
269
270
271
272
273
274
275
276
277
	static gboolean in_loop = FALSE;

	/* Die if we get re-entrant signals handler calls */
	if (in_loop) {
		_exit (EXIT_FAILURE);
	}

	switch (signo) {
	case SIGTERM:
	case SIGINT:
		in_loop = TRUE;
278
279
		g_main_loop_quit (main_loop);

280
		/* Fall through */
281
282
	default:
		if (g_strsignal (signo)) {
283
284
285
			g_debug ("Received signal:%d->'%s'",
			         signo,
			         g_strsignal (signo));
286
287
288
		}
		break;
	}
289
290

	return G_SOURCE_CONTINUE;
291
292
293
294
295
296
}

static void
initialize_signal_handler (void)
{
#ifndef G_OS_WIN32
297
298
	g_unix_signal_add (SIGTERM, signal_handler, GINT_TO_POINTER (SIGTERM));
	g_unix_signal_add (SIGINT, signal_handler, GINT_TO_POINTER (SIGINT));
299
300
301
302
#endif /* G_OS_WIN32 */
}

static void
303
initialize_priority_and_scheduling (void)
304
{
305
	/* Set CPU priority */
306
	tracker_sched_idle ();
307

308
309
310
311
312
313
314
315
	/* Set disk IO priority and scheduling */
	tracker_ioprio_init ();

	/* Set process priority:
	 * The nice() function uses attribute "warn_unused_result" and
	 * so complains if we do not check its returned value. But it
	 * seems that since glibc 2.2.4, nice() can return -1 on a
	 * successful call so we have to check value of errno too.
316
	 * Stupid...
317
318
	 */

319
	TRACKER_NOTE (CONFIG, g_message ("Setting priority nice level to 19"));
320

321
322
	errno = 0;
	if (nice (19) == -1 && errno != 0) {
323
324
325
		const gchar *str = g_strerror (errno);

		g_message ("Couldn't set nice value to 19, %s",
Martyn Russell's avatar
Martyn Russell committed
326
		           str ? str : "no error given");
327
328
329
	}
}

330
static gboolean
331
332
333
should_crawl (TrackerMinerFiles *miner_files,
              TrackerConfig     *config,
              gboolean          *forced)
334
335
336
337
338
{
	gint crawling_interval;

	crawling_interval = tracker_config_get_crawling_interval (config);

339
	TRACKER_NOTE (CONFIG, g_message ("Checking whether to crawl file system based on configured crawling interval:"));
340

341
	if (crawling_interval == -2) {
342
		TRACKER_NOTE (CONFIG, g_message ("  Disabled"));
343
		return FALSE;
344
	} else if (crawling_interval == -1) {
345
		TRACKER_NOTE (CONFIG, g_message ("  Maybe (depends on a clean last shutdown)"));
346
		return TRUE;
347
	} else if (crawling_interval == 0) {
348
		TRACKER_NOTE (CONFIG, g_message ("  Forced"));
349
350
351
352
353

		if (forced) {
			*forced = TRUE;
		}

354
355
356
		return TRUE;
	} else {
		guint64 then, now;
357

358
		then = tracker_miner_files_get_last_crawl_done (miner_files);
359

360
		if (then < 1) {
361
362
363
364
365
366
			return TRUE;
		}

		now = (guint64) time (NULL);

		if (now < then + (crawling_interval * SECONDS_PER_DAY)) {
367
			TRACKER_NOTE (CONFIG, g_message ("  Postponed"));
368
369
			return FALSE;
		} else {
370
			TRACKER_NOTE (CONFIG, g_message ("  (More than) %d days after last crawling, enabled", crawling_interval));
371
			return TRUE;
372
373
374
375
		}
	}
}

376
static void
377
miner_do_start (TrackerMiner *miner)
378
{
379
	if (!tracker_miner_is_started (miner)) {
380
		g_debug ("Starting filesystem miner...");
381
		tracker_miner_start (miner);
Martyn Russell's avatar
Martyn Russell committed
382
	}
383
384
}

385
386
387
388
389
390
391
392
393
static void
miner_maybe_start (TrackerMiner *miner)
{
	if (!slept || !graphs_ready)
		return;

	miner_do_start (miner);
}

394
static gboolean
395
miner_start_idle_cb (gpointer data)
396
{
397
398
	TrackerMiner *miner = data;

399
	miners_timeout_id = 0;
400
401
	slept = TRUE;
	miner_maybe_start (miner);
402
	return G_SOURCE_REMOVE;
403
404
405
}

static void
406
407
408
miner_start (TrackerMiner  *miner,
	     TrackerConfig *config,
	     gboolean       do_mtime_checking)
409
410
411
{
	gint initial_sleep;

412
413
	if (!do_mtime_checking) {
		g_debug ("Avoiding initial sleep, no mtime check needed");
414
		miner_maybe_start (miner);
415
416
417
		return;
	}

418
419
	/* If requesting to run as no-daemon, start right away */
	if (no_daemon) {
420
		miner_maybe_start (miner);
421
422
423
424
425
		return;
	}

	/* If no need to initially sleep, start right away */
	initial_sleep = tracker_config_get_initial_sleep (config);
426

427
	if (initial_sleep <= 0) {
428
		miner_maybe_start (miner);
429
430
431
		return;
	}

432
	slept = FALSE;
433
434
	g_debug ("Performing initial sleep of %d seconds",
	         initial_sleep);
435
	miners_timeout_id = g_timeout_add_seconds (initial_sleep,
436
437
	                                           miner_start_idle_cb,
	                                           miner);
438
439
}

440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
#ifdef HAVE_MALLOC_TRIM

static void
release_heap_memory (void)
{
	malloc_trim (0);
}

#else

static void
release_heap_memory (void)
{
	g_debug ("release_heap_memory(): Doing nothing as malloc_trim() is not available on this platform.");
}

#endif

458
459
460
static gboolean
cleanup_cb (gpointer user_data)
{
461
	release_heap_memory ();
462
463
464
465
466
467

	cleanup_id = 0;

	return G_SOURCE_REMOVE;
}

468
469
470
471
472
473
474
#if GLIB_CHECK_VERSION (2, 64, 0)
static void
on_low_memory (GMemoryMonitor            *monitor,
               GMemoryMonitorWarningLevel level,
               gpointer                   user_data)
{
	if (level > G_MEMORY_MONITOR_WARNING_LEVEL_LOW)
475
		release_heap_memory ();
476
477
478
}
#endif

479
480
481
482
483
484
485
486
487
static void
miner_started_cb (TrackerMinerFS *fs)
{
	if (cleanup_id) {
		g_source_remove (cleanup_id);
		cleanup_id = 0;
	}
}

488
static void
489
490
491
492
493
494
495
miner_finished_cb (TrackerMinerFS *fs,
                   gdouble         seconds_elapsed,
                   guint           total_directories_found,
                   guint           total_directories_ignored,
                   guint           total_files_found,
                   guint           total_files_ignored,
                   gpointer        user_data)
496
{
497
498
499
500
	g_info ("Finished mining in seconds:%f, total directories:%d, total files:%d",
	        seconds_elapsed,
	        total_directories_found,
	        total_files_found);
501

502
	if (do_crawling && !dry_run) {
503
504
		tracker_miner_files_set_last_crawl_done (TRACKER_MINER_FILES (fs),
							 TRUE);
505
506
	}

507
508
	cleanup_id = g_timeout_add_seconds (30, cleanup_cb, NULL);

509
510
511
512
	/* We're not sticking around for file updates, so stop
	 * the mainloop and exit.
	 */
	if (no_daemon && main_loop) {
513
514
		/* FIXME: wait for extractor to finish */
		g_main_loop_quit (main_loop);
515
	}
516
517
}

518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
static GList *
get_dir_children_as_gfiles (const gchar *path)
{
	GList *children = NULL;
	GDir *dir;

	dir = g_dir_open (path, 0, NULL);

	if (dir) {
		const gchar *basename;

		while ((basename = g_dir_read_name (dir)) != NULL) {
			GFile *child;
			gchar *str;

			str = g_build_filename (path, basename, NULL);
			child = g_file_new_for_path (str);
			g_free (str);

			children = g_list_prepend (children, child);
		}

		g_dir_close (dir);
	}

	return children;
}

static void
dummy_log_handler (const gchar    *domain,
                   GLogLevelFlags  log_level,
                   const gchar    *message,
                   gpointer        user_data)
{
	return;
}

555
556
557
558
559
560
561
562
563
564
565
566
567
static void
graphs_created_cb (GObject      *source,
                   GAsyncResult *res,
                   gpointer      user_data)
{
	TrackerMiner *miner = user_data;

	tracker_sparql_connection_update_finish (TRACKER_SPARQL_CONNECTION (source),
	                                         res, NULL);
	graphs_ready = TRUE;
	miner_maybe_start (miner);
}

568
static gint
569
570
check_eligible (void)
{
571
572
573
574
	TrackerSparqlConnection *sparql_conn;
	TrackerMiner *miner_files;
	TrackerIndexingTree *indexing_tree;
	TrackerDomainOntology *domain_ontology;
575
	TrackerConfig *config;
576
	GFile *ontology;
577
578
579
580
581
582
	GFile *file;
	GFileInfo *info;
	GError *error = NULL;
	gchar *path;
	guint log_handler_id;
	gboolean exists = TRUE;
583
584
	gboolean indexable;
	gboolean parents_indexable = TRUE;
585
586
587
588
589
590
591
592
593
594
	gboolean is_dir;

	/* Set log handler for library messages */
	log_handler_id = g_log_set_handler (NULL,
	                                    G_LOG_LEVEL_MASK | G_LOG_FLAG_FATAL,
	                                    dummy_log_handler,
	                                    NULL);

	g_log_set_default_handler (dummy_log_handler, NULL);

595

596
597
598
	/* Start check */
	file = g_file_new_for_commandline_arg (eligible);
	info = g_file_query_info (file,
599
600
	                          G_FILE_ATTRIBUTE_STANDARD_TYPE ","
	                          G_FILE_ATTRIBUTE_STANDARD_IS_HIDDEN,
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
	                          G_FILE_QUERY_INFO_NONE,
	                          NULL,
	                          &error);

	if (error) {
		if (error->code == G_IO_ERROR_NOT_FOUND) {
			exists = FALSE;
		}

		g_error_free (error);
	}

	if (info) {
		is_dir = g_file_info_get_file_type (info) == G_FILE_TYPE_DIRECTORY;
	} else {
		/* Assume not a dir */
		is_dir = FALSE;
	}

	config = tracker_config_new ();
	path = g_file_get_path (file);

Carlos Garnacho's avatar
Carlos Garnacho committed
623
	g_print (exists ?
624
625
	         _("Data object “%s” currently exists") :
	         _("Data object “%s” currently does not exist"),
Carlos Garnacho's avatar
Carlos Garnacho committed
626
	         path);
627
628
629

	g_print ("\n");

630
631
	domain_ontology = tracker_domain_ontology_new (domain_ontology_name, NULL, &error);
	ontology = tracker_domain_ontology_get_ontology (domain_ontology);
Carlos Garnacho's avatar
Carlos Garnacho committed
632
633
	tracker_domain_ontology_unref (domain_ontology);

634
635
636
637
638
	sparql_conn = tracker_sparql_connection_new (0,
	                                              NULL,
	                                              ontology,
	                                              NULL,
	                                              NULL);
639
640
	if (!sparql_conn) {
		g_object_unref (info);
641
		return EXIT_FAILURE;
642
	}
643

644
645
646
647
648
	/* Create new TrackerMinerFiles object */
	config = tracker_config_new ();
	miner_files = tracker_miner_files_new (sparql_conn, config,
	                                       domain_ontology_name, NULL);
	g_object_unref (config);
649

650
	if (!miner_files) {
651
		g_object_unref (info);
652
653
		g_object_unref (sparql_conn);
		return EXIT_FAILURE;
654
655
	}

656
	indexing_tree = tracker_miner_fs_get_indexing_tree (TRACKER_MINER_FS (miner_files));
657

658
	indexable = tracker_indexing_tree_file_is_indexable (indexing_tree, file, info);
659

660
661
662
663
	if (!indexable) {
		if (is_dir &&
		    tracker_indexing_tree_file_matches_filter (indexing_tree, TRACKER_FILTER_DIRECTORY, file)) {
			g_print ("  %s\n", _("Directory is NOT eligible to be indexed (based on filters)"));
664

665
666
667
668
669
670
671
672
673
		} else if (!is_dir &&
		           tracker_indexing_tree_file_matches_filter (indexing_tree, TRACKER_FILTER_FILE, file)) {
			g_print ("  %s\n", _("File is NOT eligible to be indexed (based on filters)"));
		} else if (tracker_file_is_hidden (file) &&
		           tracker_indexing_tree_get_filter_hidden (indexing_tree)) {
			g_print ("  %s\n", _("File is NOT eligible to be indexed (hidden file)"));
		} else {
			g_print ("  %s\n", _("File is NOT eligible to be indexed (not an indexed folder)"));
		}
674
675
	}

676
677
678
	if (indexable) {
		GFile *root, *parent;
		GList *files = NULL, *l;
679

680
681
		root = tracker_indexing_tree_get_root (indexing_tree, file, NULL);
		parent = file;
682

683
684
685
686
687
		/* Still, a parent folder might be filtered out, figure it out */
		while (parent && !g_file_equal (parent, root)) {
			parent = g_file_get_parent (parent);
			files = g_list_prepend (files, parent);
		}
688

689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
		for (l = files; l; l = l->next) {
			gchar *dir_path;

			dir_path = g_file_get_path (l->data);

			if (is_dir &&
			    tracker_indexing_tree_file_matches_filter (indexing_tree, TRACKER_FILTER_DIRECTORY, l->data)) {
				g_print (_("Parent directory “%s” is NOT eligible to be indexed (based on filters)"),
				         dir_path);
				g_print ("\n");
				parents_indexable = FALSE;
			} else if (tracker_file_is_hidden (l->data) &&
			           tracker_indexing_tree_get_filter_hidden (indexing_tree)) {
				g_print (_("Parent directory “%s” is NOT eligible to be indexed (hidden file)"),
				         dir_path);
				g_print ("\n");
				parents_indexable = FALSE;
			} else {
				GList *children = get_dir_children_as_gfiles (dir_path);
708

709
710
711
712
713
714
				if (!tracker_indexing_tree_parent_is_indexable (indexing_tree, l->data, children)) {
					g_print (_("Parent directory “%s” is NOT eligible to be indexed (based on content filters)"),
					         dir_path);
					g_print ("\n");
					parents_indexable = FALSE;
				}
715

716
				g_list_free_full (children, g_object_unref);
717
718
			}

719
			g_free (dir_path);
720

721
722
			if (!parents_indexable)
				break;
723
724
		}

725
		g_list_free_full (files, g_object_unref);
726
727
	}

728
	if (indexable && parents_indexable) {
729
		g_print ("  %s\n",
730
731
732
		         is_dir ?
		         _("Directory is eligible to be indexed") :
		         _("File is eligible to be indexed"));
733
734
735
736
737
738
739
740
741
	}

	if (log_handler_id != 0) {
		/* Unset log handler */
		g_log_remove_handler (NULL, log_handler_id);
	}

	g_free (path);
	g_object_unref (file);
742
	g_object_unref (miner_files);
743
	g_object_unref (info);
744
745

	return (indexable && parents_indexable) ? EXIT_SUCCESS : EXIT_FAILURE;
746
747
}

748
static gboolean
749
miner_needs_check (TrackerMiner *miner)
750
751
752
{
	/* Reasons to not mark ourselves as cleanly shutdown include:
	 *
753
	 * 1. Still crawling or with files to process in our queues.
754
755
	 * 2. We crash (out of our control usually anyway).
	 * 3. At least one of the miners is PAUSED, we have
756
	 *    to exclude the situations where the miner is actually done.
757
758
	 */
	if (!tracker_miner_is_paused (miner)) {
759
		if (tracker_miner_fs_has_items_to_process (TRACKER_MINER_FS (miner))) {
760
761
762
763
			/* There are items left to process */
			return TRUE;
		}

764
		/* FIXME: We currently don't check the applications
Sam Thursfield's avatar
Sam Thursfield committed
765
766
		 *  miner if we are finished before returning TRUE/FALSE here, should
		 *  we?
767
768
		 */

769
770
771
		/* We consider the miner finished */
		return FALSE;
	} else {
772
773
		/* Paused for other reasons, so probably not done */
		return TRUE;
774
775
776
	}
}

777
778
779
780
781
782
static void
on_domain_vanished (GDBusConnection *connection,
                    const gchar     *name,
                    gpointer         user_data)
{
	GMainLoop *loop = user_data;
783
	g_message ("Domain %s vanished: quitting now.", name);
784
785
786
	g_main_loop_quit (loop);
}

787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
TrackerSparqlConnectionFlags
get_fts_connection_flags (void)
{
	TrackerSparqlConnectionFlags flags = 0;
	TrackerFTSConfig *fts_config;

	fts_config = tracker_fts_config_new ();

	if (tracker_fts_config_get_enable_stemmer (fts_config))
		flags |= TRACKER_SPARQL_CONNECTION_FLAGS_FTS_ENABLE_STEMMER;
	if (tracker_fts_config_get_enable_unaccent (fts_config))
		flags |= TRACKER_SPARQL_CONNECTION_FLAGS_FTS_ENABLE_UNACCENT;
	if (tracker_fts_config_get_ignore_numbers (fts_config))
		flags |= TRACKER_SPARQL_CONNECTION_FLAGS_FTS_IGNORE_NUMBERS;
	if (tracker_fts_config_get_ignore_stop_words (fts_config))
		flags |= TRACKER_SPARQL_CONNECTION_FLAGS_FTS_ENABLE_STOP_WORDS;

	g_object_unref (fts_config);

	return flags;
}

809
810
811
812
813
814
815
static gboolean
setup_connection_and_endpoint (TrackerDomainOntology    *domain,
                               GDBusConnection          *connection,
                               TrackerSparqlConnection **sparql_conn,
                               TrackerEndpointDBus     **endpoint,
                               GError                  **error)
{
816
	GFile *store = NULL, *ontology;
817

818
819
	if (!dry_run)
		store = get_cache_dir (domain);
820
	ontology = tracker_domain_ontology_get_ontology (domain);
821
	*sparql_conn = tracker_sparql_connection_new (get_fts_connection_flags (),
822
	                                              store,
823
	                                              ontology,
824
825
	                                              NULL,
	                                              error);
826
	g_clear_object (&store);
827

828
829
830
831
832
833
834
835
836
837
838
839
840
841
	if (!*sparql_conn)
		return FALSE;

	*endpoint = tracker_endpoint_dbus_new (*sparql_conn,
	                                       connection,
	                                       NULL,
	                                       NULL,
	                                       error);
	if (!*endpoint)
		return FALSE;

	return TRUE;
}

842
843
844
845
846
847
848
849
850
static void
update_indexed_files_from_proxy (TrackerMinerFiles *miner,
                                 GDBusProxy        *proxy)
{
	TrackerIndexingTree *indexing_tree;
	const gchar **indexed_uris = NULL;
	GVariant *v;
	gint i;

851
	v = g_dbus_proxy_get_cached_property (proxy, "IndexedLocations");
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
	if (v)
		indexed_uris = g_variant_get_strv (v, NULL);

	indexing_tree = tracker_miner_fs_get_indexing_tree (TRACKER_MINER_FS (miner));

	/* Remove folders no longer there */
	for (i = 0; i < proxy_folders->len; i++) {
		GFile *file;
		gchar *uri;

		file = g_ptr_array_index (proxy_folders, i);
		uri = g_file_get_uri (file);

		if (!indexed_uris || !g_strv_contains (indexed_uris, uri)) {
			tracker_indexing_tree_remove (indexing_tree,
			                              file);
		}

		g_free (uri);
	}

	for (i = 0; indexed_uris && indexed_uris[i]; i++) {
		GFileInfo *file_info;
		GFile *file;

		file = g_file_new_for_uri (indexed_uris[i]);
		if (g_ptr_array_find_with_equal_func (proxy_folders,
		                                      file,
		                                      (GEqualFunc) g_file_equal,
		                                      NULL)) {
			g_object_unref (file);
			continue;
		}

		file_info = g_file_query_info (file,
887
888
		                               G_FILE_ATTRIBUTE_STANDARD_TYPE ","
		                               G_FILE_ATTRIBUTE_STANDARD_IS_HIDDEN,
889
890
891
892
893
894
895
896
897
898
		                               G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
		                               NULL, NULL);

		if (!file_info) {
			g_object_unref (file);
			continue;
		}

		if (g_file_info_get_file_type (file_info) == G_FILE_TYPE_DIRECTORY) {
			if (!tracker_indexing_tree_file_is_indexable (indexing_tree,
899
			                                              file, file_info)) {
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
				tracker_indexing_tree_add (indexing_tree,
				                           file,
				                           TRACKER_DIRECTORY_FLAG_RECURSE |
				                           TRACKER_DIRECTORY_FLAG_CHECK_MTIME |
				                           TRACKER_DIRECTORY_FLAG_MONITOR);
				g_ptr_array_add (proxy_folders, g_object_ref (file));
			} else {
				tracker_indexing_tree_notify_update (indexing_tree,
				                                     file, TRUE);
			}
		} else {
			tracker_miner_fs_check_file (TRACKER_MINER_FS (miner),
			                             file, G_PRIORITY_HIGH, TRUE);
		}

		g_object_unref (file_info);
		g_object_unref (file);
	}

	g_free (indexed_uris);
}

static void
proxy_properties_changed_cb (GDBusProxy *proxy,
                             GVariant   *changed_properties,
                             GStrv       invalidated_properties,
                             gpointer    user_data)
{
	update_indexed_files_from_proxy (user_data, proxy);
}

static void
on_tracker_index_proxy_ready (GObject      *source,
                              GAsyncResult *res,
                              gpointer      user_data)
{
	TrackerMinerFiles *miner = user_data;
	GError *error = NULL;

	index_proxy = g_dbus_proxy_new_finish (res, &error);
	if (error) {
		g_critical ("Could not set up proxy: %s", error->message);
		g_error_free (error);
		return;
	}

	g_signal_connect (index_proxy, "g-properties-changed",
	                  G_CALLBACK (proxy_properties_changed_cb), miner);
	update_indexed_files_from_proxy (miner, index_proxy);
}

951
952
953
954
int
main (gint argc, gchar *argv[])
{
	TrackerConfig *config;
955
	TrackerMiner *miner_files;
956
957
	GOptionContext *context;
	GError *error = NULL;
958
	gboolean do_mtime_checking;
959
	gboolean force_mtime_checking = FALSE;
960
961
	TrackerMinerProxy *proxy;
	GDBusConnection *connection;
962
963
	TrackerSparqlConnection *sparql_conn;
	TrackerEndpointDBus *endpoint;
964
	TrackerDomainOntology *domain_ontology;
965
	GCancellable *cancellable;
966
967
968
#if GLIB_CHECK_VERSION (2, 64, 0)
	GMemoryMonitor *memory_monitor;
#endif
969
	gchar *domain_name, *dbus_name;
970

971
	main_loop = NULL;
972
973
974
975
976
977
978
979
980
981

	setlocale (LC_ALL, "");

	bindtextdomain (GETTEXT_PACKAGE, LOCALEDIR);
	bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
	textdomain (GETTEXT_PACKAGE);

	/* Set timezone info */
	tzset ();

982
983
984
	/* This makes sure we don't steal all the system's resources */
	initialize_priority_and_scheduling ();

985
986
987
	/* Translators: this messagge will apper immediately after the
	 * usage string - Usage: COMMAND <THIS_MESSAGE>
	 */
988
	context = g_option_context_new (_("— start the tracker indexer"));
989
990
991
992
993

	g_option_context_add_main_entries (context, entries, NULL);
	g_option_context_parse (context, &argc, &argv, &error);
	g_option_context_free (context);

994
995
996
997
998
999
	if (error) {
		g_printerr ("%s\n", error->message);
		g_error_free (error);
		return EXIT_FAILURE;
	}

Martyn Russell's avatar
Martyn Russell committed
1000
1001
1002
1003
	if (version) {
		g_print ("\n" ABOUT "\n" LICENSE "\n");
		return EXIT_SUCCESS;
	}
1004

1005
	if (eligible) {
1006
		return check_eligible ();
1007
1008
	}

1009
1010
	domain_ontology = tracker_domain_ontology_new (domain_ontology_name, NULL, &error);
	if (error) {
1011
1012
1013
1014
1015
1016
		g_critical ("Could not load domain ontology '%s': %s",
		            domain_ontology_name, error->message);
		g_error_free (error);
		return EXIT_FAILURE;
	}

1017
1018
1019
1020
1021
1022
1023
1024
	connection = g_bus_get_sync (TRACKER_IPC_BUS, NULL, &error);
	if (error) {
		g_critical ("Could not create DBus connection: %s\n",
		            error->message);
		g_error_free (error);
		return EXIT_FAILURE;
	}

1025
1026
1027
1028
1029
1030
1031
	/* Initialize logging */
	config = tracker_config_new ();

	if (initial_sleep > -1) {
		tracker_config_set_initial_sleep (config, initial_sleep);
	}

1032
	log_option_values (config);
1033

1034
1035
	main_loop = g_main_loop_new (NULL, FALSE);

Sam Thursfield's avatar
Sam Thursfield committed
1036
	if (no_daemon) {
1037
		g_debug ("tracker-miner-fs-3 running in --no-daemon mode.");
1038
	} else if (domain_ontology_name) {
1039
		domain_name = tracker_domain_ontology_get_domain (domain_ontology, NULL);
Sam Thursfield's avatar
Sam Thursfield committed
1040

1041
1042
1043
		g_debug ("tracker-miner-fs-3 running in --domain-ontology mode as "
		         "%s." DBUS_NAME_SUFFIX ". The service will exit when %s "
		         "disappears from the bus.", domain_name, domain_name);
Sam Thursfield's avatar
Sam Thursfield committed
1044

1045
		g_bus_watch_name_on_connection (connection, domain_name,
1046
1047
1048
		                                G_BUS_NAME_WATCHER_FLAGS_NONE,
		                                NULL, on_domain_vanished,
		                                main_loop, NULL);
1049
		g_free (domain_name);
Sam Thursfield's avatar
Sam Thursfield committed
1050
	} else {
1051
		g_debug ("tracker-miner-fs-3 running as org.freedesktop." DBUS_NAME_SUFFIX);
1052
1053
	}

1054
1055
1056
1057
1058
1059
	if (!dry_run) {
		GFile *store = get_cache_dir (domain_ontology);
		tracker_error_report_init (store);
		g_object_unref (store);
	}

1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
	if (!setup_connection_and_endpoint (domain_ontology,
	                                    connection,
	                                    &sparql_conn,
	                                    &endpoint,
	                                    &error)) {

		g_critical ("Could not create store/endpoint: %s",
		            error->message);
		g_error_free (error);

		return EXIT_FAILURE;
	}

1073
	/* Create new TrackerMinerFiles object */
1074
1075
	miner_files = tracker_miner_files_new (sparql_conn, config,
	                                       domain_ontology_name, &error);
1076
1077
1078
1079
1080
1081
1082
	if (!miner_files) {
		g_critical ("Couldn't create new Files miner: '%s'",
		            error ? error->message : "unknown error");
		g_object_unref (config);
		return EXIT_FAILURE;
	}

1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
	proxy_folders = g_ptr_array_new_with_free_func (g_object_unref);
	cancellable = g_cancellable_new ();
	g_dbus_proxy_new (connection,
	                  G_DBUS_PROXY_FLAGS_DO_NOT_AUTO_START,
	                  NULL,
	                  "org.freedesktop.Tracker3.Miner.Files.Control",
	                  "/org/freedesktop/Tracker3/Miner/Files/Proxy",
	                  "org.freedesktop.Tracker3.Miner.Files.Proxy",
	                  cancellable,
	                  on_tracker_index_proxy_ready,
	                  miner_files);

1095
	/* If the locales changed, we need to reset some things first */
1096
	detect_locale_changed (TRACKER_MINER (miner_files), domain_ontology);
1097

1098
1099
1100
1101
1102
1103
1104
1105
1106
	proxy = tracker_miner_proxy_new (miner_files, connection, DBUS_PATH, NULL, &error);
	if (error) {
		g_critical ("Couldn't create miner proxy: %s", error->message);
		g_error_free (error);
		g_object_unref (config);
		g_object_unref (miner_files);
		return EXIT_FAILURE;
	}

1107
	/* Request DBus name */
1108
	dbus_name = tracker_domain_ontology_get_domain (domain_ontology, DBUS_NAME_SUFFIX);
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119

	if (!tracker_dbus_request_name (connection, dbus_name, &error)) {
		g_critical ("Could not request DBus name '%s': %s",
		            dbus_name, error->message);
		g_error_free (error);
		g_free (dbus_name);
		return EXIT_FAILURE;
	}

	g_free (dbus_name);

1120
1121
1122
	/* Check if we should crawl and if we should force mtime
	 * checking based on the config.
	 */
1123
1124
	do_crawling = should_crawl (TRACKER_MINER_FILES (miner_files),
	                            config, &force_mtime_checking);
1125
1126
1127
1128
1129
1130
1131

	/* Get the last shutdown state to see if we need to perform a
	 * full mtime check against the db or not.
	 *
	 * Set to TRUE here in case we crash and miss file system
	 * events.
	 */
1132
	TRACKER_NOTE (CONFIG, g_message ("Checking whether to force mtime checking during crawling (based on last clean shutdown):"));
1133
1134
1135
1136
1137

	/* Override the shutdown state decision based on the config */
	if (force_mtime_checking) {
		do_mtime_checking = TRUE;
	} else {
1138
		do_mtime_checking = tracker_miner_files_get_need_mtime_check (TRACKER_MINER_FILES (miner_files));
1139
1140
	}

1141
1142
1143
	TRACKER_NOTE (CONFIG, g_message ("  %s %s",
	                      do_mtime_checking ? "Yes" : "No",
	                      force_mtime_checking ? "(forced from config)" : ""));
1144
1145
1146
1147
1148

	/* Set the need for an mtime check to TRUE so we check in the
	 * event of a crash, this is changed back on shutdown if
	 * everything appears to be fine.
	 */
1149
1150
1151
1152
	if (!dry_run) {
		tracker_miner_files_set_need_mtime_check (TRACKER_MINER_FILES (miner_files), TRUE);
		tracker_miner_files_set_mtime_checking (TRACKER_MINER_FILES (miner_files), do_mtime_checking);
	}
1153

1154
1155
1156
	g_signal_connect (miner_files, "started",
			  G_CALLBACK (miner_started_cb),
			  NULL);
1157
1158
	g_signal_connect (miner_files, "finished",
			  G_CALLBACK (miner_finished_cb),
1159
			  NULL);
1160

1161
1162
#if GLIB_CHECK_VERSION (2, 64, 0)
	memory_monitor = g_memory_monitor_dup_default ();
1163
	g_signal_connect (memory_monitor, "low-memory-warning", G_CALLBACK (on_low_memory), NULL);
1164
1165
#endif

1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
	/* Preempt creation of graphs */
	tracker_sparql_connection_update_async (tracker_miner_get_connection (miner_files),
	                                        "CREATE SILENT GRAPH tracker:FileSystem; "
	                                        "CREATE SILENT GRAPH tracker:Software; "
	                                        "CREATE SILENT GRAPH tracker:Documents; "
	                                        "CREATE SILENT GRAPH tracker:Pictures; "
	                                        "CREATE SILENT GRAPH tracker:Audio; "
	                                        "CREATE SILENT GRAPH tracker:Video ",
	                                        NULL, graphs_created_cb, miner_files);

1176
	if (do_crawling)
1177
		miner_start (miner_files, config, do_mtime_checking);
1178

1179
1180
	initialize_signal_handler ();

1181
	/* Go, go, go! */
1182
1183
	g_main_loop_run (main_loop);

1184
	g_debug ("Shutdown started");
1185

1186
	if (!dry_run && miners_timeout_id == 0 && !miner_needs_check (miner_files)) {
1187
1188
		tracker_miner_files_set_need_mtime_check (TRACKER_MINER_FILES (miner_files), FALSE);
		save_current_locale (domain_ontology);
1189
1190
	}

1191
1192
1193
	g_main_loop_unref (main_loop);
	g_object_unref (config);

1194
1195
1196
1197
1198
	g_cancellable_cancel (cancellable);
	g_object_unref (cancellable);
	g_clear_object (&index_proxy);
	g_clear_pointer (&proxy_folders, g_ptr_array_unref);

1199
	g_object_unref (miner_files);
1200

1201
1202
	g_object_unref (proxy);
	g_object_unref (connection);
1203
	tracker_domain_ontology_unref (domain_ontology);
1204

1205
1206
1207
	tracker_sparql_connection_close (sparql_conn);
	g_object_unref (sparql_conn);

1208
1209
1210
1211
1212
#if GLIB_CHECK_VERSION (2, 64, 0)
	g_signal_handlers_disconnect_by_func (memory_monitor, on_low_memory, NULL);
	g_object_unref (memory_monitor);
#endif

1213
1214
1215
1216
	g_print ("\nOK\n\n");

	return EXIT_SUCCESS;
}