]> granicus.if.org Git - postgresql/blob - src/backend/utils/adt/misc.c
Use WaitLatch, not pg_usleep, for delaying in pg_sleep().
[postgresql] / src / backend / utils / adt / misc.c
1 /*-------------------------------------------------------------------------
2  *
3  * misc.c
4  *
5  *
6  * Portions Copyright (c) 1996-2013, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  *        src/backend/utils/adt/misc.c
12  *
13  *-------------------------------------------------------------------------
14  */
15 #include "postgres.h"
16
17 #include <sys/file.h>
18 #include <signal.h>
19 #include <dirent.h>
20 #include <math.h>
21 #include <unistd.h>
22
23 #include "catalog/catalog.h"
24 #include "catalog/pg_tablespace.h"
25 #include "catalog/pg_type.h"
26 #include "commands/dbcommands.h"
27 #include "common/relpath.h"
28 #include "funcapi.h"
29 #include "miscadmin.h"
30 #include "parser/keywords.h"
31 #include "postmaster/syslogger.h"
32 #include "rewrite/rewriteHandler.h"
33 #include "storage/fd.h"
34 #include "storage/pmsignal.h"
35 #include "storage/proc.h"
36 #include "storage/procarray.h"
37 #include "utils/lsyscache.h"
38 #include "tcop/tcopprot.h"
39 #include "utils/builtins.h"
40 #include "utils/timestamp.h"
41
42 #define atooid(x)  ((Oid) strtoul((x), NULL, 10))
43
44
45 /*
46  * current_database()
47  *      Expose the current database to the user
48  */
49 Datum
50 current_database(PG_FUNCTION_ARGS)
51 {
52         Name            db;
53
54         db = (Name) palloc(NAMEDATALEN);
55
56         namestrcpy(db, get_database_name(MyDatabaseId));
57         PG_RETURN_NAME(db);
58 }
59
60
61 /*
62  * current_query()
63  *      Expose the current query to the user (useful in stored procedures)
64  *      We might want to use ActivePortal->sourceText someday.
65  */
66 Datum
67 current_query(PG_FUNCTION_ARGS)
68 {
69         /* there is no easy way to access the more concise 'query_string' */
70         if (debug_query_string)
71                 PG_RETURN_TEXT_P(cstring_to_text(debug_query_string));
72         else
73                 PG_RETURN_NULL();
74 }
75
76 /*
77  * Send a signal to another backend.
78  *
79  * The signal is delivered if the user is either a superuser or the same
80  * role as the backend being signaled. For "dangerous" signals, an explicit
81  * check for superuser needs to be done prior to calling this function.
82  *
83  * Returns 0 on success, 1 on general failure, and 2 on permission error.
84  * In the event of a general failure (return code 1), a warning message will
85  * be emitted. For permission errors, doing that is the responsibility of
86  * the caller.
87  */
88 #define SIGNAL_BACKEND_SUCCESS 0
89 #define SIGNAL_BACKEND_ERROR 1
90 #define SIGNAL_BACKEND_NOPERMISSION 2
91 static int
92 pg_signal_backend(int pid, int sig)
93 {
94         PGPROC     *proc = BackendPidGetProc(pid);
95
96         /*
97          * BackendPidGetProc returns NULL if the pid isn't valid; but by the time
98          * we reach kill(), a process for which we get a valid proc here might
99          * have terminated on its own.  There's no way to acquire a lock on an
100          * arbitrary process to prevent that. But since so far all the callers of
101          * this mechanism involve some request for ending the process anyway, that
102          * it might end on its own first is not a problem.
103          */
104         if (proc == NULL)
105         {
106                 /*
107                  * This is just a warning so a loop-through-resultset will not abort
108                  * if one backend terminated on its own during the run.
109                  */
110                 ereport(WARNING,
111                                 (errmsg("PID %d is not a PostgreSQL server process", pid)));
112                 return SIGNAL_BACKEND_ERROR;
113         }
114
115         if (!(superuser() || proc->roleId == GetUserId()))
116                 return SIGNAL_BACKEND_NOPERMISSION;
117
118         /*
119          * Can the process we just validated above end, followed by the pid being
120          * recycled for a new process, before reaching here?  Then we'd be trying
121          * to kill the wrong thing.  Seems near impossible when sequential pid
122          * assignment and wraparound is used.  Perhaps it could happen on a system
123          * where pid re-use is randomized.      That race condition possibility seems
124          * too unlikely to worry about.
125          */
126
127         /* If we have setsid(), signal the backend's whole process group */
128 #ifdef HAVE_SETSID
129         if (kill(-pid, sig))
130 #else
131         if (kill(pid, sig))
132 #endif
133         {
134                 /* Again, just a warning to allow loops */
135                 ereport(WARNING,
136                                 (errmsg("could not send signal to process %d: %m", pid)));
137                 return SIGNAL_BACKEND_ERROR;
138         }
139         return SIGNAL_BACKEND_SUCCESS;
140 }
141
142 /*
143  * Signal to cancel a backend process.  This is allowed if you are superuser or
144  * have the same role as the process being canceled.
145  */
146 Datum
147 pg_cancel_backend(PG_FUNCTION_ARGS)
148 {
149         int                     r = pg_signal_backend(PG_GETARG_INT32(0), SIGINT);
150
151         if (r == SIGNAL_BACKEND_NOPERMISSION)
152                 ereport(ERROR,
153                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
154                                  (errmsg("must be superuser or have the same role to cancel queries running in other server processes"))));
155
156         PG_RETURN_BOOL(r == SIGNAL_BACKEND_SUCCESS);
157 }
158
159 /*
160  * Signal to terminate a backend process.  This is allowed if you are superuser
161  * or have the same role as the process being terminated.
162  */
163 Datum
164 pg_terminate_backend(PG_FUNCTION_ARGS)
165 {
166         int                     r = pg_signal_backend(PG_GETARG_INT32(0), SIGTERM);
167
168         if (r == SIGNAL_BACKEND_NOPERMISSION)
169                 ereport(ERROR,
170                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
171                                  (errmsg("must be superuser or have the same role to terminate other server processes"))));
172
173         PG_RETURN_BOOL(r == SIGNAL_BACKEND_SUCCESS);
174 }
175
176 /*
177  * Signal to reload the database configuration
178  */
179 Datum
180 pg_reload_conf(PG_FUNCTION_ARGS)
181 {
182         if (!superuser())
183                 ereport(ERROR,
184                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
185                                  (errmsg("must be superuser to signal the postmaster"))));
186
187         if (kill(PostmasterPid, SIGHUP))
188         {
189                 ereport(WARNING,
190                                 (errmsg("failed to send signal to postmaster: %m")));
191                 PG_RETURN_BOOL(false);
192         }
193
194         PG_RETURN_BOOL(true);
195 }
196
197
198 /*
199  * Rotate log file
200  */
201 Datum
202 pg_rotate_logfile(PG_FUNCTION_ARGS)
203 {
204         if (!superuser())
205                 ereport(ERROR,
206                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
207                                  (errmsg("must be superuser to rotate log files"))));
208
209         if (!Logging_collector)
210         {
211                 ereport(WARNING,
212                 (errmsg("rotation not possible because log collection not active")));
213                 PG_RETURN_BOOL(false);
214         }
215
216         SendPostmasterSignal(PMSIGNAL_ROTATE_LOGFILE);
217         PG_RETURN_BOOL(true);
218 }
219
220 /* Function to find out which databases make use of a tablespace */
221
222 typedef struct
223 {
224         char       *location;
225         DIR                *dirdesc;
226 } ts_db_fctx;
227
228 Datum
229 pg_tablespace_databases(PG_FUNCTION_ARGS)
230 {
231         FuncCallContext *funcctx;
232         struct dirent *de;
233         ts_db_fctx *fctx;
234
235         if (SRF_IS_FIRSTCALL())
236         {
237                 MemoryContext oldcontext;
238                 Oid                     tablespaceOid = PG_GETARG_OID(0);
239
240                 funcctx = SRF_FIRSTCALL_INIT();
241                 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
242
243                 fctx = palloc(sizeof(ts_db_fctx));
244
245                 /*
246                  * size = tablespace dirname length + dir sep char + oid + terminator
247                  */
248                 fctx->location = (char *) palloc(9 + 1 + OIDCHARS + 1 +
249                                                                    strlen(TABLESPACE_VERSION_DIRECTORY) + 1);
250                 if (tablespaceOid == GLOBALTABLESPACE_OID)
251                 {
252                         fctx->dirdesc = NULL;
253                         ereport(WARNING,
254                                         (errmsg("global tablespace never has databases")));
255                 }
256                 else
257                 {
258                         if (tablespaceOid == DEFAULTTABLESPACE_OID)
259                                 sprintf(fctx->location, "base");
260                         else
261                                 sprintf(fctx->location, "pg_tblspc/%u/%s", tablespaceOid,
262                                                 TABLESPACE_VERSION_DIRECTORY);
263
264                         fctx->dirdesc = AllocateDir(fctx->location);
265
266                         if (!fctx->dirdesc)
267                         {
268                                 /* the only expected error is ENOENT */
269                                 if (errno != ENOENT)
270                                         ereport(ERROR,
271                                                         (errcode_for_file_access(),
272                                                          errmsg("could not open directory \"%s\": %m",
273                                                                         fctx->location)));
274                                 ereport(WARNING,
275                                           (errmsg("%u is not a tablespace OID", tablespaceOid)));
276                         }
277                 }
278                 funcctx->user_fctx = fctx;
279                 MemoryContextSwitchTo(oldcontext);
280         }
281
282         funcctx = SRF_PERCALL_SETUP();
283         fctx = (ts_db_fctx *) funcctx->user_fctx;
284
285         if (!fctx->dirdesc)                     /* not a tablespace */
286                 SRF_RETURN_DONE(funcctx);
287
288         while ((de = ReadDir(fctx->dirdesc, fctx->location)) != NULL)
289         {
290                 char       *subdir;
291                 DIR                *dirdesc;
292                 Oid                     datOid = atooid(de->d_name);
293
294                 /* this test skips . and .., but is awfully weak */
295                 if (!datOid)
296                         continue;
297
298                 /* if database subdir is empty, don't report tablespace as used */
299
300                 /* size = path length + dir sep char + file name + terminator */
301                 subdir = palloc(strlen(fctx->location) + 1 + strlen(de->d_name) + 1);
302                 sprintf(subdir, "%s/%s", fctx->location, de->d_name);
303                 dirdesc = AllocateDir(subdir);
304                 while ((de = ReadDir(dirdesc, subdir)) != NULL)
305                 {
306                         if (strcmp(de->d_name, ".") != 0 && strcmp(de->d_name, "..") != 0)
307                                 break;
308                 }
309                 FreeDir(dirdesc);
310                 pfree(subdir);
311
312                 if (!de)
313                         continue;                       /* indeed, nothing in it */
314
315                 SRF_RETURN_NEXT(funcctx, ObjectIdGetDatum(datOid));
316         }
317
318         FreeDir(fctx->dirdesc);
319         SRF_RETURN_DONE(funcctx);
320 }
321
322
323 /*
324  * pg_tablespace_location - get location for a tablespace
325  */
326 Datum
327 pg_tablespace_location(PG_FUNCTION_ARGS)
328 {
329         Oid                     tablespaceOid = PG_GETARG_OID(0);
330         char            sourcepath[MAXPGPATH];
331         char            targetpath[MAXPGPATH];
332         int                     rllen;
333
334         /*
335          * It's useful to apply this function to pg_class.reltablespace, wherein
336          * zero means "the database's default tablespace".      So, rather than
337          * throwing an error for zero, we choose to assume that's what is meant.
338          */
339         if (tablespaceOid == InvalidOid)
340                 tablespaceOid = MyDatabaseTableSpace;
341
342         /*
343          * Return empty string for the cluster's default tablespaces
344          */
345         if (tablespaceOid == DEFAULTTABLESPACE_OID ||
346                 tablespaceOid == GLOBALTABLESPACE_OID)
347                 PG_RETURN_TEXT_P(cstring_to_text(""));
348
349 #if defined(HAVE_READLINK) || defined(WIN32)
350
351         /*
352          * Find the location of the tablespace by reading the symbolic link that
353          * is in pg_tblspc/<oid>.
354          */
355         snprintf(sourcepath, sizeof(sourcepath), "pg_tblspc/%u", tablespaceOid);
356
357         rllen = readlink(sourcepath, targetpath, sizeof(targetpath));
358         if (rllen < 0)
359                 ereport(ERROR,
360                                 (errmsg("could not read symbolic link \"%s\": %m",
361                                                 sourcepath)));
362         else if (rllen >= sizeof(targetpath))
363                 ereport(ERROR,
364                                 (errmsg("symbolic link \"%s\" target is too long",
365                                                 sourcepath)));
366         targetpath[rllen] = '\0';
367
368         PG_RETURN_TEXT_P(cstring_to_text(targetpath));
369 #else
370         ereport(ERROR,
371                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
372                          errmsg("tablespaces are not supported on this platform")));
373         PG_RETURN_NULL();
374 #endif
375 }
376
377 /*
378  * pg_sleep - delay for N seconds
379  */
380 Datum
381 pg_sleep(PG_FUNCTION_ARGS)
382 {
383         float8          secs = PG_GETARG_FLOAT8(0);
384         float8          endtime;
385
386         /*
387          * We sleep using WaitLatch, to ensure that we'll wake up promptly if an
388          * important signal (such as SIGALRM or SIGINT) arrives.  Because
389          * WaitLatch's upper limit of delay is INT_MAX milliseconds, and the user
390          * might ask for more than that, we sleep for at most 10 minutes and then
391          * loop.
392          *
393          * By computing the intended stop time initially, we avoid accumulation of
394          * extra delay across multiple sleeps.  This also ensures we won't delay
395          * less than the specified time when WaitLatch is terminated early by a
396          * non-query-cancelling signal such as SIGHUP.
397          */
398
399 #ifdef HAVE_INT64_TIMESTAMP
400 #define GetNowFloat()   ((float8) GetCurrentTimestamp() / 1000000.0)
401 #else
402 #define GetNowFloat()   GetCurrentTimestamp()
403 #endif
404
405         endtime = GetNowFloat() + secs;
406
407         for (;;)
408         {
409                 float8          delay;
410                 long            delay_ms;
411
412                 CHECK_FOR_INTERRUPTS();
413
414                 delay = endtime - GetNowFloat();
415                 if (delay >= 600.0)
416                         delay_ms = 600000;
417                 else if (delay > 0.0)
418                         delay_ms = (long) ceil(delay * 1000.0);
419                 else
420                         break;
421
422                 (void) WaitLatch(&MyProc->procLatch,
423                                                  WL_LATCH_SET | WL_TIMEOUT,
424                                                  delay_ms);
425                 ResetLatch(&MyProc->procLatch);
426         }
427
428         PG_RETURN_VOID();
429 }
430
431 /* Function to return the list of grammar keywords */
432 Datum
433 pg_get_keywords(PG_FUNCTION_ARGS)
434 {
435         FuncCallContext *funcctx;
436
437         if (SRF_IS_FIRSTCALL())
438         {
439                 MemoryContext oldcontext;
440                 TupleDesc       tupdesc;
441
442                 funcctx = SRF_FIRSTCALL_INIT();
443                 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
444
445                 tupdesc = CreateTemplateTupleDesc(3, false);
446                 TupleDescInitEntry(tupdesc, (AttrNumber) 1, "word",
447                                                    TEXTOID, -1, 0);
448                 TupleDescInitEntry(tupdesc, (AttrNumber) 2, "catcode",
449                                                    CHAROID, -1, 0);
450                 TupleDescInitEntry(tupdesc, (AttrNumber) 3, "catdesc",
451                                                    TEXTOID, -1, 0);
452
453                 funcctx->attinmeta = TupleDescGetAttInMetadata(tupdesc);
454
455                 MemoryContextSwitchTo(oldcontext);
456         }
457
458         funcctx = SRF_PERCALL_SETUP();
459
460         if (funcctx->call_cntr < NumScanKeywords)
461         {
462                 char       *values[3];
463                 HeapTuple       tuple;
464
465                 /* cast-away-const is ugly but alternatives aren't much better */
466                 values[0] = (char *) ScanKeywords[funcctx->call_cntr].name;
467
468                 switch (ScanKeywords[funcctx->call_cntr].category)
469                 {
470                         case UNRESERVED_KEYWORD:
471                                 values[1] = "U";
472                                 values[2] = _("unreserved");
473                                 break;
474                         case COL_NAME_KEYWORD:
475                                 values[1] = "C";
476                                 values[2] = _("unreserved (cannot be function or type name)");
477                                 break;
478                         case TYPE_FUNC_NAME_KEYWORD:
479                                 values[1] = "T";
480                                 values[2] = _("reserved (can be function or type name)");
481                                 break;
482                         case RESERVED_KEYWORD:
483                                 values[1] = "R";
484                                 values[2] = _("reserved");
485                                 break;
486                         default:                        /* shouldn't be possible */
487                                 values[1] = NULL;
488                                 values[2] = NULL;
489                                 break;
490                 }
491
492                 tuple = BuildTupleFromCStrings(funcctx->attinmeta, values);
493
494                 SRF_RETURN_NEXT(funcctx, HeapTupleGetDatum(tuple));
495         }
496
497         SRF_RETURN_DONE(funcctx);
498 }
499
500
501 /*
502  * Return the type of the argument.
503  */
504 Datum
505 pg_typeof(PG_FUNCTION_ARGS)
506 {
507         PG_RETURN_OID(get_fn_expr_argtype(fcinfo->flinfo, 0));
508 }
509
510
511 /*
512  * Implementation of the COLLATE FOR expression; returns the collation
513  * of the argument.
514  */
515 Datum
516 pg_collation_for(PG_FUNCTION_ARGS)
517 {
518         Oid                     typeid;
519         Oid                     collid;
520
521         typeid = get_fn_expr_argtype(fcinfo->flinfo, 0);
522         if (!typeid)
523                 PG_RETURN_NULL();
524         if (!type_is_collatable(typeid) && typeid != UNKNOWNOID)
525                 ereport(ERROR,
526                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
527                                  errmsg("collations are not supported by type %s",
528                                                 format_type_be(typeid))));
529
530         collid = PG_GET_COLLATION();
531         if (!collid)
532                 PG_RETURN_NULL();
533         PG_RETURN_TEXT_P(cstring_to_text(generate_collation_name(collid)));
534 }
535
536
537 /*
538  * pg_relation_is_updatable - determine which update events the specified
539  * relation supports.
540  *
541  * This relies on relation_is_updatable() in rewriteHandler.c, which see
542  * for additional information.
543  */
544 Datum
545 pg_relation_is_updatable(PG_FUNCTION_ARGS)
546 {
547         Oid                     reloid = PG_GETARG_OID(0);
548         bool            include_triggers = PG_GETARG_BOOL(1);
549
550         PG_RETURN_INT32(relation_is_updatable(reloid, include_triggers));
551 }
552
553 /*
554  * pg_column_is_updatable - determine whether a column is updatable
555  *
556  * Currently we just check whether the column's relation is updatable.
557  * Eventually we might allow views to have some updatable and some
558  * non-updatable columns.
559  *
560  * Also, this function encapsulates the decision about just what
561  * information_schema.columns.is_updatable actually means.      It's not clear
562  * whether deletability of the column's relation should be required, so
563  * we want that decision in C code where we could change it without initdb.
564  */
565 Datum
566 pg_column_is_updatable(PG_FUNCTION_ARGS)
567 {
568         Oid                     reloid = PG_GETARG_OID(0);
569         AttrNumber      attnum = PG_GETARG_INT16(1);
570         bool            include_triggers = PG_GETARG_BOOL(2);
571         int                     events;
572
573         /* System columns are never updatable */
574         if (attnum <= 0)
575                 PG_RETURN_BOOL(false);
576
577         events = relation_is_updatable(reloid, include_triggers);
578
579         /* We require both updatability and deletability of the relation */
580 #define REQ_EVENTS ((1 << CMD_UPDATE) | (1 << CMD_DELETE))
581
582         PG_RETURN_BOOL((events & REQ_EVENTS) == REQ_EVENTS);
583 }