Call enter_namespace before ctx_migrate.
[util-vserver-pl.git] / src / planetlab.c
1 /* Copyright 2005 Princeton University
2
3 Redistribution and use in source and binary forms, with or without
4 modification, are permitted provided that the following conditions
5 are met: 
6
7     * Redistributions of source code must retain the above copyright
8       notice, this list of conditions and the following disclaimer.
9       
10     * Redistributions in binary form must reproduce the above
11       copyright notice, this list of conditions and the following
12       disclaimer in the documentation and/or other materials provided
13       with the distribution.
14       
15     * Neither the name of the copyright holder nor the names of its
16       contributors may be used to endorse or promote products derived
17       from this software without specific prior written permission.
18       
19 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL PRINCETON
23 UNIVERSITY OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
24 INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
25 BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
26 OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
27 AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
29 WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30 POSSIBILITY OF SUCH DAMAGE. 
31
32 */
33
34 #ifdef HAVE_CONFIG_H
35 #  include <config.h>
36 #endif
37 #include <stdio.h>
38 #include <stdlib.h>
39 #include <string.h>
40 #include <errno.h>
41 #include <stdint.h>
42 #include <stdarg.h>
43 #include <unistd.h>
44 #include <ctype.h>
45 #include <sys/resource.h>
46 #include <fcntl.h>
47
48 #include "vserver.h"
49 #include "planetlab.h"
50
51 #ifndef VC_NXC_RAW_SOCKET
52 #  define VC_NXC_RAW_SOCKET     0x00000200ull
53 #endif
54 #ifndef VC_NXC_RAW_SEND
55 #  define VC_NXC_RAW_SEND       0x00000400ull
56 #endif
57 #ifndef VC_NXF_LBACK_ALLOW
58 #  define VC_NXF_LBACK_ALLOW    0x00000400ull
59 #endif
60
61 static int
62 create_context(xid_t ctx, uint64_t bcaps)
63 {
64   struct vc_ctx_caps   vc_caps;
65   struct vc_net_flags  vc_nf;
66   struct vc_net_caps   vc_ncaps;
67   uint32_t unshare_mask;
68
69   /* Create network context */
70   if (vc_net_create(ctx) == VC_NOCTX) {
71     if (errno == EEXIST)
72       goto tag;
73     return -1;
74   }
75
76   /* Make the network context persistent */
77   vc_nf.mask = vc_nf.flagword = VC_NXF_PERSISTENT | VC_NXF_LBACK_ALLOW;
78   if (vc_set_nflags(ctx, &vc_nf))
79     return -1;
80
81   /* Give it raw sockets capabilities */
82   vc_ncaps.ncaps = vc_ncaps.cmask = VC_NXC_RAW_ICMP | VC_NXC_RAW_SOCKET;
83   if (vc_set_ncaps(ctx, &vc_ncaps))
84     return -1;
85
86 tag:
87   /* Create tag context */
88   if (vc_tag_create(ctx) == VC_NOCTX)
89     return -1;
90
91 process:
92
93   /*
94    * Create context info - this sets the STATE_SETUP and STATE_INIT flags.
95    */
96   if (vc_ctx_create(ctx, 0) == VC_NOCTX)
97     return -1;
98
99   /* Unshare the net namespace if the slice if requested in the local slice configuration */
100   unshare_mask = get_space_flag(ctx);
101   if (unshare_mask != 0) {
102       sys_unshare(unshare_mask);
103       vc_set_namespace(ctx, unshare_mask);
104   }
105
106   /* Set capabilities - these don't take effect until SETUP flag is unset */
107   vc_caps.bcaps = bcaps;
108   vc_caps.bmask = ~0ULL;  /* currently unused */
109   vc_caps.ccaps = 0;      /* don't want any of these */
110   vc_caps.cmask = ~0ULL;
111   if (vc_set_ccaps(ctx, &vc_caps))
112     return -1;
113
114   if (pl_setsched(ctx, 0, 1) < 0) {
115     PERROR("pl_setsched(%u)", ctx);
116     exit(1);
117   }
118
119   return 0;
120 }
121
122 int
123 pl_setup_done(xid_t ctx)
124 {
125   struct vc_ctx_flags  vc_flags;
126
127   /* unset SETUP flag - this allows other processes to migrate */
128   /* set the PERSISTENT flag - so the context doesn't vanish */
129   /* Don't clear the STATE_INIT flag, as that would make us the init task. */
130   vc_flags.mask = VC_VXF_STATE_SETUP|VC_VXF_PERSISTENT;
131   vc_flags.flagword = VC_VXF_PERSISTENT;
132   if (vc_set_cflags(ctx, &vc_flags))
133     return -1;
134
135   return 0;
136 }
137
138 #define RETRY_LIMIT  10
139
140 int
141 pl_chcontext(xid_t ctx, uint64_t bcaps, const struct sliver_resources *slr)
142 {
143   int  retry_count = 0;
144   int  net_migrated = 0;
145
146   if (pl_set_ulimits(slr) != 0)
147     return -1;
148
149   for (;;)
150     {
151       struct vc_ctx_flags  vc_flags;
152
153       if (vc_get_cflags(ctx, &vc_flags))
154         {
155           if (errno != ESRCH)
156             return -1;
157
158           /* context doesn't exist - create it */
159           if (create_context(ctx, bcaps))
160             {
161               if (errno == EEXIST)
162                 /* another process beat us in a race */
163                 goto migrate;
164               if (errno == EBUSY)
165                 /* another process is creating - poll the SETUP flag */
166                 continue;
167               return -1;
168             }
169
170           /* created context and migrated to it i.e., we're done */
171           return 1;
172         }
173
174       /* check the SETUP flag */
175       if (vc_flags.flagword & VC_VXF_STATE_SETUP)
176         {
177           /* context is still being setup - wait a while then retry */
178           if (retry_count++ >= RETRY_LIMIT)
179             {
180               errno = EBUSY;
181               return -1;
182             }
183           sleep(1);
184           continue;
185         }
186
187       /* context has been setup */
188     migrate:
189       if (net_migrated || !vc_net_migrate(ctx))
190         {
191       /* Unshare the net namespace if the slice if requested in the local slice configuration */
192       unshare_mask = get_space_flag(ctx);
193       if (unshare_mask != 0) {
194           vc_enter_namespace(ctx, unshare_mask);
195       }
196
197           if (!vc_tag_migrate(ctx) && !vc_ctx_migrate(ctx, 0))
198             break;  /* done */
199           net_migrated = 1;
200         }
201
202       /* context disappeared - retry */
203     }
204
205   return 0;
206 }
207
208 /* it's okay for a syscall to fail because the context doesn't exist */
209 #define VC_SYSCALL(x)                           \
210 do                                              \
211 {                                               \
212   if (x)                                        \
213     return errno == ESRCH ? 0 : -1;             \
214 }                                               \
215 while (0)
216
217 int
218 pl_setsched(xid_t ctx, uint32_t cpu_min, uint32_t cpu_share)
219 {
220   struct vc_set_sched  vc_sched;
221   struct vc_ctx_flags  vc_flags;
222
223   vc_sched.set_mask = (VC_VXSM_FILL_RATE | VC_VXSM_INTERVAL | VC_VXSM_TOKENS |
224                        VC_VXSM_TOKENS_MIN | VC_VXSM_TOKENS_MAX | VC_VXSM_MSEC |
225                        VC_VXSM_FILL_RATE2 | VC_VXSM_INTERVAL2 | VC_VXSM_FORCE);
226   vc_sched.fill_rate = cpu_min; /* percent reserved */
227   vc_sched.interval = 100;
228   vc_sched.fill_rate2 = cpu_share; /* best-effort fair share of unreserved */
229   vc_sched.interval2 = 1000;  /* milliseconds */
230   vc_sched.tokens = 100;     /* initial allocation of tokens */
231   vc_sched.tokens_min = 50;  /* need this many tokens to run */
232   vc_sched.tokens_max = 100;  /* max accumulated number of tokens */
233
234   if (cpu_share) {
235     if (cpu_share == (uint32_t)VC_LIM_KEEP)
236       vc_sched.set_mask &= ~(VC_VXSM_FILL_RATE|VC_VXSM_FILL_RATE2);
237     else
238       vc_sched.set_mask |= VC_VXSM_IDLE_TIME;
239   }
240
241   VC_SYSCALL(vc_set_sched(ctx, &vc_sched));
242
243   vc_flags.mask = VC_VXF_SCHED_FLAGS;
244   vc_flags.flagword = VC_VXF_SCHED_HARD;
245   VC_SYSCALL(vc_set_cflags(ctx, &vc_flags));
246
247   return 0;
248 }
249
250 enum {
251   TYPE_LONG = 1,
252   TYPE_PERS = 2,
253 };
254
255 struct pl_resources {
256         char *name;
257         unsigned type;
258   union {
259     unsigned long long *limit;
260     unsigned long int *personality;
261   };
262 };
263
264 #define WHITESPACE(buffer,index,len)     \
265   while(isspace((int)buffer[index])) \
266         if (index < len) index++; else goto out;
267
268 #define VSERVERCONF "/etc/vservers/"
269
270 void
271 pl_get_limits(const char *context, struct sliver_resources *slr)
272 {
273   FILE *fb;
274   int cwd;
275   size_t len = strlen(VSERVERCONF) + strlen(context) + NULLBYTE_SIZE;
276   char *conf = (char *)malloc(len + strlen("rlimits/openfd.hard"));
277   struct pl_resources *r;
278   struct pl_resources sliver_list[] = {
279     {"sched/fill-rate2", TYPE_LONG, &slr->vs_cpu},
280
281     {"rlimits/nproc.hard", TYPE_LONG, &slr->vs_nproc.hard},
282     {"rlimits/nproc.soft", TYPE_LONG, &slr->vs_nproc.soft},
283     {"rlimits/nproc.min", TYPE_LONG, &slr->vs_nproc.min},
284   
285     {"rlimits/rss.hard", TYPE_LONG, &slr->vs_rss.hard},
286     {"rlimits/rss.soft", TYPE_LONG, &slr->vs_rss.soft},
287     {"rlimits/rss.min", TYPE_LONG, &slr->vs_rss.min},
288   
289     {"rlimits/as.hard", TYPE_LONG, &slr->vs_as.hard},
290     {"rlimits/as.soft", TYPE_LONG, &slr->vs_as.soft},
291     {"rlimits/as.min", TYPE_LONG, &slr->vs_as.min},
292   
293     {"rlimits/openfd.hard", TYPE_LONG, &slr->vs_openfd.hard},
294     {"rlimits/openfd.soft", TYPE_LONG, &slr->vs_openfd.soft},
295     {"rlimits/openfd.min", TYPE_LONG, &slr->vs_openfd.min},
296
297     {"personality", TYPE_PERS, &slr->personality},
298
299     {0,0}
300   };
301
302   sprintf(conf, "%s%s", VSERVERCONF, context);
303
304   slr->vs_rss.hard = VC_LIM_KEEP;
305   slr->vs_rss.soft = VC_LIM_KEEP;
306   slr->vs_rss.min = VC_LIM_KEEP;
307
308   slr->vs_as.hard = VC_LIM_KEEP;
309   slr->vs_as.soft = VC_LIM_KEEP;
310   slr->vs_as.min = VC_LIM_KEEP;
311
312   slr->vs_nproc.hard = VC_LIM_KEEP;
313   slr->vs_nproc.soft = VC_LIM_KEEP;
314   slr->vs_nproc.min = VC_LIM_KEEP;
315
316   slr->vs_openfd.hard = VC_LIM_KEEP;
317   slr->vs_openfd.soft = VC_LIM_KEEP;
318   slr->vs_openfd.min = VC_LIM_KEEP;
319
320   slr->personality = 0;
321
322   cwd = open(".", O_RDONLY);
323   if (cwd == -1) {
324     perror("cannot get a handle on .");
325     goto out;
326   }
327   if (chdir(conf) == -1) {
328     fprintf(stderr, "cannot chdir to ");
329     perror(conf);
330     goto out_fd;
331   }
332
333   for (r = &sliver_list[0]; r->name; r++) {
334     char buf[1000];
335     fb = fopen(r->name, "r");
336     if (fb == NULL)
337       continue;
338     if (fgets(buf, sizeof(buf), fb) != NULL) {
339       len=strlen(buf);
340       /* remove trailing newline */
341       if (buf[len-1] == '\n') {
342         buf[len-1]='\0';
343         len --;
344       }
345       if ( (r->type == TYPE_LONG) && isdigit(*buf)) {
346         *r->limit = atoi(buf);
347       } else if ( (r->type == TYPE_PERS) && isalpha(*buf)) {
348         unsigned long int res;
349         res = vc_str2personalitytype(buf,len);
350         if (res != VC_BAD_PERSONALITY) {
351           *r->personality = res;
352         }
353       }
354     }
355     
356     fclose(fb);
357   }
358
359   fchdir(cwd);
360 out_fd:
361   close(cwd);
362 out:
363   free(conf);
364 }
365
366 int
367 adjust_lim(const struct vc_rlimit *vcr, struct rlimit *lim)
368 {
369   int adjusted = 0;
370   if (vcr->min != VC_LIM_KEEP) {
371     if (vcr->min > lim->rlim_cur) {
372       lim->rlim_cur = vcr->min;
373       adjusted = 1;
374     }
375     if (vcr->min > lim->rlim_max) {
376       lim->rlim_max = vcr->min;
377       adjusted = 1;
378     }
379   }
380
381   if (vcr->soft != VC_LIM_KEEP) {
382     switch (vcr->min != VC_LIM_KEEP) {
383     case 1:
384       if (vcr->soft < vcr->min)
385         break;
386     case 0:
387         lim->rlim_cur = vcr->soft;
388         adjusted = 1;
389     }
390   }
391
392   if (vcr->hard != VC_LIM_KEEP) {
393     switch (vcr->min != VC_LIM_KEEP) {
394     case 1:
395       if (vcr->hard < vcr->min)
396         break;
397     case 0:
398         lim->rlim_max = vcr->hard;
399         adjusted = 1;
400     }
401   }
402   return adjusted;
403 }
404
405 static inline void
406 set_one_ulimit(int resource, const struct vc_rlimit *limit)
407 {
408   struct rlimit lim;
409   getrlimit(resource, &lim);
410   adjust_lim(limit, &lim);
411   setrlimit(resource, &lim);
412 }
413
414 static inline int 
415 set_personality(unsigned long int personality_arg)
416 {
417   if (personality_arg == 0) 
418     return 0;
419   if (personality(personality_arg) < 0) {
420     return -1;
421   }
422   return 0;
423 }
424
425 int
426 pl_set_ulimits(const struct sliver_resources *slr)
427 {
428   if (!slr)
429     return 0;
430
431   set_one_ulimit(RLIMIT_RSS, &slr->vs_rss);
432   set_one_ulimit(RLIMIT_AS, &slr->vs_as);
433   set_one_ulimit(RLIMIT_NPROC, &slr->vs_nproc);
434   set_one_ulimit(RLIMIT_NOFILE, &slr->vs_openfd);
435   return set_personality(slr->personality);
436 }