]> git.openstreetmap.org Git - nominatim.git/blob - nominatim/index.c
ca301f45b305ea5826f214fb90f5504b7ae00ed1
[nominatim.git] / nominatim / index.c
1 /*
2  * triggers indexing (reparenting etc.) through setting resetting indexed_status: update placex/osmline set indexed_status = 0 where indexed_status > 0
3  * triggers placex_update and osmline_update
4 */
5
6 #include <stdio.h>
7 #include <unistd.h>
8 #include <stdlib.h>
9 #include <string.h>
10 #include <assert.h>
11 #include <pthread.h>
12 #include <time.h>
13 #include <stdint.h>
14
15 #include <libpq-fe.h>
16
17 #include "nominatim.h"
18 #include "index.h"
19 #include "export.h"
20 #include "postgresql.h"
21
22 extern int verbose;
23
24 void run_indexing(int rank, int interpolation, PGconn *conn, int num_threads, 
25 struct index_thread_data * thread_data, const char *structuredoutputfile)
26 {
27     int tuples, count, sleepcount;
28     pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER;
29     
30     time_t rankStartTime;
31     int rankTotalTuples;
32     int rankCountTuples;
33     float rankPerSecond;
34     
35     PGresult * resSectors;
36     PGresult * resPlaces;
37     PGresult * resNULL;
38     
39     int i;
40     int iSector;
41     int iResult;
42     
43     const char *paramValues[2];
44     int         paramLengths[2];
45     int         paramFormats[2];
46     uint32_t    paramRank;
47     uint32_t    paramSector;
48     uint32_t    sector;
49     
50     xmlTextWriterPtr writer;
51     pthread_mutex_t writer_mutex = PTHREAD_MUTEX_INITIALIZER;
52     
53     // Create the output file
54     writer = NULL;
55     if (structuredoutputfile)
56     {
57         writer = nominatim_exportXMLStart(structuredoutputfile);
58     }
59     
60     if (interpolation)
61     {
62         fprintf(stderr, "Starting interpolation lines (location_property_osmline)\n");
63     }
64     else
65     {
66         fprintf(stderr, "Starting rank %d\n", rank);
67     }
68     
69     rankCountTuples = 0;
70     rankPerSecond = 0;
71
72     paramRank = PGint32(rank);
73     paramValues[0] = (char *)&paramRank;
74     paramLengths[0] = sizeof(paramRank);
75     paramFormats[0] = 1;
76     
77     if (interpolation)
78     {
79         resSectors = PQexecPrepared(conn, "index_sectors_osmline", 0, NULL, 0, NULL, 1);
80     }
81     else
82     {
83         resSectors = PQexecPrepared(conn, "index_sectors", 1, paramValues, paramLengths, paramFormats, 1);
84     }
85     if (PQresultStatus(resSectors) != PGRES_TUPLES_OK)
86     {
87         fprintf(stderr, "index_sectors: SELECT failed: %s", PQerrorMessage(conn));
88         PQclear(resSectors);
89         exit(EXIT_FAILURE);
90     }
91     if (PQftype(resSectors, 0) != PG_OID_INT4)
92     {
93         fprintf(stderr, "Sector value has unexpected type\n");
94         PQclear(resSectors);
95         exit(EXIT_FAILURE);
96     }
97     if (PQftype(resSectors, 1) != PG_OID_INT8)
98     {
99         fprintf(stderr, "Sector value has unexpected type\n");
100         PQclear(resSectors);
101         exit(EXIT_FAILURE);
102     }
103     
104     rankTotalTuples = 0;
105     for (iSector = 0; iSector < PQntuples(resSectors); iSector++)
106     {
107         rankTotalTuples += PGint64(*((uint64_t *)PQgetvalue(resSectors, iSector, 1)));
108     }
109
110     rankStartTime = time(0);
111     for (iSector = 0; iSector <= PQntuples(resSectors); iSector++)
112     {
113         if (iSector > 0)
114         {
115             resPlaces = PQgetResult(conn);
116             if (PQresultStatus(resPlaces) != PGRES_TUPLES_OK)
117             {
118                 fprintf(stderr, "index_sector_places: SELECT failed: %s", PQerrorMessage(conn));
119                 PQclear(resPlaces);
120                 exit(EXIT_FAILURE);
121             }
122             if (PQftype(resPlaces, 0) != PG_OID_INT8)
123             {
124                 fprintf(stderr, "Place_id value has unexpected type\n");
125                 PQclear(resPlaces);
126                 exit(EXIT_FAILURE);
127             }
128             resNULL = PQgetResult(conn);
129             if (resNULL != NULL)
130             {
131                 fprintf(stderr, "Unexpected non-null response\n");
132                 exit(EXIT_FAILURE);
133             }
134         }
135
136         if (iSector < PQntuples(resSectors))
137         {
138             sector = PGint32(*((uint32_t *)PQgetvalue(resSectors, iSector, 0)));
139 //                fprintf(stderr, "\n Starting sector %d size %ld\n", sector, PGint64(*((uint64_t *)PQgetvalue(resSectors, iSector, 1))));
140
141             // Get all the place_id's for this sector
142             paramRank = PGint32(rank);
143             paramValues[0] = (char *)&paramRank;
144             paramLengths[0] = sizeof(paramRank);
145             paramFormats[0] = 1;
146             paramSector = PGint32(sector);
147             paramValues[1] = (char *)&paramSector;
148             paramLengths[1] = sizeof(paramSector);
149             paramFormats[1] = 1;
150             if (rankTotalTuples-rankCountTuples < num_threads*1000)
151             {
152                 // no sectors
153                 if (interpolation)
154                 {
155                     iResult = PQsendQueryPrepared(conn, "index_nosector_places_osmline", 0, NULL, 0, NULL, 1);
156                 }
157                 else
158                 {
159                     iResult = PQsendQueryPrepared(conn, "index_nosector_places", 1, paramValues, paramLengths, paramFormats, 1);
160                 }
161             }
162             else
163             {
164                 if (interpolation)
165                 {
166                                         iResult = PQsendQueryPrepared(conn, "index_sector_places_osmline", 1, paramValues, paramLengths, paramFormats, 1);
167
168                 }
169                 else
170                 {
171                     iResult = PQsendQueryPrepared(conn, "index_sector_places", 2, paramValues, paramLengths, paramFormats, 1);
172                 }
173             }
174             if (!iResult)
175             {
176                 fprintf(stderr, "index_sector_places: SELECT failed: %s", PQerrorMessage(conn));
177                 PQclear(resPlaces);
178                 exit(EXIT_FAILURE);
179             }
180         }
181         if (iSector > 0)
182         {
183             count = 0;
184             rankPerSecond = 0;
185             tuples = PQntuples(resPlaces);
186
187             if (tuples > 0)
188             {
189                 // Spawn threads
190                 for (i = 0; i < num_threads; i++)
191                 {
192                     thread_data[i].res = resPlaces;
193                     thread_data[i].tuples = tuples;
194                     thread_data[i].count = &count;
195                     thread_data[i].count_mutex = &count_mutex;
196                     thread_data[i].writer = writer;
197                     thread_data[i].writer_mutex = &writer_mutex;
198                     if (interpolation)
199                     {
200                         thread_data[i].table = 0;  // use interpolations table
201                     }
202                     else
203                     {
204                         thread_data[i].table = 1;  // use placex table
205                     }
206                     pthread_create(&thread_data[i].thread, NULL, &nominatim_indexThread, (void *)&thread_data[i]);
207                 }
208
209                 // Monitor threads to give user feedback
210                 sleepcount = 0;
211                 while (count < tuples)
212                 {
213                     usleep(1000);
214
215                     // Aim for one update per second
216                     if (sleepcount++ > 500)
217                     {
218                         rankPerSecond = ((float)rankCountTuples + (float)count) / MAX(difftime(time(0), rankStartTime),1);
219                         fprintf(stderr, "  Done %i in %i @ %f per second - Rank %i ETA (seconds): %f\n", (rankCountTuples + count), (int)(difftime(time(0), rankStartTime)), rankPerSecond, rank, ((float)(rankTotalTuples - (rankCountTuples + count)))/rankPerSecond);
220                         sleepcount = 0;
221                     }
222                 }
223
224                 // Wait for everything to finish
225                 for (i = 0; i < num_threads; i++)
226                 {
227                     pthread_join(thread_data[i].thread, NULL);
228                 }
229
230                 rankCountTuples += tuples;
231             }
232
233             // Finished sector
234             rankPerSecond = (float)rankCountTuples / MAX(difftime(time(0), rankStartTime),1);
235             fprintf(stderr, "  Done %i in %i @ %f per second - ETA (seconds): %f\n", rankCountTuples, (int)(difftime(time(0), rankStartTime)), rankPerSecond, ((float)(rankTotalTuples - rankCountTuples))/rankPerSecond);
236
237             PQclear(resPlaces);
238         }
239         if (rankTotalTuples-rankCountTuples < num_threads*20 && iSector < PQntuples(resSectors))
240         {
241             iSector = PQntuples(resSectors) - 1;
242         }
243     }
244     // Finished rank
245     fprintf(stderr, "\r  Done %i in %i @ %f per second - FINISHED\n\n", rankCountTuples, (int)(difftime(time(0), rankStartTime)), rankPerSecond);
246
247     PQclear(resSectors);
248 }
249
250 void nominatim_index(int rank_min, int rank_max, int num_threads, const char *conninfo, const char *structuredoutputfile)
251 {
252     struct index_thread_data * thread_data;
253
254     PGconn *conn;
255     PGresult * res;
256
257     int rank;
258     
259     int i;
260
261     xmlTextWriterPtr writer;
262     pthread_mutex_t writer_mutex = PTHREAD_MUTEX_INITIALIZER;
263
264     Oid pg_prepare_params[2];
265
266     conn = PQconnectdb(conninfo);
267     if (PQstatus(conn) != CONNECTION_OK)
268     {
269         fprintf(stderr, "Connection to database failed: %s\n", PQerrorMessage(conn));
270         exit(EXIT_FAILURE);
271     }
272
273     pg_prepare_params[0] = PG_OID_INT4;
274     res = PQprepare(conn, "index_sectors",
275                     "select geometry_sector,count(*) from placex where rank_search = $1 and indexed_status > 0 group by geometry_sector order by geometry_sector",
276                     1, pg_prepare_params);
277     if (PQresultStatus(res) != PGRES_COMMAND_OK)
278     {
279         fprintf(stderr, "Failed preparing index_sectors: %s\n", PQerrorMessage(conn));
280         exit(EXIT_FAILURE);
281     }
282     PQclear(res);
283     
284     res = PQprepare(conn, "index_sectors_osmline",
285                     "select geometry_sector,count(*) from location_property_osmline where indexed_status > 0 group by geometry_sector order by geometry_sector",
286                     0, NULL);
287     if (PQresultStatus(res) != PGRES_COMMAND_OK)
288     {
289         fprintf(stderr, "Failed preparing index_sectors: %s\n", PQerrorMessage(conn));
290         exit(EXIT_FAILURE);
291     }
292     PQclear(res);
293
294     pg_prepare_params[0] = PG_OID_INT4;
295     res = PQprepare(conn, "index_nosectors",
296                     "select 0::integer,count(*) from placex where rank_search = $1 and indexed_status > 0",
297                     1, pg_prepare_params);
298     if (PQresultStatus(res) != PGRES_COMMAND_OK)
299     {
300         fprintf(stderr, "Failed preparing index_sectors: %s\n", PQerrorMessage(conn));
301         exit(EXIT_FAILURE);
302     }
303     PQclear(res);
304
305     pg_prepare_params[0] = PG_OID_INT4;
306     pg_prepare_params[1] = PG_OID_INT4;
307     res = PQprepare(conn, "index_sector_places",
308                     "select place_id from placex where rank_search = $1 and geometry_sector = $2 and indexed_status > 0",
309                     2, pg_prepare_params);
310     if (PQresultStatus(res) != PGRES_COMMAND_OK)
311     {
312         fprintf(stderr, "Failed preparing index_sector_places: %s\n", PQerrorMessage(conn));
313         exit(EXIT_FAILURE);
314     }
315     PQclear(res);
316
317     pg_prepare_params[0] = PG_OID_INT4;
318     res = PQprepare(conn, "index_nosector_places",
319                     "select place_id from placex where rank_search = $1 and indexed_status > 0 order by geometry_sector",
320                     1, pg_prepare_params);
321     if (PQresultStatus(res) != PGRES_COMMAND_OK)
322     {
323         fprintf(stderr, "Failed preparing index_nosector_places: %s\n", PQerrorMessage(conn));
324         exit(EXIT_FAILURE);
325     }
326     PQclear(res);
327     
328     pg_prepare_params[0] = PG_OID_INT4;
329     res = PQprepare(conn, "index_sector_places_osmline",
330                     "select place_id from location_property_osmline where geometry_sector = $1 and indexed_status > 0",
331                     1, pg_prepare_params);
332     if (PQresultStatus(res) != PGRES_COMMAND_OK)
333     {
334         fprintf(stderr, "Failed preparing index_sector_places: %s\n", PQerrorMessage(conn));
335         exit(EXIT_FAILURE);
336     }
337     PQclear(res);
338     
339     res = PQprepare(conn, "index_nosector_places_osmline",
340                     "select place_id from location_property_osmline where indexed_status > 0 order by geometry_sector",
341                     0, NULL);
342     if (PQresultStatus(res) != PGRES_COMMAND_OK)
343     {
344         fprintf(stderr, "Failed preparing index_nosector_places: %s\n", PQerrorMessage(conn));
345         exit(EXIT_FAILURE);
346     }
347     PQclear(res);
348     
349     // Build the data for each thread
350     thread_data = (struct index_thread_data *)malloc(sizeof(struct index_thread_data)*num_threads);
351     for (i = 0; i < num_threads; i++)
352     {
353         thread_data[i].conn = PQconnectdb(conninfo);
354         if (PQstatus(thread_data[i].conn) != CONNECTION_OK)
355         {
356             fprintf(stderr, "Connection to database failed: %s\n", PQerrorMessage(thread_data[i].conn));
357             exit(EXIT_FAILURE);
358         }
359
360         pg_prepare_params[0] = PG_OID_INT8;
361         res = PQprepare(thread_data[i].conn, "index_placex",
362                         "update placex set indexed_status = 0 where place_id = $1",
363                         1, pg_prepare_params);
364         if (PQresultStatus(res) != PGRES_COMMAND_OK)
365         {
366             fprintf(stderr, "Failed preparing index_placex: %s\n", PQerrorMessage(conn));
367             exit(EXIT_FAILURE);
368         }
369         PQclear(res);
370         
371         pg_prepare_params[0] = PG_OID_INT8;
372         res = PQprepare(thread_data[i].conn, "index_osmline",
373                         "update location_property_osmline set indexed_status = 0 where place_id = $1",
374                         1, pg_prepare_params);
375         if (PQresultStatus(res) != PGRES_COMMAND_OK)
376         {
377             fprintf(stderr, "Failed preparing index_osmline: %s\n", PQerrorMessage(conn));
378             exit(EXIT_FAILURE);
379         }
380         PQclear(res);
381
382         /*res = PQexec(thread_data[i].conn, "set enable_seqscan = false");
383         if (PQresultStatus(res) != PGRES_COMMAND_OK)
384         {
385             fprintf(stderr, "Failed disabling sequential scan: %s\n", PQerrorMessage(conn));
386             exit(EXIT_FAILURE);
387         }
388         PQclear(res);*/
389
390         nominatim_exportCreatePreparedQueries(thread_data[i].conn);
391     }
392
393
394     fprintf(stderr, "Starting indexing rank (%i to %i) using %i threads\n", rank_min, rank_max, num_threads);
395
396     for (rank = rank_min; rank <= rank_max; rank++)
397     {
398         // OSMLINE: do reindexing (=> reparenting) for interpolation lines at rank 30, but before all other objects of rank 30
399         // reason: houses (rank 30) depend on the updated interpolation line, when reparenting (see placex_update in functions.sql)
400         if (rank == 30)
401         {
402             run_indexing(rank, 1, conn, num_threads, thread_data, structuredoutputfile);
403         }
404         run_indexing(rank, 0, conn, num_threads, thread_data, structuredoutputfile);
405     }
406         // Close all connections
407         for (i = 0; i < num_threads; i++)
408         {
409                 PQfinish(thread_data[i].conn);
410         }
411         PQfinish(conn);
412 }
413
414 void *nominatim_indexThread(void * thread_data_in)
415 {
416     struct index_thread_data * thread_data = (struct index_thread_data * )thread_data_in;
417     struct export_data  querySet;
418
419     PGresult   *res;
420
421     const char  *paramValues[1];
422     int         paramLengths[1];
423     int         paramFormats[1];
424     uint64_t    paramPlaceID;
425     uint64_t    place_id;
426     time_t      updateStartTime;
427     uint        table;
428     
429     table = (uint)(thread_data->table);
430
431     while (1)
432     {
433         pthread_mutex_lock( thread_data->count_mutex );
434         if (*(thread_data->count) >= thread_data->tuples)
435         {
436             pthread_mutex_unlock( thread_data->count_mutex );
437             break;
438         }
439
440         place_id = PGint64(*((uint64_t *)PQgetvalue(thread_data->res, *thread_data->count, 0)));
441         (*thread_data->count)++;
442
443         pthread_mutex_unlock( thread_data->count_mutex );
444
445         if (verbose) fprintf(stderr, "  Processing place_id %ld\n", place_id);
446
447         updateStartTime = time(0);
448         int done = 0;
449
450         if (thread_data->writer)
451         {
452              nominatim_exportPlaceQueries(place_id, thread_data->conn, &querySet);
453         }
454
455         while(!done)
456         {
457             paramPlaceID = PGint64(place_id);
458             paramValues[0] = (char *)&paramPlaceID;
459             paramLengths[0] = sizeof(paramPlaceID);
460             paramFormats[0] = 1;
461             if (table == 1) // table=1 for placex
462             {
463                 res = PQexecPrepared(thread_data->conn, "index_placex", 1, paramValues, paramLengths, paramFormats, 1);
464             }
465             else // table=0 for osmline
466             {
467                 res = PQexecPrepared(thread_data->conn, "index_osmline", 1, paramValues, paramLengths, paramFormats, 1);
468             }
469             if (PQresultStatus(res) == PGRES_COMMAND_OK)
470                 done = 1;
471             else
472             {
473                 if (!strncmp(PQerrorMessage(thread_data->conn), "ERROR:  deadlock detected", 25))
474                 {
475                     if (table == 1)
476                     {
477                         fprintf(stderr, "index_placex: UPDATE failed - deadlock, retrying (%ld)\n", place_id);
478                     }
479                     else
480                     {
481                         fprintf(stderr, "index_osmline: UPDATE failed - deadlock, retrying (%ld)\n", place_id);
482                     }
483                     PQclear(res);
484                     sleep(rand() % 10);
485                 }
486                 else
487                 {
488                     if (table == 1)
489                     {
490                         fprintf(stderr, "index_placex: UPDATE failed: %s", PQerrorMessage(thread_data->conn));
491                     }
492                     else
493                     {
494                         fprintf(stderr, "index_osmline: UPDATE failed: %s", PQerrorMessage(thread_data->conn));
495                     }
496                     PQclear(res);
497                     exit(EXIT_FAILURE);
498                 }
499             }
500         }
501         PQclear(res);
502         if (difftime(time(0), updateStartTime) > 1) fprintf(stderr, "  Slow place_id %ld\n", place_id);
503
504         if (thread_data->writer)
505         {
506             nominatim_exportPlace(place_id, thread_data->conn, thread_data->writer, thread_data->writer_mutex, &querySet);
507             nominatim_exportFreeQueries(&querySet);
508         }
509     }
510
511     return NULL;
512 }