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 config_file_exists(const char *lxcpath
, const char *cname
)
87 /* $lxcpath + '/' + $cname + '/config' + \0 */
88 int ret
, len
= strlen(lxcpath
) + strlen(cname
) + 9;
89 char *fname
= alloca(len
);
91 ret
= snprintf(fname
, len
, "%s/%s/config", lxcpath
, cname
);
92 if (ret
< 0 || ret
>= len
)
95 return file_exists(fname
);
99 * A few functions to help detect when a container creation failed.
100 * If a container creation was killed partway through, then trying
101 * to actually start that container could harm the host. We detect
102 * this by creating a 'partial' file under the container directory,
103 * and keeping an advisory lock. When container creation completes,
104 * we remove that file. When we load or try to start a container, if
105 * we find that file, without a flock, we remove the container.
107 static int ongoing_create(struct lxc_container
*c
)
109 int len
= strlen(c
->config_path
) + strlen(c
->name
) + 10;
110 char *path
= alloca(len
);
114 ret
= snprintf(path
, len
, "%s/%s/partial", c
->config_path
, c
->name
);
115 if (ret
< 0 || ret
>= len
) {
116 ERROR("Error writing partial pathname");
120 if (!file_exists(path
))
122 fd
= open(path
, O_RDWR
);
124 // give benefit of the doubt
125 SYSERROR("Error opening partial file");
129 lk
.l_whence
= SEEK_SET
;
133 if (fcntl(fd
, F_GETLK
, &lk
) == 0 && lk
.l_pid
!= -1) {
134 // create is still ongoing
138 // create completed but partial is still there.
143 static int create_partial(struct lxc_container
*c
)
145 // $lxcpath + '/' + $name + '/partial' + \0
146 int len
= strlen(c
->config_path
) + strlen(c
->name
) + 10;
147 char *path
= alloca(len
);
151 ret
= snprintf(path
, len
, "%s/%s/partial", c
->config_path
, c
->name
);
152 if (ret
< 0 || ret
>= len
) {
153 ERROR("Error writing partial pathname");
156 if ((fd
=open(path
, O_RDWR
| O_CREAT
| O_EXCL
, 0755)) < 0) {
157 SYSERROR("Erorr creating partial file");
161 lk
.l_whence
= SEEK_SET
;
164 if (fcntl(fd
, F_SETLKW
, &lk
) < 0) {
165 SYSERROR("Error locking partial file %s", path
);
173 static void remove_partial(struct lxc_container
*c
, int fd
)
175 // $lxcpath + '/' + $name + '/partial' + \0
176 int len
= strlen(c
->config_path
) + strlen(c
->name
) + 10;
177 char *path
= alloca(len
);
181 ret
= snprintf(path
, len
, "%s/%s/partial", c
->config_path
, c
->name
);
182 if (ret
< 0 || ret
>= len
) {
183 ERROR("Error writing partial pathname");
186 if (unlink(path
) < 0)
187 SYSERROR("Error unlink partial file %s", path
);
191 * 1. container_mem_lock(c) protects the struct lxc_container from multiple threads.
192 * 2. container_disk_lock(c) protects the on-disk container data - in particular the
193 * container configuration file.
194 * The container_disk_lock also takes the container_mem_lock.
195 * 3. thread_mutex protects process data (ex: fd table) from multiple threads.
196 * NOTHING mutexes two independent programs with their own struct
197 * lxc_container for the same c->name, between API calls. For instance,
198 * c->config_read(); c->start(); Between those calls, data on disk
199 * could change (which shouldn't bother the caller unless for instance
200 * the rootfs get moved). c->config_read(); update; c->config_write();
201 * Two such updaters could race. The callers should therefore check their
202 * results. Trying to prevent that would necessarily expose us to deadlocks
203 * due to hung callers. So I prefer to keep the locks only within our own
204 * functions, not across functions.
206 * If you're going to clone while holding a lxccontainer, increment
207 * c->numthreads (under privlock) before forking. When deleting,
208 * decrement numthreads under privlock, then if it hits 0 you can delete.
209 * Do not ever use a lxccontainer whose numthreads you did not bump.
212 static void lxc_container_free(struct lxc_container
*c
)
219 c
->configfile
= NULL
;
221 if (c
->error_string
) {
222 free(c
->error_string
);
223 c
->error_string
= NULL
;
226 lxc_putlock(c
->slock
);
230 lxc_putlock(c
->privlock
);
238 lxc_conf_free(c
->lxc_conf
);
241 if (c
->config_path
) {
242 free(c
->config_path
);
243 c
->config_path
= NULL
;
250 * Consider the following case:
251 freer | racing get()er
252 ==================================================================
253 lxc_container_put() | lxc_container_get()
254 \ lxclock(c->privlock) | c->numthreads < 1? (no)
255 \ c->numthreads = 0 | \ lxclock(c->privlock) -> waits
257 \ lxc_container_free() | \ lxclock() returns
258 | \ c->numthreads < 1 -> return 0
260 \ \ sem_destroy(privlock) |
262 * When the get()er checks numthreads the first time, one of the following
264 * 1. freer has set numthreads = 0. get() returns 0
265 * 2. freer is between lxclock and setting numthreads to 0. get()er will
266 * sem_wait on privlock, get lxclock after freer() drops it, then see
267 * numthreads is 0 and exit without touching lxclock again..
268 * 3. freer has not yet locked privlock. If get()er runs first, then put()er
269 * will see --numthreads = 1 and not call lxc_container_free().
272 int lxc_container_get(struct lxc_container
*c
)
277 // if someone else has already started freeing the container, don't
278 // try to take the lock, which may be invalid
279 if (c
->numthreads
< 1)
282 if (container_mem_lock(c
))
284 if (c
->numthreads
< 1) {
285 // bail without trying to unlock, bc the privlock is now probably
290 container_mem_unlock(c
);
294 int lxc_container_put(struct lxc_container
*c
)
298 if (container_mem_lock(c
))
300 if (--c
->numthreads
< 1) {
301 container_mem_unlock(c
);
302 lxc_container_free(c
);
305 container_mem_unlock(c
);
309 static bool lxcapi_is_defined(struct lxc_container
*c
)
318 if (container_mem_lock(c
))
322 statret
= stat(c
->configfile
, &statbuf
);
328 container_mem_unlock(c
);
332 static const char *lxcapi_state(struct lxc_container
*c
)
338 s
= lxc_getstate(c
->name
, c
->config_path
);
339 return lxc_state2str(s
);
342 static bool is_stopped(struct lxc_container
*c
)
345 s
= lxc_getstate(c
->name
, c
->config_path
);
346 return (s
== STOPPED
);
349 static bool lxcapi_is_running(struct lxc_container
*c
)
356 if (!s
|| strcmp(s
, "STOPPED") == 0)
361 static bool lxcapi_freeze(struct lxc_container
*c
)
367 ret
= lxc_freeze(c
->name
, c
->config_path
);
373 static bool lxcapi_unfreeze(struct lxc_container
*c
)
379 ret
= lxc_unfreeze(c
->name
, c
->config_path
);
385 static int lxcapi_console_getfd(struct lxc_container
*c
, int *ttynum
, int *masterfd
)
391 ttyfd
= lxc_console_getfd(c
, ttynum
, masterfd
);
395 static int lxcapi_console(struct lxc_container
*c
, int ttynum
, int stdinfd
,
396 int stdoutfd
, int stderrfd
, int escape
)
398 return lxc_console(c
, ttynum
, stdinfd
, stdoutfd
, stderrfd
, escape
);
401 static pid_t
lxcapi_init_pid(struct lxc_container
*c
)
406 return lxc_cmd_get_init_pid(c
->name
, c
->config_path
);
409 static bool load_config_locked(struct lxc_container
*c
, const char *fname
)
412 c
->lxc_conf
= lxc_conf_init();
415 if (!lxc_config_read(fname
, c
->lxc_conf
, false))
420 static bool lxcapi_load_config(struct lxc_container
*c
, const char *alt_file
)
422 bool ret
= false, need_disklock
= false;
428 fname
= c
->configfile
;
434 * If we're reading something other than the container's config,
435 * we only need to lock the in-memory container. If loading the
436 * container's config file, take the disk lock.
438 if (strcmp(fname
, c
->configfile
) == 0)
439 need_disklock
= true;
442 lret
= container_disk_lock(c
);
444 lret
= container_mem_lock(c
);
448 ret
= load_config_locked(c
, fname
);
451 container_disk_unlock(c
);
453 container_mem_unlock(c
);
457 static bool lxcapi_want_daemonize(struct lxc_container
*c
, bool state
)
459 if (!c
|| !c
->lxc_conf
)
461 if (container_mem_lock(c
)) {
462 ERROR("Error getting mem lock");
465 c
->daemonize
= state
;
466 /* daemonize implies close_all_fds so set it */
468 c
->lxc_conf
->close_all_fds
= 1;
469 container_mem_unlock(c
);
473 static bool lxcapi_want_close_all_fds(struct lxc_container
*c
, bool state
)
475 if (!c
|| !c
->lxc_conf
)
477 if (container_mem_lock(c
)) {
478 ERROR("Error getting mem lock");
481 c
->lxc_conf
->close_all_fds
= state
;
482 container_mem_unlock(c
);
486 static bool lxcapi_wait(struct lxc_container
*c
, const char *state
, int timeout
)
493 ret
= lxc_wait(c
->name
, state
, timeout
, c
->config_path
);
498 static bool wait_on_daemonized_start(struct lxc_container
*c
, int pid
)
500 /* we'll probably want to make this timeout configurable? */
501 int timeout
= 5, ret
, status
;
504 * our child is going to fork again, then exit. reap the
507 ret
= waitpid(pid
, &status
, 0);
508 if (ret
== -1 || !WIFEXITED(status
) || WEXITSTATUS(status
) != 0)
509 DEBUG("failed waiting for first dual-fork child");
510 return lxcapi_wait(c
, "RUNNING", timeout
);
513 static bool am_single_threaded(void)
515 struct dirent dirent
, *direntp
;
519 dir
= opendir("/proc/self/task");
521 INFO("failed to open /proc/self/task");
525 while (!readdir_r(dir
, &dirent
, &direntp
)) {
529 if (!strcmp(direntp
->d_name
, "."))
532 if (!strcmp(direntp
->d_name
, ".."))
542 * I can't decide if it'd be more convenient for callers if we accept '...',
543 * or a null-terminated array (i.e. execl vs execv)
545 static bool lxcapi_start(struct lxc_container
*c
, int useinit
, char * const argv
[])
548 struct lxc_conf
*conf
;
549 bool daemonize
= false;
551 char *default_args
[] = {
556 /* container exists */
559 /* container has been setup */
563 if ((ret
= ongoing_create(c
)) < 0) {
564 ERROR("Error checking for incomplete creation");
568 ERROR("Error: %s creation was not completed", c
->name
);
571 } else if (ret
== 1) {
572 ERROR("Error: creation of %s is ongoing", c
->name
);
576 /* is this app meant to be run through lxcinit, as in lxc-execute? */
577 if (useinit
&& !argv
)
580 if (container_mem_lock(c
))
583 daemonize
= c
->daemonize
;
584 container_mem_unlock(c
);
587 ret
= lxc_execute(c
->name
, argv
, 1, conf
, c
->config_path
);
588 return ret
== 0 ? true : false;
595 * say, I'm not sure - what locks do we want here? Any?
596 * Is liblxc's locking enough here to protect the on disk
597 * container? We don't want to exclude things like lxc_info
598 * while container is running...
601 lxc_monitord_spawn(c
->config_path
);
608 /* Set to NULL because we don't want father unlink
609 * the PID file, child will do the free and unlink.
612 return wait_on_daemonized_start(c
, pid
);
615 /* second fork to be reparented by init */
618 SYSERROR("Error doing dual-fork");
623 /* like daemon(), chdir to / and redirect 0,1,2 to /dev/null */
625 SYSERROR("Error chdir()ing to /.");
628 lxc_check_inherited(conf
, -1);
632 open("/dev/zero", O_RDONLY
);
633 open("/dev/null", O_RDWR
);
634 open("/dev/null", O_RDWR
);
637 if (!am_single_threaded()) {
638 ERROR("Cannot start non-daemonized container when threaded");
643 /* We need to write PID file after daeminize, so we always
644 * write the right PID.
647 pid_fp
= fopen(c
->pidfile
, "w");
648 if (pid_fp
== NULL
) {
649 SYSERROR("Failed to create pidfile '%s' for '%s'",
650 c
->pidfile
, c
->name
);
654 if (fprintf(pid_fp
, "%d\n", getpid()) < 0) {
655 SYSERROR("Failed to write '%s'", c
->pidfile
);
667 ret
= lxc_start(c
->name
, argv
, conf
, c
->config_path
);
671 INFO("container requested reboot");
683 exit (ret
== 0 ? true : false);
685 return (ret
== 0 ? true : false);
689 * note there MUST be an ending NULL
691 static bool lxcapi_startl(struct lxc_container
*c
, int useinit
, ...)
694 char **inargs
= NULL
;
697 /* container exists */
701 va_start(ap
, useinit
);
702 inargs
= lxc_va_arg_list_to_argv(ap
, 0, 1);
706 ERROR("Memory allocation error.");
710 /* pass NULL if no arguments were supplied */
711 bret
= lxcapi_start(c
, useinit
, *inargs
? inargs
: NULL
);
716 for (arg
= inargs
; *arg
; arg
++)
724 static bool lxcapi_stop(struct lxc_container
*c
)
731 ret
= lxc_cmd_stop(c
->name
, c
->config_path
);
737 * create the standard expected container dir
739 static bool create_container_dir(struct lxc_container
*c
)
744 len
= strlen(c
->config_path
) + strlen(c
->name
) + 2;
748 ret
= snprintf(s
, len
, "%s/%s", c
->config_path
, c
->name
);
749 if (ret
< 0 || ret
>= len
) {
753 ret
= mkdir(s
, 0755);
758 SYSERROR("failed to create container path for %s", c
->name
);
764 static const char *lxcapi_get_config_path(struct lxc_container
*c
);
765 static bool lxcapi_set_config_item(struct lxc_container
*c
, const char *key
, const char *v
);
768 * do_bdev_create: thin wrapper around bdev_create(). Like bdev_create(),
769 * it returns a mounted bdev on success, NULL on error.
771 static struct bdev
*do_bdev_create(struct lxc_container
*c
, const char *type
,
772 struct bdev_specs
*specs
)
779 /* rootfs.path or lxcpath/lxcname/rootfs */
780 if (c
->lxc_conf
->rootfs
.path
&& access(c
->lxc_conf
->rootfs
.path
, F_OK
) == 0) {
781 const char *rpath
= c
->lxc_conf
->rootfs
.path
;
782 len
= strlen(rpath
) + 1;
784 ret
= snprintf(dest
, len
, "%s", rpath
);
786 const char *lxcpath
= lxcapi_get_config_path(c
);
787 len
= strlen(c
->name
) + strlen(lxcpath
) + 9;
789 ret
= snprintf(dest
, len
, "%s/%s/rootfs", lxcpath
, c
->name
);
791 if (ret
< 0 || ret
>= len
)
794 bdev
= bdev_create(dest
, type
, c
->name
, specs
);
796 ERROR("Failed to create backing store type %s", type
);
800 lxcapi_set_config_item(c
, "lxc.rootfs", bdev
->src
);
802 /* if we are not root, chown the rootfs dir to root in the
805 if (geteuid() != 0 || (c
->lxc_conf
&& !lxc_list_empty(&c
->lxc_conf
->id_map
))) {
806 if (chown_mapped_root(bdev
->dest
, c
->lxc_conf
) < 0) {
807 ERROR("Error chowning %s to container root", bdev
->dest
);
808 suggest_default_idmap();
818 * Given the '-t' template option to lxc-create, figure out what to
819 * do. If the template is a full executable path, use that. If it
820 * is something like 'sshd', then return $templatepath/lxc-sshd.
821 * On success return the template, on error return NULL.
823 static char *get_template_path(const char *t
)
828 if (t
[0] == '/' && access(t
, X_OK
) == 0) {
833 len
= strlen(LXCTEMPLATEDIR
) + strlen(t
) + strlen("/lxc-") + 1;
837 ret
= snprintf(tpath
, len
, "%s/lxc-%s", LXCTEMPLATEDIR
, t
);
838 if (ret
< 0 || ret
>= len
) {
842 if (access(tpath
, X_OK
) < 0) {
843 SYSERROR("bad template: %s", t
);
851 static char *lxcbasename(char *path
)
853 char *p
= path
+ strlen(path
) - 1;
854 while (*p
!= '/' && p
> path
)
859 static bool create_run_template(struct lxc_container
*c
, char *tpath
, bool quiet
,
869 SYSERROR("failed to fork task for container creation template");
873 if (pid
== 0) { // child
874 char *patharg
, *namearg
, *rootfsarg
, *src
;
875 struct bdev
*bdev
= NULL
;
877 int ret
, len
, nargs
= 0;
879 struct lxc_conf
*conf
= c
->lxc_conf
;
885 open("/dev/zero", O_RDONLY
);
886 open("/dev/null", O_RDWR
);
887 open("/dev/null", O_RDWR
);
890 src
= c
->lxc_conf
->rootfs
.path
;
892 * for an overlay create, what the user wants is the template to fill
893 * in what will become the readonly lower layer. So don't mount for
896 if (strncmp(src
, "overlayfs:", 10) == 0)
897 src
= overlay_getlower(src
+10);
898 if (strncmp(src
, "aufs:", 5) == 0)
899 src
= overlay_getlower(src
+5);
901 bdev
= bdev_init(c
->lxc_conf
, src
, c
->lxc_conf
->rootfs
.mount
, NULL
);
903 ERROR("Error opening rootfs");
907 if (geteuid() == 0) {
908 if (unshare(CLONE_NEWNS
) < 0) {
909 ERROR("error unsharing mounts");
912 if (detect_shared_rootfs()) {
913 if (mount(NULL
, "/", NULL
, MS_SLAVE
|MS_REC
, NULL
)) {
914 SYSERROR("Failed to make / rslave to run template");
915 ERROR("Continuing...");
919 if (strcmp(bdev
->type
, "dir") && strcmp(bdev
->type
, "btrfs")) {
920 if (geteuid() != 0) {
921 ERROR("non-root users can only create btrfs and directory-backed containers");
924 if (bdev
->ops
->mount(bdev
) < 0) {
925 ERROR("Error mounting rootfs");
928 } else { // TODO come up with a better way here!
931 bdev
->dest
= strdup(bdev
->src
);
935 * create our new array, pre-pend the template name and
939 for (nargs
= 0; argv
[nargs
]; nargs
++) ;
940 nargs
+= 4; // template, path, rootfs and name args
942 newargv
= malloc(nargs
* sizeof(*newargv
));
945 newargv
[0] = lxcbasename(tpath
);
947 len
= strlen(c
->config_path
) + strlen(c
->name
) + strlen("--path=") + 2;
948 patharg
= malloc(len
);
951 ret
= snprintf(patharg
, len
, "--path=%s/%s", c
->config_path
, c
->name
);
952 if (ret
< 0 || ret
>= len
)
954 newargv
[1] = patharg
;
955 len
= strlen("--name=") + strlen(c
->name
) + 1;
956 namearg
= malloc(len
);
959 ret
= snprintf(namearg
, len
, "--name=%s", c
->name
);
960 if (ret
< 0 || ret
>= len
)
962 newargv
[2] = namearg
;
964 len
= strlen("--rootfs=") + 1 + strlen(bdev
->dest
);
965 rootfsarg
= malloc(len
);
968 ret
= snprintf(rootfsarg
, len
, "--rootfs=%s", bdev
->dest
);
969 if (ret
< 0 || ret
>= len
)
971 newargv
[3] = rootfsarg
;
973 /* add passed-in args */
975 for (i
= 4; i
< nargs
; i
++)
976 newargv
[i
] = argv
[i
-4];
978 /* add trailing NULL */
980 newargv
= realloc(newargv
, nargs
* sizeof(*newargv
));
983 newargv
[nargs
- 1] = NULL
;
986 * If we're running the template in a mapped userns, then
987 * we prepend the template command with:
988 * lxc-usernsexec <-m map1> ... <-m mapn> --
989 * and we append "--mapped-uid x", where x is the mapped uid
992 if (!lxc_list_empty(&conf
->id_map
)) {
996 char **n2
= malloc(n2args
* sizeof(*n2
));
1001 SYSERROR("out of memory");
1005 tpath
= "lxc-usernsexec";
1006 n2
[0] = "lxc-usernsexec";
1007 lxc_list_for_each(it
, &conf
->id_map
) {
1010 n2
= realloc(n2
, n2args
* sizeof(char *));
1013 n2
[n2args
-2] = "-m";
1014 n2
[n2args
-1] = malloc(200);
1017 ret
= snprintf(n2
[n2args
-1], 200, "%c:%lu:%lu:%lu",
1018 map
->idtype
== ID_TYPE_UID
? 'u' : 'g',
1019 map
->nsid
, map
->hostid
, map
->range
);
1020 if (ret
< 0 || ret
>= 200)
1023 int hostid_mapped
= mapped_hostid(geteuid(), conf
, ID_TYPE_UID
);
1024 int extraargs
= hostid_mapped
>= 0 ? 1 : 3;
1025 n2
= realloc(n2
, (nargs
+ n2args
+ extraargs
) * sizeof(char *));
1028 if (hostid_mapped
< 0) {
1029 hostid_mapped
= find_unmapped_nsuid(conf
, ID_TYPE_UID
);
1030 n2
[n2args
++] = "-m";
1031 if (hostid_mapped
< 0) {
1032 ERROR("Could not find free uid to map");
1035 n2
[n2args
++] = malloc(200);
1036 if (!n2
[n2args
-1]) {
1037 SYSERROR("out of memory");
1040 ret
= snprintf(n2
[n2args
-1], 200, "u:%d:%d:1",
1041 hostid_mapped
, geteuid());
1042 if (ret
< 0 || ret
>= 200) {
1043 ERROR("string too long");
1047 int hostgid_mapped
= mapped_hostid(getegid(), conf
, ID_TYPE_GID
);
1048 extraargs
= hostgid_mapped
>= 0 ? 1 : 3;
1049 n2
= realloc(n2
, (nargs
+ n2args
+ extraargs
) * sizeof(char *));
1052 if (hostgid_mapped
< 0) {
1053 hostgid_mapped
= find_unmapped_nsuid(conf
, ID_TYPE_GID
);
1054 n2
[n2args
++] = "-m";
1055 if (hostgid_mapped
< 0) {
1056 ERROR("Could not find free uid to map");
1059 n2
[n2args
++] = malloc(200);
1060 if (!n2
[n2args
-1]) {
1061 SYSERROR("out of memory");
1064 ret
= snprintf(n2
[n2args
-1], 200, "g:%d:%d:1",
1065 hostgid_mapped
, getegid());
1066 if (ret
< 0 || ret
>= 200) {
1067 ERROR("string too long");
1071 n2
[n2args
++] = "--";
1072 for (i
= 0; i
< nargs
; i
++)
1073 n2
[i
+ n2args
] = newargv
[i
];
1075 // Finally add "--mapped-uid $uid" to tell template what to chown
1078 n2
= realloc(n2
, n2args
* sizeof(char *));
1080 SYSERROR("out of memory");
1083 // note n2[n2args-1] is NULL
1084 n2
[n2args
-5] = "--mapped-uid";
1085 snprintf(txtuid
, 20, "%d", hostid_mapped
);
1086 n2
[n2args
-4] = txtuid
;
1087 n2
[n2args
-3] = "--mapped-gid";
1088 snprintf(txtgid
, 20, "%d", hostgid_mapped
);
1089 n2
[n2args
-2] = txtgid
;
1090 n2
[n2args
-1] = NULL
;
1095 execvp(tpath
, newargv
);
1096 SYSERROR("failed to execute template %s", tpath
);
1100 if (wait_for_pid(pid
) != 0) {
1101 ERROR("container creation template for %s failed", c
->name
);
1108 static bool prepend_lxc_header(char *path
, const char *t
, char *const argv
[])
1116 unsigned char md_value
[SHA_DIGEST_LENGTH
];
1120 f
= fopen(path
, "r");
1124 if (fseek(f
, 0, SEEK_END
) < 0)
1126 if ((flen
= ftell(f
)) < 0)
1128 if (fseek(f
, 0, SEEK_SET
) < 0)
1130 if ((contents
= malloc(flen
+ 1)) == NULL
)
1132 if (fread(contents
, 1, flen
, f
) != flen
)
1133 goto out_free_contents
;
1135 contents
[flen
] = '\0';
1139 goto out_free_contents
;
1142 tpath
= get_template_path(t
);
1144 ERROR("bad template: %s", t
);
1145 goto out_free_contents
;
1148 ret
= sha1sum_file(tpath
, md_value
);
1150 ERROR("Error getting sha1sum of %s", tpath
);
1152 goto out_free_contents
;
1157 f
= fopen(path
, "w");
1159 SYSERROR("reopening config for writing");
1163 fprintf(f
, "# Template used to create this container: %s\n", t
);
1165 fprintf(f
, "# Parameters passed to the template:");
1167 fprintf(f
, " %s", *argv
);
1173 fprintf(f
, "# Template script checksum (SHA-1): ");
1174 for (i
=0; i
<SHA_DIGEST_LENGTH
; i
++)
1175 fprintf(f
, "%02x", md_value
[i
]);
1178 fprintf(f
, "# For additional config options, please look at lxc.container.conf(5)\n");
1179 if (fwrite(contents
, 1, flen
, f
) != flen
) {
1180 SYSERROR("Writing original contents");
1196 SYSERROR("Error prepending header");
1202 static void lxcapi_clear_config(struct lxc_container
*c
)
1206 lxc_conf_free(c
->lxc_conf
);
1212 static bool lxcapi_destroy(struct lxc_container
*c
);
1213 static bool container_destroy(struct lxc_container
*c
);
1214 static bool get_snappath_dir(struct lxc_container
*c
, char *snappath
);
1217 * create a container with the given parameters.
1218 * @c: container to be created. It has the lxcpath, name, and a starting
1219 * configuration already set
1220 * @t: the template to execute to instantiate the root filesystem and
1221 * adjust the configuration.
1222 * @bdevtype: backing store type to use. If NULL, dir will be used.
1223 * @specs: additional parameters for the backing store, i.e. LVM vg to
1226 * @argv: the arguments to pass to the template, terminated by NULL. If no
1227 * arguments, you can just pass NULL.
1229 static bool lxcapi_create(struct lxc_container
*c
, const char *t
,
1230 const char *bdevtype
, struct bdev_specs
*specs
, int flags
,
1242 tpath
= get_template_path(t
);
1244 ERROR("bad template: %s", t
);
1250 * If a template is passed in, and the rootfs already is defined in
1251 * the container config and exists, then * caller is trying to create
1252 * an existing container. Return an error, but do NOT delete the
1255 if (lxcapi_is_defined(c
) && c
->lxc_conf
&& c
->lxc_conf
->rootfs
.path
&&
1256 access(c
->lxc_conf
->rootfs
.path
, F_OK
) == 0 && tpath
) {
1257 ERROR("Container %s:%s already exists", c
->config_path
, c
->name
);
1262 if (!c
->load_config(c
, lxc_global_config_value("lxc.default_config"))) {
1263 ERROR("Error loading default configuration file %s", lxc_global_config_value("lxc.default_config"));
1268 if (!create_container_dir(c
))
1272 * either template or rootfs.path should be set.
1273 * if both template and rootfs.path are set, template is setup as rootfs.path.
1274 * container is already created if we have a config and rootfs.path is accessible
1276 if (!c
->lxc_conf
->rootfs
.path
&& !tpath
)
1277 /* no template passed in and rootfs does not exist: error */
1279 if (c
->lxc_conf
->rootfs
.path
&& access(c
->lxc_conf
->rootfs
.path
, F_OK
) != 0)
1280 /* rootfs passed into configuration, but does not exist: error */
1282 if (lxcapi_is_defined(c
) && c
->lxc_conf
->rootfs
.path
&& !tpath
) {
1283 /* Rootfs already existed, user just wanted to save the
1284 * loaded configuration */
1289 /* Mark that this container is being created */
1290 if ((partial_fd
= create_partial(c
)) < 0)
1293 /* no need to get disk lock bc we have the partial locked */
1296 * Create the backing store
1297 * Note we can't do this in the same task as we use to execute the
1298 * template because of the way zfs works.
1299 * After you 'zfs create', zfs mounts the fs only in the initial
1304 SYSERROR("failed to fork task for container creation template");
1308 if (pid
== 0) { // child
1309 struct bdev
*bdev
= NULL
;
1311 if (!(bdev
= do_bdev_create(c
, bdevtype
, specs
))) {
1312 ERROR("Error creating backing store type %s for %s",
1313 bdevtype
? bdevtype
: "(none)", c
->name
);
1317 /* save config file again to store the new rootfs location */
1318 if (!c
->save_config(c
, NULL
)) {
1319 ERROR("failed to save starting configuration for %s", c
->name
);
1320 // parent task won't see bdev in config so we delete it
1321 bdev
->ops
->umount(bdev
);
1322 bdev
->ops
->destroy(bdev
);
1327 if (wait_for_pid(pid
) != 0)
1330 /* reload config to get the rootfs */
1331 lxc_conf_free(c
->lxc_conf
);
1333 if (!load_config_locked(c
, c
->configfile
))
1336 if (!create_run_template(c
, tpath
, !!(flags
& LXC_CREATE_QUIET
), argv
))
1339 // now clear out the lxc_conf we have, reload from the created
1341 lxcapi_clear_config(c
);
1344 if (!prepend_lxc_header(c
->configfile
, tpath
, argv
)) {
1345 ERROR("Error prepending header to configuration file");
1349 ret
= load_config_locked(c
, c
->configfile
);
1352 if (partial_fd
>= 0)
1353 remove_partial(c
, partial_fd
);
1356 container_destroy(c
);
1363 static bool lxcapi_reboot(struct lxc_container
*c
)
1369 if (!c
->is_running(c
))
1371 pid
= c
->init_pid(c
);
1374 if (kill(pid
, SIGINT
) < 0)
1380 static bool lxcapi_shutdown(struct lxc_container
*c
, int timeout
)
1384 int haltsignal
= SIGPWR
;
1389 if (!c
->is_running(c
))
1391 pid
= c
->init_pid(c
);
1394 if (c
->lxc_conf
&& c
->lxc_conf
->haltsignal
)
1395 haltsignal
= c
->lxc_conf
->haltsignal
;
1396 kill(pid
, haltsignal
);
1397 retv
= c
->wait(c
, "STOPPED", timeout
);
1401 static bool lxcapi_createl(struct lxc_container
*c
, const char *t
,
1402 const char *bdevtype
, struct bdev_specs
*specs
, int flags
, ...)
1412 * since we're going to wait for create to finish, I don't think we
1413 * need to get a copy of the arguments.
1415 va_start(ap
, flags
);
1416 args
= lxc_va_arg_list_to_argv(ap
, 0, 0);
1419 ERROR("Memory allocation error.");
1423 bret
= c
->create(c
, t
, bdevtype
, specs
, flags
, args
);
1430 static void do_clear_unexp_config_line(struct lxc_conf
*conf
, const char *key
)
1432 if (strcmp(key
, "lxc.cgroup") == 0)
1433 clear_unexp_config_line(conf
, key
, true);
1434 else if (strcmp(key
, "lxc.network") == 0)
1435 clear_unexp_config_line(conf
, key
, true);
1436 else if (strcmp(key
, "lxc.hook") == 0)
1437 clear_unexp_config_line(conf
, key
, true);
1439 clear_unexp_config_line(conf
, key
, false);
1440 if (!do_append_unexp_config_line(conf
, key
, ""))
1441 WARN("Error clearing configuration for %s", key
);
1444 static bool lxcapi_clear_config_item(struct lxc_container
*c
, const char *key
)
1448 if (!c
|| !c
->lxc_conf
)
1450 if (container_mem_lock(c
))
1452 ret
= lxc_clear_config_item(c
->lxc_conf
, key
);
1454 do_clear_unexp_config_line(c
->lxc_conf
, key
);
1455 container_mem_unlock(c
);
1459 static inline bool enter_to_ns(struct lxc_container
*c
) {
1460 int netns
, userns
, ret
= 0, init_pid
= 0;;
1461 char new_netns_path
[MAXPATHLEN
];
1462 char new_userns_path
[MAXPATHLEN
];
1464 if (!c
->is_running(c
))
1467 init_pid
= c
->init_pid(c
);
1469 /* Switch to new userns */
1470 if ((geteuid() != 0 || (c
->lxc_conf
&& !lxc_list_empty(&c
->lxc_conf
->id_map
))) && access("/proc/self/ns/user", F_OK
) == 0) {
1471 ret
= snprintf(new_userns_path
, MAXPATHLEN
, "/proc/%d/ns/user", init_pid
);
1472 if (ret
< 0 || ret
>= MAXPATHLEN
)
1475 userns
= open(new_userns_path
, O_RDONLY
);
1477 SYSERROR("failed to open %s", new_userns_path
);
1481 if (setns(userns
, CLONE_NEWUSER
)) {
1482 SYSERROR("failed to setns for CLONE_NEWUSER");
1489 /* Switch to new netns */
1490 ret
= snprintf(new_netns_path
, MAXPATHLEN
, "/proc/%d/ns/net", init_pid
);
1491 if (ret
< 0 || ret
>= MAXPATHLEN
)
1494 netns
= open(new_netns_path
, O_RDONLY
);
1496 SYSERROR("failed to open %s", new_netns_path
);
1500 if (setns(netns
, CLONE_NEWNET
)) {
1501 SYSERROR("failed to setns for CLONE_NEWNET");
1511 // used by qsort and bsearch functions for comparing names
1512 static inline int string_cmp(char **first
, char **second
)
1514 return strcmp(*first
, *second
);
1517 // used by qsort and bsearch functions for comparing container names
1518 static inline int container_cmp(struct lxc_container
**first
, struct lxc_container
**second
)
1520 return strcmp((*first
)->name
, (*second
)->name
);
1523 static bool add_to_array(char ***names
, char *cname
, int pos
)
1525 char **newnames
= realloc(*names
, (pos
+1) * sizeof(char *));
1527 ERROR("Out of memory");
1532 newnames
[pos
] = strdup(cname
);
1536 // sort the arrray as we will use binary search on it
1537 qsort(newnames
, pos
+ 1, sizeof(char *), (int (*)(const void *,const void *))string_cmp
);
1542 static bool add_to_clist(struct lxc_container
***list
, struct lxc_container
*c
, int pos
, bool sort
)
1544 struct lxc_container
**newlist
= realloc(*list
, (pos
+1) * sizeof(struct lxc_container
*));
1546 ERROR("Out of memory");
1553 // sort the arrray as we will use binary search on it
1555 qsort(newlist
, pos
+ 1, sizeof(struct lxc_container
*), (int (*)(const void *,const void *))container_cmp
);
1560 static char** get_from_array(char ***names
, char *cname
, int size
)
1562 return (char **)bsearch(&cname
, *names
, size
, sizeof(char *), (int (*)(const void *, const void *))string_cmp
);
1566 static bool array_contains(char ***names
, char *cname
, int size
) {
1567 if(get_from_array(names
, cname
, size
) != NULL
)
1572 static bool remove_from_array(char ***names
, char *cname
, int size
)
1574 char **result
= get_from_array(names
, cname
, size
);
1575 if (result
!= NULL
) {
1582 static char** lxcapi_get_interfaces(struct lxc_container
*c
)
1585 int i
, count
= 0, pipefd
[2];
1586 char **interfaces
= NULL
;
1587 char interface
[IFNAMSIZ
];
1589 if(pipe(pipefd
) < 0) {
1590 SYSERROR("pipe failed");
1596 SYSERROR("failed to fork task to get interfaces information");
1602 if (pid
== 0) { // child
1603 int ret
= 1, nbytes
;
1604 struct ifaddrs
*interfaceArray
= NULL
, *tempIfAddr
= NULL
;
1606 /* close the read-end of the pipe */
1609 if (!enter_to_ns(c
)) {
1610 SYSERROR("failed to enter namespace");
1614 /* Grab the list of interfaces */
1615 if (getifaddrs(&interfaceArray
)) {
1616 SYSERROR("failed to get interfaces list");
1620 /* Iterate through the interfaces */
1621 for (tempIfAddr
= interfaceArray
; tempIfAddr
!= NULL
; tempIfAddr
= tempIfAddr
->ifa_next
) {
1622 nbytes
= write(pipefd
[1], tempIfAddr
->ifa_name
, IFNAMSIZ
);
1624 ERROR("write failed");
1633 freeifaddrs(interfaceArray
);
1635 /* close the write-end of the pipe, thus sending EOF to the reader */
1640 /* close the write-end of the pipe */
1643 while (read(pipefd
[0], &interface
, IFNAMSIZ
) == IFNAMSIZ
) {
1644 if (array_contains(&interfaces
, interface
, count
))
1647 if(!add_to_array(&interfaces
, interface
, count
))
1648 ERROR("PARENT: add_to_array failed");
1652 if (wait_for_pid(pid
) != 0) {
1653 for(i
=0;i
<count
;i
++)
1654 free(interfaces
[i
]);
1659 /* close the read-end of the pipe */
1662 /* Append NULL to the array */
1664 interfaces
= (char **)lxc_append_null_to_array((void **)interfaces
, count
);
1669 static char** lxcapi_get_ips(struct lxc_container
*c
, const char* interface
, const char* family
, int scope
)
1672 int i
, count
= 0, pipefd
[2];
1673 char **addresses
= NULL
;
1674 char address
[INET6_ADDRSTRLEN
];
1676 if(pipe(pipefd
) < 0) {
1677 SYSERROR("pipe failed");
1683 SYSERROR("failed to fork task to get container ips");
1689 if (pid
== 0) { // child
1690 int ret
= 1, nbytes
;
1691 struct ifaddrs
*interfaceArray
= NULL
, *tempIfAddr
= NULL
;
1692 char addressOutputBuffer
[INET6_ADDRSTRLEN
];
1693 void *tempAddrPtr
= NULL
;
1694 char *address
= NULL
;
1696 /* close the read-end of the pipe */
1699 if (!enter_to_ns(c
)) {
1700 SYSERROR("failed to enter namespace");
1704 /* Grab the list of interfaces */
1705 if (getifaddrs(&interfaceArray
)) {
1706 SYSERROR("failed to get interfaces list");
1710 /* Iterate through the interfaces */
1711 for (tempIfAddr
= interfaceArray
; tempIfAddr
!= NULL
; tempIfAddr
= tempIfAddr
->ifa_next
) {
1712 if (tempIfAddr
->ifa_addr
== NULL
)
1715 if(tempIfAddr
->ifa_addr
->sa_family
== AF_INET
) {
1716 if (family
&& strcmp(family
, "inet"))
1718 tempAddrPtr
= &((struct sockaddr_in
*)tempIfAddr
->ifa_addr
)->sin_addr
;
1721 if (family
&& strcmp(family
, "inet6"))
1724 if (((struct sockaddr_in6
*)tempIfAddr
->ifa_addr
)->sin6_scope_id
!= scope
)
1727 tempAddrPtr
= &((struct sockaddr_in6
*)tempIfAddr
->ifa_addr
)->sin6_addr
;
1730 if (interface
&& strcmp(interface
, tempIfAddr
->ifa_name
))
1732 else if (!interface
&& strcmp("lo", tempIfAddr
->ifa_name
) == 0)
1735 address
= (char *)inet_ntop(tempIfAddr
->ifa_addr
->sa_family
,
1737 addressOutputBuffer
,
1738 sizeof(addressOutputBuffer
));
1742 nbytes
= write(pipefd
[1], address
, INET6_ADDRSTRLEN
);
1744 ERROR("write failed");
1753 freeifaddrs(interfaceArray
);
1755 /* close the write-end of the pipe, thus sending EOF to the reader */
1760 /* close the write-end of the pipe */
1763 while (read(pipefd
[0], &address
, INET6_ADDRSTRLEN
) == INET6_ADDRSTRLEN
) {
1764 if(!add_to_array(&addresses
, address
, count
))
1765 ERROR("PARENT: add_to_array failed");
1769 if (wait_for_pid(pid
) != 0) {
1770 for(i
=0;i
<count
;i
++)
1776 /* close the read-end of the pipe */
1779 /* Append NULL to the array */
1781 addresses
= (char **)lxc_append_null_to_array((void **)addresses
, count
);
1786 static int lxcapi_get_config_item(struct lxc_container
*c
, const char *key
, char *retv
, int inlen
)
1790 if (!c
|| !c
->lxc_conf
)
1792 if (container_mem_lock(c
))
1794 ret
= lxc_get_config_item(c
->lxc_conf
, key
, retv
, inlen
);
1795 container_mem_unlock(c
);
1799 static char* lxcapi_get_running_config_item(struct lxc_container
*c
, const char *key
)
1803 if (!c
|| !c
->lxc_conf
)
1805 if (container_mem_lock(c
))
1807 ret
= lxc_cmd_get_config_item(c
->name
, key
, c
->get_config_path(c
));
1808 container_mem_unlock(c
);
1812 static int lxcapi_get_keys(struct lxc_container
*c
, const char *key
, char *retv
, int inlen
)
1815 return lxc_listconfigs(retv
, inlen
);
1817 * Support 'lxc.network.<idx>', i.e. 'lxc.network.0'
1818 * This is an intelligent result to show which keys are valid given
1819 * the type of nic it is
1821 if (!c
|| !c
->lxc_conf
)
1823 if (container_mem_lock(c
))
1826 if (strncmp(key
, "lxc.network.", 12) == 0)
1827 ret
= lxc_list_nicconfigs(c
->lxc_conf
, key
, retv
, inlen
);
1828 container_mem_unlock(c
);
1832 static bool lxcapi_save_config(struct lxc_container
*c
, const char *alt_file
)
1835 bool ret
= false, need_disklock
= false;
1839 alt_file
= c
->configfile
;
1841 return false; // should we write to stdout if no file is specified?
1843 // If we haven't yet loaded a config, load the stock config
1845 if (!c
->load_config(c
, lxc_global_config_value("lxc.default_config"))) {
1846 ERROR("Error loading default configuration file %s while saving %s", lxc_global_config_value("lxc.default_config"), c
->name
);
1851 if (!create_container_dir(c
))
1855 * If we're writing to the container's config file, take the
1856 * disk lock. Otherwise just take the memlock to protect the
1857 * struct lxc_container while we're traversing it.
1859 if (strcmp(c
->configfile
, alt_file
) == 0)
1860 need_disklock
= true;
1863 lret
= container_disk_lock(c
);
1865 lret
= container_mem_lock(c
);
1870 fout
= fopen(alt_file
, "w");
1873 write_config(fout
, c
->lxc_conf
);
1879 container_disk_unlock(c
);
1881 container_mem_unlock(c
);
1885 static bool mod_rdep(struct lxc_container
*c
, bool inc
)
1887 char path
[MAXPATHLEN
];
1892 if (container_disk_lock(c
))
1894 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_snapshots", c
->config_path
,
1896 if (ret
< 0 || ret
> MAXPATHLEN
)
1898 f
= fopen(path
, "r");
1900 ret
= fscanf(f
, "%d", &v
);
1903 ERROR("Corrupted file %s", path
);
1908 f
= fopen(path
, "w");
1911 if (fprintf(f
, "%d\n", v
) < 0) {
1912 ERROR("Error writing new snapshots value");
1918 SYSERROR("Error writing to or closing snapshots file");
1925 container_disk_unlock(c
);
1929 static void strip_newline(char *p
)
1931 size_t len
= strlen(p
);
1934 if (p
[len
-1] == '\n')
1938 static void mod_all_rdeps(struct lxc_container
*c
, bool inc
)
1940 struct lxc_container
*p
;
1941 char *lxcpath
= NULL
, *lxcname
= NULL
, path
[MAXPATHLEN
];
1942 size_t pathlen
= 0, namelen
= 0;
1946 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_rdepends",
1947 c
->config_path
, c
->name
);
1948 if (ret
< 0 || ret
>= MAXPATHLEN
) {
1949 ERROR("Path name too long");
1952 f
= fopen(path
, "r");
1955 while (getline(&lxcpath
, &pathlen
, f
) != -1) {
1956 if (getline(&lxcname
, &namelen
, f
) == -1) {
1957 ERROR("badly formatted file %s", path
);
1960 strip_newline(lxcpath
);
1961 strip_newline(lxcname
);
1962 if ((p
= lxc_container_new(lxcname
, lxcpath
)) == NULL
) {
1963 ERROR("Unable to find dependent container %s:%s",
1967 if (!mod_rdep(p
, inc
))
1968 ERROR("Failed to increase numsnapshots for %s:%s",
1970 lxc_container_put(p
);
1973 if (lxcpath
) free(lxcpath
);
1974 if (lxcname
) free(lxcname
);
1978 static bool has_fs_snapshots(struct lxc_container
*c
)
1980 char path
[MAXPATHLEN
];
1985 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_snapshots", c
->config_path
,
1987 if (ret
< 0 || ret
> MAXPATHLEN
)
1989 f
= fopen(path
, "r");
1992 ret
= fscanf(f
, "%d", &v
);
2002 static bool has_snapshots(struct lxc_container
*c
)
2004 char path
[MAXPATHLEN
];
2005 struct dirent dirent
, *direntp
;
2009 if (!get_snappath_dir(c
, path
))
2011 dir
= opendir(path
);
2014 while (!readdir_r(dir
, &dirent
, &direntp
)) {
2018 if (!strcmp(direntp
->d_name
, "."))
2021 if (!strcmp(direntp
->d_name
, ".."))
2030 static int lxc_rmdir_onedev_wrapper(void *data
)
2032 char *arg
= (char *) data
;
2033 return lxc_rmdir_onedev(arg
, "snaps");
2036 static int do_bdev_destroy(struct lxc_conf
*conf
)
2041 r
= bdev_init(conf
, conf
->rootfs
.path
, conf
->rootfs
.mount
, NULL
);
2045 if (r
->ops
->destroy(r
) < 0)
2051 static int bdev_destroy_wrapper(void *data
)
2053 struct lxc_conf
*conf
= data
;
2055 if (setgid(0) < 0) {
2056 ERROR("Failed to setgid to 0");
2059 if (setgroups(0, NULL
) < 0)
2060 WARN("Failed to clear groups");
2061 if (setuid(0) < 0) {
2062 ERROR("Failed to setuid to 0");
2065 return do_bdev_destroy(conf
);
2068 static bool container_destroy(struct lxc_container
*c
)
2073 if (!c
|| !lxcapi_is_defined(c
))
2076 if (container_disk_lock(c
))
2079 if (!is_stopped(c
)) {
2080 // we should queue some sort of error - in c->error_string?
2081 ERROR("container %s is not stopped", c
->name
);
2085 if (c
->lxc_conf
&& c
->lxc_conf
->rootfs
.path
&& c
->lxc_conf
->rootfs
.mount
) {
2087 ret
= userns_exec_1(c
->lxc_conf
, bdev_destroy_wrapper
, c
->lxc_conf
);
2089 ret
= do_bdev_destroy(c
->lxc_conf
);
2091 ERROR("Error destroying rootfs for %s", c
->name
);
2096 mod_all_rdeps(c
, false);
2098 const char *p1
= lxcapi_get_config_path(c
);
2099 char *path
= alloca(strlen(p1
) + strlen(c
->name
) + 2);
2100 sprintf(path
, "%s/%s", p1
, c
->name
);
2102 ret
= userns_exec_1(c
->lxc_conf
, lxc_rmdir_onedev_wrapper
, path
);
2104 ret
= lxc_rmdir_onedev(path
, "snaps");
2106 ERROR("Error destroying container directory for %s", c
->name
);
2112 container_disk_unlock(c
);
2116 static bool lxcapi_destroy(struct lxc_container
*c
)
2118 if (!c
|| !lxcapi_is_defined(c
))
2120 if (has_snapshots(c
)) {
2121 ERROR("Container %s has snapshots; not removing", c
->name
);
2125 if (has_fs_snapshots(c
)) {
2126 ERROR("container %s has snapshots on its rootfs", c
->name
);
2130 return container_destroy(c
);
2133 static bool lxcapi_snapshot_destroy_all(struct lxc_container
*c
);
2135 static bool lxcapi_destroy_with_snapshots(struct lxc_container
*c
)
2137 if (!c
|| !lxcapi_is_defined(c
))
2139 if (!lxcapi_snapshot_destroy_all(c
)) {
2140 ERROR("Error deleting all snapshots");
2143 return lxcapi_destroy(c
);
2146 static bool set_config_item_locked(struct lxc_container
*c
, const char *key
, const char *v
)
2148 struct lxc_config_t
*config
;
2151 c
->lxc_conf
= lxc_conf_init();
2154 config
= lxc_getconfig(key
);
2157 if (config
->cb(key
, v
, c
->lxc_conf
) != 0)
2159 return do_append_unexp_config_line(c
->lxc_conf
, key
, v
);
2162 static bool lxcapi_set_config_item(struct lxc_container
*c
, const char *key
, const char *v
)
2169 if (container_mem_lock(c
))
2172 b
= set_config_item_locked(c
, key
, v
);
2174 container_mem_unlock(c
);
2178 static char *lxcapi_config_file_name(struct lxc_container
*c
)
2180 if (!c
|| !c
->configfile
)
2182 return strdup(c
->configfile
);
2185 static const char *lxcapi_get_config_path(struct lxc_container
*c
)
2187 if (!c
|| !c
->config_path
)
2189 return (const char *)(c
->config_path
);
2194 * Just recalculate the c->configfile based on the
2195 * c->config_path, which must be set.
2196 * The lxc_container must be locked or not yet public.
2198 static bool set_config_filename(struct lxc_container
*c
)
2203 if (!c
->config_path
)
2206 /* $lxc_path + "/" + c->name + "/" + "config" + '\0' */
2207 len
= strlen(c
->config_path
) + strlen(c
->name
) + strlen("config") + 3;
2208 newpath
= malloc(len
);
2212 ret
= snprintf(newpath
, len
, "%s/%s/config", c
->config_path
, c
->name
);
2213 if (ret
< 0 || ret
>= len
) {
2214 fprintf(stderr
, "Error printing out config file name\n");
2220 free(c
->configfile
);
2221 c
->configfile
= newpath
;
2226 static bool lxcapi_set_config_path(struct lxc_container
*c
, const char *path
)
2230 char *oldpath
= NULL
;
2235 if (container_mem_lock(c
))
2240 ERROR("Out of memory setting new lxc path");
2246 oldpath
= c
->config_path
;
2249 /* Since we've changed the config path, we have to change the
2250 * config file name too */
2251 if (!set_config_filename(c
)) {
2252 ERROR("Out of memory setting new config filename");
2254 free(c
->config_path
);
2255 c
->config_path
= oldpath
;
2261 container_mem_unlock(c
);
2266 static bool lxcapi_set_cgroup_item(struct lxc_container
*c
, const char *subsys
, const char *value
)
2276 if (container_disk_lock(c
))
2279 ret
= lxc_cgroup_set(subsys
, value
, c
->name
, c
->config_path
);
2281 container_disk_unlock(c
);
2285 static int lxcapi_get_cgroup_item(struct lxc_container
*c
, const char *subsys
, char *retv
, int inlen
)
2295 if (container_disk_lock(c
))
2298 ret
= lxc_cgroup_get(subsys
, retv
, inlen
, c
->name
, c
->config_path
);
2300 container_disk_unlock(c
);
2304 const char *lxc_get_global_config_item(const char *key
)
2306 return lxc_global_config_value(key
);
2309 const char *lxc_get_version(void)
2314 static int copy_file(const char *old
, const char *new)
2321 if (file_exists(new)) {
2322 ERROR("copy destination %s exists", new);
2325 ret
= stat(old
, &sbuf
);
2327 INFO("Error stat'ing %s", old
);
2331 in
= open(old
, O_RDONLY
);
2333 SYSERROR("Error opening original file %s", old
);
2336 out
= open(new, O_CREAT
| O_EXCL
| O_WRONLY
, 0644);
2338 SYSERROR("Error opening new file %s", new);
2344 len
= read(in
, buf
, 8096);
2346 SYSERROR("Error reading old file %s", old
);
2351 ret
= write(out
, buf
, len
);
2352 if (ret
< len
) { // should we retry?
2353 SYSERROR("Error: write to new file %s was interrupted", new);
2360 // we set mode, but not owner/group
2361 ret
= chmod(new, sbuf
.st_mode
);
2363 SYSERROR("Error setting mode on %s", new);
2375 static int copyhooks(struct lxc_container
*oldc
, struct lxc_container
*c
)
2378 struct lxc_list
*it
;
2381 len
= strlen(oldc
->config_path
) + strlen(oldc
->name
) + 3;
2382 cpath
= alloca(len
);
2383 ret
= snprintf(cpath
, len
, "%s/%s/", oldc
->config_path
, oldc
->name
);
2384 if (ret
< 0 || ret
>= len
)
2387 for (i
=0; i
<NUM_LXC_HOOKS
; i
++) {
2388 lxc_list_for_each(it
, &c
->lxc_conf
->hooks
[i
]) {
2389 char *hookname
= it
->elem
;
2390 char *fname
= strrchr(hookname
, '/');
2391 char tmppath
[MAXPATHLEN
];
2392 if (!fname
) // relative path - we don't support, but maybe we should
2394 if (strncmp(hookname
, cpath
, len
- 1) != 0) {
2395 // this hook is public - ignore
2398 // copy the script, and change the entry in confile
2399 ret
= snprintf(tmppath
, MAXPATHLEN
, "%s/%s/%s",
2400 c
->config_path
, c
->name
, fname
+1);
2401 if (ret
< 0 || ret
>= MAXPATHLEN
)
2403 ret
= copy_file(it
->elem
, tmppath
);
2407 it
->elem
= strdup(tmppath
);
2409 ERROR("out of memory copying hook path");
2415 if (!clone_update_unexp_hooks(c
->lxc_conf
)) {
2416 ERROR("Error saving new hooks in clone");
2419 c
->save_config(c
, NULL
);
2423 static void new_hwaddr(char *hwaddr
)
2426 f
= fopen("/dev/urandom", "r");
2429 int ret
= fread(&seed
, sizeof(seed
), 1, f
);
2436 snprintf(hwaddr
, 18, "00:16:3e:%02x:%02x:%02x",
2437 rand() % 255, rand() % 255, rand() % 255);
2440 static void network_new_hwaddrs(struct lxc_container
*c
)
2442 struct lxc_list
*it
;
2444 lxc_list_for_each(it
, &c
->lxc_conf
->network
) {
2445 struct lxc_netdev
*n
= it
->elem
;
2447 new_hwaddr(n
->hwaddr
);
2451 static int copy_fstab(struct lxc_container
*oldc
, struct lxc_container
*c
)
2453 char newpath
[MAXPATHLEN
];
2454 char *oldpath
= oldc
->lxc_conf
->fstab
;
2460 clear_unexp_config_line(c
->lxc_conf
, "lxc.mount", false);
2462 char *p
= strrchr(oldpath
, '/');
2465 ret
= snprintf(newpath
, MAXPATHLEN
, "%s/%s%s",
2466 c
->config_path
, c
->name
, p
);
2467 if (ret
< 0 || ret
>= MAXPATHLEN
) {
2468 ERROR("error printing new path for %s", oldpath
);
2471 if (file_exists(newpath
)) {
2472 ERROR("error: fstab file %s exists", newpath
);
2476 if (copy_file(oldpath
, newpath
) < 0) {
2477 ERROR("error: copying %s to %s", oldpath
, newpath
);
2480 free(c
->lxc_conf
->fstab
);
2481 c
->lxc_conf
->fstab
= strdup(newpath
);
2482 if (!c
->lxc_conf
->fstab
) {
2483 ERROR("error: allocating pathname");
2486 if (!do_append_unexp_config_line(c
->lxc_conf
, "lxc.mount", newpath
)) {
2487 ERROR("error saving new lxctab");
2494 static void copy_rdepends(struct lxc_container
*c
, struct lxc_container
*c0
)
2496 char path0
[MAXPATHLEN
], path1
[MAXPATHLEN
];
2499 ret
= snprintf(path0
, MAXPATHLEN
, "%s/%s/lxc_rdepends", c0
->config_path
,
2501 if (ret
< 0 || ret
>= MAXPATHLEN
) {
2502 WARN("Error copying reverse dependencies");
2505 ret
= snprintf(path1
, MAXPATHLEN
, "%s/%s/lxc_rdepends", c
->config_path
,
2507 if (ret
< 0 || ret
>= MAXPATHLEN
) {
2508 WARN("Error copying reverse dependencies");
2511 if (copy_file(path0
, path1
) < 0) {
2512 INFO("Error copying reverse dependencies");
2517 static bool add_rdepends(struct lxc_container
*c
, struct lxc_container
*c0
)
2520 char path
[MAXPATHLEN
];
2524 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_rdepends", c
->config_path
,
2526 if (ret
< 0 || ret
>= MAXPATHLEN
)
2528 f
= fopen(path
, "a");
2532 // if anything goes wrong, just return an error
2533 if (fprintf(f
, "%s\n%s\n", c0
->config_path
, c0
->name
) < 0)
2540 static int copy_storage(struct lxc_container
*c0
, struct lxc_container
*c
,
2541 const char *newtype
, int flags
, const char *bdevdata
, uint64_t newsize
)
2546 bdev
= bdev_copy(c0
, c
->name
, c
->config_path
, newtype
, flags
,
2547 bdevdata
, newsize
, &need_rdep
);
2549 ERROR("Error copying storage");
2552 free(c
->lxc_conf
->rootfs
.path
);
2553 c
->lxc_conf
->rootfs
.path
= strdup(bdev
->src
);
2555 if (!c
->lxc_conf
->rootfs
.path
) {
2556 ERROR("Out of memory while setting storage path");
2559 // We will simply append a new lxc.rootfs entry to the unexpanded config
2560 clear_unexp_config_line(c
->lxc_conf
, "lxc.rootfs", false);
2561 if (!do_append_unexp_config_line(c
->lxc_conf
, "lxc.rootfs", c
->lxc_conf
->rootfs
.path
)) {
2562 ERROR("Error saving new rootfs to cloend config");
2565 if (flags
& LXC_CLONE_SNAPSHOT
)
2566 copy_rdepends(c
, c0
);
2568 if (!add_rdepends(c
, c0
))
2569 WARN("Error adding reverse dependency from %s to %s",
2573 mod_all_rdeps(c
, true);
2578 struct clone_update_data
{
2579 struct lxc_container
*c0
;
2580 struct lxc_container
*c1
;
2585 static int clone_update_rootfs(struct clone_update_data
*data
)
2587 struct lxc_container
*c0
= data
->c0
;
2588 struct lxc_container
*c
= data
->c1
;
2589 int flags
= data
->flags
;
2590 char **hookargs
= data
->hookargs
;
2592 char path
[MAXPATHLEN
];
2595 struct lxc_conf
*conf
= c
->lxc_conf
;
2597 /* update hostname in rootfs */
2598 /* we're going to mount, so run in a clean namespace to simplify cleanup */
2600 if (setgid(0) < 0) {
2601 ERROR("Failed to setgid to 0");
2604 if (setuid(0) < 0) {
2605 ERROR("Failed to setuid to 0");
2608 if (setgroups(0, NULL
) < 0)
2609 WARN("Failed to clear groups");
2611 if (unshare(CLONE_NEWNS
) < 0)
2613 bdev
= bdev_init(c
->lxc_conf
, c
->lxc_conf
->rootfs
.path
, c
->lxc_conf
->rootfs
.mount
, NULL
);
2616 if (strcmp(bdev
->type
, "dir") != 0) {
2617 if (unshare(CLONE_NEWNS
) < 0) {
2618 ERROR("error unsharing mounts");
2622 if (detect_shared_rootfs()) {
2623 if (mount(NULL
, "/", NULL
, MS_SLAVE
|MS_REC
, NULL
)) {
2624 SYSERROR("Failed to make / rslave");
2625 ERROR("Continuing...");
2628 if (bdev
->ops
->mount(bdev
) < 0) {
2632 } else { // TODO come up with a better way
2635 bdev
->dest
= strdup(bdev
->src
);
2638 if (!lxc_list_empty(&conf
->hooks
[LXCHOOK_CLONE
])) {
2639 /* Start of environment variable setup for hooks */
2640 if (setenv("LXC_SRC_NAME", c0
->name
, 1)) {
2641 SYSERROR("failed to set environment variable for source container name");
2643 if (setenv("LXC_NAME", c
->name
, 1)) {
2644 SYSERROR("failed to set environment variable for container name");
2646 if (setenv("LXC_CONFIG_FILE", conf
->rcfile
, 1)) {
2647 SYSERROR("failed to set environment variable for config path");
2649 if (setenv("LXC_ROOTFS_MOUNT", bdev
->dest
, 1)) {
2650 SYSERROR("failed to set environment variable for rootfs mount");
2652 if (setenv("LXC_ROOTFS_PATH", conf
->rootfs
.path
, 1)) {
2653 SYSERROR("failed to set environment variable for rootfs mount");
2656 if (run_lxc_hooks(c
->name
, "clone", conf
, c
->get_config_path(c
), hookargs
)) {
2657 ERROR("Error executing clone hook for %s", c
->name
);
2663 if (!(flags
& LXC_CLONE_KEEPNAME
)) {
2664 ret
= snprintf(path
, MAXPATHLEN
, "%s/etc/hostname", bdev
->dest
);
2667 if (ret
< 0 || ret
>= MAXPATHLEN
)
2669 if (!file_exists(path
))
2671 if (!(fout
= fopen(path
, "w"))) {
2672 SYSERROR("unable to open %s: ignoring", path
);
2675 if (fprintf(fout
, "%s", c
->name
) < 0) {
2679 if (fclose(fout
) < 0)
2688 static int clone_update_rootfs_wrapper(void *data
)
2690 struct clone_update_data
*arg
= (struct clone_update_data
*) data
;
2691 return clone_update_rootfs(arg
);
2695 * We want to support:
2696 sudo lxc-clone -o o1 -n n1 -s -L|-fssize fssize -v|--vgname vgname \
2697 -p|--lvprefix lvprefix -t|--fstype fstype -B backingstore
2699 -s [ implies overlayfs]
2703 only rootfs gets converted (copied/snapshotted) on clone.
2706 static int create_file_dirname(char *path
)
2708 char *p
= strrchr(path
, '/');
2714 ret
= mkdir(path
, 0755);
2715 if (ret
&& errno
!= EEXIST
)
2716 SYSERROR("creating container path %s", path
);
2721 static struct lxc_container
*lxcapi_clone(struct lxc_container
*c
, const char *newname
,
2722 const char *lxcpath
, int flags
,
2723 const char *bdevtype
, const char *bdevdata
, uint64_t newsize
,
2726 struct lxc_container
*c2
= NULL
;
2727 char newpath
[MAXPATHLEN
];
2728 int ret
, storage_copied
= 0;
2730 char *origroot
= NULL
;
2731 struct clone_update_data data
;
2735 if (!c
|| !c
->is_defined(c
))
2738 if (container_mem_lock(c
))
2741 if (!is_stopped(c
)) {
2742 ERROR("error: Original container (%s) is running", c
->name
);
2746 // Make sure the container doesn't yet exist.
2747 n
= newname
? newname
: c
->name
;
2748 l
= lxcpath
? lxcpath
: c
->get_config_path(c
);
2749 ret
= snprintf(newpath
, MAXPATHLEN
, "%s/%s/config", l
, n
);
2750 if (ret
< 0 || ret
>= MAXPATHLEN
) {
2751 SYSERROR("clone: failed making config pathname");
2754 if (file_exists(newpath
)) {
2755 ERROR("error: clone: %s exists", newpath
);
2759 ret
= create_file_dirname(newpath
);
2760 if (ret
< 0 && errno
!= EEXIST
) {
2761 ERROR("Error creating container dir for %s", newpath
);
2765 // copy the configuration, tweak it as needed,
2766 if (c
->lxc_conf
->rootfs
.path
) {
2767 origroot
= c
->lxc_conf
->rootfs
.path
;
2768 c
->lxc_conf
->rootfs
.path
= NULL
;
2770 fout
= fopen(newpath
, "w");
2772 SYSERROR("open %s", newpath
);
2775 write_config(fout
, c
->lxc_conf
);
2777 c
->lxc_conf
->rootfs
.path
= origroot
;
2779 sprintf(newpath
, "%s/%s/rootfs", l
, n
);
2780 if (mkdir(newpath
, 0755) < 0) {
2781 SYSERROR("error creating %s", newpath
);
2786 if (chown_mapped_root(newpath
, c
->lxc_conf
) < 0) {
2787 ERROR("Error chowning %s to container root", newpath
);
2792 c2
= lxc_container_new(n
, l
);
2794 ERROR("clone: failed to create new container (%s %s)", n
, l
);
2798 // copy/snapshot rootfs's
2799 ret
= copy_storage(c
, c2
, bdevtype
, flags
, bdevdata
, newsize
);
2803 clear_unexp_config_line(c2
->lxc_conf
, "lxc.utsname", false);
2806 if (!set_config_item_locked(c2
, "lxc.utsname", newname
)) {
2807 ERROR("Error setting new hostname");
2812 ret
= copyhooks(c
, c2
);
2814 ERROR("error copying hooks");
2818 if (copy_fstab(c
, c2
) < 0) {
2819 ERROR("error copying fstab");
2824 if (!(flags
& LXC_CLONE_KEEPMACADDR
)) {
2825 network_new_hwaddrs(c2
);
2826 if (!clone_update_unexp_network(c2
->lxc_conf
)) {
2827 ERROR("Error updating network for clone");
2832 // We've now successfully created c2's storage, so clear it out if we
2836 if (!c2
->save_config(c2
, NULL
))
2839 if ((pid
= fork()) < 0) {
2844 ret
= wait_for_pid(pid
);
2847 container_mem_unlock(c
);
2853 data
.hookargs
= hookargs
;
2855 ret
= userns_exec_1(c
->lxc_conf
, clone_update_rootfs_wrapper
,
2858 ret
= clone_update_rootfs(&data
);
2862 container_mem_unlock(c
);
2866 container_mem_unlock(c
);
2868 if (!storage_copied
)
2869 c2
->lxc_conf
->rootfs
.path
= NULL
;
2871 lxc_container_put(c2
);
2877 static bool lxcapi_rename(struct lxc_container
*c
, const char *newname
)
2880 struct lxc_container
*newc
;
2882 if (!c
|| !c
->name
|| !c
->config_path
|| !c
->lxc_conf
)
2885 if (has_fs_snapshots(c
) || has_snapshots(c
)) {
2886 ERROR("Renaming a container with snapshots is not supported");
2889 bdev
= bdev_init(c
->lxc_conf
, c
->lxc_conf
->rootfs
.path
, c
->lxc_conf
->rootfs
.mount
, NULL
);
2891 ERROR("Failed to find original backing store type");
2895 newc
= lxcapi_clone(c
, newname
, c
->config_path
, LXC_CLONE_KEEPMACADDR
, NULL
, bdev
->type
, 0, NULL
);
2898 lxc_container_put(newc
);
2902 if (newc
&& lxcapi_is_defined(newc
))
2903 lxc_container_put(newc
);
2905 if (!container_destroy(c
)) {
2906 ERROR("Could not destroy existing container %s", c
->name
);
2912 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
)
2917 return lxc_attach(c
->name
, c
->config_path
, exec_function
, exec_payload
, options
, attached_process
);
2920 static int lxcapi_attach_run_wait(struct lxc_container
*c
, lxc_attach_options_t
*options
, const char *program
, const char * const argv
[])
2922 lxc_attach_command_t command
;
2929 command
.program
= (char*)program
;
2930 command
.argv
= (char**)argv
;
2931 r
= lxc_attach(c
->name
, c
->config_path
, lxc_attach_run_command
, &command
, options
, &pid
);
2936 return lxc_wait_for_pid_status(pid
);
2939 static int get_next_index(const char *lxcpath
, char *cname
)
2945 fname
= alloca(strlen(lxcpath
) + 20);
2947 sprintf(fname
, "%s/snap%d", lxcpath
, i
);
2948 ret
= stat(fname
, &sb
);
2955 static bool get_snappath_dir(struct lxc_container
*c
, char *snappath
)
2959 * If the old style snapshot path exists, use it
2960 * /var/lib/lxc -> /var/lib/lxcsnaps
2962 ret
= snprintf(snappath
, MAXPATHLEN
, "%ssnaps", c
->config_path
);
2963 if (ret
< 0 || ret
>= MAXPATHLEN
)
2965 if (dir_exists(snappath
)) {
2966 ret
= snprintf(snappath
, MAXPATHLEN
, "%ssnaps/%s", c
->config_path
, c
->name
);
2967 if (ret
< 0 || ret
>= MAXPATHLEN
)
2973 * Use the new style path
2974 * /var/lib/lxc -> /var/lib/lxc + c->name + /snaps + \0
2976 ret
= snprintf(snappath
, MAXPATHLEN
, "%s/%s/snaps", c
->config_path
, c
->name
);
2977 if (ret
< 0 || ret
>= MAXPATHLEN
)
2982 static int lxcapi_snapshot(struct lxc_container
*c
, const char *commentfile
)
2985 struct lxc_container
*c2
;
2986 char snappath
[MAXPATHLEN
], newname
[20];
2988 if (!c
|| !lxcapi_is_defined(c
))
2991 if (!bdev_can_backup(c
->lxc_conf
)) {
2992 ERROR("%s's backing store cannot be backed up.", c
->name
);
2993 ERROR("Your container must use another backing store type.");
2997 if (!get_snappath_dir(c
, snappath
))
3000 i
= get_next_index(snappath
, c
->name
);
3002 if (mkdir_p(snappath
, 0755) < 0) {
3003 ERROR("Failed to create snapshot directory %s", snappath
);
3007 ret
= snprintf(newname
, 20, "snap%d", i
);
3008 if (ret
< 0 || ret
>= 20)
3012 * We pass LXC_CLONE_SNAPSHOT to make sure that a rdepends file entry is
3013 * created in the original container
3015 flags
= LXC_CLONE_SNAPSHOT
| LXC_CLONE_KEEPMACADDR
| LXC_CLONE_KEEPNAME
|
3016 LXC_CLONE_KEEPBDEVTYPE
| LXC_CLONE_MAYBE_SNAPSHOT
;
3017 if (bdev_is_dir(c
->lxc_conf
, c
->lxc_conf
->rootfs
.path
)) {
3018 ERROR("Snapshot of directory-backed container requested.");
3019 ERROR("Making a copy-clone. If you do want snapshots, then");
3020 ERROR("please create an aufs or overlayfs clone first, snapshot that");
3021 ERROR("and keep the original container pristine.");
3022 flags
&= ~LXC_CLONE_SNAPSHOT
| LXC_CLONE_MAYBE_SNAPSHOT
;
3024 c2
= c
->clone(c
, newname
, snappath
, flags
, NULL
, NULL
, 0, NULL
);
3026 ERROR("clone of %s:%s failed", c
->config_path
, c
->name
);
3030 lxc_container_put(c2
);
3032 // Now write down the creation time
3039 tm_info
= localtime(&timer
);
3041 strftime(buffer
, 25, "%Y:%m:%d %H:%M:%S", tm_info
);
3043 char *dfnam
= alloca(strlen(snappath
) + strlen(newname
) + 5);
3044 sprintf(dfnam
, "%s/%s/ts", snappath
, newname
);
3045 f
= fopen(dfnam
, "w");
3047 ERROR("Failed to open %s", dfnam
);
3050 if (fprintf(f
, "%s", buffer
) < 0) {
3051 SYSERROR("Writing timestamp");
3057 SYSERROR("Writing timestamp");
3062 // $p / $name / comment \0
3063 int len
= strlen(snappath
) + strlen(newname
) + 10;
3064 char *path
= alloca(len
);
3065 sprintf(path
, "%s/%s/comment", snappath
, newname
);
3066 return copy_file(commentfile
, path
) < 0 ? -1 : i
;
3072 static void lxcsnap_free(struct lxc_snapshot
*s
)
3076 if (s
->comment_pathname
)
3077 free(s
->comment_pathname
);
3084 static char *get_snapcomment_path(char* snappath
, char *name
)
3086 // $snappath/$name/comment
3087 int ret
, len
= strlen(snappath
) + strlen(name
) + 10;
3088 char *s
= malloc(len
);
3091 ret
= snprintf(s
, len
, "%s/%s/comment", snappath
, name
);
3092 if (ret
< 0 || ret
>= len
) {
3100 static char *get_timestamp(char* snappath
, char *name
)
3102 char path
[MAXPATHLEN
], *s
= NULL
;
3106 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/ts", snappath
, name
);
3107 if (ret
< 0 || ret
>= MAXPATHLEN
)
3109 fin
= fopen(path
, "r");
3112 (void) fseek(fin
, 0, SEEK_END
);
3114 (void) fseek(fin
, 0, SEEK_SET
);
3119 if (fread(s
, 1, len
, fin
) != len
) {
3120 SYSERROR("reading timestamp");
3130 static int lxcapi_snapshot_list(struct lxc_container
*c
, struct lxc_snapshot
**ret_snaps
)
3132 char snappath
[MAXPATHLEN
], path2
[MAXPATHLEN
];
3134 struct dirent dirent
, *direntp
;
3135 struct lxc_snapshot
*snaps
=NULL
, *nsnaps
;
3138 if (!c
|| !lxcapi_is_defined(c
))
3141 if (!get_snappath_dir(c
, snappath
)) {
3142 ERROR("path name too long");
3145 dir
= opendir(snappath
);
3147 INFO("failed to open %s - assuming no snapshots", snappath
);
3151 while (!readdir_r(dir
, &dirent
, &direntp
)) {
3155 if (!strcmp(direntp
->d_name
, "."))
3158 if (!strcmp(direntp
->d_name
, ".."))
3161 ret
= snprintf(path2
, MAXPATHLEN
, "%s/%s/config", snappath
, direntp
->d_name
);
3162 if (ret
< 0 || ret
>= MAXPATHLEN
) {
3163 ERROR("pathname too long");
3166 if (!file_exists(path2
))
3168 nsnaps
= realloc(snaps
, (count
+ 1)*sizeof(*snaps
));
3170 SYSERROR("Out of memory");
3174 snaps
[count
].free
= lxcsnap_free
;
3175 snaps
[count
].name
= strdup(direntp
->d_name
);
3176 if (!snaps
[count
].name
)
3178 snaps
[count
].lxcpath
= strdup(snappath
);
3179 if (!snaps
[count
].lxcpath
) {
3180 free(snaps
[count
].name
);
3183 snaps
[count
].comment_pathname
= get_snapcomment_path(snappath
, direntp
->d_name
);
3184 snaps
[count
].timestamp
= get_timestamp(snappath
, direntp
->d_name
);
3189 WARN("failed to close directory");
3197 for (i
=0; i
<count
; i
++)
3198 lxcsnap_free(&snaps
[i
]);
3202 WARN("failed to close directory");
3206 static bool lxcapi_snapshot_restore(struct lxc_container
*c
, const char *snapname
, const char *newname
)
3208 char clonelxcpath
[MAXPATHLEN
];
3210 struct lxc_container
*snap
, *rest
;
3214 if (!c
|| !c
->name
|| !c
->config_path
)
3217 if (has_fs_snapshots(c
)) {
3218 ERROR("container rootfs has dependent snapshots");
3222 bdev
= bdev_init(c
->lxc_conf
, c
->lxc_conf
->rootfs
.path
, c
->lxc_conf
->rootfs
.mount
, NULL
);
3224 ERROR("Failed to find original backing store type");
3231 if (!get_snappath_dir(c
, clonelxcpath
)) {
3235 // how should we lock this?
3237 snap
= lxc_container_new(snapname
, clonelxcpath
);
3238 if (!snap
|| !lxcapi_is_defined(snap
)) {
3239 ERROR("Could not open snapshot %s", snapname
);
3240 if (snap
) lxc_container_put(snap
);
3245 if (strcmp(c
->name
, newname
) == 0) {
3246 if (!container_destroy(c
)) {
3247 ERROR("Could not destroy existing container %s", newname
);
3248 lxc_container_put(snap
);
3254 if (strcmp(bdev
->type
, "dir") != 0 && strcmp(bdev
->type
, "loop") != 0)
3255 flags
= LXC_CLONE_SNAPSHOT
| LXC_CLONE_MAYBE_SNAPSHOT
;
3256 rest
= lxcapi_clone(snap
, newname
, c
->config_path
, flags
,
3257 bdev
->type
, NULL
, 0, NULL
);
3259 if (rest
&& lxcapi_is_defined(rest
))
3262 lxc_container_put(rest
);
3263 lxc_container_put(snap
);
3267 static bool do_snapshot_destroy(const char *snapname
, const char *clonelxcpath
)
3269 struct lxc_container
*snap
= NULL
;
3272 snap
= lxc_container_new(snapname
, clonelxcpath
);
3274 ERROR("Could not find snapshot %s", snapname
);
3278 if (!lxcapi_destroy(snap
)) {
3279 ERROR("Could not destroy snapshot %s", snapname
);
3286 lxc_container_put(snap
);
3290 static bool remove_all_snapshots(const char *path
)
3293 struct dirent dirent
, *direntp
;
3296 dir
= opendir(path
);
3298 SYSERROR("opendir on snapshot path %s", path
);
3301 while (!readdir_r(dir
, &dirent
, &direntp
)) {
3304 if (!strcmp(direntp
->d_name
, "."))
3306 if (!strcmp(direntp
->d_name
, ".."))
3308 if (!do_snapshot_destroy(direntp
->d_name
, path
)) {
3317 SYSERROR("Error removing directory %s", path
);
3322 static bool lxcapi_snapshot_destroy(struct lxc_container
*c
, const char *snapname
)
3324 char clonelxcpath
[MAXPATHLEN
];
3326 if (!c
|| !c
->name
|| !c
->config_path
|| !snapname
)
3329 if (!get_snappath_dir(c
, clonelxcpath
))
3332 return do_snapshot_destroy(snapname
, clonelxcpath
);
3335 static bool lxcapi_snapshot_destroy_all(struct lxc_container
*c
)
3337 char clonelxcpath
[MAXPATHLEN
];
3339 if (!c
|| !c
->name
|| !c
->config_path
)
3342 if (!get_snappath_dir(c
, clonelxcpath
))
3345 return remove_all_snapshots(clonelxcpath
);
3348 static bool lxcapi_may_control(struct lxc_container
*c
)
3350 return lxc_try_cmd(c
->name
, c
->config_path
) == 0;
3353 static bool do_add_remove_node(pid_t init_pid
, const char *path
, bool add
,
3356 char chrootpath
[MAXPATHLEN
];
3357 char *directory_path
= NULL
;
3361 if ((pid
= fork()) < 0) {
3362 SYSERROR("failed to fork a child helper");
3366 if (wait_for_pid(pid
) != 0) {
3367 ERROR("Failed to create note in guest");
3373 /* prepare the path */
3374 ret
= snprintf(chrootpath
, MAXPATHLEN
, "/proc/%d/root", init_pid
);
3375 if (ret
< 0 || ret
>= MAXPATHLEN
)
3378 if (chroot(chrootpath
) < 0)
3382 /* remove path if it exists */
3383 if(faccessat(AT_FDCWD
, path
, F_OK
, AT_SYMLINK_NOFOLLOW
) == 0) {
3384 if (unlink(path
) < 0) {
3385 ERROR("unlink failed");
3392 /* create any missing directories */
3393 directory_path
= dirname(strdup(path
));
3394 if (mkdir_p(directory_path
, 0755) < 0 && errno
!= EEXIST
) {
3395 ERROR("failed to create directory");
3399 /* create the device node */
3400 if (mknod(path
, st
->st_mode
, st
->st_rdev
) < 0) {
3401 ERROR("mknod failed");
3408 static bool add_remove_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
, bool add
)
3412 char value
[MAX_BUFFER
];
3415 /* make sure container is running */
3416 if (!c
->is_running(c
)) {
3417 ERROR("container is not running");
3421 /* use src_path if dest_path is NULL otherwise use dest_path */
3422 p
= dest_path
? dest_path
: src_path
;
3424 /* make sure we can access p */
3425 if(access(p
, F_OK
) < 0 || stat(p
, &st
) < 0)
3428 /* continue if path is character device or block device */
3429 if (S_ISCHR(st
.st_mode
))
3430 ret
= snprintf(value
, MAX_BUFFER
, "c %d:%d rwm", major(st
.st_rdev
), minor(st
.st_rdev
));
3431 else if (S_ISBLK(st
.st_mode
))
3432 ret
= snprintf(value
, MAX_BUFFER
, "b %d:%d rwm", major(st
.st_rdev
), minor(st
.st_rdev
));
3436 /* check snprintf return code */
3437 if (ret
< 0 || ret
>= MAX_BUFFER
)
3440 if (!do_add_remove_node(c
->init_pid(c
), p
, add
, &st
))
3443 /* add or remove device to/from cgroup access list */
3445 if (!c
->set_cgroup_item(c
, "devices.allow", value
)) {
3446 ERROR("set_cgroup_item failed while adding the device node");
3450 if (!c
->set_cgroup_item(c
, "devices.deny", value
)) {
3451 ERROR("set_cgroup_item failed while removing the device node");
3459 static bool lxcapi_add_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
)
3462 ERROR(NOT_SUPPORTED_ERROR
, __FUNCTION__
);
3465 return add_remove_device_node(c
, src_path
, dest_path
, true);
3468 static bool lxcapi_remove_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
)
3471 ERROR(NOT_SUPPORTED_ERROR
, __FUNCTION__
);
3474 return add_remove_device_node(c
, src_path
, dest_path
, false);
3477 static int lxcapi_attach_run_waitl(struct lxc_container
*c
, lxc_attach_options_t
*options
, const char *program
, const char *arg
, ...)
3487 argv
= lxc_va_arg_list_to_argv_const(ap
, 1);
3491 ERROR("Memory allocation error.");
3496 ret
= lxcapi_attach_run_wait(c
, options
, program
, (const char * const *)argv
);
3501 struct lxc_container
*lxc_container_new(const char *name
, const char *configpath
)
3503 struct lxc_container
*c
;
3508 c
= malloc(sizeof(*c
));
3510 fprintf(stderr
, "failed to malloc lxc_container\n");
3513 memset(c
, 0, sizeof(*c
));
3516 c
->config_path
= strdup(configpath
);
3518 c
->config_path
= strdup(lxc_global_config_value("lxc.lxcpath"));
3520 if (!c
->config_path
) {
3521 fprintf(stderr
, "Out of memory\n");
3525 remove_trailing_slashes(c
->config_path
);
3526 c
->name
= malloc(strlen(name
)+1);
3528 fprintf(stderr
, "Error allocating lxc_container name\n");
3531 strcpy(c
->name
, name
);
3534 if (!(c
->slock
= lxc_newlock(c
->config_path
, name
))) {
3535 fprintf(stderr
, "failed to create lock\n");
3539 if (!(c
->privlock
= lxc_newlock(NULL
, NULL
))) {
3540 fprintf(stderr
, "failed to alloc privlock\n");
3544 if (!set_config_filename(c
)) {
3545 fprintf(stderr
, "Error allocating config file pathname\n");
3549 if (file_exists(c
->configfile
) && !lxcapi_load_config(c
, NULL
))
3552 if (ongoing_create(c
) == 2) {
3553 ERROR("Error: %s creation was not completed", c
->name
);
3554 container_destroy(c
);
3555 lxcapi_clear_config(c
);
3557 c
->daemonize
= true;
3560 // assign the member functions
3561 c
->is_defined
= lxcapi_is_defined
;
3562 c
->state
= lxcapi_state
;
3563 c
->is_running
= lxcapi_is_running
;
3564 c
->freeze
= lxcapi_freeze
;
3565 c
->unfreeze
= lxcapi_unfreeze
;
3566 c
->console
= lxcapi_console
;
3567 c
->console_getfd
= lxcapi_console_getfd
;
3568 c
->init_pid
= lxcapi_init_pid
;
3569 c
->load_config
= lxcapi_load_config
;
3570 c
->want_daemonize
= lxcapi_want_daemonize
;
3571 c
->want_close_all_fds
= lxcapi_want_close_all_fds
;
3572 c
->start
= lxcapi_start
;
3573 c
->startl
= lxcapi_startl
;
3574 c
->stop
= lxcapi_stop
;
3575 c
->config_file_name
= lxcapi_config_file_name
;
3576 c
->wait
= lxcapi_wait
;
3577 c
->set_config_item
= lxcapi_set_config_item
;
3578 c
->destroy
= lxcapi_destroy
;
3579 c
->destroy_with_snapshots
= lxcapi_destroy_with_snapshots
;
3580 c
->rename
= lxcapi_rename
;
3581 c
->save_config
= lxcapi_save_config
;
3582 c
->get_keys
= lxcapi_get_keys
;
3583 c
->create
= lxcapi_create
;
3584 c
->createl
= lxcapi_createl
;
3585 c
->shutdown
= lxcapi_shutdown
;
3586 c
->reboot
= lxcapi_reboot
;
3587 c
->clear_config
= lxcapi_clear_config
;
3588 c
->clear_config_item
= lxcapi_clear_config_item
;
3589 c
->get_config_item
= lxcapi_get_config_item
;
3590 c
->get_running_config_item
= lxcapi_get_running_config_item
;
3591 c
->get_cgroup_item
= lxcapi_get_cgroup_item
;
3592 c
->set_cgroup_item
= lxcapi_set_cgroup_item
;
3593 c
->get_config_path
= lxcapi_get_config_path
;
3594 c
->set_config_path
= lxcapi_set_config_path
;
3595 c
->clone
= lxcapi_clone
;
3596 c
->get_interfaces
= lxcapi_get_interfaces
;
3597 c
->get_ips
= lxcapi_get_ips
;
3598 c
->attach
= lxcapi_attach
;
3599 c
->attach_run_wait
= lxcapi_attach_run_wait
;
3600 c
->attach_run_waitl
= lxcapi_attach_run_waitl
;
3601 c
->snapshot
= lxcapi_snapshot
;
3602 c
->snapshot_list
= lxcapi_snapshot_list
;
3603 c
->snapshot_restore
= lxcapi_snapshot_restore
;
3604 c
->snapshot_destroy
= lxcapi_snapshot_destroy
;
3605 c
->snapshot_destroy_all
= lxcapi_snapshot_destroy_all
;
3606 c
->may_control
= lxcapi_may_control
;
3607 c
->add_device_node
= lxcapi_add_device_node
;
3608 c
->remove_device_node
= lxcapi_remove_device_node
;
3610 /* we'll allow the caller to update these later */
3611 if (lxc_log_init(NULL
, "none", NULL
, "lxc_container", 0, c
->config_path
)) {
3612 fprintf(stderr
, "failed to open log\n");
3619 lxc_container_free(c
);
3623 int lxc_get_wait_states(const char **states
)
3628 for (i
=0; i
<MAX_STATE
; i
++)
3629 states
[i
] = lxc_state2str(i
);
3634 * These next two could probably be done smarter with reusing a common function
3635 * with different iterators and tests...
3637 int list_defined_containers(const char *lxcpath
, char ***names
, struct lxc_container
***cret
)
3640 int i
, cfound
= 0, nfound
= 0;
3641 struct dirent dirent
, *direntp
;
3642 struct lxc_container
*c
;
3645 lxcpath
= lxc_global_config_value("lxc.lxcpath");
3647 dir
= opendir(lxcpath
);
3649 SYSERROR("opendir on lxcpath");
3658 while (!readdir_r(dir
, &dirent
, &direntp
)) {
3661 if (!strcmp(direntp
->d_name
, "."))
3663 if (!strcmp(direntp
->d_name
, ".."))
3666 if (!config_file_exists(lxcpath
, direntp
->d_name
))
3670 if (!add_to_array(names
, direntp
->d_name
, cfound
))
3680 c
= lxc_container_new(direntp
->d_name
, lxcpath
);
3682 INFO("Container %s:%s has a config but could not be loaded",
3683 lxcpath
, direntp
->d_name
);
3685 if(!remove_from_array(names
, direntp
->d_name
, cfound
--))
3689 if (!lxcapi_is_defined(c
)) {
3690 INFO("Container %s:%s has a config but is not defined",
3691 lxcpath
, direntp
->d_name
);
3693 if(!remove_from_array(names
, direntp
->d_name
, cfound
--))
3695 lxc_container_put(c
);
3699 if (!add_to_clist(cret
, c
, nfound
, true)) {
3700 lxc_container_put(c
);
3710 if (names
&& *names
) {
3711 for (i
=0; i
<cfound
; i
++)
3715 if (cret
&& *cret
) {
3716 for (i
=0; i
<nfound
; i
++)
3717 lxc_container_put((*cret
)[i
]);
3724 int list_active_containers(const char *lxcpath
, char ***nret
,
3725 struct lxc_container
***cret
)
3727 int i
, ret
= -1, cret_cnt
= 0, ct_name_cnt
= 0;
3730 char **ct_name
= NULL
;
3732 struct lxc_container
*c
;
3735 lxcpath
= lxc_global_config_value("lxc.lxcpath");
3736 lxcpath_len
= strlen(lxcpath
);
3743 FILE *f
= fopen("/proc/net/unix", "r");
3747 while (getline(&line
, &len
, f
) != -1) {
3748 char *p
= strrchr(line
, ' '), *p2
;
3755 if (strncmp(p
, lxcpath
, lxcpath_len
) != 0)
3761 // Now p is the start of lxc_name
3763 if (!p2
|| strncmp(p2
, "/command", 8) != 0)
3767 if (array_contains(&ct_name
, p
, ct_name_cnt
))
3770 if (!add_to_array(&ct_name
, p
, ct_name_cnt
))
3771 goto free_cret_list
;
3778 c
= lxc_container_new(p
, lxcpath
);
3780 INFO("Container %s:%s is running but could not be loaded",
3782 remove_from_array(&ct_name
, p
, ct_name_cnt
--);
3787 * If this is an anonymous container, then is_defined *can*
3788 * return false. So we don't do that check. Count on the
3789 * fact that the command socket exists.
3792 if (!add_to_clist(cret
, c
, cret_cnt
, true)) {
3793 lxc_container_put(c
);
3794 goto free_cret_list
;
3799 assert(!nret
|| !cret
|| cret_cnt
== ct_name_cnt
);
3808 if (cret
&& *cret
) {
3809 for (i
= 0; i
< cret_cnt
; i
++)
3810 lxc_container_put((*cret
)[i
]);
3816 for (i
= 0; i
< ct_name_cnt
; i
++)
3829 int list_all_containers(const char *lxcpath
, char ***nret
,
3830 struct lxc_container
***cret
)
3832 int i
, ret
, active_cnt
, ct_cnt
, ct_list_cnt
;
3835 struct lxc_container
**ct_list
= NULL
;
3837 ct_cnt
= list_defined_containers(lxcpath
, &ct_name
, NULL
);
3841 active_cnt
= list_active_containers(lxcpath
, &active_name
, NULL
);
3842 if (active_cnt
< 0) {
3847 for (i
= 0; i
< active_cnt
; i
++) {
3848 if (!array_contains(&ct_name
, active_name
[i
], ct_cnt
)) {
3849 if (!add_to_array(&ct_name
, active_name
[i
], ct_cnt
)) {
3851 goto free_active_name
;
3855 free(active_name
[i
]);
3856 active_name
[i
] = NULL
;
3862 for (i
= 0, ct_list_cnt
= 0; i
< ct_cnt
&& cret
; i
++) {
3863 struct lxc_container
*c
;
3865 c
= lxc_container_new(ct_name
[i
], lxcpath
);
3867 WARN("Container %s:%s could not be loaded", lxcpath
, ct_name
[i
]);
3868 remove_from_array(&ct_name
, ct_name
[i
], ct_cnt
--);
3872 if (!add_to_clist(&ct_list
, c
, ct_list_cnt
, false)) {
3873 lxc_container_put(c
);
3892 for (i
= 0; i
< ct_list_cnt
; i
++) {
3893 lxc_container_put(ct_list
[i
]);
3899 for (i
= 0; i
< active_cnt
; i
++) {
3901 free(active_name
[i
]);
3907 for (i
= 0; i
< ct_cnt
; i
++) {