3 * Copyright © 2012 Serge Hallyn <serge.hallyn@ubuntu.com>.
4 * Copyright © 2012 Canonical Ltd.
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
26 #include <sys/types.h>
28 #include <sys/mount.h>
34 #include <arpa/inet.h>
38 #include <sys/syscall.h>
40 #include <lxc/lxccontainer.h>
41 #include <lxc/version.h>
56 #include "namespace.h"
62 #include <../include/ifaddrs.h>
65 #define MAX_BUFFER 4096
67 #define NOT_SUPPORTED_ERROR "the requested function %s is not currently supported with unprivileged containers"
69 /* Define faccessat() if missing from the C library */
70 #ifndef HAVE_FACCESSAT
71 static int faccessat(int __fd
, const char *__file
, int __type
, int __flag
)
74 return syscall(__NR_faccessat
, __fd
, __file
, __type
, __flag
);
83 lxc_log_define(lxc_container
, lxc
);
85 static bool file_exists(const char *f
)
89 return stat(f
, &statbuf
) == 0;
92 static bool config_file_exists(const char *lxcpath
, const char *cname
)
94 /* $lxcpath + '/' + $cname + '/config' + \0 */
95 int ret
, len
= strlen(lxcpath
) + strlen(cname
) + 9;
96 char *fname
= alloca(len
);
98 ret
= snprintf(fname
, len
, "%s/%s/config", lxcpath
, cname
);
99 if (ret
< 0 || ret
>= len
)
102 return file_exists(fname
);
106 * A few functions to help detect when a container creation failed.
107 * If a container creation was killed partway through, then trying
108 * to actually start that container could harm the host. We detect
109 * this by creating a 'partial' file under the container directory,
110 * and keeping an advisory lock. When container creation completes,
111 * we remove that file. When we load or try to start a container, if
112 * we find that file, without a flock, we remove the container.
114 static int ongoing_create(struct lxc_container
*c
)
116 int len
= strlen(c
->config_path
) + strlen(c
->name
) + 10;
117 char *path
= alloca(len
);
121 ret
= snprintf(path
, len
, "%s/%s/partial", c
->config_path
, c
->name
);
122 if (ret
< 0 || ret
>= len
) {
123 ERROR("Error writing partial pathname");
127 if (!file_exists(path
))
129 fd
= open(path
, O_RDWR
);
131 // give benefit of the doubt
132 SYSERROR("Error opening partial file");
136 lk
.l_whence
= SEEK_SET
;
140 if (fcntl(fd
, F_GETLK
, &lk
) == 0 && lk
.l_pid
!= -1) {
141 // create is still ongoing
145 // create completed but partial is still there.
150 static int create_partial(struct lxc_container
*c
)
152 // $lxcpath + '/' + $name + '/partial' + \0
153 int len
= strlen(c
->config_path
) + strlen(c
->name
) + 10;
154 char *path
= alloca(len
);
158 ret
= snprintf(path
, len
, "%s/%s/partial", c
->config_path
, c
->name
);
159 if (ret
< 0 || ret
>= len
) {
160 ERROR("Error writing partial pathname");
163 if ((fd
=open(path
, O_RDWR
| O_CREAT
| O_EXCL
, 0755)) < 0) {
164 SYSERROR("Erorr creating partial file");
168 lk
.l_whence
= SEEK_SET
;
171 if (fcntl(fd
, F_SETLKW
, &lk
) < 0) {
172 SYSERROR("Error locking partial file %s", path
);
180 static void remove_partial(struct lxc_container
*c
, int fd
)
182 // $lxcpath + '/' + $name + '/partial' + \0
183 int len
= strlen(c
->config_path
) + strlen(c
->name
) + 10;
184 char *path
= alloca(len
);
188 ret
= snprintf(path
, len
, "%s/%s/partial", c
->config_path
, c
->name
);
189 if (ret
< 0 || ret
>= len
) {
190 ERROR("Error writing partial pathname");
193 if (unlink(path
) < 0)
194 SYSERROR("Error unlink partial file %s", path
);
198 * 1. container_mem_lock(c) protects the struct lxc_container from multiple threads.
199 * 2. container_disk_lock(c) protects the on-disk container data - in particular the
200 * container configuration file.
201 * The container_disk_lock also takes the container_mem_lock.
202 * 3. thread_mutex protects process data (ex: fd table) from multiple threads.
203 * NOTHING mutexes two independent programs with their own struct
204 * lxc_container for the same c->name, between API calls. For instance,
205 * c->config_read(); c->start(); Between those calls, data on disk
206 * could change (which shouldn't bother the caller unless for instance
207 * the rootfs get moved). c->config_read(); update; c->config_write();
208 * Two such updaters could race. The callers should therefore check their
209 * results. Trying to prevent that would necessarily expose us to deadlocks
210 * due to hung callers. So I prefer to keep the locks only within our own
211 * functions, not across functions.
213 * If you're going to clone while holding a lxccontainer, increment
214 * c->numthreads (under privlock) before forking. When deleting,
215 * decrement numthreads under privlock, then if it hits 0 you can delete.
216 * Do not ever use a lxccontainer whose numthreads you did not bump.
219 static void lxc_container_free(struct lxc_container
*c
)
226 c
->configfile
= NULL
;
228 if (c
->error_string
) {
229 free(c
->error_string
);
230 c
->error_string
= NULL
;
233 lxc_putlock(c
->slock
);
237 lxc_putlock(c
->privlock
);
245 lxc_conf_free(c
->lxc_conf
);
248 if (c
->config_path
) {
249 free(c
->config_path
);
250 c
->config_path
= NULL
;
257 * Consider the following case:
258 freer | racing get()er
259 ==================================================================
260 lxc_container_put() | lxc_container_get()
261 \ lxclock(c->privlock) | c->numthreads < 1? (no)
262 \ c->numthreads = 0 | \ lxclock(c->privlock) -> waits
264 \ lxc_container_free() | \ lxclock() returns
265 | \ c->numthreads < 1 -> return 0
267 \ \ sem_destroy(privlock) |
269 * When the get()er checks numthreads the first time, one of the following
271 * 1. freer has set numthreads = 0. get() returns 0
272 * 2. freer is between lxclock and setting numthreads to 0. get()er will
273 * sem_wait on privlock, get lxclock after freer() drops it, then see
274 * numthreads is 0 and exit without touching lxclock again..
275 * 3. freer has not yet locked privlock. If get()er runs first, then put()er
276 * will see --numthreads = 1 and not call lxc_container_free().
279 int lxc_container_get(struct lxc_container
*c
)
284 // if someone else has already started freeing the container, don't
285 // try to take the lock, which may be invalid
286 if (c
->numthreads
< 1)
289 if (container_mem_lock(c
))
291 if (c
->numthreads
< 1) {
292 // bail without trying to unlock, bc the privlock is now probably
297 container_mem_unlock(c
);
301 int lxc_container_put(struct lxc_container
*c
)
305 if (container_mem_lock(c
))
307 if (--c
->numthreads
< 1) {
308 container_mem_unlock(c
);
309 lxc_container_free(c
);
312 container_mem_unlock(c
);
316 static bool lxcapi_is_defined(struct lxc_container
*c
)
325 if (container_mem_lock(c
))
329 statret
= stat(c
->configfile
, &statbuf
);
335 container_mem_unlock(c
);
339 static const char *lxcapi_state(struct lxc_container
*c
)
345 s
= lxc_getstate(c
->name
, c
->config_path
);
346 return lxc_state2str(s
);
349 static bool is_stopped(struct lxc_container
*c
)
352 s
= lxc_getstate(c
->name
, c
->config_path
);
353 return (s
== STOPPED
);
356 static bool lxcapi_is_running(struct lxc_container
*c
)
363 if (!s
|| strcmp(s
, "STOPPED") == 0)
368 static bool lxcapi_freeze(struct lxc_container
*c
)
374 ret
= lxc_freeze(c
->name
, c
->config_path
);
380 static bool lxcapi_unfreeze(struct lxc_container
*c
)
386 ret
= lxc_unfreeze(c
->name
, c
->config_path
);
392 static int lxcapi_console_getfd(struct lxc_container
*c
, int *ttynum
, int *masterfd
)
398 ttyfd
= lxc_console_getfd(c
, ttynum
, masterfd
);
402 static int lxcapi_console(struct lxc_container
*c
, int ttynum
, int stdinfd
,
403 int stdoutfd
, int stderrfd
, int escape
)
405 return lxc_console(c
, ttynum
, stdinfd
, stdoutfd
, stderrfd
, escape
);
408 static pid_t
lxcapi_init_pid(struct lxc_container
*c
)
413 return lxc_cmd_get_init_pid(c
->name
, c
->config_path
);
416 static bool load_config_locked(struct lxc_container
*c
, const char *fname
)
419 c
->lxc_conf
= lxc_conf_init();
420 if (c
->lxc_conf
&& !lxc_config_read(fname
, c
->lxc_conf
))
425 static bool lxcapi_load_config(struct lxc_container
*c
, const char *alt_file
)
427 bool ret
= false, need_disklock
= false;
433 fname
= c
->configfile
;
439 * If we're reading something other than the container's config,
440 * we only need to lock the in-memory container. If loading the
441 * container's config file, take the disk lock.
443 if (strcmp(fname
, c
->configfile
) == 0)
444 need_disklock
= true;
447 lret
= container_disk_lock(c
);
449 lret
= container_mem_lock(c
);
453 ret
= load_config_locked(c
, fname
);
456 container_disk_unlock(c
);
458 container_mem_unlock(c
);
462 static bool lxcapi_want_daemonize(struct lxc_container
*c
, bool state
)
464 if (!c
|| !c
->lxc_conf
)
466 if (container_mem_lock(c
)) {
467 ERROR("Error getting mem lock");
470 c
->daemonize
= state
;
471 /* daemonize implies close_all_fds so set it */
473 c
->lxc_conf
->close_all_fds
= 1;
474 container_mem_unlock(c
);
478 static bool lxcapi_want_close_all_fds(struct lxc_container
*c
, bool state
)
480 if (!c
|| !c
->lxc_conf
)
482 if (container_mem_lock(c
)) {
483 ERROR("Error getting mem lock");
486 c
->lxc_conf
->close_all_fds
= state
;
487 container_mem_unlock(c
);
491 static bool lxcapi_wait(struct lxc_container
*c
, const char *state
, int timeout
)
498 ret
= lxc_wait(c
->name
, state
, timeout
, c
->config_path
);
503 static bool wait_on_daemonized_start(struct lxc_container
*c
, int pid
)
505 /* we'll probably want to make this timeout configurable? */
506 int timeout
= 5, ret
, status
;
509 * our child is going to fork again, then exit. reap the
512 ret
= waitpid(pid
, &status
, 0);
513 if (ret
== -1 || !WIFEXITED(status
) || WEXITSTATUS(status
) != 0)
514 DEBUG("failed waiting for first dual-fork child");
515 return lxcapi_wait(c
, "RUNNING", timeout
);
518 static bool am_single_threaded(void)
520 struct dirent dirent
, *direntp
;
524 dir
= opendir("/proc/self/task");
526 INFO("failed to open /proc/self/task");
530 while (!readdir_r(dir
, &dirent
, &direntp
)) {
534 if (!strcmp(direntp
->d_name
, "."))
537 if (!strcmp(direntp
->d_name
, ".."))
547 * I can't decide if it'd be more convenient for callers if we accept '...',
548 * or a null-terminated array (i.e. execl vs execv)
550 static bool lxcapi_start(struct lxc_container
*c
, int useinit
, char * const argv
[])
553 struct lxc_conf
*conf
;
554 bool daemonize
= false;
556 char *default_args
[] = {
561 /* container exists */
564 /* container has been setup */
568 if ((ret
= ongoing_create(c
)) < 0) {
569 ERROR("Error checking for incomplete creation");
573 ERROR("Error: %s creation was not completed", c
->name
);
576 } else if (ret
== 1) {
577 ERROR("Error: creation of %s is ongoing", c
->name
);
581 /* is this app meant to be run through lxcinit, as in lxc-execute? */
582 if (useinit
&& !argv
)
585 if (container_mem_lock(c
))
588 daemonize
= c
->daemonize
;
589 container_mem_unlock(c
);
592 ret
= lxc_execute(c
->name
, argv
, 1, conf
, c
->config_path
);
593 return ret
== 0 ? true : false;
600 * say, I'm not sure - what locks do we want here? Any?
601 * Is liblxc's locking enough here to protect the on disk
602 * container? We don't want to exclude things like lxc_info
603 * while container is running...
606 lxc_monitord_spawn(c
->config_path
);
613 /* Set to NULL because we don't want father unlink
614 * the PID file, child will do the free and unlink.
617 return wait_on_daemonized_start(c
, pid
);
620 /* second fork to be reparented by init */
623 SYSERROR("Error doing dual-fork");
628 /* like daemon(), chdir to / and redirect 0,1,2 to /dev/null */
630 SYSERROR("Error chdir()ing to /.");
636 open("/dev/zero", O_RDONLY
);
637 open("/dev/null", O_RDWR
);
638 open("/dev/null", O_RDWR
);
642 if (!am_single_threaded()) {
643 ERROR("Cannot start non-daemonized container when threaded");
648 /* We need to write PID file after daeminize, so we always
649 * write the right PID.
652 pid_fp
= fopen(c
->pidfile
, "w");
653 if (pid_fp
== NULL
) {
654 SYSERROR("Failed to create pidfile '%s' for '%s'",
655 c
->pidfile
, c
->name
);
659 if (fprintf(pid_fp
, "%d\n", getpid()) < 0) {
660 SYSERROR("Failed to write '%s'", c
->pidfile
);
672 ret
= lxc_start(c
->name
, argv
, conf
, c
->config_path
);
675 INFO("container requested reboot");
687 exit (ret
== 0 ? true : false);
689 return (ret
== 0 ? true : false);
693 * note there MUST be an ending NULL
695 static bool lxcapi_startl(struct lxc_container
*c
, int useinit
, ...)
698 char **inargs
= NULL
;
701 /* container exists */
705 va_start(ap
, useinit
);
706 inargs
= lxc_va_arg_list_to_argv(ap
, 0, 1);
710 ERROR("Memory allocation error.");
714 /* pass NULL if no arguments were supplied */
715 bret
= lxcapi_start(c
, useinit
, *inargs
? inargs
: NULL
);
720 for (arg
= inargs
; *arg
; arg
++)
728 static bool lxcapi_stop(struct lxc_container
*c
)
735 ret
= lxc_cmd_stop(c
->name
, c
->config_path
);
741 * create the standard expected container dir
743 static bool create_container_dir(struct lxc_container
*c
)
748 len
= strlen(c
->config_path
) + strlen(c
->name
) + 2;
752 ret
= snprintf(s
, len
, "%s/%s", c
->config_path
, c
->name
);
753 if (ret
< 0 || ret
>= len
) {
757 ret
= mkdir(s
, 0755);
762 SYSERROR("failed to create container path for %s", c
->name
);
768 static const char *lxcapi_get_config_path(struct lxc_container
*c
);
769 static bool lxcapi_set_config_item(struct lxc_container
*c
, const char *key
, const char *v
);
772 * do_bdev_create: thin wrapper around bdev_create(). Like bdev_create(),
773 * it returns a mounted bdev on success, NULL on error.
775 static struct bdev
*do_bdev_create(struct lxc_container
*c
, const char *type
,
776 struct bdev_specs
*specs
)
783 /* rootfs.path or lxcpath/lxcname/rootfs */
784 if (c
->lxc_conf
->rootfs
.path
&& access(c
->lxc_conf
->rootfs
.path
, F_OK
) == 0) {
785 const char *rpath
= c
->lxc_conf
->rootfs
.path
;
786 len
= strlen(rpath
) + 1;
788 ret
= snprintf(dest
, len
, "%s", rpath
);
790 const char *lxcpath
= lxcapi_get_config_path(c
);
791 len
= strlen(c
->name
) + strlen(lxcpath
) + 9;
793 ret
= snprintf(dest
, len
, "%s/%s/rootfs", lxcpath
, c
->name
);
795 if (ret
< 0 || ret
>= len
)
798 bdev
= bdev_create(dest
, type
, c
->name
, specs
);
800 ERROR("Failed to create backing store type %s", type
);
804 lxcapi_set_config_item(c
, "lxc.rootfs", bdev
->src
);
806 /* if we are not root, chown the rootfs dir to root in the
809 if (geteuid() != 0 || (c
->lxc_conf
&& !lxc_list_empty(&c
->lxc_conf
->id_map
))) {
810 if (chown_mapped_root(bdev
->dest
, c
->lxc_conf
) < 0) {
811 ERROR("Error chowning %s to container root", bdev
->dest
);
821 * Given the '-t' template option to lxc-create, figure out what to
822 * do. If the template is a full executable path, use that. If it
823 * is something like 'sshd', then return $templatepath/lxc-sshd.
824 * On success return the template, on error return NULL.
826 static char *get_template_path(const char *t
)
831 if (t
[0] == '/' && access(t
, X_OK
) == 0) {
836 len
= strlen(LXCTEMPLATEDIR
) + strlen(t
) + strlen("/lxc-") + 1;
840 ret
= snprintf(tpath
, len
, "%s/lxc-%s", LXCTEMPLATEDIR
, t
);
841 if (ret
< 0 || ret
>= len
) {
845 if (access(tpath
, X_OK
) < 0) {
846 SYSERROR("bad template: %s", t
);
854 static char *lxcbasename(char *path
)
856 char *p
= path
+ strlen(path
) - 1;
857 while (*p
!= '/' && p
> path
)
862 static bool create_run_template(struct lxc_container
*c
, char *tpath
, bool quiet
,
872 SYSERROR("failed to fork task for container creation template");
876 if (pid
== 0) { // child
877 char *patharg
, *namearg
, *rootfsarg
, *src
;
878 struct bdev
*bdev
= NULL
;
880 int ret
, len
, nargs
= 0;
882 struct lxc_conf
*conf
= c
->lxc_conf
;
888 open("/dev/zero", O_RDONLY
);
889 open("/dev/null", O_RDWR
);
890 open("/dev/null", O_RDWR
);
893 src
= c
->lxc_conf
->rootfs
.path
;
895 * for an overlay create, what the user wants is the template to fill
896 * in what will become the readonly lower layer. So don't mount for
899 if (strncmp(src
, "overlayfs:", 10) == 0)
900 src
= overlay_getlower(src
+10);
901 if (strncmp(src
, "aufs:", 5) == 0)
902 src
= overlay_getlower(src
+5);
904 bdev
= bdev_init(src
, c
->lxc_conf
->rootfs
.mount
, NULL
);
906 ERROR("Error opening rootfs");
910 if (geteuid() == 0) {
911 if (unshare(CLONE_NEWNS
) < 0) {
912 ERROR("error unsharing mounts");
915 if (detect_shared_rootfs()) {
916 if (mount(NULL
, "/", NULL
, MS_SLAVE
|MS_REC
, NULL
)) {
917 SYSERROR("Failed to make / rslave to run template");
918 ERROR("Continuing...");
922 if (strcmp(bdev
->type
, "dir") != 0) {
923 if (geteuid() != 0) {
924 ERROR("non-root users can only create directory-backed containers");
927 if (bdev
->ops
->mount(bdev
) < 0) {
928 ERROR("Error mounting rootfs");
931 } else { // TODO come up with a better way here!
934 bdev
->dest
= strdup(bdev
->src
);
938 * create our new array, pre-pend the template name and
942 for (nargs
= 0; argv
[nargs
]; nargs
++) ;
943 nargs
+= 4; // template, path, rootfs and name args
945 newargv
= malloc(nargs
* sizeof(*newargv
));
948 newargv
[0] = lxcbasename(tpath
);
950 len
= strlen(c
->config_path
) + strlen(c
->name
) + strlen("--path=") + 2;
951 patharg
= malloc(len
);
954 ret
= snprintf(patharg
, len
, "--path=%s/%s", c
->config_path
, c
->name
);
955 if (ret
< 0 || ret
>= len
)
957 newargv
[1] = patharg
;
958 len
= strlen("--name=") + strlen(c
->name
) + 1;
959 namearg
= malloc(len
);
962 ret
= snprintf(namearg
, len
, "--name=%s", c
->name
);
963 if (ret
< 0 || ret
>= len
)
965 newargv
[2] = namearg
;
967 len
= strlen("--rootfs=") + 1 + strlen(bdev
->dest
);
968 rootfsarg
= malloc(len
);
971 ret
= snprintf(rootfsarg
, len
, "--rootfs=%s", bdev
->dest
);
972 if (ret
< 0 || ret
>= len
)
974 newargv
[3] = rootfsarg
;
976 /* add passed-in args */
978 for (i
= 4; i
< nargs
; i
++)
979 newargv
[i
] = argv
[i
-4];
981 /* add trailing NULL */
983 newargv
= realloc(newargv
, nargs
* sizeof(*newargv
));
986 newargv
[nargs
- 1] = NULL
;
989 * If we're running the template in a mapped userns, then
990 * we prepend the template command with:
991 * lxc-usernsexec <-m map1> ... <-m mapn> --
992 * and we append "--mapped-uid x", where x is the mapped uid
995 if (!lxc_list_empty(&conf
->id_map
)) {
999 char **n2
= malloc(n2args
* sizeof(*n2
));
1000 struct lxc_list
*it
;
1004 SYSERROR("out of memory");
1008 tpath
= "lxc-usernsexec";
1009 n2
[0] = "lxc-usernsexec";
1010 lxc_list_for_each(it
, &conf
->id_map
) {
1013 n2
= realloc(n2
, n2args
* sizeof(char *));
1016 n2
[n2args
-2] = "-m";
1017 n2
[n2args
-1] = malloc(200);
1020 ret
= snprintf(n2
[n2args
-1], 200, "%c:%lu:%lu:%lu",
1021 map
->idtype
== ID_TYPE_UID
? 'u' : 'g',
1022 map
->nsid
, map
->hostid
, map
->range
);
1023 if (ret
< 0 || ret
>= 200)
1026 int hostid_mapped
= mapped_hostid(geteuid(), conf
, ID_TYPE_UID
);
1027 int extraargs
= hostid_mapped
>= 0 ? 1 : 3;
1028 n2
= realloc(n2
, (nargs
+ n2args
+ extraargs
) * sizeof(char *));
1031 if (hostid_mapped
< 0) {
1032 hostid_mapped
= find_unmapped_nsuid(conf
, ID_TYPE_UID
);
1033 n2
[n2args
++] = "-m";
1034 if (hostid_mapped
< 0) {
1035 ERROR("Could not find free uid to map");
1038 n2
[n2args
++] = malloc(200);
1039 if (!n2
[n2args
-1]) {
1040 SYSERROR("out of memory");
1043 ret
= snprintf(n2
[n2args
-1], 200, "u:%d:%d:1",
1044 hostid_mapped
, geteuid());
1045 if (ret
< 0 || ret
>= 200) {
1046 ERROR("string too long");
1050 int hostgid_mapped
= mapped_hostid(getegid(), conf
, ID_TYPE_GID
);
1051 extraargs
= hostgid_mapped
>= 0 ? 1 : 3;
1052 n2
= realloc(n2
, (nargs
+ n2args
+ extraargs
) * sizeof(char *));
1055 if (hostgid_mapped
< 0) {
1056 hostgid_mapped
= find_unmapped_nsuid(conf
, ID_TYPE_GID
);
1057 n2
[n2args
++] = "-m";
1058 if (hostgid_mapped
< 0) {
1059 ERROR("Could not find free uid to map");
1062 n2
[n2args
++] = malloc(200);
1063 if (!n2
[n2args
-1]) {
1064 SYSERROR("out of memory");
1067 ret
= snprintf(n2
[n2args
-1], 200, "g:%d:%d:1",
1068 hostgid_mapped
, getegid());
1069 if (ret
< 0 || ret
>= 200) {
1070 ERROR("string too long");
1074 n2
[n2args
++] = "--";
1075 for (i
= 0; i
< nargs
; i
++)
1076 n2
[i
+ n2args
] = newargv
[i
];
1078 // Finally add "--mapped-uid $uid" to tell template what to chown
1081 n2
= realloc(n2
, n2args
* sizeof(char *));
1083 SYSERROR("out of memory");
1086 // note n2[n2args-1] is NULL
1087 n2
[n2args
-5] = "--mapped-uid";
1088 snprintf(txtuid
, 20, "%d", hostid_mapped
);
1089 n2
[n2args
-4] = txtuid
;
1090 n2
[n2args
-3] = "--mapped-gid";
1091 snprintf(txtgid
, 20, "%d", hostgid_mapped
);
1092 n2
[n2args
-2] = txtgid
;
1093 n2
[n2args
-1] = NULL
;
1098 execvp(tpath
, newargv
);
1099 SYSERROR("failed to execute template %s", tpath
);
1103 if (wait_for_pid(pid
) != 0) {
1104 ERROR("container creation template for %s failed", c
->name
);
1111 static bool prepend_lxc_header(char *path
, const char *t
, char *const argv
[])
1119 unsigned char md_value
[SHA_DIGEST_LENGTH
];
1123 f
= fopen(path
, "r");
1127 if (fseek(f
, 0, SEEK_END
) < 0)
1129 if ((flen
= ftell(f
)) < 0)
1131 if (fseek(f
, 0, SEEK_SET
) < 0)
1133 if ((contents
= malloc(flen
+ 1)) == NULL
)
1135 if (fread(contents
, 1, flen
, f
) != flen
)
1136 goto out_free_contents
;
1138 contents
[flen
] = '\0';
1142 goto out_free_contents
;
1145 tpath
= get_template_path(t
);
1147 ERROR("bad template: %s", t
);
1148 goto out_free_contents
;
1151 ret
= sha1sum_file(tpath
, md_value
);
1153 ERROR("Error getting sha1sum of %s", tpath
);
1155 goto out_free_contents
;
1160 f
= fopen(path
, "w");
1162 SYSERROR("reopening config for writing");
1166 fprintf(f
, "# Template used to create this container: %s\n", t
);
1168 fprintf(f
, "# Parameters passed to the template:");
1170 fprintf(f
, " %s", *argv
);
1176 fprintf(f
, "# Template script checksum (SHA-1): ");
1177 for (i
=0; i
<SHA_DIGEST_LENGTH
; i
++)
1178 fprintf(f
, "%02x", md_value
[i
]);
1181 fprintf(f
, "# For additional config options, please look at lxc.conf(5)\n");
1182 if (fwrite(contents
, 1, flen
, f
) != flen
) {
1183 SYSERROR("Writing original contents");
1199 SYSERROR("Error prepending header");
1205 static void lxcapi_clear_config(struct lxc_container
*c
)
1207 if (c
&& c
->lxc_conf
) {
1208 lxc_conf_free(c
->lxc_conf
);
1213 static bool lxcapi_destroy(struct lxc_container
*c
);
1216 * create a container with the given parameters.
1217 * @c: container to be created. It has the lxcpath, name, and a starting
1218 * configuration already set
1219 * @t: the template to execute to instantiate the root filesystem and
1220 * adjust the configuration.
1221 * @bdevtype: backing store type to use. If NULL, dir will be used.
1222 * @specs: additional parameters for the backing store, i.e. LVM vg to
1225 * @argv: the arguments to pass to the template, terminated by NULL. If no
1226 * arguments, you can just pass NULL.
1228 static bool lxcapi_create(struct lxc_container
*c
, const char *t
,
1229 const char *bdevtype
, struct bdev_specs
*specs
, int flags
,
1241 tpath
= get_template_path(t
);
1243 ERROR("bad template: %s", t
);
1249 * If a template is passed in, and the rootfs already is defined in
1250 * the container config and exists, then * caller is trying to create
1251 * an existing container. Return an error, but do NOT delete the
1254 if (lxcapi_is_defined(c
) && c
->lxc_conf
&& c
->lxc_conf
->rootfs
.path
&&
1255 access(c
->lxc_conf
->rootfs
.path
, F_OK
) == 0 && tpath
) {
1256 ERROR("Container %s:%s already exists", c
->config_path
, c
->name
);
1261 if (!c
->load_config(c
, lxc_global_config_value("lxc.default_config"))) {
1262 ERROR("Error loading default configuration file %s", lxc_global_config_value("lxc.default_config"));
1267 if (!create_container_dir(c
))
1271 * either template or rootfs.path should be set.
1272 * if both template and rootfs.path are set, template is setup as rootfs.path.
1273 * container is already created if we have a config and rootfs.path is accessible
1275 if (!c
->lxc_conf
->rootfs
.path
&& !tpath
)
1276 /* no template passed in and rootfs does not exist: error */
1278 if (c
->lxc_conf
->rootfs
.path
&& access(c
->lxc_conf
->rootfs
.path
, F_OK
) != 0)
1279 /* rootfs passed into configuration, but does not exist: error */
1281 if (lxcapi_is_defined(c
) && c
->lxc_conf
->rootfs
.path
&& !tpath
) {
1282 /* Rootfs already existed, user just wanted to save the
1283 * loaded configuration */
1288 /* Mark that this container is being created */
1289 if ((partial_fd
= create_partial(c
)) < 0)
1292 /* no need to get disk lock bc we have the partial locked */
1295 * Create the backing store
1296 * Note we can't do this in the same task as we use to execute the
1297 * template because of the way zfs works.
1298 * After you 'zfs create', zfs mounts the fs only in the initial
1303 SYSERROR("failed to fork task for container creation template");
1307 if (pid
== 0) { // child
1308 struct bdev
*bdev
= NULL
;
1310 if (!(bdev
= do_bdev_create(c
, bdevtype
, specs
))) {
1311 ERROR("Error creating backing store type %s for %s",
1312 bdevtype
? bdevtype
: "(none)", c
->name
);
1316 /* save config file again to store the new rootfs location */
1317 if (!c
->save_config(c
, NULL
)) {
1318 ERROR("failed to save starting configuration for %s", c
->name
);
1319 // parent task won't see bdev in config so we delete it
1320 bdev
->ops
->umount(bdev
);
1321 bdev
->ops
->destroy(bdev
);
1326 if (wait_for_pid(pid
) != 0)
1329 /* reload config to get the rootfs */
1330 lxc_conf_free(c
->lxc_conf
);
1332 if (!load_config_locked(c
, c
->configfile
))
1335 if (!create_run_template(c
, tpath
, !!(flags
& LXC_CREATE_QUIET
), argv
))
1338 // now clear out the lxc_conf we have, reload from the created
1340 lxcapi_clear_config(c
);
1343 if (!prepend_lxc_header(c
->configfile
, tpath
, argv
)) {
1344 ERROR("Error prepending header to configuration file");
1348 ret
= load_config_locked(c
, c
->configfile
);
1351 if (partial_fd
>= 0)
1352 remove_partial(c
, partial_fd
);
1362 static bool lxcapi_reboot(struct lxc_container
*c
)
1368 if (!c
->is_running(c
))
1370 pid
= c
->init_pid(c
);
1373 if (kill(pid
, SIGINT
) < 0)
1379 static bool lxcapi_shutdown(struct lxc_container
*c
, int timeout
)
1383 int haltsignal
= SIGPWR
;
1388 if (!c
->is_running(c
))
1390 pid
= c
->init_pid(c
);
1393 if (c
->lxc_conf
&& c
->lxc_conf
->haltsignal
)
1394 haltsignal
= c
->lxc_conf
->haltsignal
;
1395 kill(pid
, haltsignal
);
1396 retv
= c
->wait(c
, "STOPPED", timeout
);
1400 static bool lxcapi_createl(struct lxc_container
*c
, const char *t
,
1401 const char *bdevtype
, struct bdev_specs
*specs
, int flags
, ...)
1411 * since we're going to wait for create to finish, I don't think we
1412 * need to get a copy of the arguments.
1414 va_start(ap
, flags
);
1415 args
= lxc_va_arg_list_to_argv(ap
, 0, 0);
1418 ERROR("Memory allocation error.");
1422 bret
= c
->create(c
, t
, bdevtype
, specs
, flags
, args
);
1429 static bool lxcapi_clear_config_item(struct lxc_container
*c
, const char *key
)
1433 if (!c
|| !c
->lxc_conf
)
1435 if (container_mem_lock(c
))
1437 ret
= lxc_clear_config_item(c
->lxc_conf
, key
);
1438 container_mem_unlock(c
);
1442 static inline bool enter_to_ns(struct lxc_container
*c
) {
1443 int netns
, userns
, ret
= 0, init_pid
= 0;;
1444 char new_netns_path
[MAXPATHLEN
];
1445 char new_userns_path
[MAXPATHLEN
];
1447 if (!c
->is_running(c
))
1450 init_pid
= c
->init_pid(c
);
1452 /* Switch to new userns */
1453 if ((geteuid() != 0 || (c
->lxc_conf
&& !lxc_list_empty(&c
->lxc_conf
->id_map
))) && access("/proc/self/ns/user", F_OK
) == 0) {
1454 ret
= snprintf(new_userns_path
, MAXPATHLEN
, "/proc/%d/ns/user", init_pid
);
1455 if (ret
< 0 || ret
>= MAXPATHLEN
)
1458 userns
= open(new_userns_path
, O_RDONLY
);
1460 SYSERROR("failed to open %s", new_userns_path
);
1464 if (setns(userns
, CLONE_NEWUSER
)) {
1465 SYSERROR("failed to setns for CLONE_NEWUSER");
1472 /* Switch to new netns */
1473 ret
= snprintf(new_netns_path
, MAXPATHLEN
, "/proc/%d/ns/net", init_pid
);
1474 if (ret
< 0 || ret
>= MAXPATHLEN
)
1477 netns
= open(new_netns_path
, O_RDONLY
);
1479 SYSERROR("failed to open %s", new_netns_path
);
1483 if (setns(netns
, CLONE_NEWNET
)) {
1484 SYSERROR("failed to setns for CLONE_NEWNET");
1494 // used by qsort and bsearch functions for comparing names
1495 static inline int string_cmp(char **first
, char **second
)
1497 return strcmp(*first
, *second
);
1500 // used by qsort and bsearch functions for comparing container names
1501 static inline int container_cmp(struct lxc_container
**first
, struct lxc_container
**second
)
1503 return strcmp((*first
)->name
, (*second
)->name
);
1506 static bool add_to_array(char ***names
, char *cname
, int pos
)
1508 char **newnames
= realloc(*names
, (pos
+1) * sizeof(char *));
1510 ERROR("Out of memory");
1515 newnames
[pos
] = strdup(cname
);
1519 // sort the arrray as we will use binary search on it
1520 qsort(newnames
, pos
+ 1, sizeof(char *), (int (*)(const void *,const void *))string_cmp
);
1525 static bool add_to_clist(struct lxc_container
***list
, struct lxc_container
*c
, int pos
, bool sort
)
1527 struct lxc_container
**newlist
= realloc(*list
, (pos
+1) * sizeof(struct lxc_container
*));
1529 ERROR("Out of memory");
1536 // sort the arrray as we will use binary search on it
1538 qsort(newlist
, pos
+ 1, sizeof(struct lxc_container
*), (int (*)(const void *,const void *))container_cmp
);
1543 static char** get_from_array(char ***names
, char *cname
, int size
)
1545 return (char **)bsearch(&cname
, *names
, size
, sizeof(char *), (int (*)(const void *, const void *))string_cmp
);
1549 static bool array_contains(char ***names
, char *cname
, int size
) {
1550 if(get_from_array(names
, cname
, size
) != NULL
)
1555 static bool remove_from_array(char ***names
, char *cname
, int size
)
1557 char **result
= get_from_array(names
, cname
, size
);
1558 if (result
!= NULL
) {
1565 static char** lxcapi_get_interfaces(struct lxc_container
*c
)
1568 int i
, count
= 0, pipefd
[2];
1569 char **interfaces
= NULL
;
1570 char interface
[IFNAMSIZ
];
1572 if(pipe(pipefd
) < 0) {
1573 SYSERROR("pipe failed");
1579 SYSERROR("failed to fork task to get interfaces information");
1585 if (pid
== 0) { // child
1586 int ret
= 1, nbytes
;
1587 struct ifaddrs
*interfaceArray
= NULL
, *tempIfAddr
= NULL
;
1589 /* close the read-end of the pipe */
1592 if (!enter_to_ns(c
)) {
1593 SYSERROR("failed to enter namespace");
1597 /* Grab the list of interfaces */
1598 if (getifaddrs(&interfaceArray
)) {
1599 SYSERROR("failed to get interfaces list");
1603 /* Iterate through the interfaces */
1604 for (tempIfAddr
= interfaceArray
; tempIfAddr
!= NULL
; tempIfAddr
= tempIfAddr
->ifa_next
) {
1605 nbytes
= write(pipefd
[1], tempIfAddr
->ifa_name
, IFNAMSIZ
);
1607 ERROR("write failed");
1616 freeifaddrs(interfaceArray
);
1618 /* close the write-end of the pipe, thus sending EOF to the reader */
1623 /* close the write-end of the pipe */
1626 while (read(pipefd
[0], &interface
, IFNAMSIZ
) == IFNAMSIZ
) {
1627 if (array_contains(&interfaces
, interface
, count
))
1630 if(!add_to_array(&interfaces
, interface
, count
))
1631 ERROR("PARENT: add_to_array failed");
1635 if (wait_for_pid(pid
) != 0) {
1636 for(i
=0;i
<count
;i
++)
1637 free(interfaces
[i
]);
1642 /* close the read-end of the pipe */
1645 /* Append NULL to the array */
1647 interfaces
= (char **)lxc_append_null_to_array((void **)interfaces
, count
);
1652 static char** lxcapi_get_ips(struct lxc_container
*c
, const char* interface
, const char* family
, int scope
)
1655 int i
, count
= 0, pipefd
[2];
1656 char **addresses
= NULL
;
1657 char address
[INET6_ADDRSTRLEN
];
1659 if(pipe(pipefd
) < 0) {
1660 SYSERROR("pipe failed");
1666 SYSERROR("failed to fork task to get container ips");
1672 if (pid
== 0) { // child
1673 int ret
= 1, nbytes
;
1674 struct ifaddrs
*interfaceArray
= NULL
, *tempIfAddr
= NULL
;
1675 char addressOutputBuffer
[INET6_ADDRSTRLEN
];
1676 void *tempAddrPtr
= NULL
;
1677 char *address
= NULL
;
1679 /* close the read-end of the pipe */
1682 if (!enter_to_ns(c
)) {
1683 SYSERROR("failed to enter namespace");
1687 /* Grab the list of interfaces */
1688 if (getifaddrs(&interfaceArray
)) {
1689 SYSERROR("failed to get interfaces list");
1693 /* Iterate through the interfaces */
1694 for (tempIfAddr
= interfaceArray
; tempIfAddr
!= NULL
; tempIfAddr
= tempIfAddr
->ifa_next
) {
1695 if (tempIfAddr
->ifa_addr
== NULL
)
1698 if(tempIfAddr
->ifa_addr
->sa_family
== AF_INET
) {
1699 if (family
&& strcmp(family
, "inet"))
1701 tempAddrPtr
= &((struct sockaddr_in
*)tempIfAddr
->ifa_addr
)->sin_addr
;
1704 if (family
&& strcmp(family
, "inet6"))
1707 if (((struct sockaddr_in6
*)tempIfAddr
->ifa_addr
)->sin6_scope_id
!= scope
)
1710 tempAddrPtr
= &((struct sockaddr_in6
*)tempIfAddr
->ifa_addr
)->sin6_addr
;
1713 if (interface
&& strcmp(interface
, tempIfAddr
->ifa_name
))
1715 else if (!interface
&& strcmp("lo", tempIfAddr
->ifa_name
) == 0)
1718 address
= (char *)inet_ntop(tempIfAddr
->ifa_addr
->sa_family
,
1720 addressOutputBuffer
,
1721 sizeof(addressOutputBuffer
));
1725 nbytes
= write(pipefd
[1], address
, INET6_ADDRSTRLEN
);
1727 ERROR("write failed");
1736 freeifaddrs(interfaceArray
);
1738 /* close the write-end of the pipe, thus sending EOF to the reader */
1743 /* close the write-end of the pipe */
1746 while (read(pipefd
[0], &address
, INET6_ADDRSTRLEN
) == INET6_ADDRSTRLEN
) {
1747 if(!add_to_array(&addresses
, address
, count
))
1748 ERROR("PARENT: add_to_array failed");
1752 if (wait_for_pid(pid
) != 0) {
1753 for(i
=0;i
<count
;i
++)
1759 /* close the read-end of the pipe */
1762 /* Append NULL to the array */
1764 addresses
= (char **)lxc_append_null_to_array((void **)addresses
, count
);
1769 static int lxcapi_get_config_item(struct lxc_container
*c
, const char *key
, char *retv
, int inlen
)
1773 if (!c
|| !c
->lxc_conf
)
1775 if (container_mem_lock(c
))
1777 ret
= lxc_get_config_item(c
->lxc_conf
, key
, retv
, inlen
);
1778 container_mem_unlock(c
);
1782 static char* lxcapi_get_running_config_item(struct lxc_container
*c
, const char *key
)
1786 if (!c
|| !c
->lxc_conf
)
1788 if (container_mem_lock(c
))
1790 ret
= lxc_cmd_get_config_item(c
->name
, key
, c
->get_config_path(c
));
1791 container_mem_unlock(c
);
1795 static int lxcapi_get_keys(struct lxc_container
*c
, const char *key
, char *retv
, int inlen
)
1798 return lxc_listconfigs(retv
, inlen
);
1800 * Support 'lxc.network.<idx>', i.e. 'lxc.network.0'
1801 * This is an intelligent result to show which keys are valid given
1802 * the type of nic it is
1804 if (!c
|| !c
->lxc_conf
)
1806 if (container_mem_lock(c
))
1809 if (strncmp(key
, "lxc.network.", 12) == 0)
1810 ret
= lxc_list_nicconfigs(c
->lxc_conf
, key
, retv
, inlen
);
1811 container_mem_unlock(c
);
1815 static bool lxcapi_save_config(struct lxc_container
*c
, const char *alt_file
)
1818 bool ret
= false, need_disklock
= false;
1822 alt_file
= c
->configfile
;
1824 return false; // should we write to stdout if no file is specified?
1826 // If we haven't yet loaded a config, load the stock config
1828 if (!c
->load_config(c
, lxc_global_config_value("lxc.default_config"))) {
1829 ERROR("Error loading default configuration file %s while saving %s", lxc_global_config_value("lxc.default_config"), c
->name
);
1834 if (!create_container_dir(c
))
1838 * If we're writing to the container's config file, take the
1839 * disk lock. Otherwise just take the memlock to protect the
1840 * struct lxc_container while we're traversing it.
1842 if (strcmp(c
->configfile
, alt_file
) == 0)
1843 need_disklock
= true;
1846 lret
= container_disk_lock(c
);
1848 lret
= container_mem_lock(c
);
1853 fout
= fopen(alt_file
, "w");
1856 write_config(fout
, c
->lxc_conf
);
1862 container_disk_unlock(c
);
1864 container_mem_unlock(c
);
1868 static bool mod_rdep(struct lxc_container
*c
, bool inc
)
1870 char path
[MAXPATHLEN
];
1875 if (container_disk_lock(c
))
1877 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_snapshots", c
->config_path
,
1879 if (ret
< 0 || ret
> MAXPATHLEN
)
1881 f
= fopen(path
, "r");
1883 ret
= fscanf(f
, "%d", &v
);
1886 ERROR("Corrupted file %s", path
);
1891 f
= fopen(path
, "w");
1894 if (fprintf(f
, "%d\n", v
) < 0) {
1895 ERROR("Error writing new snapshots value");
1901 SYSERROR("Error writing to or closing snapshots file");
1908 container_disk_unlock(c
);
1912 static void strip_newline(char *p
)
1914 size_t len
= strlen(p
);
1917 if (p
[len
-1] == '\n')
1921 static void mod_all_rdeps(struct lxc_container
*c
, bool inc
)
1923 struct lxc_container
*p
;
1924 char *lxcpath
= NULL
, *lxcname
= NULL
, path
[MAXPATHLEN
];
1925 size_t pathlen
= 0, namelen
= 0;
1929 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_rdepends",
1930 c
->config_path
, c
->name
);
1931 if (ret
< 0 || ret
>= MAXPATHLEN
) {
1932 ERROR("Path name too long");
1935 f
= fopen(path
, "r");
1938 while (getline(&lxcpath
, &pathlen
, f
) != -1) {
1939 if (getline(&lxcname
, &namelen
, f
) == -1) {
1940 ERROR("badly formatted file %s", path
);
1943 strip_newline(lxcpath
);
1944 strip_newline(lxcname
);
1945 if ((p
= lxc_container_new(lxcname
, lxcpath
)) == NULL
) {
1946 ERROR("Unable to find dependent container %s:%s",
1950 if (!mod_rdep(p
, inc
))
1951 ERROR("Failed to increase numsnapshots for %s:%s",
1953 lxc_container_put(p
);
1956 if (lxcpath
) free(lxcpath
);
1957 if (lxcname
) free(lxcname
);
1961 static bool has_snapshots(struct lxc_container
*c
)
1963 char path
[MAXPATHLEN
];
1968 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_snapshots", c
->config_path
,
1970 if (ret
< 0 || ret
> MAXPATHLEN
)
1972 f
= fopen(path
, "r");
1975 ret
= fscanf(f
, "%d", &v
);
1985 static int lxc_rmdir_onedev_wrapper(void *data
)
1987 char *arg
= (char *) data
;
1988 return lxc_rmdir_onedev(arg
);
1991 // do we want the api to support --force, or leave that to the caller?
1992 static bool lxcapi_destroy(struct lxc_container
*c
)
1994 struct bdev
*r
= NULL
;
1998 if (!c
|| !lxcapi_is_defined(c
))
2001 if (container_disk_lock(c
))
2004 if (!is_stopped(c
)) {
2005 // we should queue some sort of error - in c->error_string?
2006 ERROR("container %s is not stopped", c
->name
);
2010 if (c
->lxc_conf
&& has_snapshots(c
)) {
2011 ERROR("container %s has dependent snapshots", c
->name
);
2015 if (!am_unpriv() && c
->lxc_conf
&& c
->lxc_conf
->rootfs
.path
&& c
->lxc_conf
->rootfs
.mount
) {
2016 r
= bdev_init(c
->lxc_conf
->rootfs
.path
, c
->lxc_conf
->rootfs
.mount
, NULL
);
2018 if (r
->ops
->destroy(r
) < 0) {
2020 ERROR("Error destroying rootfs for %s", c
->name
);
2027 mod_all_rdeps(c
, false);
2029 const char *p1
= lxcapi_get_config_path(c
);
2030 char *path
= alloca(strlen(p1
) + strlen(c
->name
) + 2);
2031 sprintf(path
, "%s/%s", p1
, c
->name
);
2033 ret
= userns_exec_1(c
->lxc_conf
, lxc_rmdir_onedev_wrapper
, path
);
2035 ret
= lxc_rmdir_onedev(path
);
2037 ERROR("Error destroying container directory for %s", c
->name
);
2043 container_disk_unlock(c
);
2047 static bool set_config_item_locked(struct lxc_container
*c
, const char *key
, const char *v
)
2049 struct lxc_config_t
*config
;
2052 c
->lxc_conf
= lxc_conf_init();
2055 config
= lxc_getconfig(key
);
2058 return (0 == config
->cb(key
, v
, c
->lxc_conf
));
2061 static bool lxcapi_set_config_item(struct lxc_container
*c
, const char *key
, const char *v
)
2068 if (container_mem_lock(c
))
2071 b
= set_config_item_locked(c
, key
, v
);
2073 container_mem_unlock(c
);
2077 static char *lxcapi_config_file_name(struct lxc_container
*c
)
2079 if (!c
|| !c
->configfile
)
2081 return strdup(c
->configfile
);
2084 static const char *lxcapi_get_config_path(struct lxc_container
*c
)
2086 if (!c
|| !c
->config_path
)
2088 return (const char *)(c
->config_path
);
2093 * Just recalculate the c->configfile based on the
2094 * c->config_path, which must be set.
2095 * The lxc_container must be locked or not yet public.
2097 static bool set_config_filename(struct lxc_container
*c
)
2102 if (!c
->config_path
)
2105 /* $lxc_path + "/" + c->name + "/" + "config" + '\0' */
2106 len
= strlen(c
->config_path
) + strlen(c
->name
) + strlen("config") + 3;
2107 newpath
= malloc(len
);
2111 ret
= snprintf(newpath
, len
, "%s/%s/config", c
->config_path
, c
->name
);
2112 if (ret
< 0 || ret
>= len
) {
2113 fprintf(stderr
, "Error printing out config file name\n");
2119 free(c
->configfile
);
2120 c
->configfile
= newpath
;
2125 static bool lxcapi_set_config_path(struct lxc_container
*c
, const char *path
)
2129 char *oldpath
= NULL
;
2134 if (container_mem_lock(c
))
2139 ERROR("Out of memory setting new lxc path");
2145 oldpath
= c
->config_path
;
2148 /* Since we've changed the config path, we have to change the
2149 * config file name too */
2150 if (!set_config_filename(c
)) {
2151 ERROR("Out of memory setting new config filename");
2153 free(c
->config_path
);
2154 c
->config_path
= oldpath
;
2160 container_mem_unlock(c
);
2165 static bool lxcapi_set_cgroup_item(struct lxc_container
*c
, const char *subsys
, const char *value
)
2175 if (container_disk_lock(c
))
2178 ret
= lxc_cgroup_set(subsys
, value
, c
->name
, c
->config_path
);
2180 container_disk_unlock(c
);
2184 static int lxcapi_get_cgroup_item(struct lxc_container
*c
, const char *subsys
, char *retv
, int inlen
)
2194 if (container_disk_lock(c
))
2197 ret
= lxc_cgroup_get(subsys
, retv
, inlen
, c
->name
, c
->config_path
);
2199 container_disk_unlock(c
);
2203 const char *lxc_get_global_config_item(const char *key
)
2205 return lxc_global_config_value(key
);
2208 const char *lxc_get_version(void)
2213 static int copy_file(const char *old
, const char *new)
2220 if (file_exists(new)) {
2221 ERROR("copy destination %s exists", new);
2224 ret
= stat(old
, &sbuf
);
2226 INFO("Error stat'ing %s", old
);
2230 in
= open(old
, O_RDONLY
);
2232 SYSERROR("Error opening original file %s", old
);
2235 out
= open(new, O_CREAT
| O_EXCL
| O_WRONLY
, 0644);
2237 SYSERROR("Error opening new file %s", new);
2243 len
= read(in
, buf
, 8096);
2245 SYSERROR("Error reading old file %s", old
);
2250 ret
= write(out
, buf
, len
);
2251 if (ret
< len
) { // should we retry?
2252 SYSERROR("Error: write to new file %s was interrupted", new);
2259 // we set mode, but not owner/group
2260 ret
= chmod(new, sbuf
.st_mode
);
2262 SYSERROR("Error setting mode on %s", new);
2274 static int copyhooks(struct lxc_container
*oldc
, struct lxc_container
*c
)
2277 struct lxc_list
*it
;
2280 len
= strlen(oldc
->config_path
) + strlen(oldc
->name
) + 3;
2281 cpath
= alloca(len
);
2282 ret
= snprintf(cpath
, len
, "%s/%s/", oldc
->config_path
, oldc
->name
);
2283 if (ret
< 0 || ret
>= len
)
2286 for (i
=0; i
<NUM_LXC_HOOKS
; i
++) {
2287 lxc_list_for_each(it
, &c
->lxc_conf
->hooks
[i
]) {
2288 char *hookname
= it
->elem
;
2289 char *fname
= strrchr(hookname
, '/');
2290 char tmppath
[MAXPATHLEN
];
2291 if (!fname
) // relative path - we don't support, but maybe we should
2293 if (strncmp(hookname
, cpath
, len
- 1) != 0) {
2294 // this hook is public - ignore
2297 // copy the script, and change the entry in confile
2298 ret
= snprintf(tmppath
, MAXPATHLEN
, "%s/%s/%s",
2299 c
->config_path
, c
->name
, fname
+1);
2300 if (ret
< 0 || ret
>= MAXPATHLEN
)
2302 ret
= copy_file(it
->elem
, tmppath
);
2306 it
->elem
= strdup(tmppath
);
2308 ERROR("out of memory copying hook path");
2314 c
->save_config(c
, NULL
);
2318 static void new_hwaddr(char *hwaddr
)
2321 f
= fopen("/dev/urandom", "r");
2324 int ret
= fread(&seed
, sizeof(seed
), 1, f
);
2331 snprintf(hwaddr
, 18, "00:16:3e:%02x:%02x:%02x",
2332 rand() % 255, rand() % 255, rand() % 255);
2335 static void network_new_hwaddrs(struct lxc_container
*c
)
2337 struct lxc_list
*it
;
2339 lxc_list_for_each(it
, &c
->lxc_conf
->network
) {
2340 struct lxc_netdev
*n
= it
->elem
;
2342 new_hwaddr(n
->hwaddr
);
2346 static int copy_fstab(struct lxc_container
*oldc
, struct lxc_container
*c
)
2348 char newpath
[MAXPATHLEN
];
2349 char *oldpath
= oldc
->lxc_conf
->fstab
;
2355 char *p
= strrchr(oldpath
, '/');
2358 ret
= snprintf(newpath
, MAXPATHLEN
, "%s/%s%s",
2359 c
->config_path
, c
->name
, p
);
2360 if (ret
< 0 || ret
>= MAXPATHLEN
) {
2361 ERROR("error printing new path for %s", oldpath
);
2364 if (file_exists(newpath
)) {
2365 ERROR("error: fstab file %s exists", newpath
);
2369 if (copy_file(oldpath
, newpath
) < 0) {
2370 ERROR("error: copying %s to %s", oldpath
, newpath
);
2373 free(c
->lxc_conf
->fstab
);
2374 c
->lxc_conf
->fstab
= strdup(newpath
);
2375 if (!c
->lxc_conf
->fstab
) {
2376 ERROR("error: allocating pathname");
2383 static void copy_rdepends(struct lxc_container
*c
, struct lxc_container
*c0
)
2385 char path0
[MAXPATHLEN
], path1
[MAXPATHLEN
];
2388 ret
= snprintf(path0
, MAXPATHLEN
, "%s/%s/lxc_rdepends", c0
->config_path
,
2390 if (ret
< 0 || ret
>= MAXPATHLEN
) {
2391 WARN("Error copying reverse dependencies");
2394 ret
= snprintf(path1
, MAXPATHLEN
, "%s/%s/lxc_rdepends", c
->config_path
,
2396 if (ret
< 0 || ret
>= MAXPATHLEN
) {
2397 WARN("Error copying reverse dependencies");
2400 if (copy_file(path0
, path1
) < 0) {
2401 INFO("Error copying reverse dependencies");
2406 static bool add_rdepends(struct lxc_container
*c
, struct lxc_container
*c0
)
2409 char path
[MAXPATHLEN
];
2413 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_rdepends", c
->config_path
,
2415 if (ret
< 0 || ret
>= MAXPATHLEN
)
2417 f
= fopen(path
, "a");
2421 // if anything goes wrong, just return an error
2422 if (fprintf(f
, "%s\n%s\n", c0
->config_path
, c0
->name
) < 0)
2429 static int copy_storage(struct lxc_container
*c0
, struct lxc_container
*c
,
2430 const char *newtype
, int flags
, const char *bdevdata
, uint64_t newsize
)
2435 bdev
= bdev_copy(c0
, c
->name
, c
->config_path
, newtype
, flags
,
2436 bdevdata
, newsize
, &need_rdep
);
2438 ERROR("Error copying storage");
2441 free(c
->lxc_conf
->rootfs
.path
);
2442 c
->lxc_conf
->rootfs
.path
= strdup(bdev
->src
);
2444 if (!c
->lxc_conf
->rootfs
.path
) {
2445 ERROR("Out of memory while setting storage path");
2448 if (flags
& LXC_CLONE_SNAPSHOT
)
2449 copy_rdepends(c
, c0
);
2451 if (!add_rdepends(c
, c0
))
2452 WARN("Error adding reverse dependency from %s to %s",
2456 mod_all_rdeps(c
, true);
2461 struct clone_update_data
{
2462 struct lxc_container
*c0
;
2463 struct lxc_container
*c1
;
2468 static int clone_update_rootfs(struct clone_update_data
*data
)
2470 struct lxc_container
*c0
= data
->c0
;
2471 struct lxc_container
*c
= data
->c1
;
2472 int flags
= data
->flags
;
2473 char **hookargs
= data
->hookargs
;
2475 char path
[MAXPATHLEN
];
2478 struct lxc_conf
*conf
= c
->lxc_conf
;
2480 /* update hostname in rootfs */
2481 /* we're going to mount, so run in a clean namespace to simplify cleanup */
2483 if (setgid(0) < 0) {
2484 ERROR("Failed to setgid to 0");
2487 if (setuid(0) < 0) {
2488 ERROR("Failed to setuid to 0");
2491 if (setgroups(0, NULL
) < 0)
2492 WARN("Failed to clear groups");
2494 if (unshare(CLONE_NEWNS
) < 0)
2496 bdev
= bdev_init(c
->lxc_conf
->rootfs
.path
, c
->lxc_conf
->rootfs
.mount
, NULL
);
2499 if (strcmp(bdev
->type
, "dir") != 0) {
2500 if (unshare(CLONE_NEWNS
) < 0) {
2501 ERROR("error unsharing mounts");
2505 if (detect_shared_rootfs()) {
2506 if (mount(NULL
, "/", NULL
, MS_SLAVE
|MS_REC
, NULL
)) {
2507 SYSERROR("Failed to make / rslave");
2508 ERROR("Continuing...");
2511 if (bdev
->ops
->mount(bdev
) < 0) {
2515 } else { // TODO come up with a better way
2518 bdev
->dest
= strdup(bdev
->src
);
2521 if (!lxc_list_empty(&conf
->hooks
[LXCHOOK_CLONE
])) {
2522 /* Start of environment variable setup for hooks */
2523 if (setenv("LXC_SRC_NAME", c0
->name
, 1)) {
2524 SYSERROR("failed to set environment variable for source container name");
2526 if (setenv("LXC_NAME", c
->name
, 1)) {
2527 SYSERROR("failed to set environment variable for container name");
2529 if (setenv("LXC_CONFIG_FILE", conf
->rcfile
, 1)) {
2530 SYSERROR("failed to set environment variable for config path");
2532 if (setenv("LXC_ROOTFS_MOUNT", bdev
->dest
, 1)) {
2533 SYSERROR("failed to set environment variable for rootfs mount");
2535 if (setenv("LXC_ROOTFS_PATH", conf
->rootfs
.path
, 1)) {
2536 SYSERROR("failed to set environment variable for rootfs mount");
2539 if (run_lxc_hooks(c
->name
, "clone", conf
, c
->get_config_path(c
), hookargs
)) {
2540 ERROR("Error executing clone hook for %s", c
->name
);
2546 if (!(flags
& LXC_CLONE_KEEPNAME
)) {
2547 ret
= snprintf(path
, MAXPATHLEN
, "%s/etc/hostname", bdev
->dest
);
2550 if (ret
< 0 || ret
>= MAXPATHLEN
)
2552 if (!file_exists(path
))
2554 if (!(fout
= fopen(path
, "w"))) {
2555 SYSERROR("unable to open %s: ignoring", path
);
2558 if (fprintf(fout
, "%s", c
->name
) < 0) {
2562 if (fclose(fout
) < 0)
2571 static int clone_update_rootfs_wrapper(void *data
)
2573 struct clone_update_data
*arg
= (struct clone_update_data
*) data
;
2574 return clone_update_rootfs(arg
);
2578 * We want to support:
2579 sudo lxc-clone -o o1 -n n1 -s -L|-fssize fssize -v|--vgname vgname \
2580 -p|--lvprefix lvprefix -t|--fstype fstype -B backingstore
2582 -s [ implies overlayfs]
2586 only rootfs gets converted (copied/snapshotted) on clone.
2589 static int create_file_dirname(char *path
)
2591 char *p
= strrchr(path
, '/');
2597 ret
= mkdir(path
, 0755);
2598 if (ret
&& errno
!= EEXIST
)
2599 SYSERROR("creating container path %s", path
);
2604 static struct lxc_container
*lxcapi_clone(struct lxc_container
*c
, const char *newname
,
2605 const char *lxcpath
, int flags
,
2606 const char *bdevtype
, const char *bdevdata
, uint64_t newsize
,
2609 struct lxc_container
*c2
= NULL
;
2610 char newpath
[MAXPATHLEN
];
2611 int ret
, storage_copied
= 0;
2613 char *origroot
= NULL
;
2614 struct clone_update_data data
;
2618 if (!c
|| !c
->is_defined(c
))
2621 if (container_mem_lock(c
))
2624 if (!is_stopped(c
)) {
2625 ERROR("error: Original container (%s) is running", c
->name
);
2629 // Make sure the container doesn't yet exist.
2630 n
= newname
? newname
: c
->name
;
2631 l
= lxcpath
? lxcpath
: c
->get_config_path(c
);
2632 ret
= snprintf(newpath
, MAXPATHLEN
, "%s/%s/config", l
, n
);
2633 if (ret
< 0 || ret
>= MAXPATHLEN
) {
2634 SYSERROR("clone: failed making config pathname");
2637 if (file_exists(newpath
)) {
2638 ERROR("error: clone: %s exists", newpath
);
2642 ret
= create_file_dirname(newpath
);
2643 if (ret
< 0 && errno
!= EEXIST
) {
2644 ERROR("Error creating container dir for %s", newpath
);
2648 // copy the configuration, tweak it as needed,
2649 if (c
->lxc_conf
->rootfs
.path
) {
2650 origroot
= c
->lxc_conf
->rootfs
.path
;
2651 c
->lxc_conf
->rootfs
.path
= NULL
;
2653 fout
= fopen(newpath
, "w");
2655 SYSERROR("open %s", newpath
);
2658 write_config(fout
, c
->lxc_conf
);
2660 c
->lxc_conf
->rootfs
.path
= origroot
;
2662 sprintf(newpath
, "%s/%s/rootfs", l
, n
);
2663 if (mkdir(newpath
, 0755) < 0) {
2664 SYSERROR("error creating %s", newpath
);
2669 if (chown_mapped_root(newpath
, c
->lxc_conf
) < 0) {
2670 ERROR("Error chowning %s to container root", newpath
);
2675 c2
= lxc_container_new(n
, l
);
2677 ERROR("clone: failed to create new container (%s %s)", n
, l
);
2680 c2
->lxc_conf
->rootfs
.path
= origroot
;
2682 // copy/snapshot rootfs's
2683 ret
= copy_storage(c
, c2
, bdevtype
, flags
, bdevdata
, newsize
);
2688 if (!set_config_item_locked(c2
, "lxc.utsname", newname
)) {
2689 ERROR("Error setting new hostname");
2694 ret
= copyhooks(c
, c2
);
2696 ERROR("error copying hooks");
2700 if (copy_fstab(c
, c2
) < 0) {
2701 ERROR("error copying fstab");
2706 if (!(flags
& LXC_CLONE_KEEPMACADDR
))
2707 network_new_hwaddrs(c2
);
2709 // We've now successfully created c2's storage, so clear it out if we
2713 if (!c2
->save_config(c2
, NULL
))
2716 if ((pid
= fork()) < 0) {
2721 ret
= wait_for_pid(pid
);
2724 container_mem_unlock(c
);
2730 data
.hookargs
= hookargs
;
2732 ret
= userns_exec_1(c
->lxc_conf
, clone_update_rootfs_wrapper
,
2735 ret
= clone_update_rootfs(&data
);
2739 container_mem_unlock(c
);
2743 container_mem_unlock(c
);
2745 if (!storage_copied
)
2746 c2
->lxc_conf
->rootfs
.path
= NULL
;
2748 lxc_container_put(c2
);
2754 static bool lxcapi_rename(struct lxc_container
*c
, const char *newname
)
2757 struct lxc_container
*newc
;
2759 if (!c
|| !c
->name
|| !c
->config_path
|| !c
->lxc_conf
)
2762 bdev
= bdev_init(c
->lxc_conf
->rootfs
.path
, c
->lxc_conf
->rootfs
.mount
, NULL
);
2764 ERROR("Failed to find original backing store type");
2768 newc
= lxcapi_clone(c
, newname
, c
->config_path
, LXC_CLONE_KEEPMACADDR
, NULL
, bdev
->type
, 0, NULL
);
2771 lxc_container_put(newc
);
2775 if (newc
&& lxcapi_is_defined(newc
))
2776 lxc_container_put(newc
);
2778 if (!lxcapi_destroy(c
)) {
2779 ERROR("Could not destroy existing container %s", c
->name
);
2785 static int lxcapi_attach(struct lxc_container
*c
, lxc_attach_exec_t exec_function
, void *exec_payload
, lxc_attach_options_t
*options
, pid_t
*attached_process
)
2790 return lxc_attach(c
->name
, c
->config_path
, exec_function
, exec_payload
, options
, attached_process
);
2793 static int lxcapi_attach_run_wait(struct lxc_container
*c
, lxc_attach_options_t
*options
, const char *program
, const char * const argv
[])
2795 lxc_attach_command_t command
;
2802 command
.program
= (char*)program
;
2803 command
.argv
= (char**)argv
;
2804 r
= lxc_attach(c
->name
, c
->config_path
, lxc_attach_run_command
, &command
, options
, &pid
);
2809 return lxc_wait_for_pid_status(pid
);
2812 static int get_next_index(const char *lxcpath
, char *cname
)
2818 fname
= alloca(strlen(lxcpath
) + 20);
2820 sprintf(fname
, "%s/snap%d", lxcpath
, i
);
2821 ret
= stat(fname
, &sb
);
2828 static int lxcapi_snapshot(struct lxc_container
*c
, const char *commentfile
)
2831 struct lxc_container
*c2
;
2832 char snappath
[MAXPATHLEN
], newname
[20];
2834 // /var/lib/lxc -> /var/lib/lxcsnaps \0
2835 ret
= snprintf(snappath
, MAXPATHLEN
, "%ssnaps/%s", c
->config_path
, c
->name
);
2836 if (ret
< 0 || ret
>= MAXPATHLEN
)
2838 i
= get_next_index(snappath
, c
->name
);
2840 if (mkdir_p(snappath
, 0755) < 0) {
2841 ERROR("Failed to create snapshot directory %s", snappath
);
2845 ret
= snprintf(newname
, 20, "snap%d", i
);
2846 if (ret
< 0 || ret
>= 20)
2850 * We pass LXC_CLONE_SNAPSHOT to make sure that a rdepends file entry is
2851 * created in the original container
2853 flags
= LXC_CLONE_SNAPSHOT
| LXC_CLONE_KEEPMACADDR
| LXC_CLONE_KEEPNAME
|
2854 LXC_CLONE_KEEPBDEVTYPE
| LXC_CLONE_MAYBE_SNAPSHOT
;
2855 if (bdev_is_dir(c
->lxc_conf
->rootfs
.path
)) {
2856 ERROR("Snapshot of directory-backed container requested.");
2857 ERROR("Making a copy-clone. If you do want snapshots, then");
2858 ERROR("please create an aufs or overlayfs clone first, snapshot that");
2859 ERROR("and keep the original container pristine.");
2860 flags
&= ~LXC_CLONE_SNAPSHOT
| LXC_CLONE_MAYBE_SNAPSHOT
;
2862 c2
= c
->clone(c
, newname
, snappath
, flags
, NULL
, NULL
, 0, NULL
);
2864 ERROR("clone of %s:%s failed", c
->config_path
, c
->name
);
2868 lxc_container_put(c2
);
2870 // Now write down the creation time
2877 tm_info
= localtime(&timer
);
2879 strftime(buffer
, 25, "%Y:%m:%d %H:%M:%S", tm_info
);
2881 char *dfnam
= alloca(strlen(snappath
) + strlen(newname
) + 5);
2882 sprintf(dfnam
, "%s/%s/ts", snappath
, newname
);
2883 f
= fopen(dfnam
, "w");
2885 ERROR("Failed to open %s", dfnam
);
2888 if (fprintf(f
, "%s", buffer
) < 0) {
2889 SYSERROR("Writing timestamp");
2895 SYSERROR("Writing timestamp");
2900 // $p / $name / comment \0
2901 int len
= strlen(snappath
) + strlen(newname
) + 10;
2902 char *path
= alloca(len
);
2903 sprintf(path
, "%s/%s/comment", snappath
, newname
);
2904 return copy_file(commentfile
, path
) < 0 ? -1 : i
;
2910 static void lxcsnap_free(struct lxc_snapshot
*s
)
2914 if (s
->comment_pathname
)
2915 free(s
->comment_pathname
);
2922 static char *get_snapcomment_path(char* snappath
, char *name
)
2924 // $snappath/$name/comment
2925 int ret
, len
= strlen(snappath
) + strlen(name
) + 10;
2926 char *s
= malloc(len
);
2929 ret
= snprintf(s
, len
, "%s/%s/comment", snappath
, name
);
2930 if (ret
< 0 || ret
>= len
) {
2938 static char *get_timestamp(char* snappath
, char *name
)
2940 char path
[MAXPATHLEN
], *s
= NULL
;
2944 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/ts", snappath
, name
);
2945 if (ret
< 0 || ret
>= MAXPATHLEN
)
2947 fin
= fopen(path
, "r");
2950 (void) fseek(fin
, 0, SEEK_END
);
2952 (void) fseek(fin
, 0, SEEK_SET
);
2957 if (fread(s
, 1, len
, fin
) != len
) {
2958 SYSERROR("reading timestamp");
2968 static int lxcapi_snapshot_list(struct lxc_container
*c
, struct lxc_snapshot
**ret_snaps
)
2970 char snappath
[MAXPATHLEN
], path2
[MAXPATHLEN
];
2971 int dirlen
, count
= 0, ret
;
2972 struct dirent dirent
, *direntp
;
2973 struct lxc_snapshot
*snaps
=NULL
, *nsnaps
;
2976 if (!c
|| !lxcapi_is_defined(c
))
2979 // snappath is ${lxcpath}snaps/${lxcname}/
2980 dirlen
= snprintf(snappath
, MAXPATHLEN
, "%ssnaps/%s", c
->config_path
, c
->name
);
2981 if (dirlen
< 0 || dirlen
>= MAXPATHLEN
) {
2982 ERROR("path name too long");
2985 dir
= opendir(snappath
);
2987 INFO("failed to open %s - assuming no snapshots", snappath
);
2991 while (!readdir_r(dir
, &dirent
, &direntp
)) {
2995 if (!strcmp(direntp
->d_name
, "."))
2998 if (!strcmp(direntp
->d_name
, ".."))
3001 ret
= snprintf(path2
, MAXPATHLEN
, "%s/%s/config", snappath
, direntp
->d_name
);
3002 if (ret
< 0 || ret
>= MAXPATHLEN
) {
3003 ERROR("pathname too long");
3006 if (!file_exists(path2
))
3008 nsnaps
= realloc(snaps
, (count
+ 1)*sizeof(*snaps
));
3010 SYSERROR("Out of memory");
3014 snaps
[count
].free
= lxcsnap_free
;
3015 snaps
[count
].name
= strdup(direntp
->d_name
);
3016 if (!snaps
[count
].name
)
3018 snaps
[count
].lxcpath
= strdup(snappath
);
3019 if (!snaps
[count
].lxcpath
) {
3020 free(snaps
[count
].name
);
3023 snaps
[count
].comment_pathname
= get_snapcomment_path(snappath
, direntp
->d_name
);
3024 snaps
[count
].timestamp
= get_timestamp(snappath
, direntp
->d_name
);
3029 WARN("failed to close directory");
3037 for (i
=0; i
<count
; i
++)
3038 lxcsnap_free(&snaps
[i
]);
3042 WARN("failed to close directory");
3046 static bool lxcapi_snapshot_restore(struct lxc_container
*c
, const char *snapname
, const char *newname
)
3048 char clonelxcpath
[MAXPATHLEN
];
3050 struct lxc_container
*snap
, *rest
;
3054 if (!c
|| !c
->name
|| !c
->config_path
)
3057 bdev
= bdev_init(c
->lxc_conf
->rootfs
.path
, c
->lxc_conf
->rootfs
.mount
, NULL
);
3059 ERROR("Failed to find original backing store type");
3065 if (strcmp(c
->name
, newname
) == 0) {
3066 if (!lxcapi_destroy(c
)) {
3067 ERROR("Could not destroy existing container %s", newname
);
3072 ret
= snprintf(clonelxcpath
, MAXPATHLEN
, "%ssnaps/%s", c
->config_path
, c
->name
);
3073 if (ret
< 0 || ret
>= MAXPATHLEN
) {
3077 // how should we lock this?
3079 snap
= lxc_container_new(snapname
, clonelxcpath
);
3080 if (!snap
|| !lxcapi_is_defined(snap
)) {
3081 ERROR("Could not open snapshot %s", snapname
);
3082 if (snap
) lxc_container_put(snap
);
3087 rest
= lxcapi_clone(snap
, newname
, c
->config_path
, 0, bdev
->type
, NULL
, 0, NULL
);
3089 if (rest
&& lxcapi_is_defined(rest
))
3092 lxc_container_put(rest
);
3093 lxc_container_put(snap
);
3097 static bool lxcapi_snapshot_destroy(struct lxc_container
*c
, const char *snapname
)
3100 char clonelxcpath
[MAXPATHLEN
];
3101 struct lxc_container
*snap
= NULL
;
3103 if (!c
|| !c
->name
|| !c
->config_path
)
3106 ret
= snprintf(clonelxcpath
, MAXPATHLEN
, "%ssnaps/%s", c
->config_path
, c
->name
);
3107 if (ret
< 0 || ret
>= MAXPATHLEN
)
3110 snap
= lxc_container_new(snapname
, clonelxcpath
);
3111 if (!snap
|| !lxcapi_is_defined(snap
)) {
3112 ERROR("Could not find snapshot %s", snapname
);
3116 if (!lxcapi_destroy(snap
)) {
3117 ERROR("Could not destroy snapshot %s", snapname
);
3120 lxc_container_put(snap
);
3125 lxc_container_put(snap
);
3129 static bool lxcapi_may_control(struct lxc_container
*c
)
3131 return lxc_try_cmd(c
->name
, c
->config_path
) == 0;
3134 static bool do_add_remove_node(pid_t init_pid
, const char *path
, bool add
,
3137 char chrootpath
[MAXPATHLEN
];
3138 char *directory_path
= NULL
;
3142 if ((pid
= fork()) < 0) {
3143 SYSERROR("failed to fork a child helper");
3147 if (wait_for_pid(pid
) != 0) {
3148 ERROR("Failed to create note in guest");
3154 /* prepare the path */
3155 ret
= snprintf(chrootpath
, MAXPATHLEN
, "/proc/%d/root", init_pid
);
3156 if (ret
< 0 || ret
>= MAXPATHLEN
)
3159 if (chroot(chrootpath
) < 0)
3163 /* remove path if it exists */
3164 if(faccessat(AT_FDCWD
, path
, F_OK
, AT_SYMLINK_NOFOLLOW
) == 0) {
3165 if (unlink(path
) < 0) {
3166 ERROR("unlink failed");
3173 /* create any missing directories */
3174 directory_path
= dirname(strdup(path
));
3175 if (mkdir_p(directory_path
, 0755) < 0 && errno
!= EEXIST
) {
3176 ERROR("failed to create directory");
3180 /* create the device node */
3181 if (mknod(path
, st
->st_mode
, st
->st_rdev
) < 0) {
3182 ERROR("mknod failed");
3189 static bool add_remove_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
, bool add
)
3193 char value
[MAX_BUFFER
];
3196 /* make sure container is running */
3197 if (!c
->is_running(c
)) {
3198 ERROR("container is not running");
3202 /* use src_path if dest_path is NULL otherwise use dest_path */
3203 p
= dest_path
? dest_path
: src_path
;
3205 /* make sure we can access p */
3206 if(access(p
, F_OK
) < 0 || stat(p
, &st
) < 0)
3209 /* continue if path is character device or block device */
3210 if (S_ISCHR(st
.st_mode
))
3211 ret
= snprintf(value
, MAX_BUFFER
, "c %d:%d rwm", major(st
.st_rdev
), minor(st
.st_rdev
));
3212 else if (S_ISBLK(st
.st_mode
))
3213 ret
= snprintf(value
, MAX_BUFFER
, "b %d:%d rwm", major(st
.st_rdev
), minor(st
.st_rdev
));
3217 /* check snprintf return code */
3218 if (ret
< 0 || ret
>= MAX_BUFFER
)
3221 if (!do_add_remove_node(c
->init_pid(c
), p
, add
, &st
))
3224 /* add or remove device to/from cgroup access list */
3226 if (!c
->set_cgroup_item(c
, "devices.allow", value
)) {
3227 ERROR("set_cgroup_item failed while adding the device node");
3231 if (!c
->set_cgroup_item(c
, "devices.deny", value
)) {
3232 ERROR("set_cgroup_item failed while removing the device node");
3240 static bool lxcapi_add_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
)
3243 ERROR(NOT_SUPPORTED_ERROR
, __FUNCTION__
);
3246 return add_remove_device_node(c
, src_path
, dest_path
, true);
3249 static bool lxcapi_remove_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
)
3252 ERROR(NOT_SUPPORTED_ERROR
, __FUNCTION__
);
3255 return add_remove_device_node(c
, src_path
, dest_path
, false);
3258 static int lxcapi_attach_run_waitl(struct lxc_container
*c
, lxc_attach_options_t
*options
, const char *program
, const char *arg
, ...)
3268 argv
= lxc_va_arg_list_to_argv_const(ap
, 1);
3272 ERROR("Memory allocation error.");
3277 ret
= lxcapi_attach_run_wait(c
, options
, program
, (const char * const *)argv
);
3282 struct lxc_container
*lxc_container_new(const char *name
, const char *configpath
)
3284 struct lxc_container
*c
;
3286 c
= malloc(sizeof(*c
));
3288 fprintf(stderr
, "failed to malloc lxc_container\n");
3291 memset(c
, 0, sizeof(*c
));
3294 c
->config_path
= strdup(configpath
);
3296 c
->config_path
= strdup(lxc_global_config_value("lxc.lxcpath"));
3298 if (!c
->config_path
) {
3299 fprintf(stderr
, "Out of memory\n");
3303 remove_trailing_slashes(c
->config_path
);
3304 c
->name
= malloc(strlen(name
)+1);
3306 fprintf(stderr
, "Error allocating lxc_container name\n");
3309 strcpy(c
->name
, name
);
3312 if (!(c
->slock
= lxc_newlock(c
->config_path
, name
))) {
3313 fprintf(stderr
, "failed to create lock\n");
3317 if (!(c
->privlock
= lxc_newlock(NULL
, NULL
))) {
3318 fprintf(stderr
, "failed to alloc privlock\n");
3322 if (!set_config_filename(c
)) {
3323 fprintf(stderr
, "Error allocating config file pathname\n");
3327 if (file_exists(c
->configfile
) && !lxcapi_load_config(c
, NULL
))
3330 if (ongoing_create(c
) == 2) {
3331 ERROR("Error: %s creation was not completed", c
->name
);
3333 lxcapi_clear_config(c
);
3335 c
->daemonize
= true;
3338 // assign the member functions
3339 c
->is_defined
= lxcapi_is_defined
;
3340 c
->state
= lxcapi_state
;
3341 c
->is_running
= lxcapi_is_running
;
3342 c
->freeze
= lxcapi_freeze
;
3343 c
->unfreeze
= lxcapi_unfreeze
;
3344 c
->console
= lxcapi_console
;
3345 c
->console_getfd
= lxcapi_console_getfd
;
3346 c
->init_pid
= lxcapi_init_pid
;
3347 c
->load_config
= lxcapi_load_config
;
3348 c
->want_daemonize
= lxcapi_want_daemonize
;
3349 c
->want_close_all_fds
= lxcapi_want_close_all_fds
;
3350 c
->start
= lxcapi_start
;
3351 c
->startl
= lxcapi_startl
;
3352 c
->stop
= lxcapi_stop
;
3353 c
->config_file_name
= lxcapi_config_file_name
;
3354 c
->wait
= lxcapi_wait
;
3355 c
->set_config_item
= lxcapi_set_config_item
;
3356 c
->destroy
= lxcapi_destroy
;
3357 c
->rename
= lxcapi_rename
;
3358 c
->save_config
= lxcapi_save_config
;
3359 c
->get_keys
= lxcapi_get_keys
;
3360 c
->create
= lxcapi_create
;
3361 c
->createl
= lxcapi_createl
;
3362 c
->shutdown
= lxcapi_shutdown
;
3363 c
->reboot
= lxcapi_reboot
;
3364 c
->clear_config
= lxcapi_clear_config
;
3365 c
->clear_config_item
= lxcapi_clear_config_item
;
3366 c
->get_config_item
= lxcapi_get_config_item
;
3367 c
->get_running_config_item
= lxcapi_get_running_config_item
;
3368 c
->get_cgroup_item
= lxcapi_get_cgroup_item
;
3369 c
->set_cgroup_item
= lxcapi_set_cgroup_item
;
3370 c
->get_config_path
= lxcapi_get_config_path
;
3371 c
->set_config_path
= lxcapi_set_config_path
;
3372 c
->clone
= lxcapi_clone
;
3373 c
->get_interfaces
= lxcapi_get_interfaces
;
3374 c
->get_ips
= lxcapi_get_ips
;
3375 c
->attach
= lxcapi_attach
;
3376 c
->attach_run_wait
= lxcapi_attach_run_wait
;
3377 c
->attach_run_waitl
= lxcapi_attach_run_waitl
;
3378 c
->snapshot
= lxcapi_snapshot
;
3379 c
->snapshot_list
= lxcapi_snapshot_list
;
3380 c
->snapshot_restore
= lxcapi_snapshot_restore
;
3381 c
->snapshot_destroy
= lxcapi_snapshot_destroy
;
3382 c
->may_control
= lxcapi_may_control
;
3383 c
->add_device_node
= lxcapi_add_device_node
;
3384 c
->remove_device_node
= lxcapi_remove_device_node
;
3386 /* we'll allow the caller to update these later */
3387 if (lxc_log_init(NULL
, "none", NULL
, "lxc_container", 0, c
->config_path
)) {
3388 fprintf(stderr
, "failed to open log\n");
3395 lxc_container_free(c
);
3399 int lxc_get_wait_states(const char **states
)
3404 for (i
=0; i
<MAX_STATE
; i
++)
3405 states
[i
] = lxc_state2str(i
);
3410 * These next two could probably be done smarter with reusing a common function
3411 * with different iterators and tests...
3413 int list_defined_containers(const char *lxcpath
, char ***names
, struct lxc_container
***cret
)
3416 int i
, cfound
= 0, nfound
= 0;
3417 struct dirent dirent
, *direntp
;
3418 struct lxc_container
*c
;
3421 lxcpath
= lxc_global_config_value("lxc.lxcpath");
3423 dir
= opendir(lxcpath
);
3425 SYSERROR("opendir on lxcpath");
3434 while (!readdir_r(dir
, &dirent
, &direntp
)) {
3437 if (!strcmp(direntp
->d_name
, "."))
3439 if (!strcmp(direntp
->d_name
, ".."))
3442 if (!config_file_exists(lxcpath
, direntp
->d_name
))
3446 if (!add_to_array(names
, direntp
->d_name
, cfound
))
3456 c
= lxc_container_new(direntp
->d_name
, lxcpath
);
3458 INFO("Container %s:%s has a config but could not be loaded",
3459 lxcpath
, direntp
->d_name
);
3461 if(!remove_from_array(names
, direntp
->d_name
, cfound
--))
3465 if (!lxcapi_is_defined(c
)) {
3466 INFO("Container %s:%s has a config but is not defined",
3467 lxcpath
, direntp
->d_name
);
3469 if(!remove_from_array(names
, direntp
->d_name
, cfound
--))
3471 lxc_container_put(c
);
3475 if (!add_to_clist(cret
, c
, nfound
, true)) {
3476 lxc_container_put(c
);
3486 if (names
&& *names
) {
3487 for (i
=0; i
<cfound
; i
++)
3491 if (cret
&& *cret
) {
3492 for (i
=0; i
<nfound
; i
++)
3493 lxc_container_put((*cret
)[i
]);
3500 int list_active_containers(const char *lxcpath
, char ***nret
,
3501 struct lxc_container
***cret
)
3503 int i
, ret
= -1, cret_cnt
= 0, ct_name_cnt
= 0;
3506 char **ct_name
= NULL
;
3508 struct lxc_container
*c
;
3511 lxcpath
= lxc_global_config_value("lxc.lxcpath");
3512 lxcpath_len
= strlen(lxcpath
);
3519 FILE *f
= fopen("/proc/net/unix", "r");
3523 while (getline(&line
, &len
, f
) != -1) {
3524 char *p
= strrchr(line
, ' '), *p2
;
3531 if (strncmp(p
, lxcpath
, lxcpath_len
) != 0)
3537 // Now p is the start of lxc_name
3539 if (!p2
|| strncmp(p2
, "/command", 8) != 0)
3543 if (array_contains(&ct_name
, p
, ct_name_cnt
))
3546 if (!add_to_array(&ct_name
, p
, ct_name_cnt
))
3547 goto free_cret_list
;
3554 c
= lxc_container_new(p
, lxcpath
);
3556 INFO("Container %s:%s is running but could not be loaded",
3558 remove_from_array(&ct_name
, p
, ct_name_cnt
--);
3563 * If this is an anonymous container, then is_defined *can*
3564 * return false. So we don't do that check. Count on the
3565 * fact that the command socket exists.
3568 if (!add_to_clist(cret
, c
, cret_cnt
, true)) {
3569 lxc_container_put(c
);
3570 goto free_cret_list
;
3575 assert(!nret
|| !cret
|| cret_cnt
== ct_name_cnt
);
3584 if (cret
&& *cret
) {
3585 for (i
= 0; i
< cret_cnt
; i
++)
3586 lxc_container_put((*cret
)[i
]);
3592 for (i
= 0; i
< ct_name_cnt
; i
++)
3605 int list_all_containers(const char *lxcpath
, char ***nret
,
3606 struct lxc_container
***cret
)
3608 int i
, ret
, active_cnt
, ct_cnt
, ct_list_cnt
;
3611 struct lxc_container
**ct_list
= NULL
;
3613 ct_cnt
= list_defined_containers(lxcpath
, &ct_name
, NULL
);
3617 active_cnt
= list_active_containers(lxcpath
, &active_name
, NULL
);
3618 if (active_cnt
< 0) {
3623 for (i
= 0; i
< active_cnt
; i
++) {
3624 if (!array_contains(&ct_name
, active_name
[i
], ct_cnt
)) {
3625 if (!add_to_array(&ct_name
, active_name
[i
], ct_cnt
)) {
3627 goto free_active_name
;
3631 free(active_name
[i
]);
3632 active_name
[i
] = NULL
;
3638 for (i
= 0, ct_list_cnt
= 0; i
< ct_cnt
&& cret
; i
++) {
3639 struct lxc_container
*c
;
3641 c
= lxc_container_new(ct_name
[i
], lxcpath
);
3643 WARN("Container %s:%s could not be loaded", lxcpath
, ct_name
[i
]);
3644 remove_from_array(&ct_name
, ct_name
[i
], ct_cnt
--);
3648 if (!add_to_clist(&ct_list
, c
, ct_list_cnt
, false)) {
3649 lxc_container_put(c
);
3668 for (i
= 0; i
< ct_list_cnt
; i
++) {
3669 lxc_container_put(ct_list
[i
]);
3675 for (i
= 0; i
< active_cnt
; i
++) {
3677 free(active_name
[i
]);
3683 for (i
= 0; i
< ct_cnt
; i
++) {