Whamcloud - gitweb
842def4f07465f01b37e3f2025bde20ff5fddbdf
[fs/lustre-release.git] / lustre / obdclass / jobid.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License version 2 for more details (a copy is included
14  * in the LICENSE file that accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License
17  * version 2 along with this program; If not, see
18  * http://www.gnu.org/licenses/gpl-2.0.html
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2011, 2014, Intel Corporation.
27  *
28  * Copyright 2017 Cray Inc, all rights reserved.
29  * Author: Ben Evans.
30  *
31  * Store PID->JobID mappings
32  */
33
34 #define DEBUG_SUBSYSTEM S_RPC
35 #include <linux/user_namespace.h>
36 #ifdef HAVE_UIDGID_HEADER
37 #include <linux/uidgid.h>
38 #endif
39 #include <linux/utsname.h>
40
41 #include <libcfs/linux/linux-misc.h>
42 #include <obd_support.h>
43 #include <obd_class.h>
44 #include <lustre_net.h>
45
46 static struct cfs_hash *jobid_hash;
47 static struct cfs_hash_ops jobid_hash_ops;
48 spinlock_t jobid_hash_lock;
49
50 #define RESCAN_INTERVAL 30
51 #define DELETE_INTERVAL 300
52
53 char obd_jobid_var[JOBSTATS_JOBID_VAR_MAX_LEN + 1] = JOBSTATS_DISABLE;
54 char obd_jobid_name[LUSTRE_JOBID_SIZE] = "%e.%u";
55
56 /**
57  * Structure to store a single PID->JobID mapping
58  */
59 struct jobid_pid_map {
60         struct hlist_node       jp_hash;
61         time64_t                jp_time;
62         spinlock_t              jp_lock; /* protects jp_jobid */
63         char                    jp_jobid[LUSTRE_JOBID_SIZE];
64         unsigned int            jp_joblen;
65         atomic_t                jp_refcount;
66         pid_t                   jp_pid;
67 };
68
69 /*
70  * Get jobid of current process by reading the environment variable
71  * stored in between the "env_start" & "env_end" of task struct.
72  *
73  * If some job scheduler doesn't store jobid in the "env_start/end",
74  * then an upcall could be issued here to get the jobid by utilizing
75  * the userspace tools/API. Then, the jobid must be cached.
76  */
77 int jobid_get_from_environ(char *jobid_var, char *jobid, int *jobid_len)
78 {
79         static bool printed;
80         int rc;
81
82         rc = cfs_get_environ(jobid_var, jobid, jobid_len);
83         if (!rc)
84                 goto out;
85
86         if (unlikely(rc == -EOVERFLOW && !printed)) {
87                 /* For the PBS_JOBID and LOADL_STEP_ID keys (which are
88                  * variable length strings instead of just numbers), it
89                  * might make sense to keep the unique parts for JobID,
90                  * instead of just returning an error.  That means a
91                  * larger temp buffer for cfs_get_environ(), then
92                  * truncating the string at some separator to fit into
93                  * the specified jobid_len.  Fix later if needed. */
94                 LCONSOLE_ERROR_MSG(0x16b,
95                                    "jobid: '%s' value too large (%d)\n",
96                                    obd_jobid_var, *jobid_len);
97                 printed = true;
98                 rc = 0;
99         }
100         if (rc) {
101                 CDEBUG((rc == -ENOENT || rc == -EINVAL ||
102                         rc == -EDEADLK) ? D_INFO : D_ERROR,
103                        "jobid: get '%s' failed: rc = %d\n",
104                        obd_jobid_var, rc);
105         }
106
107 out:
108         return rc;
109 }
110
111 /*
112  * jobid_should_free_item
113  *
114  * Each item is checked to see if it should be released
115  * Removed from hash table by caller
116  * Actually freed in jobid_put_locked
117  *
118  * Returns 1 if item is to be freed, 0 if it is to be kept
119  */
120
121 static int jobid_should_free_item(void *obj, void *data)
122 {
123         char *jobid = data;
124         struct jobid_pid_map *pidmap = obj;
125         int rc = 0;
126
127         if (obj == NULL)
128                 return 0;
129
130         spin_lock(&pidmap->jp_lock);
131         if (jobid == NULL)
132                 rc = 1;
133         else if (jobid[0] == '\0')
134                 rc = 1;
135         else if (ktime_get_real_seconds() - pidmap->jp_time > DELETE_INTERVAL)
136                 rc = 1;
137         else if (strcmp(pidmap->jp_jobid, jobid) == 0)
138                 rc = 1;
139         spin_unlock(&pidmap->jp_lock);
140
141         return rc;
142 }
143
144 /*
145  * jobid_name_is_valid
146  *
147  * Checks if the jobid is a Lustre process
148  *
149  * Returns true if jobid is valid
150  * Returns false if jobid looks like it's a Lustre process
151  */
152 static bool jobid_name_is_valid(char *jobid)
153 {
154         const char *const lustre_reserved[] = { "ll_ping", "ptlrpc",
155                                                 "ldlm", "ll_sa", NULL };
156         int i;
157
158         if (jobid[0] == '\0')
159                 return false;
160
161         for (i = 0; lustre_reserved[i] != NULL; i++) {
162                 if (strncmp(jobid, lustre_reserved[i],
163                             strlen(lustre_reserved[i])) == 0)
164                         return false;
165         }
166         return true;
167 }
168
169 /*
170  * jobid_get_from_cache()
171  *
172  * Returns contents of jobid_var from process environment for current PID.
173  * This will be cached for some time to avoid overhead scanning environment.
174  *
175  * Return: -ENOMEM if allocating a new pidmap fails
176  *         -ENOENT if no entry could be found
177  *         +ve string length for success (something was returned in jobid)
178  */
179 static int jobid_get_from_cache(char *jobid, size_t joblen)
180 {
181         static time64_t last_expire;
182         bool expire_cache = false;
183         pid_t pid = current_pid();
184         struct jobid_pid_map *pidmap = NULL;
185         time64_t now = ktime_get_real_seconds();
186         int rc = 0;
187         ENTRY;
188
189         LASSERT(jobid_hash != NULL);
190
191         /* scan hash periodically to remove old PID entries from cache */
192         spin_lock(&jobid_hash_lock);
193         if (unlikely(last_expire + DELETE_INTERVAL <= now)) {
194                 expire_cache = true;
195                 last_expire = now;
196         }
197         spin_unlock(&jobid_hash_lock);
198
199         if (expire_cache)
200                 cfs_hash_cond_del(jobid_hash, jobid_should_free_item,
201                                   "intentionally_bad_jobid");
202
203         /* first try to find PID in the hash and use that value */
204         pidmap = cfs_hash_lookup(jobid_hash, &pid);
205         if (pidmap == NULL) {
206                 struct jobid_pid_map *pidmap2;
207
208                 OBD_ALLOC_PTR(pidmap);
209                 if (pidmap == NULL)
210                         GOTO(out, rc = -ENOMEM);
211
212                 pidmap->jp_pid = pid;
213                 pidmap->jp_time = 0;
214                 pidmap->jp_jobid[0] = '\0';
215                 spin_lock_init(&pidmap->jp_lock);
216                 INIT_HLIST_NODE(&pidmap->jp_hash);
217
218                 /*
219                  * Add the newly created map to the hash, on key collision we
220                  * lost a racing addition and must destroy our newly allocated
221                  * map.  The object which exists in the hash will be returned.
222                  */
223                 pidmap2 = cfs_hash_findadd_unique(jobid_hash, &pid,
224                                                   &pidmap->jp_hash);
225                 if (unlikely(pidmap != pidmap2)) {
226                         CDEBUG(D_INFO, "jobid: duplicate found for PID=%u\n",
227                                pid);
228                         OBD_FREE_PTR(pidmap);
229                         pidmap = pidmap2;
230                 } else {
231                         cfs_hash_get(jobid_hash, &pidmap->jp_hash);
232                 }
233         }
234
235         /*
236          * If pidmap is old (this is always true for new entries) refresh it.
237          * If obd_jobid_var is not found, cache empty entry and try again
238          * later, to avoid repeat lookups for PID if obd_jobid_var missing.
239          */
240         spin_lock(&pidmap->jp_lock);
241         if (pidmap->jp_time + RESCAN_INTERVAL <= now) {
242                 char env_jobid[LUSTRE_JOBID_SIZE] = "";
243                 int env_len = sizeof(env_jobid);
244
245                 pidmap->jp_time = now;
246
247                 spin_unlock(&pidmap->jp_lock);
248                 rc = jobid_get_from_environ(obd_jobid_var, env_jobid, &env_len);
249
250                 CDEBUG(D_INFO, "jobid: PID mapping established: %d->%s\n",
251                        pidmap->jp_pid, env_jobid);
252                 spin_lock(&pidmap->jp_lock);
253                 if (!rc) {
254                         pidmap->jp_joblen = env_len;
255                         strlcpy(pidmap->jp_jobid, env_jobid,
256                                 sizeof(pidmap->jp_jobid));
257                         rc = 0;
258                 } else if (rc == -ENOENT) {
259                         /* It might have been deleted, clear out old entry */
260                         pidmap->jp_joblen = 0;
261                         pidmap->jp_jobid[0] = '\0';
262                 }
263         }
264
265         /*
266          * Regardless of how pidmap was found, if it contains a valid entry
267          * use that for now.  If there was a technical error (e.g. -ENOMEM)
268          * use the old cached value until it can be looked up again properly.
269          * If a cached missing entry was found, return -ENOENT.
270          */
271         if (pidmap->jp_joblen) {
272                 strlcpy(jobid, pidmap->jp_jobid, joblen);
273                 joblen = pidmap->jp_joblen;
274                 rc = 0;
275         } else if (!rc) {
276                 rc = -ENOENT;
277         }
278         spin_unlock(&pidmap->jp_lock);
279
280         cfs_hash_put(jobid_hash, &pidmap->jp_hash);
281
282         EXIT;
283 out:
284         return rc < 0 ? rc : joblen;
285 }
286
287 /*
288  * jobid_interpret_string()
289  *
290  * Interpret the jobfmt string to expand specified fields, like coredumps do:
291  *   %e = executable
292  *   %g = gid
293  *   %h = hostname
294  *   %j = jobid from environment
295  *   %p = pid
296  *   %u = uid
297  *
298  * Unknown escape strings are dropped.  Other characters are copied through,
299  * excluding whitespace (to avoid making jobid parsing difficult).
300  *
301  * Return: -EOVERFLOW if the expanded string does not fit within @joblen
302  *         0 for success
303  */
304 static int jobid_interpret_string(const char *jobfmt, char *jobid,
305                                   ssize_t joblen)
306 {
307         char c;
308
309         while ((c = *jobfmt++) && joblen > 1) {
310                 char f;
311                 int l;
312
313                 if (isspace(c)) /* Don't allow embedded spaces */
314                         continue;
315
316                 if (c != '%') {
317                         *jobid = c;
318                         joblen--;
319                         jobid++;
320                         continue;
321                 }
322
323                 switch ((f = *jobfmt++)) {
324                 case 'e': /* executable name */
325                         l = snprintf(jobid, joblen, "%s", current_comm());
326                         break;
327                 case 'g': /* group ID */
328                         l = snprintf(jobid, joblen, "%u",
329                                      from_kgid(&init_user_ns, current_fsgid()));
330                         break;
331                 case 'h': /* hostname */
332                         l = snprintf(jobid, joblen, "%s",
333                                      init_utsname()->nodename);
334                         break;
335                 case 'j': /* jobid stored in process environment */
336                         l = jobid_get_from_cache(jobid, joblen);
337                         if (l < 0)
338                                 l = 0;
339                         break;
340                 case 'p': /* process ID */
341                         l = snprintf(jobid, joblen, "%u", current_pid());
342                         break;
343                 case 'u': /* user ID */
344                         l = snprintf(jobid, joblen, "%u",
345                                      from_kuid(&init_user_ns, current_fsuid()));
346                         break;
347                 case '\0': /* '%' at end of format string */
348                         l = 0;
349                         goto out;
350                 default: /* drop unknown %x format strings */
351                         l = 0;
352                         break;
353                 }
354                 jobid += l;
355                 joblen -= l;
356         }
357         /*
358          * This points at the end of the buffer, so long as jobid is always
359          * incremented the same amount as joblen is decremented.
360          */
361 out:
362         jobid[joblen - 1] = '\0';
363
364         return joblen < 0 ? -EOVERFLOW : 0;
365 }
366
367 /*
368  * Hash initialization, copied from server-side job stats bucket sizes
369  */
370 #define HASH_JOBID_BKT_BITS 5
371 #define HASH_JOBID_CUR_BITS 7
372 #define HASH_JOBID_MAX_BITS 12
373
374 int jobid_cache_init(void)
375 {
376         int rc = 0;
377         ENTRY;
378
379         if (jobid_hash)
380                 return 0;
381
382         spin_lock_init(&jobid_hash_lock);
383         jobid_hash = cfs_hash_create("JOBID_HASH", HASH_JOBID_CUR_BITS,
384                                      HASH_JOBID_MAX_BITS, HASH_JOBID_BKT_BITS,
385                                      0, CFS_HASH_MIN_THETA, CFS_HASH_MAX_THETA,
386                                      &jobid_hash_ops, CFS_HASH_DEFAULT);
387         if (!jobid_hash)
388                 rc = -ENOMEM;
389
390         RETURN(rc);
391 }
392 EXPORT_SYMBOL(jobid_cache_init);
393
394 void jobid_cache_fini(void)
395 {
396         struct cfs_hash *tmp_hash;
397         ENTRY;
398
399         spin_lock(&jobid_hash_lock);
400         tmp_hash = jobid_hash;
401         jobid_hash = NULL;
402         spin_unlock(&jobid_hash_lock);
403
404         if (tmp_hash != NULL) {
405                 cfs_hash_cond_del(tmp_hash, jobid_should_free_item, NULL);
406                 cfs_hash_putref(tmp_hash);
407         }
408
409         EXIT;
410 }
411 EXPORT_SYMBOL(jobid_cache_fini);
412
413 /*
414  * Hash operations for pid<->jobid
415  */
416 static unsigned jobid_hashfn(struct cfs_hash *hs, const void *key,
417                              unsigned mask)
418 {
419         return cfs_hash_djb2_hash(key, sizeof(pid_t), mask);
420 }
421
422 static void *jobid_key(struct hlist_node *hnode)
423 {
424         struct jobid_pid_map *pidmap;
425
426         pidmap = hlist_entry(hnode, struct jobid_pid_map, jp_hash);
427         return &pidmap->jp_pid;
428 }
429
430 static int jobid_keycmp(const void *key, struct hlist_node *hnode)
431 {
432         const pid_t *pid_key1;
433         const pid_t *pid_key2;
434
435         LASSERT(key != NULL);
436         pid_key1 = (pid_t *)key;
437         pid_key2 = (pid_t *)jobid_key(hnode);
438
439         return *pid_key1 == *pid_key2;
440 }
441
442 static void *jobid_object(struct hlist_node *hnode)
443 {
444         return hlist_entry(hnode, struct jobid_pid_map, jp_hash);
445 }
446
447 static void jobid_get(struct cfs_hash *hs, struct hlist_node *hnode)
448 {
449         struct jobid_pid_map *pidmap;
450
451         pidmap = hlist_entry(hnode, struct jobid_pid_map, jp_hash);
452
453         atomic_inc(&pidmap->jp_refcount);
454 }
455
456 static void jobid_put_locked(struct cfs_hash *hs, struct hlist_node *hnode)
457 {
458         struct jobid_pid_map *pidmap;
459
460         if (hnode == NULL)
461                 return;
462
463         pidmap = hlist_entry(hnode, struct jobid_pid_map, jp_hash);
464         LASSERT(atomic_read(&pidmap->jp_refcount) > 0);
465         if (atomic_dec_and_test(&pidmap->jp_refcount)) {
466                 CDEBUG(D_INFO, "Freeing: %d->%s\n",
467                        pidmap->jp_pid, pidmap->jp_jobid);
468
469                 OBD_FREE_PTR(pidmap);
470         }
471 }
472
473 static struct cfs_hash_ops jobid_hash_ops = {
474         .hs_hash        = jobid_hashfn,
475         .hs_keycmp      = jobid_keycmp,
476         .hs_key         = jobid_key,
477         .hs_object      = jobid_object,
478         .hs_get         = jobid_get,
479         .hs_put         = jobid_put_locked,
480         .hs_put_locked  = jobid_put_locked,
481 };
482
483 /**
484  * Generate the job identifier string for this process for tracking purposes.
485  *
486  * Fill in @jobid string based on the value of obd_jobid_var:
487  * JOBSTATS_DISABLE:      none
488  * JOBSTATS_NODELOCAL:    content of obd_jobid_node (jobid_interpret_string())
489  * JOBSTATS_PROCNAME_UID: process name/UID
490  * anything else:         look up obd_jobid_var in the processes environment
491  *
492  * Return -ve error number, 0 on success.
493  */
494 int lustre_get_jobid(char *jobid, size_t joblen)
495 {
496         int rc = 0;
497         ENTRY;
498
499         if (unlikely(joblen < 2)) {
500                 if (joblen == 1)
501                         jobid[0] = '\0';
502                 RETURN(-EINVAL);
503         }
504
505         if (strcmp(obd_jobid_var, JOBSTATS_DISABLE) == 0) {
506                 /* Jobstats isn't enabled */
507                 memset(jobid, 0, joblen);
508         } else if (strcmp(obd_jobid_var, JOBSTATS_NODELOCAL) == 0) {
509                 /* Whole node dedicated to single job */
510                 rc = jobid_interpret_string(obd_jobid_name, jobid, joblen);
511         } else if (strcmp(obd_jobid_var, JOBSTATS_PROCNAME_UID) == 0) {
512                 rc = jobid_interpret_string("%e.%u", jobid, joblen);
513         } else if (jobid_name_is_valid(current_comm())) {
514                 /*
515                  * obd_jobid_var holds the jobid environment variable name.
516                  * Skip initial check if obd_jobid_name already uses "%j",
517                  * otherwise try just "%j" first, then fall back to whatever
518                  * is in obd_jobid_name if obd_jobid_var is not found.
519                  */
520                 rc = -EAGAIN;
521                 if (!strnstr(obd_jobid_name, "%j", joblen))
522                         rc = jobid_get_from_cache(jobid, joblen);
523
524                 /* fall back to jobid_node if jobid_var not in environment */
525                 if (rc < 0) {
526                         int rc2 = jobid_interpret_string(obd_jobid_name,
527                                                          jobid, joblen);
528                         if (!rc2)
529                                 rc = 0;
530                 }
531         }
532
533         RETURN(rc);
534 }
535 EXPORT_SYMBOL(lustre_get_jobid);
536
537 /*
538  * lustre_jobid_clear
539  *
540  * Search cache for JobID given by @find_jobid.
541  * If any entries in the hash table match the value, they are removed
542  */
543 void lustre_jobid_clear(const char *find_jobid)
544 {
545         char jobid[LUSTRE_JOBID_SIZE];
546         char *end;
547
548         if (jobid_hash == NULL)
549                 return;
550
551         strlcpy(jobid, find_jobid, sizeof(jobid));
552         /* trim \n off the end of the incoming jobid */
553         end = strchr(jobid, '\n');
554         if (end && *end == '\n')
555                 *end = '\0';
556
557         CDEBUG(D_INFO, "Clearing Jobid: %s\n", jobid);
558         cfs_hash_cond_del(jobid_hash, jobid_should_free_item, jobid);
559
560         CDEBUG(D_INFO, "%d items remain in jobID table\n",
561                atomic_read(&jobid_hash->hs_count));
562 }