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>
36 #include <lxc/lxccontainer.h>
47 #include <lxc/utils.h>
48 #include <lxc/monitor.h>
49 #include <lxc/namespace.h>
51 #include <arpa/inet.h>
58 #include <../include/ifaddrs.h>
63 #include <../include/getline.h>
67 #define MAX_BUFFER 4096
69 lxc_log_define(lxc_container
, lxc
);
71 static bool file_exists(const char *f
)
75 return stat(f
, &statbuf
) == 0;
78 static bool config_file_exists(const char *lxcpath
, const char *cname
)
80 /* $lxcpath + '/' + $cname + '/config' + \0 */
81 int ret
, len
= strlen(lxcpath
) + strlen(cname
) + 9;
82 char *fname
= alloca(len
);
84 ret
= snprintf(fname
, len
, "%s/%s/config", lxcpath
, cname
);
85 if (ret
< 0 || ret
>= len
)
88 return file_exists(fname
);
92 * A few functions to help detect when a container creation failed.
93 * If a container creation was killed partway through, then trying
94 * to actually start that container could harm the host. We detect
95 * this by creating a 'partial' file under the container directory,
96 * and keeping an advisory lock. When container creation completes,
97 * we remove that file. When we load or try to start a container, if
98 * we find that file, without a flock, we remove the container.
100 int ongoing_create(struct lxc_container
*c
)
102 int len
= strlen(c
->config_path
) + strlen(c
->name
) + 10;
103 char *path
= alloca(len
);
107 ret
= snprintf(path
, len
, "%s/%s/partial", c
->config_path
, c
->name
);
108 if (ret
< 0 || ret
>= len
) {
109 ERROR("Error writing partial pathname");
113 if (!file_exists(path
))
116 fd
= open(path
, O_RDWR
);
119 // give benefit of the doubt
120 SYSERROR("Error opening partial file");
124 lk
.l_whence
= SEEK_SET
;
128 if (fcntl(fd
, F_GETLK
, &lk
) == 0 && lk
.l_pid
!= -1) {
129 // create is still ongoing
135 // create completed but partial is still there.
142 int create_partial(struct lxc_container
*c
)
144 // $lxcpath + '/' + $name + '/partial' + \0
145 int len
= strlen(c
->config_path
) + strlen(c
->name
) + 10;
146 char *path
= alloca(len
);
150 ret
= snprintf(path
, len
, "%s/%s/partial", c
->config_path
, c
->name
);
151 if (ret
< 0 || ret
>= len
) {
152 ERROR("Error writing partial pathname");
156 if ((fd
=open(path
, O_RDWR
| O_CREAT
| O_EXCL
, 0755)) < 0) {
157 SYSERROR("Erorr creating partial file");
162 lk
.l_whence
= SEEK_SET
;
165 if (fcntl(fd
, F_SETLKW
, &lk
) < 0) {
166 SYSERROR("Error locking partial file %s", path
);
176 void remove_partial(struct lxc_container
*c
, int fd
)
178 // $lxcpath + '/' + $name + '/partial' + \0
179 int len
= strlen(c
->config_path
) + strlen(c
->name
) + 10;
180 char *path
= alloca(len
);
186 ret
= snprintf(path
, len
, "%s/%s/partial", c
->config_path
, c
->name
);
187 if (ret
< 0 || ret
>= len
) {
188 ERROR("Error writing partial pathname");
191 if (unlink(path
) < 0)
192 SYSERROR("Error unlink partial file %s", path
);
196 * 1. container_mem_lock(c) protects the struct lxc_container from multiple threads.
197 * 2. container_disk_lock(c) protects the on-disk container data - in particular the
198 * container configuration file.
199 * The container_disk_lock also takes the container_mem_lock.
200 * 3. thread_mutex protects process data (ex: fd table) from multiple threads.
201 * NOTHING mutexes two independent programs with their own struct
202 * lxc_container for the same c->name, between API calls. For instance,
203 * c->config_read(); c->start(); Between those calls, data on disk
204 * could change (which shouldn't bother the caller unless for instance
205 * the rootfs get moved). c->config_read(); update; c->config_write();
206 * Two such updaters could race. The callers should therefore check their
207 * results. Trying to prevent that would necessarily expose us to deadlocks
208 * due to hung callers. So I prefer to keep the locks only within our own
209 * functions, not across functions.
211 * If you're going to clone while holding a lxccontainer, increment
212 * c->numthreads (under privlock) before forking. When deleting,
213 * decrement numthreads under privlock, then if it hits 0 you can delete.
214 * Do not ever use a lxccontainer whose numthreads you did not bump.
217 static void lxc_container_free(struct lxc_container
*c
)
224 c
->configfile
= NULL
;
226 if (c
->error_string
) {
227 free(c
->error_string
);
228 c
->error_string
= NULL
;
231 lxc_putlock(c
->slock
);
235 lxc_putlock(c
->privlock
);
243 lxc_conf_free(c
->lxc_conf
);
246 if (c
->config_path
) {
247 free(c
->config_path
);
248 c
->config_path
= NULL
;
254 * Consider the following case:
255 freer | racing get()er
256 ==================================================================
257 lxc_container_put() | lxc_container_get()
258 \ lxclock(c->privlock) | c->numthreads < 1? (no)
259 \ c->numthreads = 0 | \ lxclock(c->privlock) -> waits
261 \ lxc_container_free() | \ lxclock() returns
262 | \ c->numthreads < 1 -> return 0
264 \ \ sem_destroy(privlock) |
266 * When the get()er checks numthreads the first time, one of the following
268 * 1. freer has set numthreads = 0. get() returns 0
269 * 2. freer is between lxclock and setting numthreads to 0. get()er will
270 * sem_wait on privlock, get lxclock after freer() drops it, then see
271 * numthreads is 0 and exit without touching lxclock again..
272 * 3. freer has not yet locked privlock. If get()er runs first, then put()er
273 * will see --numthreads = 1 and not call lxc_container_free().
276 int lxc_container_get(struct lxc_container
*c
)
281 // if someone else has already started freeing the container, don't
282 // try to take the lock, which may be invalid
283 if (c
->numthreads
< 1)
286 if (container_mem_lock(c
))
288 if (c
->numthreads
< 1) {
289 // bail without trying to unlock, bc the privlock is now probably
294 container_mem_unlock(c
);
298 int lxc_container_put(struct lxc_container
*c
)
302 if (container_mem_lock(c
))
304 if (--c
->numthreads
< 1) {
305 container_mem_unlock(c
);
306 lxc_container_free(c
);
309 container_mem_unlock(c
);
313 static bool lxcapi_is_defined(struct lxc_container
*c
)
322 if (container_mem_lock(c
))
326 statret
= stat(c
->configfile
, &statbuf
);
332 container_mem_unlock(c
);
336 static const char *lxcapi_state(struct lxc_container
*c
)
342 s
= lxc_getstate(c
->name
, c
->config_path
);
343 return lxc_state2str(s
);
346 static bool is_stopped(struct lxc_container
*c
)
349 s
= lxc_getstate(c
->name
, c
->config_path
);
350 return (s
== STOPPED
);
353 static bool lxcapi_is_running(struct lxc_container
*c
)
360 if (!s
|| strcmp(s
, "STOPPED") == 0)
365 static bool lxcapi_freeze(struct lxc_container
*c
)
371 ret
= lxc_freeze(c
->name
, c
->config_path
);
377 static bool lxcapi_unfreeze(struct lxc_container
*c
)
383 ret
= lxc_unfreeze(c
->name
, c
->config_path
);
389 static int lxcapi_console_getfd(struct lxc_container
*c
, int *ttynum
, int *masterfd
)
395 ttyfd
= lxc_console_getfd(c
, ttynum
, masterfd
);
399 static int lxcapi_console(struct lxc_container
*c
, int ttynum
, int stdinfd
,
400 int stdoutfd
, int stderrfd
, int escape
)
402 return lxc_console(c
, ttynum
, stdinfd
, stdoutfd
, stderrfd
, escape
);
405 static pid_t
lxcapi_init_pid(struct lxc_container
*c
)
410 return lxc_cmd_get_init_pid(c
->name
, c
->config_path
);
413 static bool load_config_locked(struct lxc_container
*c
, const char *fname
)
416 c
->lxc_conf
= lxc_conf_init();
417 if (c
->lxc_conf
&& !lxc_config_read(fname
, c
->lxc_conf
))
422 static bool lxcapi_load_config(struct lxc_container
*c
, const char *alt_file
)
424 bool ret
= false, need_disklock
= false;
430 fname
= c
->configfile
;
436 * If we're reading something other than the container's config,
437 * we only need to lock the in-memory container. If loading the
438 * container's config file, take the disk lock.
440 if (strcmp(fname
, c
->configfile
) == 0)
441 need_disklock
= true;
444 lret
= container_disk_lock(c
);
446 lret
= container_mem_lock(c
);
450 ret
= load_config_locked(c
, fname
);
453 container_disk_unlock(c
);
455 container_mem_unlock(c
);
459 static bool lxcapi_want_daemonize(struct lxc_container
*c
, bool state
)
461 if (!c
|| !c
->lxc_conf
)
463 if (container_mem_lock(c
)) {
464 ERROR("Error getting mem lock");
467 c
->daemonize
= state
;
468 /* daemonize implies close_all_fds so set it */
470 c
->lxc_conf
->close_all_fds
= 1;
471 container_mem_unlock(c
);
475 static bool lxcapi_want_close_all_fds(struct lxc_container
*c
, bool state
)
477 if (!c
|| !c
->lxc_conf
)
479 if (container_mem_lock(c
)) {
480 ERROR("Error getting mem lock");
483 c
->lxc_conf
->close_all_fds
= state
;
484 container_mem_unlock(c
);
488 static bool lxcapi_wait(struct lxc_container
*c
, const char *state
, int timeout
)
495 ret
= lxc_wait(c
->name
, state
, timeout
, c
->config_path
);
500 static bool wait_on_daemonized_start(struct lxc_container
*c
, int pid
)
502 /* we'll probably want to make this timeout configurable? */
503 int timeout
= 5, ret
, status
;
506 * our child is going to fork again, then exit. reap the
509 ret
= waitpid(pid
, &status
, 0);
510 if (ret
== -1 || !WIFEXITED(status
) || WEXITSTATUS(status
) != 0)
511 DEBUG("failed waiting for first dual-fork child");
512 return lxcapi_wait(c
, "RUNNING", timeout
);
515 static bool am_single_threaded(void)
517 struct dirent dirent
, *direntp
;
522 dir
= opendir("/proc/self/task");
525 INFO("failed to open /proc/self/task");
529 while (!readdir_r(dir
, &dirent
, &direntp
)) {
533 if (!strcmp(direntp
->d_name
, "."))
536 if (!strcmp(direntp
->d_name
, ".."))
548 * I can't decide if it'd be more convenient for callers if we accept '...',
549 * or a null-terminated array (i.e. execl vs execv)
551 static bool lxcapi_start(struct lxc_container
*c
, int useinit
, char * const argv
[])
554 struct lxc_conf
*conf
;
555 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 if (!lxc_container_get(c
))
608 lxc_monitord_spawn(c
->config_path
);
612 lxc_container_put(c
);
616 return wait_on_daemonized_start(c
, pid
);
618 process_unlock(); // we're no longer sharing
619 /* second fork to be reparented by init */
622 SYSERROR("Error doing dual-fork");
627 /* like daemon(), chdir to / and redirect 0,1,2 to /dev/null */
629 SYSERROR("Error chdir()ing to /.");
635 open("/dev/zero", O_RDONLY
);
636 open("/dev/null", O_RDWR
);
637 open("/dev/null", O_RDWR
);
640 if (!am_single_threaded()) {
641 ERROR("Cannot start non-daemonized container when threaded");
648 ret
= lxc_start(c
->name
, argv
, conf
, c
->config_path
);
651 INFO("container requested reboot");
657 lxc_container_put(c
);
658 exit (ret
== 0 ? true : false);
660 return (ret
== 0 ? true : false);
665 * note there MUST be an ending NULL
667 static bool lxcapi_startl(struct lxc_container
*c
, int useinit
, ...)
670 char **inargs
= NULL
;
673 /* container exists */
677 va_start(ap
, useinit
);
678 inargs
= lxc_va_arg_list_to_argv(ap
, 0, 1);
682 ERROR("Memory allocation error.");
686 /* pass NULL if no arguments were supplied */
687 bret
= lxcapi_start(c
, useinit
, *inargs
? inargs
: NULL
);
692 for (arg
= inargs
; *arg
; arg
++)
700 static bool lxcapi_stop(struct lxc_container
*c
)
707 ret
= lxc_cmd_stop(c
->name
, c
->config_path
);
713 * create the standard expected container dir
715 static bool create_container_dir(struct lxc_container
*c
)
720 len
= strlen(c
->config_path
) + strlen(c
->name
) + 2;
724 ret
= snprintf(s
, len
, "%s/%s", c
->config_path
, c
->name
);
725 if (ret
< 0 || ret
>= len
) {
729 ret
= mkdir(s
, 0755);
734 SYSERROR("failed to create container path for %s\n", c
->name
);
740 static const char *lxcapi_get_config_path(struct lxc_container
*c
);
741 static bool lxcapi_set_config_item(struct lxc_container
*c
, const char *key
, const char *v
);
744 * do_bdev_create: thin wrapper around bdev_create(). Like bdev_create(),
745 * it returns a mounted bdev on success, NULL on error.
747 static struct bdev
*do_bdev_create(struct lxc_container
*c
, const char *type
,
748 struct bdev_specs
*specs
)
755 /* rootfs.path or lxcpath/lxcname/rootfs */
756 if (c
->lxc_conf
->rootfs
.path
&& access(c
->lxc_conf
->rootfs
.path
, F_OK
) == 0) {
757 const char *rpath
= c
->lxc_conf
->rootfs
.path
;
758 len
= strlen(rpath
) + 1;
760 ret
= snprintf(dest
, len
, "%s", rpath
);
762 const char *lxcpath
= lxcapi_get_config_path(c
);
763 len
= strlen(c
->name
) + strlen(lxcpath
) + 9;
765 ret
= snprintf(dest
, len
, "%s/%s/rootfs", lxcpath
, c
->name
);
767 if (ret
< 0 || ret
>= len
)
770 bdev
= bdev_create(dest
, type
, c
->name
, specs
);
772 ERROR("Failed to create backing store type %s\n", type
);
776 lxcapi_set_config_item(c
, "lxc.rootfs", bdev
->src
);
778 /* if we are not root, chown the rootfs dir to root in the
781 if (geteuid() != 0) {
782 if (chown_mapped_root(bdev
->dest
, c
->lxc_conf
) < 0) {
783 ERROR("Error chowning %s to container root\n", bdev
->dest
);
793 * Given the '-t' template option to lxc-create, figure out what to
794 * do. If the template is a full executable path, use that. If it
795 * is something like 'sshd', then return $templatepath/lxc-sshd.
796 * On success return the template, on error return NULL.
798 static char *get_template_path(const char *t
)
803 if (t
[0] == '/' && access(t
, X_OK
) == 0) {
808 len
= strlen(LXCTEMPLATEDIR
) + strlen(t
) + strlen("/lxc-") + 1;
812 ret
= snprintf(tpath
, len
, "%s/lxc-%s", LXCTEMPLATEDIR
, t
);
813 if (ret
< 0 || ret
>= len
) {
817 if (access(tpath
, X_OK
) < 0) {
818 SYSERROR("bad template: %s\n", t
);
826 static char *lxcbasename(char *path
)
828 char *p
= path
+ strlen(path
) - 1;
829 while (*p
!= '/' && p
> path
)
834 static bool create_run_template(struct lxc_container
*c
, char *tpath
, bool quiet
,
844 SYSERROR("failed to fork task for container creation template\n");
848 if (pid
== 0) { // child
849 char *patharg
, *namearg
, *rootfsarg
, *src
;
850 struct bdev
*bdev
= NULL
;
852 int ret
, len
, nargs
= 0;
854 struct lxc_conf
*conf
= c
->lxc_conf
;
856 process_unlock(); // we're no longer sharing
861 open("/dev/zero", O_RDONLY
);
862 open("/dev/null", O_RDWR
);
863 open("/dev/null", O_RDWR
);
866 src
= c
->lxc_conf
->rootfs
.path
;
868 * for an overlayfs create, what the user wants is the template to fill
869 * in what will become the readonly lower layer. So don't mount for
872 if (strncmp(src
, "overlayfs:", 10) == 0) {
873 src
= overlayfs_getlower(src
+10);
875 bdev
= bdev_init(src
, c
->lxc_conf
->rootfs
.mount
, NULL
);
877 ERROR("Error opening rootfs");
881 if (geteuid() == 0) {
882 if (unshare(CLONE_NEWNS
) < 0) {
883 ERROR("error unsharing mounts");
886 if (detect_shared_rootfs()) {
887 if (mount("", "", NULL
, MS_SLAVE
|MS_REC
, 0)) {
888 SYSERROR("Failed to make / rslave to run template");
889 ERROR("Continuing...");
893 if (strcmp(bdev
->type
, "dir") != 0) {
894 if (geteuid() != 0) {
895 ERROR("non-root users can only create directory-backed containers");
898 if (bdev
->ops
->mount(bdev
) < 0) {
899 ERROR("Error mounting rootfs");
902 } else { // TODO come up with a better way here!
905 bdev
->dest
= strdup(bdev
->src
);
909 * create our new array, pre-pend the template name and
913 for (nargs
= 0; argv
[nargs
]; nargs
++) ;
914 nargs
+= 4; // template, path, rootfs and name args
916 newargv
= malloc(nargs
* sizeof(*newargv
));
919 newargv
[0] = lxcbasename(tpath
);
921 len
= strlen(c
->config_path
) + strlen(c
->name
) + strlen("--path=") + 2;
922 patharg
= malloc(len
);
925 ret
= snprintf(patharg
, len
, "--path=%s/%s", c
->config_path
, c
->name
);
926 if (ret
< 0 || ret
>= len
)
928 newargv
[1] = patharg
;
929 len
= strlen("--name=") + strlen(c
->name
) + 1;
930 namearg
= malloc(len
);
933 ret
= snprintf(namearg
, len
, "--name=%s", c
->name
);
934 if (ret
< 0 || ret
>= len
)
936 newargv
[2] = namearg
;
938 len
= strlen("--rootfs=") + 1 + strlen(bdev
->dest
);
939 rootfsarg
= malloc(len
);
942 ret
= snprintf(rootfsarg
, len
, "--rootfs=%s", bdev
->dest
);
943 if (ret
< 0 || ret
>= len
)
945 newargv
[3] = rootfsarg
;
947 /* add passed-in args */
949 for (i
= 4; i
< nargs
; i
++)
950 newargv
[i
] = argv
[i
-4];
952 /* add trailing NULL */
954 newargv
= realloc(newargv
, nargs
* sizeof(*newargv
));
957 newargv
[nargs
- 1] = NULL
;
960 * If we're running the template in a mapped userns, then
961 * we prepend the template command with:
962 * lxc-usernsexec <-m map1> ... <-m mapn> --
963 * and we append "--mapped-uid x", where x is the mapped uid
966 if (geteuid() != 0 && !lxc_list_empty(&conf
->id_map
)) {
969 char **n2
= malloc(n2args
* sizeof(*n2
));
974 SYSERROR("out of memory");
978 tpath
= "lxc-usernsexec";
979 n2
[0] = "lxc-usernsexec";
980 lxc_list_for_each(it
, &conf
->id_map
) {
983 n2
= realloc(n2
, n2args
* sizeof(char *));
987 n2
[n2args
-1] = malloc(200);
990 ret
= snprintf(n2
[n2args
-1], 200, "%c:%lu:%lu:%lu",
991 map
->idtype
== ID_TYPE_UID
? 'u' : 'g',
992 map
->nsid
, map
->hostid
, map
->range
);
993 if (ret
< 0 || ret
>= 200)
996 int hostid_mapped
= mapped_hostid(geteuid(), conf
);
997 int extraargs
= hostid_mapped
>= 0 ? 1 : 3;
998 n2
= realloc(n2
, (nargs
+ n2args
+ extraargs
) * sizeof(char *));
1001 if (hostid_mapped
< 0) {
1002 hostid_mapped
= find_unmapped_nsuid(conf
);
1003 n2
[n2args
++] = "-m";
1004 if (hostid_mapped
< 0) {
1005 ERROR("Could not find free uid to map");
1008 n2
[n2args
++] = malloc(200);
1009 if (!n2
[n2args
-1]) {
1010 SYSERROR("out of memory");
1013 ret
= snprintf(n2
[n2args
-1], 200, "u:%d:%d:1",
1014 hostid_mapped
, geteuid());
1015 if (ret
< 0 || ret
>= 200) {
1016 ERROR("string too long");
1020 n2
[n2args
++] = "--";
1021 for (i
= 0; i
< nargs
; i
++)
1022 n2
[i
+ n2args
] = newargv
[i
];
1024 // Finally add "--mapped-uid $uid" to tell template what to chown
1027 n2
= realloc(n2
, n2args
* sizeof(char *));
1029 SYSERROR("out of memory");
1032 // note n2[n2args-1] is NULL
1033 n2
[n2args
-3] = "--mapped-uid";
1034 snprintf(txtuid
, 20, "%d", hostid_mapped
);
1035 n2
[n2args
-2] = txtuid
;
1036 n2
[n2args
-1] = NULL
;
1041 execvp(tpath
, newargv
);
1042 SYSERROR("failed to execute template %s", tpath
);
1046 if (wait_for_pid(pid
) != 0) {
1047 ERROR("container creation template for %s failed\n", c
->name
);
1054 bool prepend_lxc_header(char *path
, const char *t
, char *const argv
[])
1062 unsigned char md_value
[SHA_DIGEST_LENGTH
];
1067 f
= fopen(path
, "r");
1072 if (fseek(f
, 0, SEEK_END
) < 0)
1074 if ((flen
= ftell(f
)) < 0)
1076 if (fseek(f
, 0, SEEK_SET
) < 0)
1078 if ((contents
= malloc(flen
+ 1)) == NULL
)
1080 if (fread(contents
, 1, flen
, f
) != flen
)
1081 goto out_free_contents
;
1083 contents
[flen
] = '\0';
1089 goto out_free_contents
;
1092 tpath
= get_template_path(t
);
1094 ERROR("bad template: %s\n", t
);
1095 goto out_free_contents
;
1098 ret
= sha1sum_file(tpath
, md_value
);
1100 ERROR("Error getting sha1sum of %s", tpath
);
1102 goto out_free_contents
;
1108 f
= fopen(path
, "w");
1111 SYSERROR("reopening config for writing");
1115 fprintf(f
, "# Template used to create this container: %s\n", t
);
1117 fprintf(f
, "# Parameters passed to the template:");
1119 fprintf(f
, " %s", *argv
);
1125 fprintf(f
, "# Template script checksum (SHA-1): ");
1126 for (i
=0; i
<SHA_DIGEST_LENGTH
; i
++)
1127 fprintf(f
, "%02x", md_value
[i
]);
1130 fprintf(f
, "# For additional config options, please look at lxc.conf(5)\n");
1131 if (fwrite(contents
, 1, flen
, f
) != flen
) {
1132 SYSERROR("Writing original contents");
1152 SYSERROR("Error prepending header");
1158 static void lxcapi_clear_config(struct lxc_container
*c
)
1160 if (c
&& c
->lxc_conf
) {
1161 lxc_conf_free(c
->lxc_conf
);
1166 static bool lxcapi_destroy(struct lxc_container
*c
);
1169 * create a container with the given parameters.
1170 * @c: container to be created. It has the lxcpath, name, and a starting
1171 * configuration already set
1172 * @t: the template to execute to instantiate the root filesystem and
1173 * adjust the configuration.
1174 * @bdevtype: backing store type to use. If NULL, dir will be used.
1175 * @specs: additional parameters for the backing store, i.e. LVM vg to
1178 * @argv: the arguments to pass to the template, terminated by NULL. If no
1179 * arguments, you can just pass NULL.
1181 static bool lxcapi_create(struct lxc_container
*c
, const char *t
,
1182 const char *bdevtype
, struct bdev_specs
*specs
, int flags
,
1194 tpath
= get_template_path(t
);
1196 ERROR("bad template: %s\n", t
);
1202 * If a template is passed in, and the rootfs already is defined in
1203 * the container config and exists, then * caller is trying to create
1204 * an existing container. Return an error, but do NOT delete the
1207 if (lxcapi_is_defined(c
) && c
->lxc_conf
&& c
->lxc_conf
->rootfs
.path
&&
1208 access(c
->lxc_conf
->rootfs
.path
, F_OK
) == 0 && tpath
) {
1209 ERROR("Container %s:%s already exists", c
->config_path
, c
->name
);
1214 if (!c
->load_config(c
, LXC_DEFAULT_CONFIG
)) {
1215 ERROR("Error loading default configuration file %s\n", LXC_DEFAULT_CONFIG
);
1220 if (!create_container_dir(c
))
1224 * either template or rootfs.path should be set.
1225 * if both template and rootfs.path are set, template is setup as rootfs.path.
1226 * container is already created if we have a config and rootfs.path is accessible
1228 if (!c
->lxc_conf
->rootfs
.path
&& !tpath
)
1229 /* no template passed in and rootfs does not exist: error */
1231 if (c
->lxc_conf
->rootfs
.path
&& access(c
->lxc_conf
->rootfs
.path
, F_OK
) != 0)
1232 /* rootfs passed into configuration, but does not exist: error */
1234 if (lxcapi_is_defined(c
) && c
->lxc_conf
->rootfs
.path
&& !tpath
) {
1235 /* Rootfs already existed, user just wanted to save the
1236 * loaded configuration */
1241 /* Mark that this container is being created */
1242 if ((partial_fd
= create_partial(c
)) < 0)
1245 /* no need to get disk lock bc we have the partial locked */
1248 * Create the backing store
1249 * Note we can't do this in the same task as we use to execute the
1250 * template because of the way zfs works.
1251 * After you 'zfs create', zfs mounts the fs only in the initial
1256 SYSERROR("failed to fork task for container creation template\n");
1260 if (pid
== 0) { // child
1261 struct bdev
*bdev
= NULL
;
1263 process_unlock(); // we're no longer sharing
1264 if (!(bdev
= do_bdev_create(c
, bdevtype
, specs
))) {
1265 ERROR("Error creating backing store type %s for %s",
1266 bdevtype
? bdevtype
: "(none)", c
->name
);
1270 /* save config file again to store the new rootfs location */
1271 if (!c
->save_config(c
, NULL
)) {
1272 ERROR("failed to save starting configuration for %s\n", c
->name
);
1273 // parent task won't see bdev in config so we delete it
1274 bdev
->ops
->umount(bdev
);
1275 bdev
->ops
->destroy(bdev
);
1280 if (wait_for_pid(pid
) != 0)
1283 /* reload config to get the rootfs */
1284 lxc_conf_free(c
->lxc_conf
);
1286 if (!load_config_locked(c
, c
->configfile
))
1289 if (!create_run_template(c
, tpath
, !!(flags
& LXC_CREATE_QUIET
), argv
))
1292 // now clear out the lxc_conf we have, reload from the created
1294 lxcapi_clear_config(c
);
1297 if (!prepend_lxc_header(c
->configfile
, tpath
, argv
)) {
1298 ERROR("Error prepending header to configuration file");
1302 ret
= load_config_locked(c
, c
->configfile
);
1305 if (partial_fd
>= 0)
1306 remove_partial(c
, partial_fd
);
1316 static bool lxcapi_reboot(struct lxc_container
*c
)
1322 if (!c
->is_running(c
))
1324 pid
= c
->init_pid(c
);
1327 if (kill(pid
, SIGINT
) < 0)
1333 static bool lxcapi_shutdown(struct lxc_container
*c
, int timeout
)
1343 if (!c
->is_running(c
))
1345 pid
= c
->init_pid(c
);
1349 retv
= c
->wait(c
, "STOPPED", timeout
);
1350 if (!retv
&& timeout
> 0) {
1352 retv
= c
->wait(c
, "STOPPED", 0); // 0 means don't wait
1357 static bool lxcapi_createl(struct lxc_container
*c
, const char *t
,
1358 const char *bdevtype
, struct bdev_specs
*specs
, int flags
, ...)
1368 * since we're going to wait for create to finish, I don't think we
1369 * need to get a copy of the arguments.
1371 va_start(ap
, flags
);
1372 args
= lxc_va_arg_list_to_argv(ap
, 0, 0);
1375 ERROR("Memory allocation error.");
1379 bret
= c
->create(c
, t
, bdevtype
, specs
, flags
, args
);
1386 static bool lxcapi_clear_config_item(struct lxc_container
*c
, const char *key
)
1390 if (!c
|| !c
->lxc_conf
)
1392 if (container_mem_lock(c
))
1394 ret
= lxc_clear_config_item(c
->lxc_conf
, key
);
1395 container_mem_unlock(c
);
1399 static inline void exit_from_ns(struct lxc_container
*c
, int *old_netns
, int *new_netns
) {
1400 /* Switch back to original netns */
1401 if (*old_netns
>= 0 && setns(*old_netns
, CLONE_NEWNET
))
1402 SYSERROR("failed to setns");
1404 if (*new_netns
>= 0)
1406 if (*old_netns
>= 0)
1411 static inline bool enter_to_ns(struct lxc_container
*c
, int *old_netns
, int *new_netns
) {
1413 char new_netns_path
[MAXPATHLEN
];
1415 if (!c
->is_running(c
))
1418 /* Save reference to old netns */
1420 *old_netns
= open("/proc/self/ns/net", O_RDONLY
);
1422 if (*old_netns
< 0) {
1423 SYSERROR("failed to open /proc/self/ns/net");
1427 /* Switch to new netns */
1428 ret
= snprintf(new_netns_path
, MAXPATHLEN
, "/proc/%d/ns/net", c
->init_pid(c
));
1429 if (ret
< 0 || ret
>= MAXPATHLEN
)
1433 *new_netns
= open(new_netns_path
, O_RDONLY
);
1435 if (*new_netns
< 0) {
1436 SYSERROR("failed to open %s", new_netns_path
);
1440 if (setns(*new_netns
, CLONE_NEWNET
)) {
1441 SYSERROR("failed to setns");
1446 exit_from_ns(c
, old_netns
, new_netns
);
1450 // used by qsort and bsearch functions for comparing names
1451 static inline int string_cmp(char **first
, char **second
)
1453 return strcmp(*first
, *second
);
1456 // used by qsort and bsearch functions for comparing container names
1457 static inline int container_cmp(struct lxc_container
**first
, struct lxc_container
**second
)
1459 return strcmp((*first
)->name
, (*second
)->name
);
1462 static bool add_to_array(char ***names
, char *cname
, int pos
)
1464 char **newnames
= realloc(*names
, (pos
+1) * sizeof(char *));
1466 ERROR("Out of memory");
1471 newnames
[pos
] = strdup(cname
);
1475 // sort the arrray as we will use binary search on it
1476 qsort(newnames
, pos
+ 1, sizeof(char *), (int (*)(const void *,const void *))string_cmp
);
1481 static bool add_to_clist(struct lxc_container
***list
, struct lxc_container
*c
, int pos
, bool sort
)
1483 struct lxc_container
**newlist
= realloc(*list
, (pos
+1) * sizeof(struct lxc_container
*));
1485 ERROR("Out of memory");
1492 // sort the arrray as we will use binary search on it
1494 qsort(newlist
, pos
+ 1, sizeof(struct lxc_container
*), (int (*)(const void *,const void *))container_cmp
);
1499 static char** get_from_array(char ***names
, char *cname
, int size
)
1501 return (char **)bsearch(&cname
, *names
, size
, sizeof(char *), (int (*)(const void *, const void *))string_cmp
);
1505 static bool array_contains(char ***names
, char *cname
, int size
) {
1506 if(get_from_array(names
, cname
, size
) != NULL
)
1511 static bool remove_from_array(char ***names
, char *cname
, int size
)
1513 char **result
= get_from_array(names
, cname
, size
);
1514 if (result
!= NULL
) {
1521 static char** lxcapi_get_interfaces(struct lxc_container
*c
)
1524 struct ifaddrs
*interfaceArray
= NULL
, *tempIfAddr
= NULL
;
1525 char **interfaces
= NULL
;
1526 int old_netns
= -1, new_netns
= -1;
1528 if (!enter_to_ns(c
, &old_netns
, &new_netns
))
1531 /* Grab the list of interfaces */
1532 if (getifaddrs(&interfaceArray
)) {
1533 SYSERROR("failed to get interfaces list");
1537 /* Iterate through the interfaces */
1538 for (tempIfAddr
= interfaceArray
; tempIfAddr
!= NULL
; tempIfAddr
= tempIfAddr
->ifa_next
) {
1539 if (array_contains(&interfaces
, tempIfAddr
->ifa_name
, count
))
1542 if(!add_to_array(&interfaces
, tempIfAddr
->ifa_name
, count
))
1549 freeifaddrs(interfaceArray
);
1551 exit_from_ns(c
, &old_netns
, &new_netns
);
1553 /* Append NULL to the array */
1555 interfaces
= (char **)lxc_append_null_to_array((void **)interfaces
, count
);
1560 for(i
=0;i
<count
;i
++)
1561 free(interfaces
[i
]);
1567 static char** lxcapi_get_ips(struct lxc_container
*c
, const char* interface
, const char* family
, int scope
)
1570 struct ifaddrs
*interfaceArray
= NULL
, *tempIfAddr
= NULL
;
1571 char addressOutputBuffer
[INET6_ADDRSTRLEN
];
1572 void *tempAddrPtr
= NULL
;
1573 char **addresses
= NULL
;
1574 char *address
= NULL
;
1575 int old_netns
= -1, new_netns
= -1;
1577 if (!enter_to_ns(c
, &old_netns
, &new_netns
))
1580 /* Grab the list of interfaces */
1581 if (getifaddrs(&interfaceArray
)) {
1582 SYSERROR("failed to get interfaces list");
1586 /* Iterate through the interfaces */
1587 for (tempIfAddr
= interfaceArray
; tempIfAddr
!= NULL
; tempIfAddr
= tempIfAddr
->ifa_next
) {
1588 if (tempIfAddr
->ifa_addr
== NULL
)
1591 if(tempIfAddr
->ifa_addr
->sa_family
== AF_INET
) {
1592 if (family
&& strcmp(family
, "inet"))
1594 tempAddrPtr
= &((struct sockaddr_in
*)tempIfAddr
->ifa_addr
)->sin_addr
;
1597 if (family
&& strcmp(family
, "inet6"))
1600 if (((struct sockaddr_in6
*)tempIfAddr
->ifa_addr
)->sin6_scope_id
!= scope
)
1603 tempAddrPtr
= &((struct sockaddr_in6
*)tempIfAddr
->ifa_addr
)->sin6_addr
;
1606 if (interface
&& strcmp(interface
, tempIfAddr
->ifa_name
))
1608 else if (!interface
&& strcmp("lo", tempIfAddr
->ifa_name
) == 0)
1611 address
= (char *)inet_ntop(tempIfAddr
->ifa_addr
->sa_family
,
1613 addressOutputBuffer
,
1614 sizeof(addressOutputBuffer
));
1618 if(!add_to_array(&addresses
, address
, count
))
1625 freeifaddrs(interfaceArray
);
1627 exit_from_ns(c
, &old_netns
, &new_netns
);
1629 /* Append NULL to the array */
1631 addresses
= (char **)lxc_append_null_to_array((void **)addresses
, count
);
1636 for(i
=0;i
<count
;i
++)
1644 static int lxcapi_get_config_item(struct lxc_container
*c
, const char *key
, char *retv
, int inlen
)
1648 if (!c
|| !c
->lxc_conf
)
1650 if (container_mem_lock(c
))
1652 ret
= lxc_get_config_item(c
->lxc_conf
, key
, retv
, inlen
);
1653 container_mem_unlock(c
);
1657 static int lxcapi_get_keys(struct lxc_container
*c
, const char *key
, char *retv
, int inlen
)
1660 return lxc_listconfigs(retv
, inlen
);
1662 * Support 'lxc.network.<idx>', i.e. 'lxc.network.0'
1663 * This is an intelligent result to show which keys are valid given
1664 * the type of nic it is
1666 if (!c
|| !c
->lxc_conf
)
1668 if (container_mem_lock(c
))
1671 if (strncmp(key
, "lxc.network.", 12) == 0)
1672 ret
= lxc_list_nicconfigs(c
->lxc_conf
, key
, retv
, inlen
);
1673 container_mem_unlock(c
);
1677 static bool lxcapi_save_config(struct lxc_container
*c
, const char *alt_file
)
1680 bool ret
= false, need_disklock
= false;
1684 alt_file
= c
->configfile
;
1686 return false; // should we write to stdout if no file is specified?
1688 // If we haven't yet loaded a config, load the stock config
1690 if (!c
->load_config(c
, LXC_DEFAULT_CONFIG
)) {
1691 ERROR("Error loading default configuration file %s while saving %s\n", LXC_DEFAULT_CONFIG
, c
->name
);
1696 if (!create_container_dir(c
))
1700 * If we're writing to the container's config file, take the
1701 * disk lock. Otherwise just take the memlock to protect the
1702 * struct lxc_container while we're traversing it.
1704 if (strcmp(c
->configfile
, alt_file
) == 0)
1705 need_disklock
= true;
1708 lret
= container_disk_lock(c
);
1710 lret
= container_mem_lock(c
);
1716 fout
= fopen(alt_file
, "w");
1720 write_config(fout
, c
->lxc_conf
);
1728 container_disk_unlock(c
);
1730 container_mem_unlock(c
);
1734 static bool mod_rdep(struct lxc_container
*c
, bool inc
)
1736 char path
[MAXPATHLEN
];
1741 if (container_disk_lock(c
))
1743 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_snapshots", c
->config_path
,
1745 if (ret
< 0 || ret
> MAXPATHLEN
)
1748 f
= fopen(path
, "r");
1751 ret
= fscanf(f
, "%d", &v
);
1756 ERROR("Corrupted file %s", path
);
1762 f
= fopen(path
, "w");
1766 if (fprintf(f
, "%d\n", v
) < 0) {
1767 ERROR("Error writing new snapshots value");
1777 SYSERROR("Error writing to or closing snapshots file");
1784 container_disk_unlock(c
);
1788 static void strip_newline(char *p
)
1790 size_t len
= strlen(p
);
1793 if (p
[len
-1] == '\n')
1797 static void mod_all_rdeps(struct lxc_container
*c
, bool inc
)
1799 struct lxc_container
*p
;
1800 char *lxcpath
= NULL
, *lxcname
= NULL
, path
[MAXPATHLEN
];
1801 size_t pathlen
= 0, namelen
= 0;
1805 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_rdepends",
1806 c
->config_path
, c
->name
);
1807 if (ret
< 0 || ret
>= MAXPATHLEN
) {
1808 ERROR("Path name too long");
1812 f
= fopen(path
, "r");
1816 while (getline(&lxcpath
, &pathlen
, f
) != -1) {
1817 if (getline(&lxcname
, &namelen
, f
) == -1) {
1818 ERROR("badly formatted file %s\n", path
);
1821 strip_newline(lxcpath
);
1822 strip_newline(lxcname
);
1823 if ((p
= lxc_container_new(lxcname
, lxcpath
)) == NULL
) {
1824 ERROR("Unable to find dependent container %s:%s",
1828 if (!mod_rdep(p
, inc
))
1829 ERROR("Failed to increase numsnapshots for %s:%s",
1831 lxc_container_put(p
);
1834 if (lxcpath
) free(lxcpath
);
1835 if (lxcname
) free(lxcname
);
1841 static bool has_snapshots(struct lxc_container
*c
)
1843 char path
[MAXPATHLEN
];
1848 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_snapshots", c
->config_path
,
1850 if (ret
< 0 || ret
> MAXPATHLEN
)
1853 f
= fopen(path
, "r");
1857 ret
= fscanf(f
, "%d", &v
);
1869 static int lxc_rmdir_onedev_wrapper(void *data
)
1871 char *arg
= (char *) data
;
1872 return lxc_rmdir_onedev(arg
);
1875 // do we want the api to support --force, or leave that to the caller?
1876 static bool lxcapi_destroy(struct lxc_container
*c
)
1878 struct bdev
*r
= NULL
;
1879 bool bret
= false, am_unpriv
;
1882 if (!c
|| !lxcapi_is_defined(c
))
1885 if (container_disk_lock(c
))
1888 if (!is_stopped(c
)) {
1889 // we should queue some sort of error - in c->error_string?
1890 ERROR("container %s is not stopped", c
->name
);
1894 am_unpriv
= c
->lxc_conf
&& geteuid() != 0 && !lxc_list_empty(&c
->lxc_conf
->id_map
);
1896 if (c
->lxc_conf
&& has_snapshots(c
)) {
1897 ERROR("container %s has dependent snapshots", c
->name
);
1901 if (!am_unpriv
&& c
->lxc_conf
->rootfs
.path
&& c
->lxc_conf
->rootfs
.mount
) {
1902 r
= bdev_init(c
->lxc_conf
->rootfs
.path
, c
->lxc_conf
->rootfs
.mount
, NULL
);
1904 if (r
->ops
->destroy(r
) < 0) {
1906 ERROR("Error destroying rootfs for %s", c
->name
);
1913 mod_all_rdeps(c
, false);
1915 const char *p1
= lxcapi_get_config_path(c
);
1916 char *path
= alloca(strlen(p1
) + strlen(c
->name
) + 2);
1917 sprintf(path
, "%s/%s", p1
, c
->name
);
1919 ret
= userns_exec_1(c
->lxc_conf
, lxc_rmdir_onedev_wrapper
, path
);
1921 ret
= lxc_rmdir_onedev(path
);
1923 ERROR("Error destroying container directory for %s", c
->name
);
1929 container_disk_unlock(c
);
1933 static bool set_config_item_locked(struct lxc_container
*c
, const char *key
, const char *v
)
1935 struct lxc_config_t
*config
;
1938 c
->lxc_conf
= lxc_conf_init();
1941 config
= lxc_getconfig(key
);
1944 return (0 == config
->cb(key
, v
, c
->lxc_conf
));
1947 static bool lxcapi_set_config_item(struct lxc_container
*c
, const char *key
, const char *v
)
1954 if (container_mem_lock(c
))
1957 b
= set_config_item_locked(c
, key
, v
);
1959 container_mem_unlock(c
);
1963 static char *lxcapi_config_file_name(struct lxc_container
*c
)
1965 if (!c
|| !c
->configfile
)
1967 return strdup(c
->configfile
);
1970 static const char *lxcapi_get_config_path(struct lxc_container
*c
)
1972 if (!c
|| !c
->config_path
)
1974 return (const char *)(c
->config_path
);
1979 * Just recalculate the c->configfile based on the
1980 * c->config_path, which must be set.
1981 * The lxc_container must be locked or not yet public.
1983 static bool set_config_filename(struct lxc_container
*c
)
1988 if (!c
->config_path
)
1991 /* $lxc_path + "/" + c->name + "/" + "config" + '\0' */
1992 len
= strlen(c
->config_path
) + strlen(c
->name
) + strlen("config") + 3;
1993 newpath
= malloc(len
);
1997 ret
= snprintf(newpath
, len
, "%s/%s/config", c
->config_path
, c
->name
);
1998 if (ret
< 0 || ret
>= len
) {
1999 fprintf(stderr
, "Error printing out config file name\n");
2005 free(c
->configfile
);
2006 c
->configfile
= newpath
;
2011 static bool lxcapi_set_config_path(struct lxc_container
*c
, const char *path
)
2015 char *oldpath
= NULL
;
2020 if (container_mem_lock(c
))
2025 ERROR("Out of memory setting new lxc path");
2031 oldpath
= c
->config_path
;
2034 /* Since we've changed the config path, we have to change the
2035 * config file name too */
2036 if (!set_config_filename(c
)) {
2037 ERROR("Out of memory setting new config filename");
2039 free(c
->config_path
);
2040 c
->config_path
= oldpath
;
2046 container_mem_unlock(c
);
2051 static bool lxcapi_set_cgroup_item(struct lxc_container
*c
, const char *subsys
, const char *value
)
2061 if (container_disk_lock(c
))
2064 ret
= lxc_cgroup_set(subsys
, value
, c
->name
, c
->config_path
);
2066 container_disk_unlock(c
);
2070 static int lxcapi_get_cgroup_item(struct lxc_container
*c
, const char *subsys
, char *retv
, int inlen
)
2080 if (container_disk_lock(c
))
2083 ret
= lxc_cgroup_get(subsys
, retv
, inlen
, c
->name
, c
->config_path
);
2085 container_disk_unlock(c
);
2089 const char *lxc_get_default_config_path(void)
2091 return default_lxc_path();
2094 const char *lxc_get_default_lvm_vg(void)
2096 return default_lvm_vg();
2099 const char *lxc_get_default_lvm_thin_pool(void)
2101 return default_lvm_thin_pool();
2104 const char *lxc_get_default_zfs_root(void)
2106 return default_zfs_root();
2109 const char *lxc_get_version(void)
2114 static int copy_file(const char *old
, const char *new)
2121 if (file_exists(new)) {
2122 ERROR("copy destination %s exists", new);
2125 ret
= stat(old
, &sbuf
);
2127 INFO("Error stat'ing %s", old
);
2132 in
= open(old
, O_RDONLY
);
2135 SYSERROR("Error opening original file %s", old
);
2139 out
= open(new, O_CREAT
| O_EXCL
| O_WRONLY
, 0644);
2142 SYSERROR("Error opening new file %s", new);
2150 len
= read(in
, buf
, 8096);
2152 SYSERROR("Error reading old file %s", old
);
2157 ret
= write(out
, buf
, len
);
2158 if (ret
< len
) { // should we retry?
2159 SYSERROR("Error: write to new file %s was interrupted", new);
2168 // we set mode, but not owner/group
2169 ret
= chmod(new, sbuf
.st_mode
);
2171 SYSERROR("Error setting mode on %s", new);
2185 static int copyhooks(struct lxc_container
*oldc
, struct lxc_container
*c
)
2189 struct lxc_list
*it
;
2191 for (i
=0; i
<NUM_LXC_HOOKS
; i
++) {
2192 lxc_list_for_each(it
, &c
->lxc_conf
->hooks
[i
]) {
2193 char *hookname
= it
->elem
;
2194 char *fname
= strrchr(hookname
, '/');
2195 char tmppath
[MAXPATHLEN
];
2196 if (!fname
) // relative path - we don't support, but maybe we should
2198 // copy the script, and change the entry in confile
2199 ret
= snprintf(tmppath
, MAXPATHLEN
, "%s/%s/%s",
2200 c
->config_path
, c
->name
, fname
+1);
2201 if (ret
< 0 || ret
>= MAXPATHLEN
)
2203 ret
= copy_file(it
->elem
, tmppath
);
2207 it
->elem
= strdup(tmppath
);
2209 ERROR("out of memory copying hook path");
2215 c
->save_config(c
, NULL
);
2219 static void new_hwaddr(char *hwaddr
)
2223 f
= fopen("/dev/urandom", "r");
2227 int ret
= fread(&seed
, sizeof(seed
), 1, f
);
2236 snprintf(hwaddr
, 18, "00:16:3e:%02x:%02x:%02x",
2237 rand() % 255, rand() % 255, rand() % 255);
2240 static void network_new_hwaddrs(struct lxc_container
*c
)
2242 struct lxc_list
*it
;
2244 lxc_list_for_each(it
, &c
->lxc_conf
->network
) {
2245 struct lxc_netdev
*n
= it
->elem
;
2247 new_hwaddr(n
->hwaddr
);
2251 static int copy_fstab(struct lxc_container
*oldc
, struct lxc_container
*c
)
2253 char newpath
[MAXPATHLEN
];
2254 char *oldpath
= oldc
->lxc_conf
->fstab
;
2260 char *p
= strrchr(oldpath
, '/');
2263 ret
= snprintf(newpath
, MAXPATHLEN
, "%s/%s%s",
2264 c
->config_path
, c
->name
, p
);
2265 if (ret
< 0 || ret
>= MAXPATHLEN
) {
2266 ERROR("error printing new path for %s", oldpath
);
2269 if (file_exists(newpath
)) {
2270 ERROR("error: fstab file %s exists", newpath
);
2274 if (copy_file(oldpath
, newpath
) < 0) {
2275 ERROR("error: copying %s to %s", oldpath
, newpath
);
2278 free(c
->lxc_conf
->fstab
);
2279 c
->lxc_conf
->fstab
= strdup(newpath
);
2280 if (!c
->lxc_conf
->fstab
) {
2281 ERROR("error: allocating pathname");
2288 static void copy_rdepends(struct lxc_container
*c
, struct lxc_container
*c0
)
2290 char path0
[MAXPATHLEN
], path1
[MAXPATHLEN
];
2293 ret
= snprintf(path0
, MAXPATHLEN
, "%s/%s/lxc_rdepends", c0
->config_path
,
2295 if (ret
< 0 || ret
>= MAXPATHLEN
) {
2296 WARN("Error copying reverse dependencies");
2299 ret
= snprintf(path1
, MAXPATHLEN
, "%s/%s/lxc_rdepends", c
->config_path
,
2301 if (ret
< 0 || ret
>= MAXPATHLEN
) {
2302 WARN("Error copying reverse dependencies");
2305 if (copy_file(path0
, path1
) < 0) {
2306 INFO("Error copying reverse dependencies");
2311 static bool add_rdepends(struct lxc_container
*c
, struct lxc_container
*c0
)
2314 char path
[MAXPATHLEN
];
2318 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_rdepends", c
->config_path
,
2320 if (ret
< 0 || ret
>= MAXPATHLEN
)
2323 f
= fopen(path
, "a");
2328 // if anything goes wrong, just return an error
2329 if (fprintf(f
, "%s\n%s\n", c0
->config_path
, c0
->name
) < 0)
2338 static int copy_storage(struct lxc_container
*c0
, struct lxc_container
*c
,
2339 const char *newtype
, int flags
, const char *bdevdata
, unsigned long newsize
)
2344 bdev
= bdev_copy(c0
->lxc_conf
->rootfs
.path
, c0
->name
, c
->name
,
2345 c0
->config_path
, c
->config_path
, newtype
, !!(flags
& LXC_CLONE_SNAPSHOT
),
2346 bdevdata
, newsize
, &need_rdep
);
2348 ERROR("Error copying storage");
2351 free(c
->lxc_conf
->rootfs
.path
);
2352 c
->lxc_conf
->rootfs
.path
= strdup(bdev
->src
);
2354 if (!c
->lxc_conf
->rootfs
.path
) {
2355 ERROR("Out of memory while setting storage path");
2358 if (flags
& LXC_CLONE_SNAPSHOT
)
2359 copy_rdepends(c
, c0
);
2361 if (!add_rdepends(c
, c0
))
2362 WARN("Error adding reverse dependency from %s to %s",
2366 mod_all_rdeps(c
, true);
2371 static int clone_update_rootfs(struct lxc_container
*c0
,
2372 struct lxc_container
*c
, int flags
,
2376 char path
[MAXPATHLEN
];
2380 struct lxc_conf
*conf
= c
->lxc_conf
;
2382 /* update hostname in rootfs */
2383 /* we're going to mount, so run in a clean namespace to simplify cleanup */
2389 return wait_for_pid(pid
);
2391 process_unlock(); // we're no longer sharing
2392 bdev
= bdev_init(c
->lxc_conf
->rootfs
.path
, c
->lxc_conf
->rootfs
.mount
, NULL
);
2395 if (strcmp(bdev
->type
, "dir") != 0) {
2396 if (unshare(CLONE_NEWNS
) < 0) {
2397 ERROR("error unsharing mounts");
2400 if (bdev
->ops
->mount(bdev
) < 0)
2402 } else { // TODO come up with a better way
2405 bdev
->dest
= strdup(bdev
->src
);
2408 if (!lxc_list_empty(&conf
->hooks
[LXCHOOK_CLONE
])) {
2409 /* Start of environment variable setup for hooks */
2410 if (setenv("LXC_SRC_NAME", c0
->name
, 1)) {
2411 SYSERROR("failed to set environment variable for source container name");
2413 if (setenv("LXC_NAME", c
->name
, 1)) {
2414 SYSERROR("failed to set environment variable for container name");
2416 if (setenv("LXC_CONFIG_FILE", conf
->rcfile
, 1)) {
2417 SYSERROR("failed to set environment variable for config path");
2419 if (setenv("LXC_ROOTFS_MOUNT", bdev
->dest
, 1)) {
2420 SYSERROR("failed to set environment variable for rootfs mount");
2422 if (setenv("LXC_ROOTFS_PATH", conf
->rootfs
.path
, 1)) {
2423 SYSERROR("failed to set environment variable for rootfs mount");
2426 if (run_lxc_hooks(c
->name
, "clone", conf
, c
->get_config_path(c
), hookargs
)) {
2427 ERROR("Error executing clone hook for %s", c
->name
);
2432 if (!(flags
& LXC_CLONE_KEEPNAME
)) {
2433 ret
= snprintf(path
, MAXPATHLEN
, "%s/etc/hostname", bdev
->dest
);
2434 if (ret
< 0 || ret
>= MAXPATHLEN
)
2436 if (!file_exists(path
))
2438 if (!(fout
= fopen(path
, "w"))) {
2439 SYSERROR("unable to open %s: ignoring\n", path
);
2442 if (fprintf(fout
, "%s", c
->name
) < 0)
2444 if (fclose(fout
) < 0)
2451 * We want to support:
2452 sudo lxc-clone -o o1 -n n1 -s -L|-fssize fssize -v|--vgname vgname \
2453 -p|--lvprefix lvprefix -t|--fstype fstype -B backingstore
2455 -s [ implies overlayfs]
2459 only rootfs gets converted (copied/snapshotted) on clone.
2462 static int create_file_dirname(char *path
)
2464 char *p
= strrchr(path
, '/');
2470 ret
= mkdir(path
, 0755);
2471 if (ret
&& errno
!= EEXIST
)
2472 SYSERROR("creating container path %s\n", path
);
2477 struct lxc_container
*lxcapi_clone(struct lxc_container
*c
, const char *newname
,
2478 const char *lxcpath
, int flags
,
2479 const char *bdevtype
, const char *bdevdata
, unsigned long newsize
,
2482 struct lxc_container
*c2
= NULL
;
2483 char newpath
[MAXPATHLEN
];
2484 int ret
, storage_copied
= 0;
2488 if (!c
|| !c
->is_defined(c
))
2491 if (container_mem_lock(c
))
2494 if (!is_stopped(c
)) {
2495 ERROR("error: Original container (%s) is running", c
->name
);
2499 // Make sure the container doesn't yet exist.
2500 n
= newname
? newname
: c
->name
;
2501 l
= lxcpath
? lxcpath
: c
->get_config_path(c
);
2502 ret
= snprintf(newpath
, MAXPATHLEN
, "%s/%s/config", l
, n
);
2503 if (ret
< 0 || ret
>= MAXPATHLEN
) {
2504 SYSERROR("clone: failed making config pathname");
2507 if (file_exists(newpath
)) {
2508 ERROR("error: clone: %s exists", newpath
);
2512 ret
= create_file_dirname(newpath
);
2513 if (ret
< 0 && errno
!= EEXIST
) {
2514 ERROR("Error creating container dir for %s", newpath
);
2518 // copy the configuration, tweak it as needed,
2520 fout
= fopen(newpath
, "w");
2523 SYSERROR("open %s", newpath
);
2526 write_config(fout
, c
->lxc_conf
);
2531 sprintf(newpath
, "%s/%s/rootfs", l
, n
);
2532 if (mkdir(newpath
, 0755) < 0) {
2533 SYSERROR("error creating %s", newpath
);
2537 c2
= lxc_container_new(n
, l
);
2539 ERROR("clone: failed to create new container (%s %s)", n
, l
);
2544 if (!set_config_item_locked(c2
, "lxc.utsname", newname
)) {
2545 ERROR("Error setting new hostname");
2550 // copy hooks if requested
2551 if (flags
& LXC_CLONE_COPYHOOKS
) {
2552 ret
= copyhooks(c
, c2
);
2554 ERROR("error copying hooks");
2559 if (copy_fstab(c
, c2
) < 0) {
2560 ERROR("error copying fstab");
2565 if (!(flags
& LXC_CLONE_KEEPMACADDR
))
2566 network_new_hwaddrs(c2
);
2568 // copy/snapshot rootfs's
2569 ret
= copy_storage(c
, c2
, bdevtype
, flags
, bdevdata
, newsize
);
2573 // We've now successfully created c2's storage, so clear it out if we
2577 if (!c2
->save_config(c2
, NULL
))
2580 if (clone_update_rootfs(c
, c2
, flags
, hookargs
) < 0)
2583 // TODO: update c's lxc.snapshot = count
2584 container_mem_unlock(c
);
2588 container_mem_unlock(c
);
2590 if (!storage_copied
)
2591 c2
->lxc_conf
->rootfs
.path
= NULL
;
2593 lxc_container_put(c2
);
2599 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
)
2604 return lxc_attach(c
->name
, c
->config_path
, exec_function
, exec_payload
, options
, attached_process
);
2607 static int lxcapi_attach_run_wait(struct lxc_container
*c
, lxc_attach_options_t
*options
, const char *program
, const char * const argv
[])
2609 lxc_attach_command_t command
;
2616 command
.program
= (char*)program
;
2617 command
.argv
= (char**)argv
;
2618 r
= lxc_attach(c
->name
, c
->config_path
, lxc_attach_run_command
, &command
, options
, &pid
);
2623 return lxc_wait_for_pid_status(pid
);
2626 int get_next_index(const char *lxcpath
, char *cname
)
2632 fname
= alloca(strlen(lxcpath
) + 20);
2634 sprintf(fname
, "%s/snap%d", lxcpath
, i
);
2635 ret
= stat(fname
, &sb
);
2642 static int lxcapi_snapshot(struct lxc_container
*c
, const char *commentfile
)
2645 struct lxc_container
*c2
;
2646 char snappath
[MAXPATHLEN
], newname
[20];
2648 // /var/lib/lxc -> /var/lib/lxcsnaps \0
2649 ret
= snprintf(snappath
, MAXPATHLEN
, "%ssnaps/%s", c
->config_path
, c
->name
);
2650 if (ret
< 0 || ret
>= MAXPATHLEN
)
2652 i
= get_next_index(snappath
, c
->name
);
2654 if (mkdir_p(snappath
, 0755) < 0) {
2655 ERROR("Failed to create snapshot directory %s", snappath
);
2659 ret
= snprintf(newname
, 20, "snap%d", i
);
2660 if (ret
< 0 || ret
>= 20)
2663 flags
= LXC_CLONE_SNAPSHOT
| LXC_CLONE_KEEPMACADDR
| LXC_CLONE_KEEPNAME
;
2664 c2
= c
->clone(c
, newname
, snappath
, flags
, NULL
, NULL
, 0, NULL
);
2666 ERROR("clone of %s:%s failed\n", c
->config_path
, c
->name
);
2670 lxc_container_put(c2
);
2672 // Now write down the creation time
2679 tm_info
= localtime(&timer
);
2681 strftime(buffer
, 25, "%Y:%m:%d %H:%M:%S", tm_info
);
2683 char *dfnam
= alloca(strlen(snappath
) + strlen(newname
) + 5);
2684 sprintf(dfnam
, "%s/%s/ts", snappath
, newname
);
2686 f
= fopen(dfnam
, "w");
2689 ERROR("Failed to open %s\n", dfnam
);
2692 if (fprintf(f
, "%s", buffer
) < 0) {
2693 SYSERROR("Writing timestamp");
2701 SYSERROR("Writing timestamp");
2706 // $p / $name / comment \0
2707 int len
= strlen(snappath
) + strlen(newname
) + 10;
2708 char *path
= alloca(len
);
2709 sprintf(path
, "%s/%s/comment", snappath
, newname
);
2710 return copy_file(commentfile
, path
) < 0 ? -1 : i
;
2716 static void lxcsnap_free(struct lxc_snapshot
*s
)
2720 if (s
->comment_pathname
)
2721 free(s
->comment_pathname
);
2728 static char *get_snapcomment_path(char* snappath
, char *name
)
2730 // $snappath/$name/comment
2731 int ret
, len
= strlen(snappath
) + strlen(name
) + 10;
2732 char *s
= malloc(len
);
2735 ret
= snprintf(s
, len
, "%s/%s/comment", snappath
, name
);
2736 if (ret
< 0 || ret
>= len
) {
2744 static char *get_timestamp(char* snappath
, char *name
)
2746 char path
[MAXPATHLEN
], *s
= NULL
;
2750 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/ts", snappath
, name
);
2751 if (ret
< 0 || ret
>= MAXPATHLEN
)
2754 fin
= fopen(path
, "r");
2758 (void) fseek(fin
, 0, SEEK_END
);
2760 (void) fseek(fin
, 0, SEEK_SET
);
2765 if (fread(s
, 1, len
, fin
) != len
) {
2766 SYSERROR("reading timestamp");
2778 static int lxcapi_snapshot_list(struct lxc_container
*c
, struct lxc_snapshot
**ret_snaps
)
2780 char snappath
[MAXPATHLEN
], path2
[MAXPATHLEN
];
2781 int dirlen
, count
= 0, ret
;
2782 struct dirent dirent
, *direntp
;
2783 struct lxc_snapshot
*snaps
=NULL
, *nsnaps
;
2786 if (!c
|| !lxcapi_is_defined(c
))
2788 // snappath is ${lxcpath}snaps/${lxcname}/
2789 dirlen
= snprintf(snappath
, MAXPATHLEN
, "%ssnaps/%s", c
->config_path
, c
->name
);
2790 if (dirlen
< 0 || dirlen
>= MAXPATHLEN
) {
2791 ERROR("path name too long");
2795 dir
= opendir(snappath
);
2798 INFO("failed to open %s - assuming no snapshots", snappath
);
2802 while (!readdir_r(dir
, &dirent
, &direntp
)) {
2806 if (!strcmp(direntp
->d_name
, "."))
2809 if (!strcmp(direntp
->d_name
, ".."))
2812 ret
= snprintf(path2
, MAXPATHLEN
, "%s/%s/config", snappath
, direntp
->d_name
);
2813 if (ret
< 0 || ret
>= MAXPATHLEN
) {
2814 ERROR("pathname too long");
2817 if (!file_exists(path2
))
2819 nsnaps
= realloc(snaps
, (count
+ 1)*sizeof(*snaps
));
2821 SYSERROR("Out of memory");
2825 snaps
[count
].free
= lxcsnap_free
;
2826 snaps
[count
].name
= strdup(direntp
->d_name
);
2827 if (!snaps
[count
].name
)
2829 snaps
[count
].lxcpath
= strdup(snappath
);
2830 if (!snaps
[count
].lxcpath
) {
2831 free(snaps
[count
].name
);
2834 snaps
[count
].comment_pathname
= get_snapcomment_path(snappath
, direntp
->d_name
);
2835 snaps
[count
].timestamp
= get_timestamp(snappath
, direntp
->d_name
);
2841 WARN("failed to close directory");
2850 for (i
=0; i
<count
; i
++)
2851 lxcsnap_free(&snaps
[i
]);
2856 WARN("failed to close directory");
2861 static bool lxcapi_snapshot_restore(struct lxc_container
*c
, const char *snapname
, const char *newname
)
2863 char clonelxcpath
[MAXPATHLEN
];
2865 struct lxc_container
*snap
, *rest
;
2869 if (!c
|| !c
->name
|| !c
->config_path
)
2872 bdev
= bdev_init(c
->lxc_conf
->rootfs
.path
, c
->lxc_conf
->rootfs
.mount
, NULL
);
2874 ERROR("Failed to find original backing store type");
2880 if (strcmp(c
->name
, newname
) == 0) {
2881 if (!lxcapi_destroy(c
)) {
2882 ERROR("Could not destroy existing container %s", newname
);
2887 ret
= snprintf(clonelxcpath
, MAXPATHLEN
, "%ssnaps/%s", c
->config_path
, c
->name
);
2888 if (ret
< 0 || ret
>= MAXPATHLEN
) {
2892 // how should we lock this?
2894 snap
= lxc_container_new(snapname
, clonelxcpath
);
2895 if (!snap
|| !lxcapi_is_defined(snap
)) {
2896 ERROR("Could not open snapshot %s", snapname
);
2897 if (snap
) lxc_container_put(snap
);
2902 rest
= lxcapi_clone(snap
, newname
, c
->config_path
, 0, bdev
->type
, NULL
, 0, NULL
);
2904 if (rest
&& lxcapi_is_defined(rest
))
2907 lxc_container_put(rest
);
2908 lxc_container_put(snap
);
2912 static bool lxcapi_snapshot_destroy(struct lxc_container
*c
, const char *snapname
)
2915 char clonelxcpath
[MAXPATHLEN
];
2916 struct lxc_container
*snap
= NULL
;
2918 if (!c
|| !c
->name
|| !c
->config_path
)
2921 ret
= snprintf(clonelxcpath
, MAXPATHLEN
, "%ssnaps/%s", c
->config_path
, c
->name
);
2922 if (ret
< 0 || ret
>= MAXPATHLEN
)
2925 snap
= lxc_container_new(snapname
, clonelxcpath
);
2926 if (!snap
|| !lxcapi_is_defined(snap
)) {
2927 ERROR("Could not find snapshot %s", snapname
);
2931 if (!lxcapi_destroy(snap
)) {
2932 ERROR("Could not destroy snapshot %s", snapname
);
2935 lxc_container_put(snap
);
2940 lxc_container_put(snap
);
2944 static bool lxcapi_may_control(struct lxc_container
*c
)
2946 return lxc_try_cmd(c
->name
, c
->config_path
) == 0;
2949 static bool add_remove_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
, bool add
)
2953 char path
[MAXPATHLEN
];
2954 char value
[MAX_BUFFER
];
2955 char *directory_path
= NULL
;
2958 /* make sure container is running */
2959 if (!c
->is_running(c
)) {
2960 ERROR("container is not running");
2964 /* use src_path if dest_path is NULL otherwise use dest_path */
2965 p
= dest_path
? dest_path
: src_path
;
2967 /* prepare the path */
2968 ret
= snprintf(path
, MAXPATHLEN
, "/proc/%d/root/%s", c
->init_pid(c
), p
);
2969 if (ret
< 0 || ret
>= MAXPATHLEN
)
2971 remove_trailing_slashes(path
);
2973 p
= add
? src_path
: path
;
2974 /* make sure we can access p */
2975 if(access(p
, F_OK
) < 0 || stat(p
, &st
) < 0)
2978 /* continue if path is character device or block device */
2979 if (S_ISCHR(st
.st_mode
))
2980 ret
= snprintf(value
, MAX_BUFFER
, "c %d:%d rwm", major(st
.st_rdev
), minor(st
.st_rdev
));
2981 else if (S_ISBLK(st
.st_mode
))
2982 ret
= snprintf(value
, MAX_BUFFER
, "b %d:%d rwm", major(st
.st_rdev
), minor(st
.st_rdev
));
2986 /* check snprintf return code */
2987 if (ret
< 0 || ret
>= MAX_BUFFER
)
2990 directory_path
= dirname(strdup(path
));
2991 /* remove path and directory_path (if empty) */
2992 if(access(path
, F_OK
) == 0) {
2993 if (unlink(path
) < 0) {
2994 ERROR("unlink failed");
2997 if (rmdir(directory_path
) < 0 && errno
!= ENOTEMPTY
) {
2998 ERROR("rmdir failed");
3004 /* create the missing directories */
3005 if (mkdir_p(directory_path
, 0755) < 0) {
3006 ERROR("failed to create directory");
3010 /* create the device node */
3011 if (mknod(path
, st
.st_mode
, st
.st_rdev
) < 0) {
3012 ERROR("mknod failed");
3016 /* add device node to device list */
3017 if (!c
->set_cgroup_item(c
, "devices.allow", value
)) {
3018 ERROR("set_cgroup_item failed while adding the device node");
3022 /* remove device node from device list */
3023 if (!c
->set_cgroup_item(c
, "devices.deny", value
)) {
3024 ERROR("set_cgroup_item failed while removing the device node");
3031 free(directory_path
);
3035 static bool lxcapi_add_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
)
3037 return add_remove_device_node(c
, src_path
, dest_path
, true);
3040 static bool lxcapi_remove_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
)
3042 return add_remove_device_node(c
, src_path
, dest_path
, false);
3045 static int lxcapi_attach_run_waitl(struct lxc_container
*c
, lxc_attach_options_t
*options
, const char *program
, const char *arg
, ...)
3055 argv
= lxc_va_arg_list_to_argv_const(ap
, 1);
3059 ERROR("Memory allocation error.");
3064 ret
= lxcapi_attach_run_wait(c
, options
, program
, (const char * const *)argv
);
3069 struct lxc_container
*lxc_container_new(const char *name
, const char *configpath
)
3071 struct lxc_container
*c
;
3073 c
= malloc(sizeof(*c
));
3075 fprintf(stderr
, "failed to malloc lxc_container\n");
3078 memset(c
, 0, sizeof(*c
));
3081 c
->config_path
= strdup(configpath
);
3083 c
->config_path
= strdup(default_lxc_path());
3085 if (!c
->config_path
) {
3086 fprintf(stderr
, "Out of memory");
3090 remove_trailing_slashes(c
->config_path
);
3091 c
->name
= malloc(strlen(name
)+1);
3093 fprintf(stderr
, "Error allocating lxc_container name\n");
3096 strcpy(c
->name
, name
);
3099 if (!(c
->slock
= lxc_newlock(c
->config_path
, name
))) {
3100 fprintf(stderr
, "failed to create lock\n");
3104 if (!(c
->privlock
= lxc_newlock(NULL
, NULL
))) {
3105 fprintf(stderr
, "failed to alloc privlock\n");
3109 if (!set_config_filename(c
)) {
3110 fprintf(stderr
, "Error allocating config file pathname\n");
3114 if (file_exists(c
->configfile
))
3115 lxcapi_load_config(c
, NULL
);
3117 if (ongoing_create(c
) == 2) {
3118 ERROR("Error: %s creation was not completed", c
->name
);
3120 lxcapi_clear_config(c
);
3123 // assign the member functions
3124 c
->is_defined
= lxcapi_is_defined
;
3125 c
->state
= lxcapi_state
;
3126 c
->is_running
= lxcapi_is_running
;
3127 c
->freeze
= lxcapi_freeze
;
3128 c
->unfreeze
= lxcapi_unfreeze
;
3129 c
->console
= lxcapi_console
;
3130 c
->console_getfd
= lxcapi_console_getfd
;
3131 c
->init_pid
= lxcapi_init_pid
;
3132 c
->load_config
= lxcapi_load_config
;
3133 c
->want_daemonize
= lxcapi_want_daemonize
;
3134 c
->want_close_all_fds
= lxcapi_want_close_all_fds
;
3135 c
->start
= lxcapi_start
;
3136 c
->startl
= lxcapi_startl
;
3137 c
->stop
= lxcapi_stop
;
3138 c
->config_file_name
= lxcapi_config_file_name
;
3139 c
->wait
= lxcapi_wait
;
3140 c
->set_config_item
= lxcapi_set_config_item
;
3141 c
->destroy
= lxcapi_destroy
;
3142 c
->save_config
= lxcapi_save_config
;
3143 c
->get_keys
= lxcapi_get_keys
;
3144 c
->create
= lxcapi_create
;
3145 c
->createl
= lxcapi_createl
;
3146 c
->shutdown
= lxcapi_shutdown
;
3147 c
->reboot
= lxcapi_reboot
;
3148 c
->clear_config
= lxcapi_clear_config
;
3149 c
->clear_config_item
= lxcapi_clear_config_item
;
3150 c
->get_config_item
= lxcapi_get_config_item
;
3151 c
->get_cgroup_item
= lxcapi_get_cgroup_item
;
3152 c
->set_cgroup_item
= lxcapi_set_cgroup_item
;
3153 c
->get_config_path
= lxcapi_get_config_path
;
3154 c
->set_config_path
= lxcapi_set_config_path
;
3155 c
->clone
= lxcapi_clone
;
3156 c
->get_interfaces
= lxcapi_get_interfaces
;
3157 c
->get_ips
= lxcapi_get_ips
;
3158 c
->attach
= lxcapi_attach
;
3159 c
->attach_run_wait
= lxcapi_attach_run_wait
;
3160 c
->attach_run_waitl
= lxcapi_attach_run_waitl
;
3161 c
->snapshot
= lxcapi_snapshot
;
3162 c
->snapshot_list
= lxcapi_snapshot_list
;
3163 c
->snapshot_restore
= lxcapi_snapshot_restore
;
3164 c
->snapshot_destroy
= lxcapi_snapshot_destroy
;
3165 c
->may_control
= lxcapi_may_control
;
3166 c
->add_device_node
= lxcapi_add_device_node
;
3167 c
->remove_device_node
= lxcapi_remove_device_node
;
3169 /* we'll allow the caller to update these later */
3170 if (lxc_log_init(NULL
, "none", NULL
, "lxc_container", 0, c
->config_path
)) {
3171 fprintf(stderr
, "failed to open log\n");
3178 lxc_container_free(c
);
3182 int lxc_get_wait_states(const char **states
)
3187 for (i
=0; i
<MAX_STATE
; i
++)
3188 states
[i
] = lxc_state2str(i
);
3193 * These next two could probably be done smarter with reusing a common function
3194 * with different iterators and tests...
3196 int list_defined_containers(const char *lxcpath
, char ***names
, struct lxc_container
***cret
)
3199 int i
, cfound
= 0, nfound
= 0;
3200 struct dirent dirent
, *direntp
;
3201 struct lxc_container
*c
;
3204 lxcpath
= default_lxc_path();
3207 dir
= opendir(lxcpath
);
3211 SYSERROR("opendir on lxcpath");
3220 while (!readdir_r(dir
, &dirent
, &direntp
)) {
3223 if (!strcmp(direntp
->d_name
, "."))
3225 if (!strcmp(direntp
->d_name
, ".."))
3228 if (!config_file_exists(lxcpath
, direntp
->d_name
))
3232 if (!add_to_array(names
, direntp
->d_name
, cfound
))
3242 c
= lxc_container_new(direntp
->d_name
, lxcpath
);
3244 INFO("Container %s:%s has a config but could not be loaded",
3245 lxcpath
, direntp
->d_name
);
3247 if(!remove_from_array(names
, direntp
->d_name
, cfound
--))
3251 if (!lxcapi_is_defined(c
)) {
3252 INFO("Container %s:%s has a config but is not defined",
3253 lxcpath
, direntp
->d_name
);
3255 if(!remove_from_array(names
, direntp
->d_name
, cfound
--))
3257 lxc_container_put(c
);
3261 if (!add_to_clist(cret
, c
, nfound
, true)) {
3262 lxc_container_put(c
);
3274 if (names
&& *names
) {
3275 for (i
=0; i
<cfound
; i
++)
3279 if (cret
&& *cret
) {
3280 for (i
=0; i
<nfound
; i
++)
3281 lxc_container_put((*cret
)[i
]);
3290 int list_active_containers(const char *lxcpath
, char ***nret
,
3291 struct lxc_container
***cret
)
3293 int i
, ret
= -1, cret_cnt
= 0, ct_name_cnt
= 0;
3296 char **ct_name
= NULL
;
3298 struct lxc_container
*c
;
3301 lxcpath
= default_lxc_path();
3302 lxcpath_len
= strlen(lxcpath
);
3310 FILE *f
= fopen("/proc/net/unix", "r");
3315 while (getline(&line
, &len
, f
) != -1) {
3316 char *p
= strrchr(line
, ' '), *p2
;
3323 if (strncmp(p
, lxcpath
, lxcpath_len
) != 0)
3329 // Now p is the start of lxc_name
3331 if (!p2
|| strncmp(p2
, "/command", 8) != 0)
3335 if (array_contains(&ct_name
, p
, ct_name_cnt
))
3338 if (!add_to_array(&ct_name
, p
, ct_name_cnt
))
3339 goto free_cret_list
;
3346 c
= lxc_container_new(p
, lxcpath
);
3348 INFO("Container %s:%s is running but could not be loaded",
3350 remove_from_array(&ct_name
, p
, ct_name_cnt
--);
3355 * If this is an anonymous container, then is_defined *can*
3356 * return false. So we don't do that check. Count on the
3357 * fact that the command socket exists.
3360 if (!add_to_clist(cret
, c
, cret_cnt
, true)) {
3361 lxc_container_put(c
);
3362 goto free_cret_list
;
3367 assert(!nret
|| !cret
|| cret_cnt
== ct_name_cnt
);
3376 if (cret
&& *cret
) {
3377 for (i
= 0; i
< cret_cnt
; i
++)
3378 lxc_container_put((*cret
)[i
]);
3384 for (i
= 0; i
< ct_name_cnt
; i
++)
3399 int list_all_containers(const char *lxcpath
, char ***nret
,
3400 struct lxc_container
***cret
)
3402 int i
, ret
, active_cnt
, ct_cnt
, ct_list_cnt
;
3405 struct lxc_container
**ct_list
= NULL
;
3407 ct_cnt
= list_defined_containers(lxcpath
, &ct_name
, NULL
);
3411 active_cnt
= list_active_containers(lxcpath
, &active_name
, NULL
);
3412 if (active_cnt
< 0) {
3417 for (i
= 0; i
< active_cnt
; i
++) {
3418 if (!array_contains(&ct_name
, active_name
[i
], ct_cnt
)) {
3419 if (!add_to_array(&ct_name
, active_name
[i
], ct_cnt
)) {
3421 goto free_active_name
;
3425 free(active_name
[i
]);
3426 active_name
[i
] = NULL
;
3432 for (i
= 0, ct_list_cnt
= 0; i
< ct_cnt
&& cret
; i
++) {
3433 struct lxc_container
*c
;
3435 c
= lxc_container_new(ct_name
[i
], lxcpath
);
3437 WARN("Container %s:%s could not be loaded", lxcpath
, ct_name
[i
]);
3438 remove_from_array(&ct_name
, ct_name
[i
], ct_cnt
--);
3442 if (!add_to_clist(&ct_list
, c
, ct_list_cnt
, false)) {
3443 lxc_container_put(c
);
3462 for (i
= 0; i
< ct_list_cnt
; i
++) {
3463 lxc_container_put(ct_list
[i
]);
3469 for (i
= 0; i
< active_cnt
; i
++) {
3471 free(active_name
[i
]);
3477 for (i
= 0; i
< ct_cnt
; i
++) {