]> git.proxmox.com Git - mirror_lxc.git/blame - src/lxc/lxccontainer.c
locking: update per Dwight's comment
[mirror_lxc.git] / src / lxc / lxccontainer.c
CommitLineData
72d0e1cb
SG
1/* liblxcapi
2 *
3 * Copyright © 2012 Serge Hallyn <serge.hallyn@ubuntu.com>.
4 * Copyright © 2012 Canonical Ltd.
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, as
8 * published by the Free Software Foundation.
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 along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
9be53773 20#define _GNU_SOURCE
71454076 21#include <pthread.h>
9be53773
SH
22#include <unistd.h>
23#include <sys/types.h>
24#include <sys/wait.h>
25#include <errno.h>
26#include <sched.h>
27#include "config.h"
72d0e1cb
SG
28#include "lxc.h"
29#include "state.h"
30#include "lxccontainer.h"
31#include "conf.h"
72d0e1cb
SG
32#include "confile.h"
33#include "cgroup.h"
34#include "commands.h"
b6b918a1 35#include "version.h"
72d0e1cb 36#include "log.h"
9be53773 37#include "bdev.h"
6a44839f 38#include "utils.h"
2a59a681 39#include <lxc/utils.h>
e51d4895 40#include <lxc/monitor.h>
9c83a661
SG
41#include <sched.h>
42#include <fcntl.h>
43#include <arpa/inet.h>
44#include <ifaddrs.h>
72d0e1cb
SG
45
46lxc_log_define(lxc_container, lxc);
47
48/* LOCKING
df271a59
SH
49 * 1. c->privlock protects the struct lxc_container from multiple threads.
50 * 2. c->slock protects the on-disk container data
51 * 3. thread_mutex protects process data (ex: fd table) from multiple threads
52 * slock is an flock, which does not exclude threads. Therefore slock should
53 * always be wrapped inside privlock.
72d0e1cb
SG
54 * NOTHING mutexes two independent programs with their own struct
55 * lxc_container for the same c->name, between API calls. For instance,
56 * c->config_read(); c->start(); Between those calls, data on disk
57 * could change (which shouldn't bother the caller unless for instance
58 * the rootfs get moved). c->config_read(); update; c->config_write();
59 * Two such updaters could race. The callers should therefore check their
60 * results. Trying to prevent that would necessarily expose us to deadlocks
61 * due to hung callers. So I prefer to keep the locks only within our own
62 * functions, not across functions.
63 *
64 * If you're going to fork while holding a lxccontainer, increment
65 * c->numthreads (under privlock) before forking. When deleting,
66 * decrement numthreads under privlock, then if it hits 0 you can delete.
67 * Do not ever use a lxccontainer whose numthreads you did not bump.
68 */
69
70static void lxc_container_free(struct lxc_container *c)
71{
72 if (!c)
73 return;
74
75 if (c->configfile) {
76 free(c->configfile);
77 c->configfile = NULL;
78 }
79 if (c->error_string) {
80 free(c->error_string);
81 c->error_string = NULL;
82 }
d95db067 83 if (c->slock) {
df271a59 84 lxc_putlock(c->slock);
d95db067
DE
85 c->slock = NULL;
86 }
72d0e1cb 87 if (c->privlock) {
df271a59 88 lxc_putlock(c->privlock);
72d0e1cb
SG
89 c->privlock = NULL;
90 }
91 if (c->name) {
92 free(c->name);
93 c->name = NULL;
94 }
d95db067
DE
95 if (c->lxc_conf) {
96 lxc_conf_free(c->lxc_conf);
97 c->lxc_conf = NULL;
98 }
2a59a681
SH
99 if (c->config_path) {
100 free(c->config_path);
101 c->config_path = NULL;
102 }
72d0e1cb
SG
103 free(c);
104}
105
43d1aa34
SH
106/*
107 * Consider the following case:
108freer | racing get()er
109==================================================================
110lxc_container_put() | lxc_container_get()
111\ lxclock(c->privlock) | c->numthreads < 1? (no)
112\ c->numthreads = 0 | \ lxclock(c->privlock) -> waits
113\ lxcunlock() | \
114\ lxc_container_free() | \ lxclock() returns
115 | \ c->numthreads < 1 -> return 0
116\ \ (free stuff) |
117\ \ sem_destroy(privlock) |
118
119 * When the get()er checks numthreads the first time, one of the following
120 * is true:
121 * 1. freer has set numthreads = 0. get() returns 0
122 * 2. freer is between lxclock and setting numthreads to 0. get()er will
123 * sem_wait on privlock, get lxclock after freer() drops it, then see
124 * numthreads is 0 and exit without touching lxclock again..
125 * 3. freer has not yet locked privlock. If get()er runs first, then put()er
126 * will see --numthreads = 1 and not call lxc_container_free().
127*/
128
72d0e1cb
SG
129int lxc_container_get(struct lxc_container *c)
130{
131 if (!c)
132 return 0;
133
43d1aa34
SH
134 // if someone else has already started freeing the container, don't
135 // try to take the lock, which may be invalid
136 if (c->numthreads < 1)
137 return 0;
138
5cee8c50 139 if (container_mem_lock(c))
72d0e1cb
SG
140 return 0;
141 if (c->numthreads < 1) {
142 // bail without trying to unlock, bc the privlock is now probably
143 // in freed memory
144 return 0;
145 }
146 c->numthreads++;
5cee8c50 147 container_mem_unlock(c);
72d0e1cb
SG
148 return 1;
149}
150
151int lxc_container_put(struct lxc_container *c)
152{
153 if (!c)
154 return -1;
5cee8c50 155 if (container_mem_lock(c))
72d0e1cb
SG
156 return -1;
157 if (--c->numthreads < 1) {
5cee8c50 158 container_mem_unlock(c);
72d0e1cb
SG
159 lxc_container_free(c);
160 return 1;
161 }
5cee8c50 162 container_mem_unlock(c);
72d0e1cb
SG
163 return 0;
164}
165
166static bool file_exists(char *f)
167{
168 struct stat statbuf;
169
170 return stat(f, &statbuf) == 0;
171}
172
173static bool lxcapi_is_defined(struct lxc_container *c)
174{
175 struct stat statbuf;
176 bool ret = false;
177 int statret;
178
179 if (!c)
180 return false;
181
5cee8c50 182 if (container_mem_lock(c))
72d0e1cb
SG
183 return false;
184 if (!c->configfile)
185 goto out;
186 statret = stat(c->configfile, &statbuf);
187 if (statret != 0)
188 goto out;
189 ret = true;
190
191out:
5cee8c50 192 container_mem_unlock(c);
72d0e1cb
SG
193 return ret;
194}
195
196static const char *lxcapi_state(struct lxc_container *c)
197{
198 const char *ret;
199 lxc_state_t s;
200
201 if (!c)
202 return NULL;
5cee8c50 203 if (container_disk_lock(c))
72d0e1cb 204 return NULL;
13f5be62 205 s = lxc_getstate(c->name, c->config_path);
72d0e1cb 206 ret = lxc_state2str(s);
5cee8c50 207 container_disk_unlock(c);
72d0e1cb
SG
208
209 return ret;
210}
211
794dd120
SH
212static bool is_stopped_nolock(struct lxc_container *c)
213{
214 lxc_state_t s;
13f5be62 215 s = lxc_getstate(c->name, c->config_path);
794dd120
SH
216 return (s == STOPPED);
217}
218
72d0e1cb
SG
219static bool lxcapi_is_running(struct lxc_container *c)
220{
221 const char *s;
222
223 if (!c)
224 return false;
225 s = lxcapi_state(c);
226 if (!s || strcmp(s, "STOPPED") == 0)
227 return false;
228 return true;
229}
230
231static bool lxcapi_freeze(struct lxc_container *c)
232{
233 int ret;
234 if (!c)
235 return false;
236
5cee8c50 237 if (container_disk_lock(c))
df271a59 238 return false;
9123e471 239 ret = lxc_freeze(c->name, c->config_path);
5cee8c50 240 container_disk_unlock(c);
72d0e1cb
SG
241 if (ret)
242 return false;
243 return true;
244}
245
246static bool lxcapi_unfreeze(struct lxc_container *c)
247{
248 int ret;
249 if (!c)
250 return false;
251
5cee8c50 252 if (container_disk_lock(c))
df271a59 253 return false;
9123e471 254 ret = lxc_unfreeze(c->name, c->config_path);
5cee8c50 255 container_disk_unlock(c);
72d0e1cb
SG
256 if (ret)
257 return false;
258 return true;
259}
260
261static pid_t lxcapi_init_pid(struct lxc_container *c)
262{
72d0e1cb
SG
263 if (!c)
264 return -1;
265
5cee8c50 266 return lxc_cmd_get_init_pid(c->name, c->config_path);
72d0e1cb
SG
267}
268
12a50cc6 269static bool load_config_locked(struct lxc_container *c, const char *fname)
8eb5694b
SH
270{
271 if (!c->lxc_conf)
272 c->lxc_conf = lxc_conf_init();
273 if (c->lxc_conf && !lxc_config_read(fname, c->lxc_conf))
274 return true;
275 return false;
276}
277
12a50cc6 278static bool lxcapi_load_config(struct lxc_container *c, const char *alt_file)
72d0e1cb
SG
279{
280 bool ret = false;
12a50cc6 281 const char *fname;
72d0e1cb
SG
282 if (!c)
283 return false;
284
285 fname = c->configfile;
286 if (alt_file)
287 fname = alt_file;
288 if (!fname)
289 return false;
5cee8c50 290 if (container_disk_lock(c))
72d0e1cb 291 return false;
8eb5694b 292 ret = load_config_locked(c, fname);
5cee8c50 293 container_disk_unlock(c);
72d0e1cb
SG
294 return ret;
295}
296
297static void lxcapi_want_daemonize(struct lxc_container *c)
298{
299 if (!c)
300 return;
301 c->daemonize = 1;
302}
303
12a50cc6 304static bool lxcapi_wait(struct lxc_container *c, const char *state, int timeout)
7a44c8b4
SG
305{
306 int ret;
307
308 if (!c)
309 return false;
310
67e571de 311 ret = lxc_wait(c->name, state, timeout, c->config_path);
7a44c8b4
SG
312 return ret == 0;
313}
314
315
316static bool wait_on_daemonized_start(struct lxc_container *c)
317{
318 /* we'll probably want to make this timeout configurable? */
697fa639 319 int timeout = 5, ret, status;
7a44c8b4 320
697fa639
SH
321 /*
322 * our child is going to fork again, then exit. reap the
323 * child
324 */
325 ret = wait(&status);
326 if (ret == -1 || !WIFEXITED(status) || WEXITSTATUS(status) != 0)
327 DEBUG("failed waiting for first dual-fork child");
7a44c8b4
SG
328 return lxcapi_wait(c, "RUNNING", timeout);
329}
330
72d0e1cb
SG
331/*
332 * I can't decide if it'd be more convenient for callers if we accept '...',
333 * or a null-terminated array (i.e. execl vs execv)
334 */
12a50cc6 335static bool lxcapi_start(struct lxc_container *c, int useinit, char * const argv[])
72d0e1cb
SG
336{
337 int ret;
338 struct lxc_conf *conf;
339 int daemonize = 0;
340 char *default_args[] = {
341 "/sbin/init",
342 '\0',
343 };
344
345 /* container exists */
346 if (!c)
347 return false;
348 /* container has been setup */
349 if (!c->lxc_conf)
350 return false;
351
352 /* is this app meant to be run through lxcinit, as in lxc-execute? */
353 if (useinit && !argv)
354 return false;
355
5cee8c50 356 if (container_mem_lock(c))
72d0e1cb
SG
357 return false;
358 conf = c->lxc_conf;
359 daemonize = c->daemonize;
5cee8c50 360 container_mem_unlock(c);
72d0e1cb
SG
361
362 if (useinit) {
13f5be62 363 ret = lxc_execute(c->name, argv, 1, conf, c->config_path);
72d0e1cb
SG
364 return ret == 0 ? true : false;
365 }
366
367 if (!argv)
368 argv = default_args;
369
370 /*
371 * say, I'm not sure - what locks do we want here? Any?
372 * Is liblxc's locking enough here to protect the on disk
373 * container? We don't want to exclude things like lxc_info
374 * while container is running...
375 */
376 if (daemonize) {
377 if (!lxc_container_get(c))
378 return false;
e51d4895 379 lxc_monitord_spawn(c->config_path);
71454076 380
5cee8c50 381 if (process_lock())
71454076 382 return false;
72d0e1cb
SG
383 pid_t pid = fork();
384 if (pid < 0) {
385 lxc_container_put(c);
5cee8c50 386 process_unlock();
72d0e1cb
SG
387 return false;
388 }
71454076
DE
389 if (pid != 0) {
390 ret = wait_on_daemonized_start(c);
5cee8c50 391 process_unlock();
71454076
DE
392 return ret;
393 }
5cee8c50 394 process_unlock();
697fa639
SH
395 /* second fork to be reparented by init */
396 pid = fork();
397 if (pid < 0) {
398 SYSERROR("Error doing dual-fork");
399 return false;
400 }
401 if (pid != 0)
402 exit(0);
72d0e1cb 403 /* like daemon(), chdir to / and redirect 0,1,2 to /dev/null */
c278cef2
SH
404 if (chdir("/")) {
405 SYSERROR("Error chdir()ing to /.");
406 return false;
407 }
72d0e1cb
SG
408 close(0);
409 close(1);
410 close(2);
411 open("/dev/null", O_RDONLY);
412 open("/dev/null", O_RDWR);
413 open("/dev/null", O_RDWR);
414 setsid();
415 }
416
72d0e1cb
SG
417reboot:
418 conf->reboot = 0;
13f5be62 419 ret = lxc_start(c->name, argv, conf, c->config_path);
72d0e1cb
SG
420
421 if (conf->reboot) {
422 INFO("container requested reboot");
423 conf->reboot = 0;
72d0e1cb
SG
424 goto reboot;
425 }
426
427 if (daemonize) {
428 lxc_container_put(c);
429 exit (ret == 0 ? true : false);
430 } else {
431 return (ret == 0 ? true : false);
432 }
433}
434
435/*
436 * note there MUST be an ending NULL
437 */
438static bool lxcapi_startl(struct lxc_container *c, int useinit, ...)
439{
440 va_list ap;
441 char **inargs = NULL, **temp;
442 int n_inargs = 0;
443 bool bret = false;
444
445 /* container exists */
446 if (!c)
447 return false;
448
449 /* build array of arguments if any */
450 va_start(ap, useinit);
451 while (1) {
452 char *arg;
453 arg = va_arg(ap, char *);
454 if (!arg)
455 break;
456 n_inargs++;
457 temp = realloc(inargs, n_inargs * sizeof(*inargs));
586d4e9b
SH
458 if (!temp) {
459 va_end(ap);
72d0e1cb 460 goto out;
586d4e9b 461 }
72d0e1cb
SG
462 inargs = temp;
463 inargs[n_inargs - 1] = strdup(arg); // not sure if it's safe not to copy
464 }
465 va_end(ap);
466
467 /* add trailing NULL */
468 if (n_inargs) {
469 n_inargs++;
470 temp = realloc(inargs, n_inargs * sizeof(*inargs));
471 if (!temp)
472 goto out;
473 inargs = temp;
474 inargs[n_inargs - 1] = NULL;
475 }
476
477 bret = lxcapi_start(c, useinit, inargs);
478
479out:
480 if (inargs) {
481 int i;
482 for (i = 0; i < n_inargs; i++) {
483 if (inargs[i])
484 free(inargs[i]);
485 }
486 free(inargs);
487 }
488
489 return bret;
490}
491
492static bool lxcapi_stop(struct lxc_container *c)
493{
494 int ret;
495
496 if (!c)
497 return false;
498
ef6e34ee 499 ret = lxc_cmd_stop(c->name, c->config_path);
72d0e1cb
SG
500
501 return ret == 0;
72d0e1cb
SG
502}
503
504static bool valid_template(char *t)
505{
506 struct stat statbuf;
507 int statret;
508
509 statret = stat(t, &statbuf);
510 if (statret == 0)
511 return true;
512 return false;
513}
514
515/*
516 * create the standard expected container dir
517 */
518static bool create_container_dir(struct lxc_container *c)
519{
520 char *s;
521 int len, ret;
522
2a59a681 523 len = strlen(c->config_path) + strlen(c->name) + 2;
72d0e1cb
SG
524 s = malloc(len);
525 if (!s)
526 return false;
2a59a681 527 ret = snprintf(s, len, "%s/%s", c->config_path, c->name);
72d0e1cb
SG
528 if (ret < 0 || ret >= len) {
529 free(s);
530 return false;
531 }
532 ret = mkdir(s, 0755);
533 if (ret) {
534 if (errno == EEXIST)
535 ret = 0;
536 else
537 SYSERROR("failed to create container path for %s\n", c->name);
538 }
539 free(s);
540 return ret == 0;
541}
542
543/*
544 * backing stores not (yet) supported
545 * for ->create, argv contains the arguments to pass to the template,
546 * terminated by NULL. If no arguments, you can just pass NULL.
547 */
2acf7795 548static bool lxcapi_create(struct lxc_container *c, const char *t, char *const argv[])
72d0e1cb
SG
549{
550 bool bret = false;
551 pid_t pid;
9be53773
SH
552 char *tpath = NULL, **newargv;
553 int ret, len, nargs = 0;
72d0e1cb
SG
554
555 if (!c)
556 return false;
557
558 len = strlen(LXCTEMPLATEDIR) + strlen(t) + strlen("/lxc-") + 1;
559 tpath = malloc(len);
560 if (!tpath)
561 return false;
562 ret = snprintf(tpath, len, "%s/lxc-%s", LXCTEMPLATEDIR, t);
563 if (ret < 0 || ret >= len)
564 goto out;
565 if (!valid_template(tpath)) {
566 ERROR("bad template: %s\n", t);
567 goto out;
568 }
569
72d0e1cb
SG
570 if (!c->save_config(c, NULL)) {
571 ERROR("failed to save starting configuration for %s\n", c->name);
572 goto out;
573 }
574
5a3d2e1e 575 /* container is already created if we have a config and rootfs.path is accessible */
e51d4895 576 if (lxcapi_is_defined(c) && c->lxc_conf && c->lxc_conf->rootfs.path && access(c->lxc_conf->rootfs.path, F_OK) == 0)
a741a85d 577 goto out;
5a3d2e1e 578
72d0e1cb 579 /* we're going to fork. but since we'll wait for our child, we
9be53773 580 * don't need to lxc_container_get */
72d0e1cb 581
5cee8c50 582 if (container_disk_lock(c))
df271a59 583 goto out;
72d0e1cb
SG
584
585 pid = fork();
586 if (pid < 0) {
587 SYSERROR("failed to fork task for container creation template\n");
588 goto out_unlock;
589 }
590
591 if (pid == 0) { // child
592 char *patharg, *namearg;
593 int i;
594
595 close(0);
596 close(1);
597 close(2);
598 open("/dev/null", O_RDONLY);
599 open("/dev/null", O_RDWR);
600 open("/dev/null", O_RDWR);
601
602 /*
603 * create our new array, pre-pend the template name and
604 * base args
605 */
606 if (argv)
607 for (; argv[nargs]; nargs++) ;
608 nargs += 3; // template, path and name args
609 newargv = malloc(nargs * sizeof(*newargv));
610 if (!newargv)
611 exit(1);
2acf7795 612 newargv[0] = (char *)t;
72d0e1cb 613
2a59a681 614 len = strlen(c->config_path) + strlen(c->name) + strlen("--path=") + 2;
72d0e1cb
SG
615 patharg = malloc(len);
616 if (!patharg)
617 exit(1);
2a59a681 618 ret = snprintf(patharg, len, "--path=%s/%s", c->config_path, c->name);
72d0e1cb
SG
619 if (ret < 0 || ret >= len)
620 exit(1);
621 newargv[1] = patharg;
622 len = strlen("--name=") + strlen(c->name) + 1;
623 namearg = malloc(len);
624 if (!namearg)
625 exit(1);
626 ret = snprintf(namearg, len, "--name=%s", c->name);
627 if (ret < 0 || ret >= len)
628 exit(1);
629 newargv[2] = namearg;
630
631 /* add passed-in args */
632 if (argv)
633 for (i = 3; i < nargs; i++)
634 newargv[i] = argv[i-3];
635
636 /* add trailing NULL */
637 nargs++;
638 newargv = realloc(newargv, nargs * sizeof(*newargv));
639 if (!newargv)
640 exit(1);
641 newargv[nargs - 1] = NULL;
642
643 /* execute */
e6a19d26 644 execv(tpath, newargv);
72d0e1cb
SG
645 SYSERROR("failed to execute template %s", tpath);
646 exit(1);
647 }
648
9be53773
SH
649 if (wait_for_pid(pid) != 0) {
650 ERROR("container creation template for %s failed\n", c->name);
8eb5694b
SH
651 goto out_unlock;
652 }
653
654 // now clear out the lxc_conf we have, reload from the created
655 // container
656 if (c->lxc_conf)
657 lxc_conf_free(c->lxc_conf);
658 c->lxc_conf = NULL;
659 bret = load_config_locked(c, c->configfile);
72d0e1cb
SG
660
661out_unlock:
5cee8c50 662 container_disk_unlock(c);
72d0e1cb
SG
663out:
664 if (tpath)
665 free(tpath);
666 return bret;
667}
668
669static bool lxcapi_shutdown(struct lxc_container *c, int timeout)
670{
671 bool retv;
672 pid_t pid;
673
674 if (!c)
675 return false;
676
677 if (!timeout)
678 timeout = -1;
679 if (!c->is_running(c))
680 return true;
681 pid = c->init_pid(c);
682 if (pid <= 0)
683 return true;
684 kill(pid, SIGPWR);
685 retv = c->wait(c, "STOPPED", timeout);
f6144ed4 686 if (!retv && timeout > 0) {
72d0e1cb
SG
687 c->stop(c);
688 retv = c->wait(c, "STOPPED", 0); // 0 means don't wait
689 }
690 return retv;
691}
692
2acf7795 693static bool lxcapi_createl(struct lxc_container *c, const char *t, ...)
72d0e1cb
SG
694{
695 bool bret = false;
696 char **args = NULL, **temp;
697 va_list ap;
698 int nargs = 0;
699
700 if (!c)
701 return false;
702
703 /*
704 * since we're going to wait for create to finish, I don't think we
705 * need to get a copy of the arguments.
706 */
707 va_start(ap, t);
708 while (1) {
709 char *arg;
710 arg = va_arg(ap, char *);
711 if (!arg)
712 break;
713 nargs++;
83cab6e0 714 temp = realloc(args, (nargs+1) * sizeof(*args));
41670788
SH
715 if (!temp) {
716 va_end(ap);
72d0e1cb 717 goto out;
41670788 718 }
72d0e1cb
SG
719 args = temp;
720 args[nargs - 1] = arg;
721 }
722 va_end(ap);
63e414f8
SH
723 if (args)
724 args[nargs] = NULL;
72d0e1cb
SG
725
726 bret = c->create(c, t, args);
727
728out:
729 if (args)
730 free(args);
731 return bret;
732}
733
12a50cc6 734static bool lxcapi_clear_config_item(struct lxc_container *c, const char *key)
72d0e1cb
SG
735{
736 int ret;
737
738 if (!c || !c->lxc_conf)
739 return false;
5cee8c50 740 if (container_mem_lock(c))
72d0e1cb 741 return false;
72d0e1cb 742 ret = lxc_clear_config_item(c->lxc_conf, key);
5cee8c50 743 container_mem_unlock(c);
72d0e1cb
SG
744 return ret == 0;
745}
746
9c83a661
SG
747char** lxcapi_get_ips(struct lxc_container *c, char* interface, char* family, int scope)
748{
749 int count = 0;
750 struct ifaddrs *interfaceArray = NULL, *tempIfAddr = NULL;
751 char addressOutputBuffer[INET6_ADDRSTRLEN];
752 void *tempAddrPtr = NULL;
753 char **addresses = NULL, **temp;
754 char *address = NULL;
755 char new_netns_path[MAXPATHLEN];
756 int old_netns = -1, new_netns = -1, ret = 0;
757
758 if (!c->is_running(c))
759 goto out;
760
761 /* Save reference to old netns */
762 old_netns = open("/proc/self/ns/net", O_RDONLY);
763 if (old_netns < 0) {
764 SYSERROR("failed to open /proc/self/ns/net");
765 goto out;
766 }
767
768 /* Switch to new netns */
769 ret = snprintf(new_netns_path, MAXPATHLEN, "/proc/%d/ns/net", c->init_pid(c));
770 if (ret < 0 || ret >= MAXPATHLEN)
771 goto out;
772
773 new_netns = open(new_netns_path, O_RDONLY);
774 if (new_netns < 0) {
775 SYSERROR("failed to open %s", new_netns_path);
776 goto out;
777 }
778
779 if (setns(new_netns, CLONE_NEWNET)) {
780 SYSERROR("failed to setns");
781 goto out;
782 }
783
784 /* Grab the list of interfaces */
785 if (getifaddrs(&interfaceArray)) {
786 SYSERROR("failed to get interfaces list");
787 goto out;
788 }
789
790 /* Iterate through the interfaces */
791 for (tempIfAddr = interfaceArray; tempIfAddr != NULL; tempIfAddr = tempIfAddr->ifa_next) {
792 if(tempIfAddr->ifa_addr->sa_family == AF_INET) {
793 if (family && strcmp(family, "inet"))
794 continue;
795 tempAddrPtr = &((struct sockaddr_in *)tempIfAddr->ifa_addr)->sin_addr;
796 }
797 else {
798 if (family && strcmp(family, "inet6"))
799 continue;
800
801 if (((struct sockaddr_in6 *)tempIfAddr->ifa_addr)->sin6_scope_id != scope)
802 continue;
803
804 tempAddrPtr = &((struct sockaddr_in6 *)tempIfAddr->ifa_addr)->sin6_addr;
805 }
806
807 if (interface && strcmp(interface, tempIfAddr->ifa_name))
808 continue;
809 else if (!interface && strcmp("lo", tempIfAddr->ifa_name) == 0)
810 continue;
811
812 address = (char *)inet_ntop(tempIfAddr->ifa_addr->sa_family,
813 tempAddrPtr,
814 addressOutputBuffer,
815 sizeof(addressOutputBuffer));
816 if (!address)
817 continue;
818
819 count += 1;
820 temp = realloc(addresses, count * sizeof(*addresses));
821 if (!temp) {
822 count--;
823 goto out;
824 }
825 addresses = temp;
826 addresses[count - 1] = strdup(address);
827 }
828
829out:
830 if(interfaceArray)
831 freeifaddrs(interfaceArray);
832
833 /* Switch back to original netns */
834 if (old_netns >= 0 && setns(old_netns, CLONE_NEWNET))
835 SYSERROR("failed to setns");
836 if (new_netns >= 0)
837 close(new_netns);
838 if (old_netns >= 0)
839 close(old_netns);
840
841 /* Append NULL to the array */
842 if (count) {
843 count++;
844 temp = realloc(addresses, count * sizeof(*addresses));
845 if (!temp) {
fca3080f
DE
846 int i;
847 for (i = 0; i < count-1; i++)
9c83a661
SG
848 free(addresses[i]);
849 free(addresses);
850 return NULL;
851 }
852 addresses = temp;
853 addresses[count - 1] = NULL;
854 }
855
856 return addresses;
857}
858
12a50cc6 859static int lxcapi_get_config_item(struct lxc_container *c, const char *key, char *retv, int inlen)
72d0e1cb
SG
860{
861 int ret;
862
863 if (!c || !c->lxc_conf)
864 return -1;
5cee8c50 865 if (container_mem_lock(c))
72d0e1cb 866 return -1;
72d0e1cb 867 ret = lxc_get_config_item(c->lxc_conf, key, retv, inlen);
5cee8c50 868 container_mem_unlock(c);
72d0e1cb
SG
869 return ret;
870}
871
12a50cc6 872static int lxcapi_get_keys(struct lxc_container *c, const char *key, char *retv, int inlen)
72d0e1cb
SG
873{
874 if (!key)
875 return lxc_listconfigs(retv, inlen);
876 /*
877 * Support 'lxc.network.<idx>', i.e. 'lxc.network.0'
878 * This is an intelligent result to show which keys are valid given
879 * the type of nic it is
880 */
881 if (!c || !c->lxc_conf)
882 return -1;
5cee8c50 883 if (container_mem_lock(c))
72d0e1cb
SG
884 return -1;
885 int ret = -1;
886 if (strncmp(key, "lxc.network.", 12) == 0)
887 ret = lxc_list_nicconfigs(c->lxc_conf, key, retv, inlen);
5cee8c50 888 container_mem_unlock(c);
72d0e1cb
SG
889 return ret;
890}
891
892
893/* default config file - should probably come through autoconf */
bb9702b5 894#define LXC_DEFAULT_CONFIG "/etc/lxc/default.conf"
12a50cc6 895static bool lxcapi_save_config(struct lxc_container *c, const char *alt_file)
72d0e1cb
SG
896{
897 if (!alt_file)
898 alt_file = c->configfile;
899 if (!alt_file)
900 return false; // should we write to stdout if no file is specified?
901 if (!c->lxc_conf)
902 if (!c->load_config(c, LXC_DEFAULT_CONFIG)) {
903 ERROR("Error loading default configuration file %s while saving %s\n", LXC_DEFAULT_CONFIG, c->name);
904 return false;
905 }
906
5a3d2e1e
SG
907 if (!create_container_dir(c))
908 return false;
909
72d0e1cb
SG
910 FILE *fout = fopen(alt_file, "w");
911 if (!fout)
912 return false;
5cee8c50 913 if (container_mem_lock(c)) {
72d0e1cb
SG
914 fclose(fout);
915 return false;
916 }
917 write_config(fout, c->lxc_conf);
918 fclose(fout);
5cee8c50 919 container_mem_unlock(c);
72d0e1cb
SG
920 return true;
921}
922
923static bool lxcapi_destroy(struct lxc_container *c)
924{
925 pid_t pid;
72d0e1cb
SG
926
927 if (!c)
928 return false;
929
5a3d2e1e 930 /* container is already destroyed if we don't have a config and rootfs.path is not accessible */
e51d4895 931 if (!lxcapi_is_defined(c) && (!c->lxc_conf || !c->lxc_conf->rootfs.path || access(c->lxc_conf->rootfs.path, F_OK) != 0))
5a3d2e1e
SG
932 return false;
933
72d0e1cb
SG
934 pid = fork();
935 if (pid < 0)
936 return false;
937 if (pid == 0) { // child
e6a19d26 938 execlp("lxc-destroy", "lxc-destroy", "-n", c->name, "-P", c->config_path, NULL);
72d0e1cb
SG
939 perror("execl");
940 exit(1);
941 }
942
9be53773
SH
943 if (wait_for_pid(pid) < 0) {
944 ERROR("Error destroying container %s", c->name);
72d0e1cb
SG
945 return false;
946 }
947
9be53773 948 return true;
72d0e1cb
SG
949}
950
12a50cc6 951static bool lxcapi_set_config_item(struct lxc_container *c, const char *key, const char *v)
72d0e1cb
SG
952{
953 int ret;
954 bool b = false;
955 struct lxc_config_t *config;
956
957 if (!c)
958 return false;
959
5cee8c50 960 if (container_mem_lock(c))
72d0e1cb
SG
961 return false;
962
963 if (!c->lxc_conf)
964 c->lxc_conf = lxc_conf_init();
965 if (!c->lxc_conf)
966 goto err;
967 config = lxc_getconfig(key);
968 if (!config)
969 goto err;
970 ret = config->cb(key, v, c->lxc_conf);
971 if (!ret)
972 b = true;
973
974err:
5cee8c50 975 container_mem_unlock(c);
72d0e1cb
SG
976 return b;
977}
978
979static char *lxcapi_config_file_name(struct lxc_container *c)
980{
981 if (!c || !c->configfile)
982 return NULL;
983 return strdup(c->configfile);
984}
985
2a59a681
SH
986static const char *lxcapi_get_config_path(struct lxc_container *c)
987{
988 if (!c || !c->config_path)
989 return NULL;
990 return (const char *)(c->config_path);
991}
992
afeecbba
SH
993/*
994 * not for export
995 * Just recalculate the c->configfile based on the
996 * c->config_path, which must be set.
997 * The lxc_container must be locked or not yet public.
998 */
999static bool set_config_filename(struct lxc_container *c)
1000{
1001 char *newpath;
1002 int len, ret;
1003
1004 if (!c->config_path)
1005 return false;
1006
1007 /* $lxc_path + "/" + c->name + "/" + "config" + '\0' */
1008 len = strlen(c->config_path) + strlen(c->name) + strlen("config") + 3;
1009 newpath = malloc(len);
1010 if (!newpath)
1011 return false;
1012
1013 ret = snprintf(newpath, len, "%s/%s/config", c->config_path, c->name);
1014 if (ret < 0 || ret >= len) {
1015 fprintf(stderr, "Error printing out config file name\n");
1016 free(newpath);
1017 return false;
1018 }
1019
1020 if (c->configfile)
1021 free(c->configfile);
1022 c->configfile = newpath;
1023
1024 return true;
1025}
1026
2a59a681
SH
1027static bool lxcapi_set_config_path(struct lxc_container *c, const char *path)
1028{
1029 char *p;
1030 bool b = false;
afeecbba 1031 char *oldpath = NULL;
2a59a681
SH
1032
1033 if (!c)
1034 return b;
1035
5cee8c50 1036 if (container_mem_lock(c))
2a59a681
SH
1037 return b;
1038
1039 p = strdup(path);
afeecbba
SH
1040 if (!p) {
1041 ERROR("Out of memory setting new lxc path");
2a59a681 1042 goto err;
afeecbba
SH
1043 }
1044
2a59a681
SH
1045 b = true;
1046 if (c->config_path)
afeecbba 1047 oldpath = c->config_path;
2a59a681 1048 c->config_path = p;
afeecbba
SH
1049
1050 /* Since we've changed the config path, we have to change the
1051 * config file name too */
1052 if (!set_config_filename(c)) {
1053 ERROR("Out of memory setting new config filename");
1054 b = false;
1055 free(c->config_path);
1056 c->config_path = oldpath;
1057 oldpath = NULL;
1058 }
2a59a681 1059err:
afeecbba
SH
1060 if (oldpath)
1061 free(oldpath);
5cee8c50 1062 container_mem_unlock(c);
2a59a681
SH
1063 return b;
1064}
1065
1066
794dd120
SH
1067static bool lxcapi_set_cgroup_item(struct lxc_container *c, const char *subsys, const char *value)
1068{
1069 int ret;
1070 bool b = false;
1071
1072 if (!c)
1073 return false;
1074
5cee8c50 1075 if (container_mem_lock(c))
794dd120
SH
1076 return false;
1077
1078 if (is_stopped_nolock(c))
1079 goto err;
1080
ae5c8b8e 1081 ret = lxc_cgroup_set(c->name, subsys, value, c->config_path);
794dd120
SH
1082 if (!ret)
1083 b = true;
1084err:
5cee8c50 1085 container_mem_unlock(c);
794dd120
SH
1086 return b;
1087}
1088
1089static int lxcapi_get_cgroup_item(struct lxc_container *c, const char *subsys, char *retv, int inlen)
1090{
1091 int ret = -1;
1092
1093 if (!c || !c->lxc_conf)
1094 return -1;
1095
5cee8c50 1096 if (container_mem_lock(c))
794dd120
SH
1097 return -1;
1098
1099 if (is_stopped_nolock(c))
1100 goto out;
1101
ae5c8b8e 1102 ret = lxc_cgroup_get(c->name, subsys, retv, inlen, c->config_path);
794dd120
SH
1103
1104out:
5cee8c50 1105 container_mem_unlock(c);
794dd120
SH
1106 return ret;
1107}
1108
67e571de 1109const char *lxc_get_default_config_path(void)
83c98d82
DE
1110{
1111 return default_lxc_path();
1112}
794dd120 1113
a8428dfa
SH
1114const char *lxc_get_default_lvm_vg(void)
1115{
1116 return default_lvm_vg();
1117}
1118
1119const char *lxc_get_default_zfs_root(void)
1120{
1121 return default_zfs_root();
1122}
1123
b6b918a1
SG
1124const char *lxc_get_version(void)
1125{
1126 return lxc_version();
1127}
1128
9be53773
SH
1129static int copy_file(char *old, char *new)
1130{
1131 int in, out;
1132 ssize_t len, ret;
1133 char buf[8096];
1134 struct stat sbuf;
1135
1136 if (file_exists(new)) {
1137 ERROR("copy destination %s exists", new);
1138 return -1;
1139 }
1140 ret = stat(old, &sbuf);
1141 if (ret < 0) {
1142 SYSERROR("stat'ing %s", old);
1143 return -1;
1144 }
1145
1146 in = open(old, O_RDONLY);
1147 if (in < 0) {
1148 SYSERROR("opening original file %s", old);
1149 return -1;
1150 }
1151 out = open(new, O_CREAT | O_EXCL | O_WRONLY, 0644);
1152 if (out < 0) {
1153 SYSERROR("opening new file %s", new);
1154 close(in);
1155 return -1;
1156 }
1157
1158 while (1) {
1159 len = read(in, buf, 8096);
1160 if (len < 0) {
1161 SYSERROR("reading old file %s", old);
1162 goto err;
1163 }
1164 if (len == 0)
1165 break;
1166 ret = write(out, buf, len);
1167 if (ret < len) { // should we retry?
1168 SYSERROR("write to new file %s was interrupted", new);
1169 goto err;
1170 }
1171 }
1172 close(in);
1173 close(out);
1174
1175 // we set mode, but not owner/group
1176 ret = chmod(new, sbuf.st_mode);
1177 if (ret) {
1178 SYSERROR("setting mode on %s", new);
1179 return -1;
1180 }
1181
1182 return 0;
1183
1184err:
1185 close(in);
1186 close(out);
1187 return -1;
1188}
1189
1190/*
1191 * we're being passed result of two strstrs(x, y). We want to write
1192 * all data up to the first found string, or to end of the string if
1193 * neither string was found.
1194 * This function will return the earliest found string if any, or else
1195 * NULL
1196 */
1197static const char *lowest_nonnull(const char *p1, const char *p2)
1198{
1199 if (!p1)
1200 return p2;
1201 if (!p2)
1202 return p1;
1203 return p1 < p2 ? p1 : p2;
1204}
1205
1206static int is_word_sep(char c)
1207{
1208 switch(c) {
1209 case '\0':
1210 case '\n':
1211 case '\r':
1212 case '\t':
1213 case ' ':
1214 case '=':
1215 case '/':
1216 return 1;
1217 default: return 0;
1218 }
1219}
1220
1221static const char *find_first_wholeword(const char *p, const char *word)
1222{
1223 if (!p)
1224 return NULL;
1225
1226 while ((p = strstr(p, word)) != NULL) {
1227 if (is_word_sep(*(p-1)) && is_word_sep(p[strlen(word)]))
1228 return p;
1229 p++;
1230 }
1231 return NULL;
1232}
1233
1234static int update_name_and_paths(const char *path, struct lxc_container *oldc,
1235 const char *newname, const char *newpath)
1236{
1237 FILE *f;
a7478944 1238 long flen;
9be53773
SH
1239 char *contents;
1240 const char *p0, *p1, *p2, *end;
1241 const char *oldpath = oldc->get_config_path(oldc);
1242 const char *oldname = oldc->name;
1243
1244 f = fopen(path, "r");
1245 if (!f) {
1246 SYSERROR("opening old config");
1247 return -1;
1248 }
1249 if (fseek(f, 0, SEEK_END) < 0) {
1250 SYSERROR("seeking to end of old config");
1251 fclose(f);
1252 return -1;
1253 }
1254 flen = ftell(f);
1255 if (flen < 0) {
1256 fclose(f);
1257 SYSERROR("telling size of old config");
1258 return -1;
1259 }
1260 if (fseek(f, 0, SEEK_SET) < 0) {
1261 fclose(f);
1262 SYSERROR("rewinding old config");
1263 return -1;
1264 }
a2eea3c1 1265 contents = malloc(flen+1);
9be53773
SH
1266 if (!contents) {
1267 SYSERROR("out of memory");
1268 fclose(f);
a2eea3c1 1269 return -1;
9be53773
SH
1270 }
1271 if (fread(contents, 1, flen, f) != flen) {
1272 free(contents);
1273 fclose(f);
1274 SYSERROR("reading old config");
1275 return -1;
1276 }
a2eea3c1 1277 contents[flen] = '\0';
9be53773
SH
1278 if (fclose(f) < 0) {
1279 free(contents);
1280 SYSERROR("closing old config");
1281 return -1;
1282 }
1283
1284 f = fopen(path, "w");
1285 if (!f) {
1286 SYSERROR("reopening config");
1287 free(contents);
1288 return -1;
1289 }
1290
1291 p0 = contents;
1292 end = contents + flen;
1293 while (1) {
1294 p1 = find_first_wholeword(p0, oldpath);
1295 p2 = find_first_wholeword(p0, oldname);
1296 if (!p1 && !p2) {
1297 // write the rest and be done
1298 if (fwrite(p0, 1, (end-p0), f) != (end-p0)) {
1299 SYSERROR("writing new config");
1300 free(contents);
1301 fclose(f);
1302 return -1;
1303 }
1304 free(contents);
1305 fclose(f);
1306 // success
1307 return 0;
1308 } else {
1309 const char *p = lowest_nonnull(p1, p2);
1310 const char *new = (p == p2) ? newname : newpath;
1311 if (fwrite(p0, 1, (p-p0), f) != (p-p0)) {
1312 SYSERROR("writing new config");
1313 free(contents);
1314 fclose(f);
1315 return -1;
1316 }
1317 p0 = p;
1318 // now write the newpath or newname
1319 if (fwrite(new, 1, strlen(new), f) != strlen(new)) {
1320 SYSERROR("writing new name or path in new config");
1321 free(contents);
1322 fclose(f);
1323 return -1;
1324 }
1325 p0 += (p == p2) ? strlen(oldname) : strlen(oldpath);
1326 }
1327 }
1328}
1329
1330static int copyhooks(struct lxc_container *oldc, struct lxc_container *c)
1331{
1332 int i;
1333 int ret;
1334 struct lxc_list *it;
1335
1336 for (i=0; i<NUM_LXC_HOOKS; i++) {
1337 lxc_list_for_each(it, &c->lxc_conf->hooks[i]) {
1338 char *hookname = it->elem;
1339 char *fname = rindex(hookname, '/');
1340 char tmppath[MAXPATHLEN];
1341 if (!fname) // relative path - we don't support, but maybe we should
1342 return 0;
1343 // copy the script, and change the entry in confile
1344 ret = snprintf(tmppath, MAXPATHLEN, "%s/%s/%s",
1345 c->config_path, c->name, fname+1);
1346 if (ret < 0 || ret >= MAXPATHLEN)
1347 return -1;
1348 ret = copy_file(it->elem, tmppath);
1349 if (ret < 0)
1350 return -1;
1351 free(it->elem);
1352 it->elem = strdup(tmppath);
1353 if (!it->elem) {
1354 ERROR("out of memory copying hook path");
1355 return -1;
1356 }
1357 update_name_and_paths(it->elem, oldc, c->name, c->get_config_path(c));
1358 }
1359 }
1360
1361 c->save_config(c, NULL);
1362 return 0;
1363}
1364
1365static void new_hwaddr(char *hwaddr)
1366{
1367 FILE *f = fopen("/dev/urandom", "r");
1368 if (f) {
1369 unsigned int seed;
1370 int ret = fread(&seed, sizeof(seed), 1, f);
1371 if (ret != 1)
1372 seed = time(NULL);
1373 fclose(f);
1374 srand(seed);
1375 } else
1376 srand(time(NULL));
1377 snprintf(hwaddr, 18, "00:16:3e:%02x:%02x:%02x",
1378 rand() % 255, rand() % 255, rand() % 255);
1379}
1380
1381static void network_new_hwaddrs(struct lxc_container *c)
1382{
1383 struct lxc_list *it;
1384
1385 lxc_list_for_each(it, &c->lxc_conf->network) {
1386 struct lxc_netdev *n = it->elem;
1387 if (n->hwaddr)
1388 new_hwaddr(n->hwaddr);
1389 }
1390}
1391
1392static int copy_fstab(struct lxc_container *oldc, struct lxc_container *c)
1393{
1394 char newpath[MAXPATHLEN];
1395 char *oldpath = oldc->lxc_conf->fstab;
1396 int ret;
1397
1398 if (!oldpath)
1399 return 0;
1400
1401 char *p = rindex(oldpath, '/');
1402 if (!p)
1403 return -1;
1404 ret = snprintf(newpath, MAXPATHLEN, "%s/%s%s",
1405 c->config_path, c->name, p);
1406 if (ret < 0 || ret >= MAXPATHLEN) {
1407 ERROR("error printing new path for %s", oldpath);
1408 return -1;
1409 }
1410 if (file_exists(newpath)) {
1411 ERROR("error: fstab file %s exists", newpath);
1412 return -1;
1413 }
1414
1415 if (copy_file(oldpath, newpath) < 0) {
1416 ERROR("error: copying %s to %s", oldpath, newpath);
1417 return -1;
1418 }
1419 free(c->lxc_conf->fstab);
1420 c->lxc_conf->fstab = strdup(newpath);
1421 if (!c->lxc_conf->fstab) {
1422 ERROR("error: allocating pathname");
1423 return -1;
1424 }
1425
1426 return 0;
1427}
1428
1429static int copy_storage(struct lxc_container *c0, struct lxc_container *c,
1430 const char *newtype, int flags, const char *bdevdata, unsigned long newsize)
1431{
1432 struct bdev *bdev;
1433
1434 bdev = bdev_copy(c0->lxc_conf->rootfs.path, c0->name, c->name,
1435 c0->config_path, c->config_path, newtype, !!(flags & LXC_CLONE_SNAPSHOT),
1436 bdevdata, newsize);
1437 if (!bdev) {
1438 ERROR("error copying storage");
1439 return -1;
1440 }
1441 free(c->lxc_conf->rootfs.path);
1442 c->lxc_conf->rootfs.path = strdup(bdev->src);
1443 bdev_put(bdev);
1444 if (!c->lxc_conf->rootfs.path)
1445 return -1;
1446 // here we could also update all lxc.mount.entries or even
1447 // items in the lxc.mount fstab list. As discussed on m-l,
1448 // we could do either any source paths starting with the
1449 // lxcpath/oldname, or simply anythign which is not a virtual
1450 // fs or a bind mount.
1451 return 0;
1452}
1453
148e91f5 1454static int clone_update_rootfs(struct lxc_container *c, int flags, char **hookargs)
9be53773
SH
1455{
1456 int ret = -1;
1457 char path[MAXPATHLEN];
1458 struct bdev *bdev;
1459 FILE *fout;
1460 pid_t pid;
148e91f5 1461 struct lxc_conf *conf = c->lxc_conf;
9be53773
SH
1462
1463 /* update hostname in rootfs */
1464 /* we're going to mount, so run in a clean namespace to simplify cleanup */
1465
1466 pid = fork();
1467 if (pid < 0)
1468 return -1;
1469 if (pid > 0)
1470 return wait_for_pid(pid);
1471
1472 if (unshare(CLONE_NEWNS) < 0) {
1473 ERROR("error unsharing mounts");
1474 exit(1);
1475 }
1476 bdev = bdev_init(c->lxc_conf->rootfs.path, c->lxc_conf->rootfs.mount, NULL);
1477 if (!bdev)
1478 exit(1);
1479 if (bdev->ops->mount(bdev) < 0)
1480 exit(1);
148e91f5
SH
1481
1482 if (!lxc_list_empty(&conf->hooks[LXCHOOK_CLONE])) {
1483 /* Start of environment variable setup for hooks */
1484 if (setenv("LXC_NAME", c->name, 1)) {
1485 SYSERROR("failed to set environment variable for container name");
1486 }
1487 if (setenv("LXC_CONFIG_FILE", conf->rcfile, 1)) {
1488 SYSERROR("failed to set environment variable for config path");
1489 }
1490 if (setenv("LXC_ROOTFS_MOUNT", conf->rootfs.mount, 1)) {
1491 SYSERROR("failed to set environment variable for rootfs mount");
1492 }
1493 if (setenv("LXC_ROOTFS_PATH", conf->rootfs.path, 1)) {
1494 SYSERROR("failed to set environment variable for rootfs mount");
1495 }
1496
1497 if (run_lxc_hooks(c->name, "clone", conf, hookargs)) {
1498 ERROR("Error executing clone hook for %s", c->name);
1499 exit(1);
1500 }
1501 }
1502
1503 if (!(flags & LXC_CLONE_KEEPNAME)) {
1504 ret = snprintf(path, MAXPATHLEN, "%s/etc/hostname", bdev->dest);
1505 if (ret < 0 || ret >= MAXPATHLEN)
1506 exit(1);
1507 if (!(fout = fopen(path, "w"))) {
1508 SYSERROR("unable to open %s: ignoring\n", path);
1509 exit(0);
1510 }
1511 if (fprintf(fout, "%s", c->name) < 0)
1512 exit(1);
1513 if (fclose(fout) < 0)
1514 exit(1);
9be53773 1515 }
9be53773
SH
1516 exit(0);
1517}
1518
1519/*
1520 * We want to support:
1521sudo lxc-clone -o o1 -n n1 -s -L|-fssize fssize -v|--vgname vgname \
1522 -p|--lvprefix lvprefix -t|--fstype fstype -B backingstore
1523
1524-s [ implies overlayfs]
1525-s -B overlayfs
1526-s -B aufs
1527
1528only rootfs gets converted (copied/snapshotted) on clone.
1529*/
1530
1531static int create_file_dirname(char *path)
1532{
1533 char *p = rindex(path, '/');
1534 int ret;
1535
1536 if (!p)
1537 return -1;
1538 *p = '\0';
1539 ret = mkdir(path, 0755);
1540 if (ret && errno != EEXIST)
1541 SYSERROR("creating container path %s\n", path);
1542 *p = '/';
1543 return ret;
1544}
1545
1546struct lxc_container *lxcapi_clone(struct lxc_container *c, const char *newname,
1547 const char *lxcpath, int flags,
148e91f5
SH
1548 const char *bdevtype, const char *bdevdata, unsigned long newsize,
1549 char **hookargs)
9be53773
SH
1550{
1551 struct lxc_container *c2 = NULL;
1552 char newpath[MAXPATHLEN];
1553 int ret;
1554 const char *n, *l;
1555 FILE *fout;
1556
1557 if (!c || !c->is_defined(c))
1558 return NULL;
1559
5cee8c50 1560 if (container_mem_lock(c))
9be53773
SH
1561 return NULL;
1562
1563 if (c->is_running(c)) {
1564 ERROR("error: Original container (%s) is running", c->name);
1565 goto out;
1566 }
1567
1568 // Make sure the container doesn't yet exist.
1569 n = newname ? newname : c->name;
1570 l = lxcpath ? lxcpath : c->get_config_path(c);
1571 ret = snprintf(newpath, MAXPATHLEN, "%s/%s/config", l, n);
1572 if (ret < 0 || ret >= MAXPATHLEN) {
1573 SYSERROR("clone: failed making config pathname");
1574 goto out;
1575 }
1576 if (file_exists(newpath)) {
1577 ERROR("error: clone: %s exists", newpath);
1578 goto out;
1579 }
1580
1581 if (create_file_dirname(newpath) < 0) {
1582 ERROR("Error creating container dir for %s", newpath);
1583 goto out;
1584 }
1585
1586 // copy the configuration, tweak it as needed,
1587 fout = fopen(newpath, "w");
1588 if (!fout) {
1589 SYSERROR("open %s", newpath);
1590 goto out;
1591 }
1592 write_config(fout, c->lxc_conf);
1593 fclose(fout);
1594
1595 if (update_name_and_paths(newpath, c, n, l) < 0) {
1596 ERROR("Error updating name in cloned config");
1597 goto out;
1598 }
1599
1600 sprintf(newpath, "%s/%s/rootfs", l, n);
1601 if (mkdir(newpath, 0755) < 0) {
1602 SYSERROR("error creating %s", newpath);
1603 goto out;
1604 }
1605
1606 c2 = lxc_container_new(n, l);
375c2258 1607 if (!c2) {
9be53773
SH
1608 ERROR("clone: failed to create new container (%s %s)", n, l);
1609 goto out;
1610 }
1611
1612 // copy hooks if requested
1613 if (flags & LXC_CLONE_COPYHOOKS) {
1614 ret = copyhooks(c, c2);
1615 if (ret < 0) {
1616 ERROR("error copying hooks");
9be53773
SH
1617 goto out;
1618 }
1619 }
1620
1621 if (copy_fstab(c, c2) < 0) {
1622 ERROR("error copying fstab");
9be53773
SH
1623 goto out;
1624 }
1625
1626 // update macaddrs
1627 if (!(flags & LXC_CLONE_KEEPMACADDR))
1628 network_new_hwaddrs(c2);
1629
1630 // copy/snapshot rootfs's
1631 ret = copy_storage(c, c2, bdevtype, flags, bdevdata, newsize);
375c2258 1632 if (ret < 0)
9be53773 1633 goto out;
9be53773 1634
375c2258 1635 if (!c2->save_config(c2, NULL))
9be53773 1636 goto out;
9be53773 1637
148e91f5 1638 if (clone_update_rootfs(c2, flags, hookargs) < 0)
9be53773 1639 goto out;
9be53773
SH
1640
1641 // TODO: update c's lxc.snapshot = count
5cee8c50 1642 container_mem_unlock(c);
9be53773
SH
1643 return c2;
1644
1645out:
5cee8c50 1646 container_mem_unlock(c);
375c2258
SH
1647 if (c2) {
1648 c2->destroy(c2);
9be53773 1649 lxc_container_put(c2);
375c2258 1650 }
9be53773
SH
1651
1652 return NULL;
1653}
1654
afeecbba 1655struct lxc_container *lxc_container_new(const char *name, const char *configpath)
72d0e1cb
SG
1656{
1657 struct lxc_container *c;
72d0e1cb
SG
1658
1659 c = malloc(sizeof(*c));
1660 if (!c) {
1661 fprintf(stderr, "failed to malloc lxc_container\n");
1662 return NULL;
1663 }
1664 memset(c, 0, sizeof(*c));
1665
afeecbba
SH
1666 if (configpath)
1667 c->config_path = strdup(configpath);
1668 else
67e571de 1669 c->config_path = strdup(default_lxc_path());
afeecbba 1670
2a59a681
SH
1671 if (!c->config_path) {
1672 fprintf(stderr, "Out of memory");
1673 goto err;
1674 }
1675
72d0e1cb
SG
1676 c->name = malloc(strlen(name)+1);
1677 if (!c->name) {
1678 fprintf(stderr, "Error allocating lxc_container name\n");
1679 goto err;
1680 }
1681 strcpy(c->name, name);
1682
1683 c->numthreads = 1;
df271a59 1684 if (!(c->slock = lxc_newlock(c->config_path, name))) {
72d0e1cb
SG
1685 fprintf(stderr, "failed to create lock\n");
1686 goto err;
1687 }
1688
df271a59 1689 if (!(c->privlock = lxc_newlock(NULL, NULL))) {
72d0e1cb
SG
1690 fprintf(stderr, "failed to alloc privlock\n");
1691 goto err;
1692 }
1693
afeecbba 1694 if (!set_config_filename(c)) {
72d0e1cb
SG
1695 fprintf(stderr, "Error allocating config file pathname\n");
1696 goto err;
1697 }
72d0e1cb
SG
1698
1699 if (file_exists(c->configfile))
1700 lxcapi_load_config(c, NULL);
1701
1702 // assign the member functions
1703 c->is_defined = lxcapi_is_defined;
1704 c->state = lxcapi_state;
1705 c->is_running = lxcapi_is_running;
1706 c->freeze = lxcapi_freeze;
1707 c->unfreeze = lxcapi_unfreeze;
1708 c->init_pid = lxcapi_init_pid;
1709 c->load_config = lxcapi_load_config;
1710 c->want_daemonize = lxcapi_want_daemonize;
1711 c->start = lxcapi_start;
1712 c->startl = lxcapi_startl;
1713 c->stop = lxcapi_stop;
1714 c->config_file_name = lxcapi_config_file_name;
1715 c->wait = lxcapi_wait;
1716 c->set_config_item = lxcapi_set_config_item;
1717 c->destroy = lxcapi_destroy;
1718 c->save_config = lxcapi_save_config;
1719 c->get_keys = lxcapi_get_keys;
1720 c->create = lxcapi_create;
1721 c->createl = lxcapi_createl;
1722 c->shutdown = lxcapi_shutdown;
1723 c->clear_config_item = lxcapi_clear_config_item;
1724 c->get_config_item = lxcapi_get_config_item;
794dd120
SH
1725 c->get_cgroup_item = lxcapi_get_cgroup_item;
1726 c->set_cgroup_item = lxcapi_set_cgroup_item;
2a59a681
SH
1727 c->get_config_path = lxcapi_get_config_path;
1728 c->set_config_path = lxcapi_set_config_path;
9be53773 1729 c->clone = lxcapi_clone;
9c83a661 1730 c->get_ips = lxcapi_get_ips;
72d0e1cb
SG
1731
1732 /* we'll allow the caller to update these later */
ab1bf971 1733 if (lxc_log_init(NULL, "none", NULL, "lxc_container", 0, c->config_path)) {
72d0e1cb
SG
1734 fprintf(stderr, "failed to open log\n");
1735 goto err;
1736 }
1737
72d0e1cb
SG
1738 return c;
1739
1740err:
1741 lxc_container_free(c);
1742 return NULL;
1743}
1744
4a7c7daa 1745int lxc_get_wait_states(const char **states)
72d0e1cb
SG
1746{
1747 int i;
1748
1749 if (states)
1750 for (i=0; i<MAX_STATE; i++)
1751 states[i] = lxc_state2str(i);
1752 return MAX_STATE;
1753}