try to read limits from dir only, when '--dir' was used
[util-vserver.git] / util-vserver / src / vlimit.c
1 // $Id$
2
3 // Copyright (C) 2003 Enrico Scholz <enrico.scholz@informatik.tu-chemnitz.de>
4 //  
5 // This program is free software; you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation; either version 2, or (at your option)
8 // any later version.
9 //  
10 // This program is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 // GNU General Public License for more details.
14 //  
15 // You should have received a copy of the GNU General Public License
16 // along with this program; if not, write to the Free Software
17 // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
18
19 /*
20         Set the global per context limit of a resource (memory, file handle).
21         This utility can do it either for the current context or a selected
22         one.
23
24         It uses the same options as ulimit, when possible
25 */
26 #ifdef HAVE_CONFIG_H
27 #  include <config.h>
28 #endif
29 #include "compat.h"
30
31 #include "vserver.h"
32 #include "internal.h"
33 #include "util.h"
34
35 #include <getopt.h>
36 #include <string.h>
37 #include <unistd.h>
38 #include <assert.h>
39 #include <stdbool.h>
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <libgen.h>
43 #include <sys/resource.h>
44 #include <errno.h>
45 #include <fcntl.h>
46 #include <sys/stat.h>
47 #include <ctype.h>
48
49 #define ENSC_WRAPPERS_PREFIX    "vlimit: "
50 #define ENSC_WRAPPERS_UNISTD    1
51 #define ENSC_WRAPPERS_VSERVER   1
52 #include <wrappers.h>
53
54 #define CMD_DIR         0x8000
55 #define CMD_MISSINGOK   0x8001
56
57 int             wrapper_exit_code = 255;
58
59 #define NUMLIM(X) \
60 { #X, required_argument, 0, 2048|X }
61 #define OPT_RESLIM(RES,V) \
62   { #RES, required_argument, 0, 2048|RLIMIT_##V }
63
64 static struct option const
65 CMDLINE_OPTIONS[] = {
66   { "help",      no_argument,       0, 'h' },
67   { "version",   no_argument,       0, 'v' },
68   { "all",       no_argument,       0, 'a' },
69   { "dir",       required_argument, 0, CMD_DIR },
70   { "missingok", no_argument,       0, CMD_MISSINGOK },
71   NUMLIM( 0), NUMLIM( 1), NUMLIM( 2), NUMLIM( 3),
72   NUMLIM( 4), NUMLIM( 5), NUMLIM( 6), NUMLIM( 7),
73   NUMLIM( 8), NUMLIM( 9), NUMLIM(10), NUMLIM(11),
74   NUMLIM(12), NUMLIM(13), NUMLIM(14), NUMLIM(15),
75   NUMLIM(16), NUMLIM(17), NUMLIM(18), NUMLIM(19),
76   NUMLIM(20), NUMLIM(21), NUMLIM(22), NUMLIM(23),
77   NUMLIM(24), NUMLIM(25), NUMLIM(26), NUMLIM(27),
78   NUMLIM(28), NUMLIM(29), NUMLIM(30), NUMLIM(31),
79   OPT_RESLIM(cpu,     CPU),
80   OPT_RESLIM(fsize,   FSIZE),
81   OPT_RESLIM(data,    DATA),
82   OPT_RESLIM(stack,   STACK),
83   OPT_RESLIM(core,    CORE),
84   OPT_RESLIM(rss,     RSS),
85   OPT_RESLIM(nproc,   NPROC),
86   OPT_RESLIM(nofile,  NOFILE),
87   OPT_RESLIM(memlock, MEMLOCK),
88   OPT_RESLIM(as,      AS),
89   OPT_RESLIM(locks,   LOCKS),
90   { 0,0,0,0 }
91 };
92
93 #define REV_RESLIM(X)   [RLIMIT_##X] = #X
94 static char const * const LIMIT_STR[] = {
95   REV_RESLIM(CPU),     REV_RESLIM(FSIZE), REV_RESLIM(DATA),  REV_RESLIM(STACK),
96   REV_RESLIM(CORE),    REV_RESLIM(RSS),   REV_RESLIM(NPROC), REV_RESLIM(NOFILE),
97   REV_RESLIM(MEMLOCK), REV_RESLIM(AS),    REV_RESLIM(LOCKS)
98 };
99
100 static void
101 showHelp(int fd, char const *cmd, int res)
102 {
103   VSERVER_DECLARE_CMD(cmd);
104   
105   WRITE_MSG(fd, "Usage:  ");
106   WRITE_STR(fd, cmd);
107   WRITE_MSG(fd,
108             " [-c <xid>] [-nd] [-a|--all] [[-MSH] --(<resource>|<nr>) <value>]*\n"
109             "               [--dir <pathname> [--missingok]] [--] [<program> <args>*]\n\n"
110             "Options:\n"
111             "    -c <xid>    ...  operate on context <xid>\n"
112             "    -a|--all    ...  show all available limits\n"
113             "    -n          ...  do not resolve limit-names\n"
114             "    -d          ...  show limits in decimal\n"
115             "    -M          ...  set Minimum limit\n"
116             "    -S          ...  set Soft limit\n"
117             "    -H          ...  set Hard limit (assumed by default, when neither\n"
118             "                     M nor S was requested)\n"
119             "    --dir <pathname>\n"
120             "                ...  read limits from <pathname>/; allowed filenames are\n"
121             "                     <resource> and <resource>.{min,soft,hard}. When a limit\n"
122             "                     was set by the CLI already, the corresponding file\n"
123             "                     will be ignored\n"
124             "    --missingok ...  do not fail when <pathname> does not exist\n"
125             "    --<resource>|<nr> <value>\n"
126             "                ...  set specified (MSH) limit for <resource> to <value>\n\n"
127             "Valid values for resource are cpu, fsize, data, stack, core, rss, nproc,\n"
128             "nofile, memlock, as and locks.\n\n"
129             "Please report bugs to " PACKAGE_BUGREPORT "\n");
130   exit(res);
131 }
132
133 static void
134 showVersion()
135 {
136   WRITE_MSG(1,
137             "vlimit " VERSION " -- limits context-resources\n"
138             "This program is part of " PACKAGE_STRING "\n\n"
139             "Copyright (C) 2003 Enrico Scholz\n"
140             VERSION_COPYRIGHT_DISCLAIMER);
141   exit(0);
142 }
143
144 static size_t
145 fmtHex(char *ptr, vc_limit_t lim)
146 {
147   memcpy(ptr, "0x", 2);
148   return utilvserver_fmt_xuint64(ptr+2, lim) + 2;
149 }
150
151 static bool             do_resolve = true;
152 static size_t           (*fmt_func)(char *, vc_limit_t) = fmtHex;
153
154 static void *
155 appendLimit(char *ptr, bool do_it, vc_limit_t lim)
156 {
157   memcpy(ptr, "  ", 2);
158   ptr += 2;
159   if (do_it) {
160     if (lim==VC_LIM_INFINITY) {
161       strcpy(ptr, "INF");
162       ptr += 3;
163     }
164     else {
165       ptr += (*fmt_func)(ptr, lim);
166       *ptr = ' ';
167     }
168   }
169   else {
170     memcpy(ptr, "N/A", 3);
171     ptr += 3;
172   }
173
174   return ptr;
175 }
176
177 static void
178 showAll(int ctx)
179 {
180   struct vc_rlimit_mask mask;
181   size_t                i;
182
183   if (vc_get_rlimit_mask(ctx, &mask)==-1) {
184     perror("vc_get_rlimit_mask()");
185     exit(wrapper_exit_code);
186   }
187
188   for (i=0; i<32; ++i) {
189     uint32_t            bitmask = (1<<i);
190     struct vc_rlimit    limit;
191     char                buf[128], *ptr=buf;
192
193     if (((mask.min|mask.soft|mask.hard) & bitmask)==0) continue;
194     if (vc_get_rlimit(ctx, i, &limit)==-1) {
195       perror("vc_get_rlimit()");
196       //continue;
197     }
198
199     memset(buf, ' ', sizeof buf);
200     if (do_resolve && i<DIM_OF(LIMIT_STR)) {
201       size_t            l = strlen(LIMIT_STR[i]);
202       memcpy(ptr, LIMIT_STR[i], l);
203       ptr += l;
204     }
205     else {
206       ptr += utilvserver_fmt_uint(ptr, i);
207       *ptr = ' ';
208     }
209
210     ptr  = appendLimit(buf+10, mask.min &bitmask, limit.min);
211     ptr  = appendLimit(buf+30, mask.soft&bitmask, limit.soft);
212     ptr  = appendLimit(buf+50, mask.hard&bitmask, limit.hard);
213
214     *ptr++ = '\n';
215     write(1, buf, ptr-buf);
216   }
217 }
218
219 static void
220 setLimits(int ctx, struct vc_rlimit const limits[], uint32_t mask)
221 {
222   size_t                i;
223   for (i=0; i<32; ++i) {
224     if ((mask & (1<<i))==0) continue;
225     if (vc_set_rlimit(ctx, i, limits+i)) {
226       perror("vc_set_rlimit()");
227     }
228   }
229 }
230
231 static vc_limit_t
232 readValue(int fd, char const *filename)
233 {
234   char          buf[128];
235   size_t        len = Eread(fd, buf, sizeof(buf)-1);
236   vc_limit_t    res;
237
238   buf[len] = '\0';
239
240   if (!vc_parseLimit(buf, &res)) {
241     WRITE_MSG(2, "Invalid limit in '");
242     WRITE_STR(2, filename);
243     WRITE_STR(2, "'\n");
244     exit(wrapper_exit_code);
245   }
246
247   return res;
248 }
249
250 static bool
251 readFile(char const *file, char *base, char const *suffix,
252          vc_limit_t *limit)
253 {
254   int           fd;
255   
256   memcpy(base, suffix, strlen(suffix)+1);
257   fd = open(file, O_RDONLY);
258   if (fd!=-1) {
259     *limit = readValue(fd, file);
260     Eclose(fd);
261   }
262
263   return fd!=-1;
264 }
265          
266 static void
267 readFromDir(struct vc_rlimit limits[32], uint_least32_t *mask,
268             char const *pathname, bool missing_ok)
269 {
270   struct stat           st;
271   size_t                i;
272   size_t                l_pathname = strlen(pathname);
273   char                  buf[l_pathname + sizeof("/memlock.hard") + 32];
274   
275   if (stat(pathname, &st)==-1) {
276     if (errno==ENOENT && missing_ok) return;
277     PERROR_Q("vlimit: fstat", pathname);
278     exit(wrapper_exit_code);
279   }
280
281   memcpy(buf, pathname, l_pathname);
282   if (l_pathname>0 && pathname[l_pathname-1]!='/')
283     buf[l_pathname++] = '/';
284     
285   for (i=0; i<DIM_OF(LIMIT_STR); ++i) {
286     size_t      l_res;
287     char *      ptr   = buf+l_pathname;
288
289     // ignore unimplemented limits
290     if (LIMIT_STR[i]==0) continue;
291     
292     // ignore limits set on cli already
293     if (*mask & (1<<i)) continue;
294
295     l_res = strlen(LIMIT_STR[i]);
296     memcpy(ptr, LIMIT_STR[i], l_res+1);
297     while (*ptr) {
298       *ptr = tolower(*ptr);
299       ++ptr;
300     }
301
302     if (readFile(buf, ptr, "", &limits[i].min)) {
303       limits[i].soft = limits[i].hard = limits[i].min;
304       *mask |= (1<<i);
305     }
306
307     if (readFile(buf, ptr, ".min",  &limits[i].min))
308       *mask |= (1<<i);
309
310     if (readFile(buf, ptr, ".soft", &limits[i].soft))
311       *mask |= (1<<i);
312
313     if (readFile(buf, ptr, ".hard", &limits[i].hard))
314       *mask |= (1<<i);
315   }
316 }
317
318 int main (int argc, char *argv[])
319 {
320   // overall used limits
321   uint32_t              lim_mask = 0;
322   int                   set_mask = 0;
323   struct vc_rlimit      limits[32];
324   bool                  show_all   = false;
325   xid_t                 ctx        = VC_NOCTX;
326   char const *          dir        = 0;
327   bool                  missing_ok = false;
328
329   {
330     size_t              i;
331     for (i=0; i<32; ++i) {
332       limits[i].min  = VC_LIM_KEEP;
333       limits[i].soft = VC_LIM_KEEP;
334       limits[i].hard = VC_LIM_KEEP;
335     }
336   }
337   
338   while (1) {
339     int         c = getopt_long(argc, argv, "MSHndhvac:", CMDLINE_OPTIONS, 0);
340     if (c==-1) break;
341
342     if (2048<=c && c<2048+32) {
343       int               id  = c-2048;
344       vc_limit_t        val;
345       
346       if (!vc_parseLimit(optarg, &val)) {
347         WRITE_MSG(2, "Can not parse limit '");
348         WRITE_STR(2, optarg);
349         WRITE_STR(2, "'\n");
350         exit(wrapper_exit_code);
351       }
352
353       if (set_mask==0)  set_mask=4;
354       
355       if (set_mask & 1) limits[id].min  = val;
356       if (set_mask & 2) limits[id].soft = val;
357       if (set_mask & 4) limits[id].hard = val;
358
359       lim_mask |= (1<<id);
360       set_mask  = 0;
361     }
362     else switch (c) {
363       case 'h'          :  showHelp(1, argv[0], 0);
364       case 'v'          :  showVersion();
365       case 'c'          :  ctx        = atoi(optarg); break;
366       case 'a'          :  show_all   = true;         break;
367       case 'n'          :  do_resolve = false;        break;
368       case 'd'          :  fmt_func   = utilvserver_fmt_uint64; break;
369       case CMD_DIR      :  dir        = optarg;       break;
370       case CMD_MISSINGOK:  missing_ok = true;         break;
371       case 'M'          :
372       case 'S'          :
373       case 'H'          :
374         switch (c) {
375           case 'M'      :  set_mask |= 1; break;
376           case 'S'      :  set_mask |= 2; break;
377           case 'H'      :  set_mask |= 4; break;
378           default       :  assert(false);
379         }
380         break;
381         
382       default           :
383         WRITE_MSG(2, "Try '");
384         WRITE_STR(2, argv[0]);
385         WRITE_MSG(2, " --help\" for more information.\n");
386         exit(wrapper_exit_code) ;
387         break;
388     }
389   }
390
391   if (ctx==VC_NOCTX)
392     ctx = Evc_get_task_xid(0);
393
394   if (dir)
395     readFromDir(limits, &lim_mask, dir, missing_ok);
396
397   setLimits(ctx, limits, lim_mask);
398   if (show_all) showAll(ctx);
399
400   if (optind<argc)
401     EexecvpD(argv[optind], argv+optind);
402
403   return EXIT_SUCCESS;
404 }