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>
37 #include <lxc/lxccontainer.h>
38 #include <lxc/version.h>
54 #include "namespace.h"
60 #include <../include/ifaddrs.h>
65 #include <../include/getline.h>
69 #define MAX_BUFFER 4096
71 lxc_log_define(lxc_container
, lxc
);
73 static bool file_exists(const char *f
)
77 return stat(f
, &statbuf
) == 0;
80 static bool config_file_exists(const char *lxcpath
, const char *cname
)
82 /* $lxcpath + '/' + $cname + '/config' + \0 */
83 int ret
, len
= strlen(lxcpath
) + strlen(cname
) + 9;
84 char *fname
= alloca(len
);
86 ret
= snprintf(fname
, len
, "%s/%s/config", lxcpath
, cname
);
87 if (ret
< 0 || ret
>= len
)
90 return file_exists(fname
);
94 * A few functions to help detect when a container creation failed.
95 * If a container creation was killed partway through, then trying
96 * to actually start that container could harm the host. We detect
97 * this by creating a 'partial' file under the container directory,
98 * and keeping an advisory lock. When container creation completes,
99 * we remove that file. When we load or try to start a container, if
100 * we find that file, without a flock, we remove the container.
102 static int ongoing_create(struct lxc_container
*c
)
104 int len
= strlen(c
->config_path
) + strlen(c
->name
) + 10;
105 char *path
= alloca(len
);
109 ret
= snprintf(path
, len
, "%s/%s/partial", c
->config_path
, c
->name
);
110 if (ret
< 0 || ret
>= len
) {
111 ERROR("Error writing partial pathname");
115 if (!file_exists(path
))
117 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
133 // create completed but partial is still there.
138 static int create_partial(struct lxc_container
*c
)
140 // $lxcpath + '/' + $name + '/partial' + \0
141 int len
= strlen(c
->config_path
) + strlen(c
->name
) + 10;
142 char *path
= alloca(len
);
146 ret
= snprintf(path
, len
, "%s/%s/partial", c
->config_path
, c
->name
);
147 if (ret
< 0 || ret
>= len
) {
148 ERROR("Error writing partial pathname");
151 if ((fd
=open(path
, O_RDWR
| O_CREAT
| O_EXCL
, 0755)) < 0) {
152 SYSERROR("Erorr creating partial file");
156 lk
.l_whence
= SEEK_SET
;
159 if (fcntl(fd
, F_SETLKW
, &lk
) < 0) {
160 SYSERROR("Error locking partial file %s", path
);
168 static void remove_partial(struct lxc_container
*c
, int fd
)
170 // $lxcpath + '/' + $name + '/partial' + \0
171 int len
= strlen(c
->config_path
) + strlen(c
->name
) + 10;
172 char *path
= alloca(len
);
176 ret
= snprintf(path
, len
, "%s/%s/partial", c
->config_path
, c
->name
);
177 if (ret
< 0 || ret
>= len
) {
178 ERROR("Error writing partial pathname");
181 if (unlink(path
) < 0)
182 SYSERROR("Error unlink partial file %s", path
);
186 * 1. container_mem_lock(c) protects the struct lxc_container from multiple threads.
187 * 2. container_disk_lock(c) protects the on-disk container data - in particular the
188 * container configuration file.
189 * The container_disk_lock also takes the container_mem_lock.
190 * 3. thread_mutex protects process data (ex: fd table) from multiple threads.
191 * NOTHING mutexes two independent programs with their own struct
192 * lxc_container for the same c->name, between API calls. For instance,
193 * c->config_read(); c->start(); Between those calls, data on disk
194 * could change (which shouldn't bother the caller unless for instance
195 * the rootfs get moved). c->config_read(); update; c->config_write();
196 * Two such updaters could race. The callers should therefore check their
197 * results. Trying to prevent that would necessarily expose us to deadlocks
198 * due to hung callers. So I prefer to keep the locks only within our own
199 * functions, not across functions.
201 * If you're going to clone while holding a lxccontainer, increment
202 * c->numthreads (under privlock) before forking. When deleting,
203 * decrement numthreads under privlock, then if it hits 0 you can delete.
204 * Do not ever use a lxccontainer whose numthreads you did not bump.
207 static void lxc_container_free(struct lxc_container
*c
)
214 c
->configfile
= NULL
;
216 if (c
->error_string
) {
217 free(c
->error_string
);
218 c
->error_string
= NULL
;
221 lxc_putlock(c
->slock
);
225 lxc_putlock(c
->privlock
);
233 lxc_conf_free(c
->lxc_conf
);
236 if (c
->config_path
) {
237 free(c
->config_path
);
238 c
->config_path
= NULL
;
244 * Consider the following case:
245 freer | racing get()er
246 ==================================================================
247 lxc_container_put() | lxc_container_get()
248 \ lxclock(c->privlock) | c->numthreads < 1? (no)
249 \ c->numthreads = 0 | \ lxclock(c->privlock) -> waits
251 \ lxc_container_free() | \ lxclock() returns
252 | \ c->numthreads < 1 -> return 0
254 \ \ sem_destroy(privlock) |
256 * When the get()er checks numthreads the first time, one of the following
258 * 1. freer has set numthreads = 0. get() returns 0
259 * 2. freer is between lxclock and setting numthreads to 0. get()er will
260 * sem_wait on privlock, get lxclock after freer() drops it, then see
261 * numthreads is 0 and exit without touching lxclock again..
262 * 3. freer has not yet locked privlock. If get()er runs first, then put()er
263 * will see --numthreads = 1 and not call lxc_container_free().
266 int lxc_container_get(struct lxc_container
*c
)
271 // if someone else has already started freeing the container, don't
272 // try to take the lock, which may be invalid
273 if (c
->numthreads
< 1)
276 if (container_mem_lock(c
))
278 if (c
->numthreads
< 1) {
279 // bail without trying to unlock, bc the privlock is now probably
284 container_mem_unlock(c
);
288 int lxc_container_put(struct lxc_container
*c
)
292 if (container_mem_lock(c
))
294 if (--c
->numthreads
< 1) {
295 container_mem_unlock(c
);
296 lxc_container_free(c
);
299 container_mem_unlock(c
);
303 static bool lxcapi_is_defined(struct lxc_container
*c
)
312 if (container_mem_lock(c
))
316 statret
= stat(c
->configfile
, &statbuf
);
322 container_mem_unlock(c
);
326 static const char *lxcapi_state(struct lxc_container
*c
)
332 s
= lxc_getstate(c
->name
, c
->config_path
);
333 return lxc_state2str(s
);
336 static bool is_stopped(struct lxc_container
*c
)
339 s
= lxc_getstate(c
->name
, c
->config_path
);
340 return (s
== STOPPED
);
343 static bool lxcapi_is_running(struct lxc_container
*c
)
350 if (!s
|| strcmp(s
, "STOPPED") == 0)
355 static bool lxcapi_freeze(struct lxc_container
*c
)
361 ret
= lxc_freeze(c
->name
, c
->config_path
);
367 static bool lxcapi_unfreeze(struct lxc_container
*c
)
373 ret
= lxc_unfreeze(c
->name
, c
->config_path
);
379 static int lxcapi_console_getfd(struct lxc_container
*c
, int *ttynum
, int *masterfd
)
385 ttyfd
= lxc_console_getfd(c
, ttynum
, masterfd
);
389 static int lxcapi_console(struct lxc_container
*c
, int ttynum
, int stdinfd
,
390 int stdoutfd
, int stderrfd
, int escape
)
392 return lxc_console(c
, ttynum
, stdinfd
, stdoutfd
, stderrfd
, escape
);
395 static pid_t
lxcapi_init_pid(struct lxc_container
*c
)
400 return lxc_cmd_get_init_pid(c
->name
, c
->config_path
);
403 static bool load_config_locked(struct lxc_container
*c
, const char *fname
)
406 c
->lxc_conf
= lxc_conf_init();
407 if (c
->lxc_conf
&& !lxc_config_read(fname
, c
->lxc_conf
))
412 static bool lxcapi_load_config(struct lxc_container
*c
, const char *alt_file
)
414 bool ret
= false, need_disklock
= false;
420 fname
= c
->configfile
;
426 * If we're reading something other than the container's config,
427 * we only need to lock the in-memory container. If loading the
428 * container's config file, take the disk lock.
430 if (strcmp(fname
, c
->configfile
) == 0)
431 need_disklock
= true;
434 lret
= container_disk_lock(c
);
436 lret
= container_mem_lock(c
);
440 ret
= load_config_locked(c
, fname
);
443 container_disk_unlock(c
);
445 container_mem_unlock(c
);
449 static bool lxcapi_want_daemonize(struct lxc_container
*c
, bool state
)
451 if (!c
|| !c
->lxc_conf
)
453 if (container_mem_lock(c
)) {
454 ERROR("Error getting mem lock");
457 c
->daemonize
= state
;
458 /* daemonize implies close_all_fds so set it */
460 c
->lxc_conf
->close_all_fds
= 1;
461 container_mem_unlock(c
);
465 static bool lxcapi_want_close_all_fds(struct lxc_container
*c
, bool state
)
467 if (!c
|| !c
->lxc_conf
)
469 if (container_mem_lock(c
)) {
470 ERROR("Error getting mem lock");
473 c
->lxc_conf
->close_all_fds
= state
;
474 container_mem_unlock(c
);
478 static bool lxcapi_wait(struct lxc_container
*c
, const char *state
, int timeout
)
485 ret
= lxc_wait(c
->name
, state
, timeout
, c
->config_path
);
490 static bool wait_on_daemonized_start(struct lxc_container
*c
, int pid
)
492 /* we'll probably want to make this timeout configurable? */
493 int timeout
= 5, ret
, status
;
496 * our child is going to fork again, then exit. reap the
499 ret
= waitpid(pid
, &status
, 0);
500 if (ret
== -1 || !WIFEXITED(status
) || WEXITSTATUS(status
) != 0)
501 DEBUG("failed waiting for first dual-fork child");
502 return lxcapi_wait(c
, "RUNNING", timeout
);
505 static bool am_single_threaded(void)
507 struct dirent dirent
, *direntp
;
511 dir
= opendir("/proc/self/task");
513 INFO("failed to open /proc/self/task");
517 while (!readdir_r(dir
, &dirent
, &direntp
)) {
521 if (!strcmp(direntp
->d_name
, "."))
524 if (!strcmp(direntp
->d_name
, ".."))
534 * I can't decide if it'd be more convenient for callers if we accept '...',
535 * or a null-terminated array (i.e. execl vs execv)
537 static bool lxcapi_start(struct lxc_container
*c
, int useinit
, char * const argv
[])
540 struct lxc_conf
*conf
;
541 bool daemonize
= false;
542 char *default_args
[] = {
547 /* container exists */
550 /* container has been setup */
554 if ((ret
= ongoing_create(c
)) < 0) {
555 ERROR("Error checking for incomplete creation");
559 ERROR("Error: %s creation was not completed", c
->name
);
562 } else if (ret
== 1) {
563 ERROR("Error: creation of %s is ongoing", c
->name
);
567 /* is this app meant to be run through lxcinit, as in lxc-execute? */
568 if (useinit
&& !argv
)
571 if (container_mem_lock(c
))
574 daemonize
= c
->daemonize
;
575 container_mem_unlock(c
);
578 ret
= lxc_execute(c
->name
, argv
, 1, conf
, c
->config_path
);
579 return ret
== 0 ? true : false;
586 * say, I'm not sure - what locks do we want here? Any?
587 * Is liblxc's locking enough here to protect the on disk
588 * container? We don't want to exclude things like lxc_info
589 * while container is running...
592 if (!lxc_container_get(c
))
594 lxc_monitord_spawn(c
->config_path
);
598 lxc_container_put(c
);
602 return wait_on_daemonized_start(c
, pid
);
604 /* second fork to be reparented by init */
607 SYSERROR("Error doing dual-fork");
612 /* like daemon(), chdir to / and redirect 0,1,2 to /dev/null */
614 SYSERROR("Error chdir()ing to /.");
620 open("/dev/zero", O_RDONLY
);
621 open("/dev/null", O_RDWR
);
622 open("/dev/null", O_RDWR
);
625 if (!am_single_threaded()) {
626 ERROR("Cannot start non-daemonized container when threaded");
633 ret
= lxc_start(c
->name
, argv
, conf
, c
->config_path
);
636 INFO("container requested reboot");
642 lxc_container_put(c
);
643 exit (ret
== 0 ? true : false);
645 return (ret
== 0 ? true : false);
650 * note there MUST be an ending NULL
652 static bool lxcapi_startl(struct lxc_container
*c
, int useinit
, ...)
655 char **inargs
= NULL
;
658 /* container exists */
662 va_start(ap
, useinit
);
663 inargs
= lxc_va_arg_list_to_argv(ap
, 0, 1);
667 ERROR("Memory allocation error.");
671 /* pass NULL if no arguments were supplied */
672 bret
= lxcapi_start(c
, useinit
, *inargs
? inargs
: NULL
);
677 for (arg
= inargs
; *arg
; arg
++)
685 static bool lxcapi_stop(struct lxc_container
*c
)
692 ret
= lxc_cmd_stop(c
->name
, c
->config_path
);
698 * create the standard expected container dir
700 static bool create_container_dir(struct lxc_container
*c
)
705 len
= strlen(c
->config_path
) + strlen(c
->name
) + 2;
709 ret
= snprintf(s
, len
, "%s/%s", c
->config_path
, c
->name
);
710 if (ret
< 0 || ret
>= len
) {
714 ret
= mkdir(s
, 0755);
719 SYSERROR("failed to create container path for %s\n", c
->name
);
725 static const char *lxcapi_get_config_path(struct lxc_container
*c
);
726 static bool lxcapi_set_config_item(struct lxc_container
*c
, const char *key
, const char *v
);
729 * do_bdev_create: thin wrapper around bdev_create(). Like bdev_create(),
730 * it returns a mounted bdev on success, NULL on error.
732 static struct bdev
*do_bdev_create(struct lxc_container
*c
, const char *type
,
733 struct bdev_specs
*specs
)
740 /* rootfs.path or lxcpath/lxcname/rootfs */
741 if (c
->lxc_conf
->rootfs
.path
&& access(c
->lxc_conf
->rootfs
.path
, F_OK
) == 0) {
742 const char *rpath
= c
->lxc_conf
->rootfs
.path
;
743 len
= strlen(rpath
) + 1;
745 ret
= snprintf(dest
, len
, "%s", rpath
);
747 const char *lxcpath
= lxcapi_get_config_path(c
);
748 len
= strlen(c
->name
) + strlen(lxcpath
) + 9;
750 ret
= snprintf(dest
, len
, "%s/%s/rootfs", lxcpath
, c
->name
);
752 if (ret
< 0 || ret
>= len
)
755 bdev
= bdev_create(dest
, type
, c
->name
, specs
);
757 ERROR("Failed to create backing store type %s\n", type
);
761 lxcapi_set_config_item(c
, "lxc.rootfs", bdev
->src
);
763 /* if we are not root, chown the rootfs dir to root in the
766 if (geteuid() != 0) {
767 if (chown_mapped_root(bdev
->dest
, c
->lxc_conf
) < 0) {
768 ERROR("Error chowning %s to container root\n", bdev
->dest
);
778 * Given the '-t' template option to lxc-create, figure out what to
779 * do. If the template is a full executable path, use that. If it
780 * is something like 'sshd', then return $templatepath/lxc-sshd.
781 * On success return the template, on error return NULL.
783 static char *get_template_path(const char *t
)
788 if (t
[0] == '/' && access(t
, X_OK
) == 0) {
793 len
= strlen(LXCTEMPLATEDIR
) + strlen(t
) + strlen("/lxc-") + 1;
797 ret
= snprintf(tpath
, len
, "%s/lxc-%s", LXCTEMPLATEDIR
, t
);
798 if (ret
< 0 || ret
>= len
) {
802 if (access(tpath
, X_OK
) < 0) {
803 SYSERROR("bad template: %s\n", t
);
811 static char *lxcbasename(char *path
)
813 char *p
= path
+ strlen(path
) - 1;
814 while (*p
!= '/' && p
> path
)
819 static bool create_run_template(struct lxc_container
*c
, char *tpath
, bool quiet
,
829 SYSERROR("failed to fork task for container creation template\n");
833 if (pid
== 0) { // child
834 char *patharg
, *namearg
, *rootfsarg
, *src
;
835 struct bdev
*bdev
= NULL
;
837 int ret
, len
, nargs
= 0;
839 struct lxc_conf
*conf
= c
->lxc_conf
;
845 open("/dev/zero", O_RDONLY
);
846 open("/dev/null", O_RDWR
);
847 open("/dev/null", O_RDWR
);
850 src
= c
->lxc_conf
->rootfs
.path
;
852 * for an overlayfs create, what the user wants is the template to fill
853 * in what will become the readonly lower layer. So don't mount for
856 if (strncmp(src
, "overlayfs:", 10) == 0) {
857 src
= overlayfs_getlower(src
+10);
859 bdev
= bdev_init(src
, c
->lxc_conf
->rootfs
.mount
, NULL
);
861 ERROR("Error opening rootfs");
865 if (geteuid() == 0) {
866 if (unshare(CLONE_NEWNS
) < 0) {
867 ERROR("error unsharing mounts");
870 if (detect_shared_rootfs()) {
871 if (mount("", "", NULL
, MS_SLAVE
|MS_REC
, 0)) {
872 SYSERROR("Failed to make / rslave to run template");
873 ERROR("Continuing...");
877 if (strcmp(bdev
->type
, "dir") != 0) {
878 if (geteuid() != 0) {
879 ERROR("non-root users can only create directory-backed containers");
882 if (bdev
->ops
->mount(bdev
) < 0) {
883 ERROR("Error mounting rootfs");
886 } else { // TODO come up with a better way here!
889 bdev
->dest
= strdup(bdev
->src
);
893 * create our new array, pre-pend the template name and
897 for (nargs
= 0; argv
[nargs
]; nargs
++) ;
898 nargs
+= 4; // template, path, rootfs and name args
900 newargv
= malloc(nargs
* sizeof(*newargv
));
903 newargv
[0] = lxcbasename(tpath
);
905 len
= strlen(c
->config_path
) + strlen(c
->name
) + strlen("--path=") + 2;
906 patharg
= malloc(len
);
909 ret
= snprintf(patharg
, len
, "--path=%s/%s", c
->config_path
, c
->name
);
910 if (ret
< 0 || ret
>= len
)
912 newargv
[1] = patharg
;
913 len
= strlen("--name=") + strlen(c
->name
) + 1;
914 namearg
= malloc(len
);
917 ret
= snprintf(namearg
, len
, "--name=%s", c
->name
);
918 if (ret
< 0 || ret
>= len
)
920 newargv
[2] = namearg
;
922 len
= strlen("--rootfs=") + 1 + strlen(bdev
->dest
);
923 rootfsarg
= malloc(len
);
926 ret
= snprintf(rootfsarg
, len
, "--rootfs=%s", bdev
->dest
);
927 if (ret
< 0 || ret
>= len
)
929 newargv
[3] = rootfsarg
;
931 /* add passed-in args */
933 for (i
= 4; i
< nargs
; i
++)
934 newargv
[i
] = argv
[i
-4];
936 /* add trailing NULL */
938 newargv
= realloc(newargv
, nargs
* sizeof(*newargv
));
941 newargv
[nargs
- 1] = NULL
;
944 * If we're running the template in a mapped userns, then
945 * we prepend the template command with:
946 * lxc-usernsexec <-m map1> ... <-m mapn> --
947 * and we append "--mapped-uid x", where x is the mapped uid
950 if (geteuid() != 0 && !lxc_list_empty(&conf
->id_map
)) {
953 char **n2
= malloc(n2args
* sizeof(*n2
));
958 SYSERROR("out of memory");
962 tpath
= "lxc-usernsexec";
963 n2
[0] = "lxc-usernsexec";
964 lxc_list_for_each(it
, &conf
->id_map
) {
967 n2
= realloc(n2
, n2args
* sizeof(char *));
971 n2
[n2args
-1] = malloc(200);
974 ret
= snprintf(n2
[n2args
-1], 200, "%c:%lu:%lu:%lu",
975 map
->idtype
== ID_TYPE_UID
? 'u' : 'g',
976 map
->nsid
, map
->hostid
, map
->range
);
977 if (ret
< 0 || ret
>= 200)
980 int hostid_mapped
= mapped_hostid(geteuid(), conf
);
981 int extraargs
= hostid_mapped
>= 0 ? 1 : 3;
982 n2
= realloc(n2
, (nargs
+ n2args
+ extraargs
) * sizeof(char *));
985 if (hostid_mapped
< 0) {
986 hostid_mapped
= find_unmapped_nsuid(conf
);
988 if (hostid_mapped
< 0) {
989 ERROR("Could not find free uid to map");
992 n2
[n2args
++] = malloc(200);
994 SYSERROR("out of memory");
997 ret
= snprintf(n2
[n2args
-1], 200, "u:%d:%d:1",
998 hostid_mapped
, geteuid());
999 if (ret
< 0 || ret
>= 200) {
1000 ERROR("string too long");
1004 n2
[n2args
++] = "--";
1005 for (i
= 0; i
< nargs
; i
++)
1006 n2
[i
+ n2args
] = newargv
[i
];
1008 // Finally add "--mapped-uid $uid" to tell template what to chown
1011 n2
= realloc(n2
, n2args
* sizeof(char *));
1013 SYSERROR("out of memory");
1016 // note n2[n2args-1] is NULL
1017 n2
[n2args
-3] = "--mapped-uid";
1018 snprintf(txtuid
, 20, "%d", hostid_mapped
);
1019 n2
[n2args
-2] = txtuid
;
1020 n2
[n2args
-1] = NULL
;
1025 execvp(tpath
, newargv
);
1026 SYSERROR("failed to execute template %s", tpath
);
1030 if (wait_for_pid(pid
) != 0) {
1031 ERROR("container creation template for %s failed\n", c
->name
);
1038 static bool prepend_lxc_header(char *path
, const char *t
, char *const argv
[])
1046 unsigned char md_value
[SHA_DIGEST_LENGTH
];
1050 f
= fopen(path
, "r");
1054 if (fseek(f
, 0, SEEK_END
) < 0)
1056 if ((flen
= ftell(f
)) < 0)
1058 if (fseek(f
, 0, SEEK_SET
) < 0)
1060 if ((contents
= malloc(flen
+ 1)) == NULL
)
1062 if (fread(contents
, 1, flen
, f
) != flen
)
1063 goto out_free_contents
;
1065 contents
[flen
] = '\0';
1069 goto out_free_contents
;
1072 tpath
= get_template_path(t
);
1074 ERROR("bad template: %s\n", t
);
1075 goto out_free_contents
;
1078 ret
= sha1sum_file(tpath
, md_value
);
1080 ERROR("Error getting sha1sum of %s", tpath
);
1082 goto out_free_contents
;
1087 f
= fopen(path
, "w");
1089 SYSERROR("reopening config for writing");
1093 fprintf(f
, "# Template used to create this container: %s\n", t
);
1095 fprintf(f
, "# Parameters passed to the template:");
1097 fprintf(f
, " %s", *argv
);
1103 fprintf(f
, "# Template script checksum (SHA-1): ");
1104 for (i
=0; i
<SHA_DIGEST_LENGTH
; i
++)
1105 fprintf(f
, "%02x", md_value
[i
]);
1108 fprintf(f
, "# For additional config options, please look at lxc.conf(5)\n");
1109 if (fwrite(contents
, 1, flen
, f
) != flen
) {
1110 SYSERROR("Writing original contents");
1126 SYSERROR("Error prepending header");
1132 static void lxcapi_clear_config(struct lxc_container
*c
)
1134 if (c
&& c
->lxc_conf
) {
1135 lxc_conf_free(c
->lxc_conf
);
1140 static bool lxcapi_destroy(struct lxc_container
*c
);
1143 * create a container with the given parameters.
1144 * @c: container to be created. It has the lxcpath, name, and a starting
1145 * configuration already set
1146 * @t: the template to execute to instantiate the root filesystem and
1147 * adjust the configuration.
1148 * @bdevtype: backing store type to use. If NULL, dir will be used.
1149 * @specs: additional parameters for the backing store, i.e. LVM vg to
1152 * @argv: the arguments to pass to the template, terminated by NULL. If no
1153 * arguments, you can just pass NULL.
1155 static bool lxcapi_create(struct lxc_container
*c
, const char *t
,
1156 const char *bdevtype
, struct bdev_specs
*specs
, int flags
,
1168 tpath
= get_template_path(t
);
1170 ERROR("bad template: %s\n", t
);
1176 * If a template is passed in, and the rootfs already is defined in
1177 * the container config and exists, then * caller is trying to create
1178 * an existing container. Return an error, but do NOT delete the
1181 if (lxcapi_is_defined(c
) && c
->lxc_conf
&& c
->lxc_conf
->rootfs
.path
&&
1182 access(c
->lxc_conf
->rootfs
.path
, F_OK
) == 0 && tpath
) {
1183 ERROR("Container %s:%s already exists", c
->config_path
, c
->name
);
1188 if (!c
->load_config(c
, LXC_DEFAULT_CONFIG
)) {
1189 ERROR("Error loading default configuration file %s\n", LXC_DEFAULT_CONFIG
);
1194 if (!create_container_dir(c
))
1198 * either template or rootfs.path should be set.
1199 * if both template and rootfs.path are set, template is setup as rootfs.path.
1200 * container is already created if we have a config and rootfs.path is accessible
1202 if (!c
->lxc_conf
->rootfs
.path
&& !tpath
)
1203 /* no template passed in and rootfs does not exist: error */
1205 if (c
->lxc_conf
->rootfs
.path
&& access(c
->lxc_conf
->rootfs
.path
, F_OK
) != 0)
1206 /* rootfs passed into configuration, but does not exist: error */
1208 if (lxcapi_is_defined(c
) && c
->lxc_conf
->rootfs
.path
&& !tpath
) {
1209 /* Rootfs already existed, user just wanted to save the
1210 * loaded configuration */
1215 /* Mark that this container is being created */
1216 if ((partial_fd
= create_partial(c
)) < 0)
1219 /* no need to get disk lock bc we have the partial locked */
1222 * Create the backing store
1223 * Note we can't do this in the same task as we use to execute the
1224 * template because of the way zfs works.
1225 * After you 'zfs create', zfs mounts the fs only in the initial
1230 SYSERROR("failed to fork task for container creation template\n");
1234 if (pid
== 0) { // child
1235 struct bdev
*bdev
= NULL
;
1237 if (!(bdev
= do_bdev_create(c
, bdevtype
, specs
))) {
1238 ERROR("Error creating backing store type %s for %s",
1239 bdevtype
? bdevtype
: "(none)", c
->name
);
1243 /* save config file again to store the new rootfs location */
1244 if (!c
->save_config(c
, NULL
)) {
1245 ERROR("failed to save starting configuration for %s\n", c
->name
);
1246 // parent task won't see bdev in config so we delete it
1247 bdev
->ops
->umount(bdev
);
1248 bdev
->ops
->destroy(bdev
);
1253 if (wait_for_pid(pid
) != 0)
1256 /* reload config to get the rootfs */
1257 lxc_conf_free(c
->lxc_conf
);
1259 if (!load_config_locked(c
, c
->configfile
))
1262 if (!create_run_template(c
, tpath
, !!(flags
& LXC_CREATE_QUIET
), argv
))
1265 // now clear out the lxc_conf we have, reload from the created
1267 lxcapi_clear_config(c
);
1270 if (!prepend_lxc_header(c
->configfile
, tpath
, argv
)) {
1271 ERROR("Error prepending header to configuration file");
1275 ret
= load_config_locked(c
, c
->configfile
);
1278 if (partial_fd
>= 0)
1279 remove_partial(c
, partial_fd
);
1289 static bool lxcapi_reboot(struct lxc_container
*c
)
1295 if (!c
->is_running(c
))
1297 pid
= c
->init_pid(c
);
1300 if (kill(pid
, SIGINT
) < 0)
1306 static bool lxcapi_shutdown(struct lxc_container
*c
, int timeout
)
1316 if (!c
->is_running(c
))
1318 pid
= c
->init_pid(c
);
1322 retv
= c
->wait(c
, "STOPPED", timeout
);
1323 if (!retv
&& timeout
> 0) {
1325 retv
= c
->wait(c
, "STOPPED", 0); // 0 means don't wait
1330 static bool lxcapi_createl(struct lxc_container
*c
, const char *t
,
1331 const char *bdevtype
, struct bdev_specs
*specs
, int flags
, ...)
1341 * since we're going to wait for create to finish, I don't think we
1342 * need to get a copy of the arguments.
1344 va_start(ap
, flags
);
1345 args
= lxc_va_arg_list_to_argv(ap
, 0, 0);
1348 ERROR("Memory allocation error.");
1352 bret
= c
->create(c
, t
, bdevtype
, specs
, flags
, args
);
1359 static bool lxcapi_clear_config_item(struct lxc_container
*c
, const char *key
)
1363 if (!c
|| !c
->lxc_conf
)
1365 if (container_mem_lock(c
))
1367 ret
= lxc_clear_config_item(c
->lxc_conf
, key
);
1368 container_mem_unlock(c
);
1372 static inline void exit_from_ns(struct lxc_container
*c
, int *old_netns
, int *new_netns
) {
1373 /* Switch back to original netns */
1374 if (*old_netns
>= 0 && setns(*old_netns
, CLONE_NEWNET
))
1375 SYSERROR("failed to setns");
1376 if (*new_netns
>= 0)
1378 if (*old_netns
>= 0)
1382 static inline bool enter_to_ns(struct lxc_container
*c
, int *old_netns
, int *new_netns
) {
1384 char new_netns_path
[MAXPATHLEN
];
1386 if (!c
->is_running(c
))
1389 /* Save reference to old netns */
1390 *old_netns
= open("/proc/self/ns/net", O_RDONLY
);
1391 if (*old_netns
< 0) {
1392 SYSERROR("failed to open /proc/self/ns/net");
1396 /* Switch to new netns */
1397 ret
= snprintf(new_netns_path
, MAXPATHLEN
, "/proc/%d/ns/net", c
->init_pid(c
));
1398 if (ret
< 0 || ret
>= MAXPATHLEN
)
1401 *new_netns
= open(new_netns_path
, O_RDONLY
);
1402 if (*new_netns
< 0) {
1403 SYSERROR("failed to open %s", new_netns_path
);
1407 if (setns(*new_netns
, CLONE_NEWNET
)) {
1408 SYSERROR("failed to setns");
1413 exit_from_ns(c
, old_netns
, new_netns
);
1417 // used by qsort and bsearch functions for comparing names
1418 static inline int string_cmp(char **first
, char **second
)
1420 return strcmp(*first
, *second
);
1423 // used by qsort and bsearch functions for comparing container names
1424 static inline int container_cmp(struct lxc_container
**first
, struct lxc_container
**second
)
1426 return strcmp((*first
)->name
, (*second
)->name
);
1429 static bool add_to_array(char ***names
, char *cname
, int pos
)
1431 char **newnames
= realloc(*names
, (pos
+1) * sizeof(char *));
1433 ERROR("Out of memory");
1438 newnames
[pos
] = strdup(cname
);
1442 // sort the arrray as we will use binary search on it
1443 qsort(newnames
, pos
+ 1, sizeof(char *), (int (*)(const void *,const void *))string_cmp
);
1448 static bool add_to_clist(struct lxc_container
***list
, struct lxc_container
*c
, int pos
, bool sort
)
1450 struct lxc_container
**newlist
= realloc(*list
, (pos
+1) * sizeof(struct lxc_container
*));
1452 ERROR("Out of memory");
1459 // sort the arrray as we will use binary search on it
1461 qsort(newlist
, pos
+ 1, sizeof(struct lxc_container
*), (int (*)(const void *,const void *))container_cmp
);
1466 static char** get_from_array(char ***names
, char *cname
, int size
)
1468 return (char **)bsearch(&cname
, *names
, size
, sizeof(char *), (int (*)(const void *, const void *))string_cmp
);
1472 static bool array_contains(char ***names
, char *cname
, int size
) {
1473 if(get_from_array(names
, cname
, size
) != NULL
)
1478 static bool remove_from_array(char ***names
, char *cname
, int size
)
1480 char **result
= get_from_array(names
, cname
, size
);
1481 if (result
!= NULL
) {
1488 static char** lxcapi_get_interfaces(struct lxc_container
*c
)
1491 struct ifaddrs
*interfaceArray
= NULL
, *tempIfAddr
= NULL
;
1492 char **interfaces
= NULL
;
1493 int old_netns
= -1, new_netns
= -1;
1495 if (!enter_to_ns(c
, &old_netns
, &new_netns
))
1498 /* Grab the list of interfaces */
1499 if (getifaddrs(&interfaceArray
)) {
1500 SYSERROR("failed to get interfaces list");
1504 /* Iterate through the interfaces */
1505 for (tempIfAddr
= interfaceArray
; tempIfAddr
!= NULL
; tempIfAddr
= tempIfAddr
->ifa_next
) {
1506 if (array_contains(&interfaces
, tempIfAddr
->ifa_name
, count
))
1509 if(!add_to_array(&interfaces
, tempIfAddr
->ifa_name
, count
))
1516 freeifaddrs(interfaceArray
);
1518 exit_from_ns(c
, &old_netns
, &new_netns
);
1520 /* Append NULL to the array */
1522 interfaces
= (char **)lxc_append_null_to_array((void **)interfaces
, count
);
1527 for(i
=0;i
<count
;i
++)
1528 free(interfaces
[i
]);
1534 static char** lxcapi_get_ips(struct lxc_container
*c
, const char* interface
, const char* family
, int scope
)
1537 struct ifaddrs
*interfaceArray
= NULL
, *tempIfAddr
= NULL
;
1538 char addressOutputBuffer
[INET6_ADDRSTRLEN
];
1539 void *tempAddrPtr
= NULL
;
1540 char **addresses
= NULL
;
1541 char *address
= NULL
;
1542 int old_netns
= -1, new_netns
= -1;
1544 if (!enter_to_ns(c
, &old_netns
, &new_netns
))
1547 /* Grab the list of interfaces */
1548 if (getifaddrs(&interfaceArray
)) {
1549 SYSERROR("failed to get interfaces list");
1553 /* Iterate through the interfaces */
1554 for (tempIfAddr
= interfaceArray
; tempIfAddr
!= NULL
; tempIfAddr
= tempIfAddr
->ifa_next
) {
1555 if (tempIfAddr
->ifa_addr
== NULL
)
1558 if(tempIfAddr
->ifa_addr
->sa_family
== AF_INET
) {
1559 if (family
&& strcmp(family
, "inet"))
1561 tempAddrPtr
= &((struct sockaddr_in
*)tempIfAddr
->ifa_addr
)->sin_addr
;
1564 if (family
&& strcmp(family
, "inet6"))
1567 if (((struct sockaddr_in6
*)tempIfAddr
->ifa_addr
)->sin6_scope_id
!= scope
)
1570 tempAddrPtr
= &((struct sockaddr_in6
*)tempIfAddr
->ifa_addr
)->sin6_addr
;
1573 if (interface
&& strcmp(interface
, tempIfAddr
->ifa_name
))
1575 else if (!interface
&& strcmp("lo", tempIfAddr
->ifa_name
) == 0)
1578 address
= (char *)inet_ntop(tempIfAddr
->ifa_addr
->sa_family
,
1580 addressOutputBuffer
,
1581 sizeof(addressOutputBuffer
));
1585 if(!add_to_array(&addresses
, address
, count
))
1592 freeifaddrs(interfaceArray
);
1594 exit_from_ns(c
, &old_netns
, &new_netns
);
1596 /* Append NULL to the array */
1598 addresses
= (char **)lxc_append_null_to_array((void **)addresses
, count
);
1603 for(i
=0;i
<count
;i
++)
1611 static int lxcapi_get_config_item(struct lxc_container
*c
, const char *key
, char *retv
, int inlen
)
1615 if (!c
|| !c
->lxc_conf
)
1617 if (container_mem_lock(c
))
1619 ret
= lxc_get_config_item(c
->lxc_conf
, key
, retv
, inlen
);
1620 container_mem_unlock(c
);
1624 static int lxcapi_get_keys(struct lxc_container
*c
, const char *key
, char *retv
, int inlen
)
1627 return lxc_listconfigs(retv
, inlen
);
1629 * Support 'lxc.network.<idx>', i.e. 'lxc.network.0'
1630 * This is an intelligent result to show which keys are valid given
1631 * the type of nic it is
1633 if (!c
|| !c
->lxc_conf
)
1635 if (container_mem_lock(c
))
1638 if (strncmp(key
, "lxc.network.", 12) == 0)
1639 ret
= lxc_list_nicconfigs(c
->lxc_conf
, key
, retv
, inlen
);
1640 container_mem_unlock(c
);
1644 static bool lxcapi_save_config(struct lxc_container
*c
, const char *alt_file
)
1647 bool ret
= false, need_disklock
= false;
1651 alt_file
= c
->configfile
;
1653 return false; // should we write to stdout if no file is specified?
1655 // If we haven't yet loaded a config, load the stock config
1657 if (!c
->load_config(c
, LXC_DEFAULT_CONFIG
)) {
1658 ERROR("Error loading default configuration file %s while saving %s\n", LXC_DEFAULT_CONFIG
, c
->name
);
1663 if (!create_container_dir(c
))
1667 * If we're writing to the container's config file, take the
1668 * disk lock. Otherwise just take the memlock to protect the
1669 * struct lxc_container while we're traversing it.
1671 if (strcmp(c
->configfile
, alt_file
) == 0)
1672 need_disklock
= true;
1675 lret
= container_disk_lock(c
);
1677 lret
= container_mem_lock(c
);
1682 fout
= fopen(alt_file
, "w");
1685 write_config(fout
, c
->lxc_conf
);
1691 container_disk_unlock(c
);
1693 container_mem_unlock(c
);
1697 static bool mod_rdep(struct lxc_container
*c
, bool inc
)
1699 char path
[MAXPATHLEN
];
1704 if (container_disk_lock(c
))
1706 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_snapshots", c
->config_path
,
1708 if (ret
< 0 || ret
> MAXPATHLEN
)
1710 f
= fopen(path
, "r");
1712 ret
= fscanf(f
, "%d", &v
);
1715 ERROR("Corrupted file %s", path
);
1720 f
= fopen(path
, "w");
1723 if (fprintf(f
, "%d\n", v
) < 0) {
1724 ERROR("Error writing new snapshots value");
1730 SYSERROR("Error writing to or closing snapshots file");
1737 container_disk_unlock(c
);
1741 static void strip_newline(char *p
)
1743 size_t len
= strlen(p
);
1746 if (p
[len
-1] == '\n')
1750 static void mod_all_rdeps(struct lxc_container
*c
, bool inc
)
1752 struct lxc_container
*p
;
1753 char *lxcpath
= NULL
, *lxcname
= NULL
, path
[MAXPATHLEN
];
1754 size_t pathlen
= 0, namelen
= 0;
1758 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_rdepends",
1759 c
->config_path
, c
->name
);
1760 if (ret
< 0 || ret
>= MAXPATHLEN
) {
1761 ERROR("Path name too long");
1764 f
= fopen(path
, "r");
1767 while (getline(&lxcpath
, &pathlen
, f
) != -1) {
1768 if (getline(&lxcname
, &namelen
, f
) == -1) {
1769 ERROR("badly formatted file %s\n", path
);
1772 strip_newline(lxcpath
);
1773 strip_newline(lxcname
);
1774 if ((p
= lxc_container_new(lxcname
, lxcpath
)) == NULL
) {
1775 ERROR("Unable to find dependent container %s:%s",
1779 if (!mod_rdep(p
, inc
))
1780 ERROR("Failed to increase numsnapshots for %s:%s",
1782 lxc_container_put(p
);
1785 if (lxcpath
) free(lxcpath
);
1786 if (lxcname
) free(lxcname
);
1790 static bool has_snapshots(struct lxc_container
*c
)
1792 char path
[MAXPATHLEN
];
1797 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_snapshots", c
->config_path
,
1799 if (ret
< 0 || ret
> MAXPATHLEN
)
1801 f
= fopen(path
, "r");
1804 ret
= fscanf(f
, "%d", &v
);
1814 static int lxc_rmdir_onedev_wrapper(void *data
)
1816 char *arg
= (char *) data
;
1817 return lxc_rmdir_onedev(arg
);
1820 // do we want the api to support --force, or leave that to the caller?
1821 static bool lxcapi_destroy(struct lxc_container
*c
)
1823 struct bdev
*r
= NULL
;
1824 bool bret
= false, am_unpriv
;
1827 if (!c
|| !lxcapi_is_defined(c
))
1830 if (container_disk_lock(c
))
1833 if (!is_stopped(c
)) {
1834 // we should queue some sort of error - in c->error_string?
1835 ERROR("container %s is not stopped", c
->name
);
1839 am_unpriv
= c
->lxc_conf
&& geteuid() != 0 && !lxc_list_empty(&c
->lxc_conf
->id_map
);
1841 if (c
->lxc_conf
&& has_snapshots(c
)) {
1842 ERROR("container %s has dependent snapshots", c
->name
);
1846 if (!am_unpriv
&& c
->lxc_conf
->rootfs
.path
&& c
->lxc_conf
->rootfs
.mount
) {
1847 r
= bdev_init(c
->lxc_conf
->rootfs
.path
, c
->lxc_conf
->rootfs
.mount
, NULL
);
1849 if (r
->ops
->destroy(r
) < 0) {
1851 ERROR("Error destroying rootfs for %s", c
->name
);
1858 mod_all_rdeps(c
, false);
1860 const char *p1
= lxcapi_get_config_path(c
);
1861 char *path
= alloca(strlen(p1
) + strlen(c
->name
) + 2);
1862 sprintf(path
, "%s/%s", p1
, c
->name
);
1864 ret
= userns_exec_1(c
->lxc_conf
, lxc_rmdir_onedev_wrapper
, path
);
1866 ret
= lxc_rmdir_onedev(path
);
1868 ERROR("Error destroying container directory for %s", c
->name
);
1874 container_disk_unlock(c
);
1878 static bool set_config_item_locked(struct lxc_container
*c
, const char *key
, const char *v
)
1880 struct lxc_config_t
*config
;
1883 c
->lxc_conf
= lxc_conf_init();
1886 config
= lxc_getconfig(key
);
1889 return (0 == config
->cb(key
, v
, c
->lxc_conf
));
1892 static bool lxcapi_set_config_item(struct lxc_container
*c
, const char *key
, const char *v
)
1899 if (container_mem_lock(c
))
1902 b
= set_config_item_locked(c
, key
, v
);
1904 container_mem_unlock(c
);
1908 static char *lxcapi_config_file_name(struct lxc_container
*c
)
1910 if (!c
|| !c
->configfile
)
1912 return strdup(c
->configfile
);
1915 static const char *lxcapi_get_config_path(struct lxc_container
*c
)
1917 if (!c
|| !c
->config_path
)
1919 return (const char *)(c
->config_path
);
1924 * Just recalculate the c->configfile based on the
1925 * c->config_path, which must be set.
1926 * The lxc_container must be locked or not yet public.
1928 static bool set_config_filename(struct lxc_container
*c
)
1933 if (!c
->config_path
)
1936 /* $lxc_path + "/" + c->name + "/" + "config" + '\0' */
1937 len
= strlen(c
->config_path
) + strlen(c
->name
) + strlen("config") + 3;
1938 newpath
= malloc(len
);
1942 ret
= snprintf(newpath
, len
, "%s/%s/config", c
->config_path
, c
->name
);
1943 if (ret
< 0 || ret
>= len
) {
1944 fprintf(stderr
, "Error printing out config file name\n");
1950 free(c
->configfile
);
1951 c
->configfile
= newpath
;
1956 static bool lxcapi_set_config_path(struct lxc_container
*c
, const char *path
)
1960 char *oldpath
= NULL
;
1965 if (container_mem_lock(c
))
1970 ERROR("Out of memory setting new lxc path");
1976 oldpath
= c
->config_path
;
1979 /* Since we've changed the config path, we have to change the
1980 * config file name too */
1981 if (!set_config_filename(c
)) {
1982 ERROR("Out of memory setting new config filename");
1984 free(c
->config_path
);
1985 c
->config_path
= oldpath
;
1991 container_mem_unlock(c
);
1996 static bool lxcapi_set_cgroup_item(struct lxc_container
*c
, const char *subsys
, const char *value
)
2006 if (container_disk_lock(c
))
2009 ret
= lxc_cgroup_set(subsys
, value
, c
->name
, c
->config_path
);
2011 container_disk_unlock(c
);
2015 static int lxcapi_get_cgroup_item(struct lxc_container
*c
, const char *subsys
, char *retv
, int inlen
)
2025 if (container_disk_lock(c
))
2028 ret
= lxc_cgroup_get(subsys
, retv
, inlen
, c
->name
, c
->config_path
);
2030 container_disk_unlock(c
);
2034 const char *lxc_get_default_config_path(void)
2036 return default_lxc_path();
2039 const char *lxc_get_default_lvm_vg(void)
2041 return default_lvm_vg();
2044 const char *lxc_get_default_lvm_thin_pool(void)
2046 return default_lvm_thin_pool();
2049 const char *lxc_get_default_zfs_root(void)
2051 return default_zfs_root();
2054 const char *lxc_get_version(void)
2059 static int copy_file(const char *old
, const char *new)
2066 if (file_exists(new)) {
2067 ERROR("copy destination %s exists", new);
2070 ret
= stat(old
, &sbuf
);
2072 INFO("Error stat'ing %s", old
);
2076 in
= open(old
, O_RDONLY
);
2078 SYSERROR("Error opening original file %s", old
);
2081 out
= open(new, O_CREAT
| O_EXCL
| O_WRONLY
, 0644);
2083 SYSERROR("Error opening new file %s", new);
2089 len
= read(in
, buf
, 8096);
2091 SYSERROR("Error reading old file %s", old
);
2096 ret
= write(out
, buf
, len
);
2097 if (ret
< len
) { // should we retry?
2098 SYSERROR("Error: write to new file %s was interrupted", new);
2105 // we set mode, but not owner/group
2106 ret
= chmod(new, sbuf
.st_mode
);
2108 SYSERROR("Error setting mode on %s", new);
2120 static int copyhooks(struct lxc_container
*oldc
, struct lxc_container
*c
)
2123 struct lxc_list
*it
;
2126 len
= strlen(oldc
->config_path
) + strlen(oldc
->name
) + 3;
2127 cpath
= alloca(len
);
2128 ret
= snprintf(cpath
, len
, "%s/%s/", oldc
->config_path
, oldc
->name
);
2129 if (ret
< 0 || ret
>= len
)
2132 for (i
=0; i
<NUM_LXC_HOOKS
; i
++) {
2133 lxc_list_for_each(it
, &c
->lxc_conf
->hooks
[i
]) {
2134 char *hookname
= it
->elem
;
2135 char *fname
= strrchr(hookname
, '/');
2136 char tmppath
[MAXPATHLEN
];
2137 if (!fname
) // relative path - we don't support, but maybe we should
2139 if (strncmp(hookname
, cpath
, len
- 1) != 0) {
2140 // this hook is public - ignore
2143 // copy the script, and change the entry in confile
2144 ret
= snprintf(tmppath
, MAXPATHLEN
, "%s/%s/%s",
2145 c
->config_path
, c
->name
, fname
+1);
2146 if (ret
< 0 || ret
>= MAXPATHLEN
)
2148 ret
= copy_file(it
->elem
, tmppath
);
2152 it
->elem
= strdup(tmppath
);
2154 ERROR("out of memory copying hook path");
2160 c
->save_config(c
, NULL
);
2164 static void new_hwaddr(char *hwaddr
)
2167 f
= fopen("/dev/urandom", "r");
2170 int ret
= fread(&seed
, sizeof(seed
), 1, f
);
2177 snprintf(hwaddr
, 18, "00:16:3e:%02x:%02x:%02x",
2178 rand() % 255, rand() % 255, rand() % 255);
2181 static void network_new_hwaddrs(struct lxc_container
*c
)
2183 struct lxc_list
*it
;
2185 lxc_list_for_each(it
, &c
->lxc_conf
->network
) {
2186 struct lxc_netdev
*n
= it
->elem
;
2188 new_hwaddr(n
->hwaddr
);
2192 static int copy_fstab(struct lxc_container
*oldc
, struct lxc_container
*c
)
2194 char newpath
[MAXPATHLEN
];
2195 char *oldpath
= oldc
->lxc_conf
->fstab
;
2201 char *p
= strrchr(oldpath
, '/');
2204 ret
= snprintf(newpath
, MAXPATHLEN
, "%s/%s%s",
2205 c
->config_path
, c
->name
, p
);
2206 if (ret
< 0 || ret
>= MAXPATHLEN
) {
2207 ERROR("error printing new path for %s", oldpath
);
2210 if (file_exists(newpath
)) {
2211 ERROR("error: fstab file %s exists", newpath
);
2215 if (copy_file(oldpath
, newpath
) < 0) {
2216 ERROR("error: copying %s to %s", oldpath
, newpath
);
2219 free(c
->lxc_conf
->fstab
);
2220 c
->lxc_conf
->fstab
= strdup(newpath
);
2221 if (!c
->lxc_conf
->fstab
) {
2222 ERROR("error: allocating pathname");
2229 static void copy_rdepends(struct lxc_container
*c
, struct lxc_container
*c0
)
2231 char path0
[MAXPATHLEN
], path1
[MAXPATHLEN
];
2234 ret
= snprintf(path0
, MAXPATHLEN
, "%s/%s/lxc_rdepends", c0
->config_path
,
2236 if (ret
< 0 || ret
>= MAXPATHLEN
) {
2237 WARN("Error copying reverse dependencies");
2240 ret
= snprintf(path1
, MAXPATHLEN
, "%s/%s/lxc_rdepends", c
->config_path
,
2242 if (ret
< 0 || ret
>= MAXPATHLEN
) {
2243 WARN("Error copying reverse dependencies");
2246 if (copy_file(path0
, path1
) < 0) {
2247 INFO("Error copying reverse dependencies");
2252 static bool add_rdepends(struct lxc_container
*c
, struct lxc_container
*c0
)
2255 char path
[MAXPATHLEN
];
2259 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_rdepends", c
->config_path
,
2261 if (ret
< 0 || ret
>= MAXPATHLEN
)
2263 f
= fopen(path
, "a");
2267 // if anything goes wrong, just return an error
2268 if (fprintf(f
, "%s\n%s\n", c0
->config_path
, c0
->name
) < 0)
2275 static int copy_storage(struct lxc_container
*c0
, struct lxc_container
*c
,
2276 const char *newtype
, int flags
, const char *bdevdata
, unsigned long newsize
)
2281 bdev
= bdev_copy(c0
->lxc_conf
->rootfs
.path
, c0
->name
, c
->name
,
2282 c0
->config_path
, c
->config_path
, newtype
, flags
,
2283 bdevdata
, newsize
, &need_rdep
);
2285 ERROR("Error copying storage");
2288 free(c
->lxc_conf
->rootfs
.path
);
2289 c
->lxc_conf
->rootfs
.path
= strdup(bdev
->src
);
2291 if (!c
->lxc_conf
->rootfs
.path
) {
2292 ERROR("Out of memory while setting storage path");
2295 if (flags
& LXC_CLONE_SNAPSHOT
)
2296 copy_rdepends(c
, c0
);
2298 if (!add_rdepends(c
, c0
))
2299 WARN("Error adding reverse dependency from %s to %s",
2303 mod_all_rdeps(c
, true);
2308 static int clone_update_rootfs(struct lxc_container
*c0
,
2309 struct lxc_container
*c
, int flags
,
2313 char path
[MAXPATHLEN
];
2317 struct lxc_conf
*conf
= c
->lxc_conf
;
2319 /* update hostname in rootfs */
2320 /* we're going to mount, so run in a clean namespace to simplify cleanup */
2326 return wait_for_pid(pid
);
2328 bdev
= bdev_init(c
->lxc_conf
->rootfs
.path
, c
->lxc_conf
->rootfs
.mount
, NULL
);
2331 if (strcmp(bdev
->type
, "dir") != 0) {
2332 if (unshare(CLONE_NEWNS
) < 0) {
2333 ERROR("error unsharing mounts");
2336 if (bdev
->ops
->mount(bdev
) < 0)
2338 } else { // TODO come up with a better way
2341 bdev
->dest
= strdup(bdev
->src
);
2344 if (!lxc_list_empty(&conf
->hooks
[LXCHOOK_CLONE
])) {
2345 /* Start of environment variable setup for hooks */
2346 if (setenv("LXC_SRC_NAME", c0
->name
, 1)) {
2347 SYSERROR("failed to set environment variable for source container name");
2349 if (setenv("LXC_NAME", c
->name
, 1)) {
2350 SYSERROR("failed to set environment variable for container name");
2352 if (setenv("LXC_CONFIG_FILE", conf
->rcfile
, 1)) {
2353 SYSERROR("failed to set environment variable for config path");
2355 if (setenv("LXC_ROOTFS_MOUNT", bdev
->dest
, 1)) {
2356 SYSERROR("failed to set environment variable for rootfs mount");
2358 if (setenv("LXC_ROOTFS_PATH", conf
->rootfs
.path
, 1)) {
2359 SYSERROR("failed to set environment variable for rootfs mount");
2362 if (run_lxc_hooks(c
->name
, "clone", conf
, c
->get_config_path(c
), hookargs
)) {
2363 ERROR("Error executing clone hook for %s", c
->name
);
2368 if (!(flags
& LXC_CLONE_KEEPNAME
)) {
2369 ret
= snprintf(path
, MAXPATHLEN
, "%s/etc/hostname", bdev
->dest
);
2370 if (ret
< 0 || ret
>= MAXPATHLEN
)
2372 if (!file_exists(path
))
2374 if (!(fout
= fopen(path
, "w"))) {
2375 SYSERROR("unable to open %s: ignoring\n", path
);
2378 if (fprintf(fout
, "%s", c
->name
) < 0)
2380 if (fclose(fout
) < 0)
2387 * We want to support:
2388 sudo lxc-clone -o o1 -n n1 -s -L|-fssize fssize -v|--vgname vgname \
2389 -p|--lvprefix lvprefix -t|--fstype fstype -B backingstore
2391 -s [ implies overlayfs]
2395 only rootfs gets converted (copied/snapshotted) on clone.
2398 static int create_file_dirname(char *path
)
2400 char *p
= strrchr(path
, '/');
2406 ret
= mkdir(path
, 0755);
2407 if (ret
&& errno
!= EEXIST
)
2408 SYSERROR("creating container path %s\n", path
);
2413 static struct lxc_container
*lxcapi_clone(struct lxc_container
*c
, const char *newname
,
2414 const char *lxcpath
, int flags
,
2415 const char *bdevtype
, const char *bdevdata
, unsigned long newsize
,
2418 struct lxc_container
*c2
= NULL
;
2419 char newpath
[MAXPATHLEN
];
2420 int ret
, storage_copied
= 0;
2424 if (!c
|| !c
->is_defined(c
))
2427 if (container_mem_lock(c
))
2430 if (!is_stopped(c
)) {
2431 ERROR("error: Original container (%s) is running", c
->name
);
2435 // Make sure the container doesn't yet exist.
2436 n
= newname
? newname
: c
->name
;
2437 l
= lxcpath
? lxcpath
: c
->get_config_path(c
);
2438 ret
= snprintf(newpath
, MAXPATHLEN
, "%s/%s/config", l
, n
);
2439 if (ret
< 0 || ret
>= MAXPATHLEN
) {
2440 SYSERROR("clone: failed making config pathname");
2443 if (file_exists(newpath
)) {
2444 ERROR("error: clone: %s exists", newpath
);
2448 ret
= create_file_dirname(newpath
);
2449 if (ret
< 0 && errno
!= EEXIST
) {
2450 ERROR("Error creating container dir for %s", newpath
);
2454 // copy the configuration, tweak it as needed,
2455 fout
= fopen(newpath
, "w");
2457 SYSERROR("open %s", newpath
);
2460 write_config(fout
, c
->lxc_conf
);
2463 sprintf(newpath
, "%s/%s/rootfs", l
, n
);
2464 if (mkdir(newpath
, 0755) < 0) {
2465 SYSERROR("error creating %s", newpath
);
2469 c2
= lxc_container_new(n
, l
);
2471 ERROR("clone: failed to create new container (%s %s)", n
, l
);
2476 if (!set_config_item_locked(c2
, "lxc.utsname", newname
)) {
2477 ERROR("Error setting new hostname");
2482 ret
= copyhooks(c
, c2
);
2484 ERROR("error copying hooks");
2488 if (copy_fstab(c
, c2
) < 0) {
2489 ERROR("error copying fstab");
2494 if (!(flags
& LXC_CLONE_KEEPMACADDR
))
2495 network_new_hwaddrs(c2
);
2497 // copy/snapshot rootfs's
2498 ret
= copy_storage(c
, c2
, bdevtype
, flags
, bdevdata
, newsize
);
2502 // We've now successfully created c2's storage, so clear it out if we
2506 if (!c2
->save_config(c2
, NULL
))
2509 if (clone_update_rootfs(c
, c2
, flags
, hookargs
) < 0)
2512 // TODO: update c's lxc.snapshot = count
2513 container_mem_unlock(c
);
2517 container_mem_unlock(c
);
2519 if (!storage_copied
)
2520 c2
->lxc_conf
->rootfs
.path
= NULL
;
2522 lxc_container_put(c2
);
2528 static bool lxcapi_rename(struct lxc_container
*c
, const char *newname
)
2531 struct lxc_container
*newc
;
2533 if (!c
|| !c
->name
|| !c
->config_path
)
2536 bdev
= bdev_init(c
->lxc_conf
->rootfs
.path
, c
->lxc_conf
->rootfs
.mount
, NULL
);
2538 ERROR("Failed to find original backing store type");
2542 newc
= lxcapi_clone(c
, newname
, c
->config_path
, LXC_CLONE_KEEPMACADDR
, NULL
, bdev
->type
, 0, NULL
);
2545 lxc_container_put(newc
);
2549 if (newc
&& lxcapi_is_defined(newc
))
2550 lxc_container_put(newc
);
2552 if (!lxcapi_destroy(c
)) {
2553 ERROR("Could not destroy existing container %s", c
->name
);
2559 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
)
2564 return lxc_attach(c
->name
, c
->config_path
, exec_function
, exec_payload
, options
, attached_process
);
2567 static int lxcapi_attach_run_wait(struct lxc_container
*c
, lxc_attach_options_t
*options
, const char *program
, const char * const argv
[])
2569 lxc_attach_command_t command
;
2576 command
.program
= (char*)program
;
2577 command
.argv
= (char**)argv
;
2578 r
= lxc_attach(c
->name
, c
->config_path
, lxc_attach_run_command
, &command
, options
, &pid
);
2583 return lxc_wait_for_pid_status(pid
);
2586 static int get_next_index(const char *lxcpath
, char *cname
)
2592 fname
= alloca(strlen(lxcpath
) + 20);
2594 sprintf(fname
, "%s/snap%d", lxcpath
, i
);
2595 ret
= stat(fname
, &sb
);
2602 static int lxcapi_snapshot(struct lxc_container
*c
, const char *commentfile
)
2605 struct lxc_container
*c2
;
2606 char snappath
[MAXPATHLEN
], newname
[20];
2608 // /var/lib/lxc -> /var/lib/lxcsnaps \0
2609 ret
= snprintf(snappath
, MAXPATHLEN
, "%ssnaps/%s", c
->config_path
, c
->name
);
2610 if (ret
< 0 || ret
>= MAXPATHLEN
)
2612 i
= get_next_index(snappath
, c
->name
);
2614 if (mkdir_p(snappath
, 0755) < 0) {
2615 ERROR("Failed to create snapshot directory %s", snappath
);
2619 ret
= snprintf(newname
, 20, "snap%d", i
);
2620 if (ret
< 0 || ret
>= 20)
2624 * We pass LXC_CLONE_SNAPSHOT to make sure that a rdepends file entry is
2625 * created in the original container
2627 flags
= LXC_CLONE_SNAPSHOT
| LXC_CLONE_KEEPMACADDR
| LXC_CLONE_KEEPNAME
|
2628 LXC_CLONE_KEEPBDEVTYPE
| LXC_CLONE_MAYBE_SNAPSHOT
;
2629 c2
= c
->clone(c
, newname
, snappath
, flags
, NULL
, NULL
, 0, NULL
);
2631 ERROR("clone of %s:%s failed\n", c
->config_path
, c
->name
);
2635 lxc_container_put(c2
);
2637 // Now write down the creation time
2644 tm_info
= localtime(&timer
);
2646 strftime(buffer
, 25, "%Y:%m:%d %H:%M:%S", tm_info
);
2648 char *dfnam
= alloca(strlen(snappath
) + strlen(newname
) + 5);
2649 sprintf(dfnam
, "%s/%s/ts", snappath
, newname
);
2650 f
= fopen(dfnam
, "w");
2652 ERROR("Failed to open %s\n", dfnam
);
2655 if (fprintf(f
, "%s", buffer
) < 0) {
2656 SYSERROR("Writing timestamp");
2662 SYSERROR("Writing timestamp");
2667 // $p / $name / comment \0
2668 int len
= strlen(snappath
) + strlen(newname
) + 10;
2669 char *path
= alloca(len
);
2670 sprintf(path
, "%s/%s/comment", snappath
, newname
);
2671 return copy_file(commentfile
, path
) < 0 ? -1 : i
;
2677 static void lxcsnap_free(struct lxc_snapshot
*s
)
2681 if (s
->comment_pathname
)
2682 free(s
->comment_pathname
);
2689 static char *get_snapcomment_path(char* snappath
, char *name
)
2691 // $snappath/$name/comment
2692 int ret
, len
= strlen(snappath
) + strlen(name
) + 10;
2693 char *s
= malloc(len
);
2696 ret
= snprintf(s
, len
, "%s/%s/comment", snappath
, name
);
2697 if (ret
< 0 || ret
>= len
) {
2705 static char *get_timestamp(char* snappath
, char *name
)
2707 char path
[MAXPATHLEN
], *s
= NULL
;
2711 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/ts", snappath
, name
);
2712 if (ret
< 0 || ret
>= MAXPATHLEN
)
2714 fin
= fopen(path
, "r");
2717 (void) fseek(fin
, 0, SEEK_END
);
2719 (void) fseek(fin
, 0, SEEK_SET
);
2724 if (fread(s
, 1, len
, fin
) != len
) {
2725 SYSERROR("reading timestamp");
2735 static int lxcapi_snapshot_list(struct lxc_container
*c
, struct lxc_snapshot
**ret_snaps
)
2737 char snappath
[MAXPATHLEN
], path2
[MAXPATHLEN
];
2738 int dirlen
, count
= 0, ret
;
2739 struct dirent dirent
, *direntp
;
2740 struct lxc_snapshot
*snaps
=NULL
, *nsnaps
;
2743 if (!c
|| !lxcapi_is_defined(c
))
2745 // snappath is ${lxcpath}snaps/${lxcname}/
2746 dirlen
= snprintf(snappath
, MAXPATHLEN
, "%ssnaps/%s", c
->config_path
, c
->name
);
2747 if (dirlen
< 0 || dirlen
>= MAXPATHLEN
) {
2748 ERROR("path name too long");
2751 dir
= opendir(snappath
);
2753 INFO("failed to open %s - assuming no snapshots", snappath
);
2757 while (!readdir_r(dir
, &dirent
, &direntp
)) {
2761 if (!strcmp(direntp
->d_name
, "."))
2764 if (!strcmp(direntp
->d_name
, ".."))
2767 ret
= snprintf(path2
, MAXPATHLEN
, "%s/%s/config", snappath
, direntp
->d_name
);
2768 if (ret
< 0 || ret
>= MAXPATHLEN
) {
2769 ERROR("pathname too long");
2772 if (!file_exists(path2
))
2774 nsnaps
= realloc(snaps
, (count
+ 1)*sizeof(*snaps
));
2776 SYSERROR("Out of memory");
2780 snaps
[count
].free
= lxcsnap_free
;
2781 snaps
[count
].name
= strdup(direntp
->d_name
);
2782 if (!snaps
[count
].name
)
2784 snaps
[count
].lxcpath
= strdup(snappath
);
2785 if (!snaps
[count
].lxcpath
) {
2786 free(snaps
[count
].name
);
2789 snaps
[count
].comment_pathname
= get_snapcomment_path(snappath
, direntp
->d_name
);
2790 snaps
[count
].timestamp
= get_timestamp(snappath
, direntp
->d_name
);
2795 WARN("failed to close directory");
2803 for (i
=0; i
<count
; i
++)
2804 lxcsnap_free(&snaps
[i
]);
2808 WARN("failed to close directory");
2812 static bool lxcapi_snapshot_restore(struct lxc_container
*c
, const char *snapname
, const char *newname
)
2814 char clonelxcpath
[MAXPATHLEN
];
2816 struct lxc_container
*snap
, *rest
;
2820 if (!c
|| !c
->name
|| !c
->config_path
)
2823 bdev
= bdev_init(c
->lxc_conf
->rootfs
.path
, c
->lxc_conf
->rootfs
.mount
, NULL
);
2825 ERROR("Failed to find original backing store type");
2831 if (strcmp(c
->name
, newname
) == 0) {
2832 if (!lxcapi_destroy(c
)) {
2833 ERROR("Could not destroy existing container %s", newname
);
2838 ret
= snprintf(clonelxcpath
, MAXPATHLEN
, "%ssnaps/%s", c
->config_path
, c
->name
);
2839 if (ret
< 0 || ret
>= MAXPATHLEN
) {
2843 // how should we lock this?
2845 snap
= lxc_container_new(snapname
, clonelxcpath
);
2846 if (!snap
|| !lxcapi_is_defined(snap
)) {
2847 ERROR("Could not open snapshot %s", snapname
);
2848 if (snap
) lxc_container_put(snap
);
2853 rest
= lxcapi_clone(snap
, newname
, c
->config_path
, 0, bdev
->type
, NULL
, 0, NULL
);
2855 if (rest
&& lxcapi_is_defined(rest
))
2858 lxc_container_put(rest
);
2859 lxc_container_put(snap
);
2863 static bool lxcapi_snapshot_destroy(struct lxc_container
*c
, const char *snapname
)
2866 char clonelxcpath
[MAXPATHLEN
];
2867 struct lxc_container
*snap
= NULL
;
2869 if (!c
|| !c
->name
|| !c
->config_path
)
2872 ret
= snprintf(clonelxcpath
, MAXPATHLEN
, "%ssnaps/%s", c
->config_path
, c
->name
);
2873 if (ret
< 0 || ret
>= MAXPATHLEN
)
2876 snap
= lxc_container_new(snapname
, clonelxcpath
);
2877 if (!snap
|| !lxcapi_is_defined(snap
)) {
2878 ERROR("Could not find snapshot %s", snapname
);
2882 if (!lxcapi_destroy(snap
)) {
2883 ERROR("Could not destroy snapshot %s", snapname
);
2886 lxc_container_put(snap
);
2891 lxc_container_put(snap
);
2895 static bool lxcapi_may_control(struct lxc_container
*c
)
2897 return lxc_try_cmd(c
->name
, c
->config_path
) == 0;
2900 static bool add_remove_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
, bool add
)
2904 char path
[MAXPATHLEN
];
2905 char value
[MAX_BUFFER
];
2906 char *directory_path
= NULL
;
2909 /* make sure container is running */
2910 if (!c
->is_running(c
)) {
2911 ERROR("container is not running");
2915 /* use src_path if dest_path is NULL otherwise use dest_path */
2916 p
= dest_path
? dest_path
: src_path
;
2918 /* prepare the path */
2919 ret
= snprintf(path
, MAXPATHLEN
, "/proc/%d/root/%s", c
->init_pid(c
), p
);
2920 if (ret
< 0 || ret
>= MAXPATHLEN
)
2922 remove_trailing_slashes(path
);
2924 p
= add
? src_path
: path
;
2925 /* make sure we can access p */
2926 if(access(p
, F_OK
) < 0 || stat(p
, &st
) < 0)
2929 /* continue if path is character device or block device */
2930 if (S_ISCHR(st
.st_mode
))
2931 ret
= snprintf(value
, MAX_BUFFER
, "c %d:%d rwm", major(st
.st_rdev
), minor(st
.st_rdev
));
2932 else if (S_ISBLK(st
.st_mode
))
2933 ret
= snprintf(value
, MAX_BUFFER
, "b %d:%d rwm", major(st
.st_rdev
), minor(st
.st_rdev
));
2937 /* check snprintf return code */
2938 if (ret
< 0 || ret
>= MAX_BUFFER
)
2941 directory_path
= dirname(strdup(path
));
2942 /* remove path and directory_path (if empty) */
2943 if(access(path
, F_OK
) == 0) {
2944 if (unlink(path
) < 0) {
2945 ERROR("unlink failed");
2948 if (rmdir(directory_path
) < 0 && errno
!= ENOTEMPTY
) {
2949 ERROR("rmdir failed");
2955 /* create the missing directories */
2956 if (mkdir_p(directory_path
, 0755) < 0) {
2957 ERROR("failed to create directory");
2961 /* create the device node */
2962 if (mknod(path
, st
.st_mode
, st
.st_rdev
) < 0) {
2963 ERROR("mknod failed");
2967 /* add device node to device list */
2968 if (!c
->set_cgroup_item(c
, "devices.allow", value
)) {
2969 ERROR("set_cgroup_item failed while adding the device node");
2973 /* remove device node from device list */
2974 if (!c
->set_cgroup_item(c
, "devices.deny", value
)) {
2975 ERROR("set_cgroup_item failed while removing the device node");
2982 free(directory_path
);
2986 static bool lxcapi_add_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
)
2988 return add_remove_device_node(c
, src_path
, dest_path
, true);
2991 static bool lxcapi_remove_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
)
2993 return add_remove_device_node(c
, src_path
, dest_path
, false);
2996 static int lxcapi_attach_run_waitl(struct lxc_container
*c
, lxc_attach_options_t
*options
, const char *program
, const char *arg
, ...)
3006 argv
= lxc_va_arg_list_to_argv_const(ap
, 1);
3010 ERROR("Memory allocation error.");
3015 ret
= lxcapi_attach_run_wait(c
, options
, program
, (const char * const *)argv
);
3020 struct lxc_container
*lxc_container_new(const char *name
, const char *configpath
)
3022 struct lxc_container
*c
;
3024 c
= malloc(sizeof(*c
));
3026 fprintf(stderr
, "failed to malloc lxc_container\n");
3029 memset(c
, 0, sizeof(*c
));
3032 c
->config_path
= strdup(configpath
);
3034 c
->config_path
= strdup(default_lxc_path());
3036 if (!c
->config_path
) {
3037 fprintf(stderr
, "Out of memory");
3041 remove_trailing_slashes(c
->config_path
);
3042 c
->name
= malloc(strlen(name
)+1);
3044 fprintf(stderr
, "Error allocating lxc_container name\n");
3047 strcpy(c
->name
, name
);
3050 if (!(c
->slock
= lxc_newlock(c
->config_path
, name
))) {
3051 fprintf(stderr
, "failed to create lock\n");
3055 if (!(c
->privlock
= lxc_newlock(NULL
, NULL
))) {
3056 fprintf(stderr
, "failed to alloc privlock\n");
3060 if (!set_config_filename(c
)) {
3061 fprintf(stderr
, "Error allocating config file pathname\n");
3065 if (file_exists(c
->configfile
))
3066 lxcapi_load_config(c
, NULL
);
3068 if (ongoing_create(c
) == 2) {
3069 ERROR("Error: %s creation was not completed", c
->name
);
3071 lxcapi_clear_config(c
);
3074 // assign the member functions
3075 c
->is_defined
= lxcapi_is_defined
;
3076 c
->state
= lxcapi_state
;
3077 c
->is_running
= lxcapi_is_running
;
3078 c
->freeze
= lxcapi_freeze
;
3079 c
->unfreeze
= lxcapi_unfreeze
;
3080 c
->console
= lxcapi_console
;
3081 c
->console_getfd
= lxcapi_console_getfd
;
3082 c
->init_pid
= lxcapi_init_pid
;
3083 c
->load_config
= lxcapi_load_config
;
3084 c
->want_daemonize
= lxcapi_want_daemonize
;
3085 c
->want_close_all_fds
= lxcapi_want_close_all_fds
;
3086 c
->start
= lxcapi_start
;
3087 c
->startl
= lxcapi_startl
;
3088 c
->stop
= lxcapi_stop
;
3089 c
->config_file_name
= lxcapi_config_file_name
;
3090 c
->wait
= lxcapi_wait
;
3091 c
->set_config_item
= lxcapi_set_config_item
;
3092 c
->destroy
= lxcapi_destroy
;
3093 c
->rename
= lxcapi_rename
;
3094 c
->save_config
= lxcapi_save_config
;
3095 c
->get_keys
= lxcapi_get_keys
;
3096 c
->create
= lxcapi_create
;
3097 c
->createl
= lxcapi_createl
;
3098 c
->shutdown
= lxcapi_shutdown
;
3099 c
->reboot
= lxcapi_reboot
;
3100 c
->clear_config
= lxcapi_clear_config
;
3101 c
->clear_config_item
= lxcapi_clear_config_item
;
3102 c
->get_config_item
= lxcapi_get_config_item
;
3103 c
->get_cgroup_item
= lxcapi_get_cgroup_item
;
3104 c
->set_cgroup_item
= lxcapi_set_cgroup_item
;
3105 c
->get_config_path
= lxcapi_get_config_path
;
3106 c
->set_config_path
= lxcapi_set_config_path
;
3107 c
->clone
= lxcapi_clone
;
3108 c
->get_interfaces
= lxcapi_get_interfaces
;
3109 c
->get_ips
= lxcapi_get_ips
;
3110 c
->attach
= lxcapi_attach
;
3111 c
->attach_run_wait
= lxcapi_attach_run_wait
;
3112 c
->attach_run_waitl
= lxcapi_attach_run_waitl
;
3113 c
->snapshot
= lxcapi_snapshot
;
3114 c
->snapshot_list
= lxcapi_snapshot_list
;
3115 c
->snapshot_restore
= lxcapi_snapshot_restore
;
3116 c
->snapshot_destroy
= lxcapi_snapshot_destroy
;
3117 c
->may_control
= lxcapi_may_control
;
3118 c
->add_device_node
= lxcapi_add_device_node
;
3119 c
->remove_device_node
= lxcapi_remove_device_node
;
3121 /* we'll allow the caller to update these later */
3122 if (lxc_log_init(NULL
, "none", NULL
, "lxc_container", 0, c
->config_path
)) {
3123 fprintf(stderr
, "failed to open log\n");
3130 lxc_container_free(c
);
3134 int lxc_get_wait_states(const char **states
)
3139 for (i
=0; i
<MAX_STATE
; i
++)
3140 states
[i
] = lxc_state2str(i
);
3145 * These next two could probably be done smarter with reusing a common function
3146 * with different iterators and tests...
3148 int list_defined_containers(const char *lxcpath
, char ***names
, struct lxc_container
***cret
)
3151 int i
, cfound
= 0, nfound
= 0;
3152 struct dirent dirent
, *direntp
;
3153 struct lxc_container
*c
;
3156 lxcpath
= default_lxc_path();
3158 dir
= opendir(lxcpath
);
3160 SYSERROR("opendir on lxcpath");
3169 while (!readdir_r(dir
, &dirent
, &direntp
)) {
3172 if (!strcmp(direntp
->d_name
, "."))
3174 if (!strcmp(direntp
->d_name
, ".."))
3177 if (!config_file_exists(lxcpath
, direntp
->d_name
))
3181 if (!add_to_array(names
, direntp
->d_name
, cfound
))
3191 c
= lxc_container_new(direntp
->d_name
, lxcpath
);
3193 INFO("Container %s:%s has a config but could not be loaded",
3194 lxcpath
, direntp
->d_name
);
3196 if(!remove_from_array(names
, direntp
->d_name
, cfound
--))
3200 if (!lxcapi_is_defined(c
)) {
3201 INFO("Container %s:%s has a config but is not defined",
3202 lxcpath
, direntp
->d_name
);
3204 if(!remove_from_array(names
, direntp
->d_name
, cfound
--))
3206 lxc_container_put(c
);
3210 if (!add_to_clist(cret
, c
, nfound
, true)) {
3211 lxc_container_put(c
);
3221 if (names
&& *names
) {
3222 for (i
=0; i
<cfound
; i
++)
3226 if (cret
&& *cret
) {
3227 for (i
=0; i
<nfound
; i
++)
3228 lxc_container_put((*cret
)[i
]);
3235 int list_active_containers(const char *lxcpath
, char ***nret
,
3236 struct lxc_container
***cret
)
3238 int i
, ret
= -1, cret_cnt
= 0, ct_name_cnt
= 0;
3241 char **ct_name
= NULL
;
3243 struct lxc_container
*c
;
3246 lxcpath
= default_lxc_path();
3247 lxcpath_len
= strlen(lxcpath
);
3254 FILE *f
= fopen("/proc/net/unix", "r");
3258 while (getline(&line
, &len
, f
) != -1) {
3259 char *p
= strrchr(line
, ' '), *p2
;
3266 if (strncmp(p
, lxcpath
, lxcpath_len
) != 0)
3272 // Now p is the start of lxc_name
3274 if (!p2
|| strncmp(p2
, "/command", 8) != 0)
3278 if (array_contains(&ct_name
, p
, ct_name_cnt
))
3281 if (!add_to_array(&ct_name
, p
, ct_name_cnt
))
3282 goto free_cret_list
;
3289 c
= lxc_container_new(p
, lxcpath
);
3291 INFO("Container %s:%s is running but could not be loaded",
3293 remove_from_array(&ct_name
, p
, ct_name_cnt
--);
3298 * If this is an anonymous container, then is_defined *can*
3299 * return false. So we don't do that check. Count on the
3300 * fact that the command socket exists.
3303 if (!add_to_clist(cret
, c
, cret_cnt
, true)) {
3304 lxc_container_put(c
);
3305 goto free_cret_list
;
3310 assert(!nret
|| !cret
|| cret_cnt
== ct_name_cnt
);
3319 if (cret
&& *cret
) {
3320 for (i
= 0; i
< cret_cnt
; i
++)
3321 lxc_container_put((*cret
)[i
]);
3327 for (i
= 0; i
< ct_name_cnt
; i
++)
3340 int list_all_containers(const char *lxcpath
, char ***nret
,
3341 struct lxc_container
***cret
)
3343 int i
, ret
, active_cnt
, ct_cnt
, ct_list_cnt
;
3346 struct lxc_container
**ct_list
= NULL
;
3348 ct_cnt
= list_defined_containers(lxcpath
, &ct_name
, NULL
);
3352 active_cnt
= list_active_containers(lxcpath
, &active_name
, NULL
);
3353 if (active_cnt
< 0) {
3358 for (i
= 0; i
< active_cnt
; i
++) {
3359 if (!array_contains(&ct_name
, active_name
[i
], ct_cnt
)) {
3360 if (!add_to_array(&ct_name
, active_name
[i
], ct_cnt
)) {
3362 goto free_active_name
;
3366 free(active_name
[i
]);
3367 active_name
[i
] = NULL
;
3373 for (i
= 0, ct_list_cnt
= 0; i
< ct_cnt
&& cret
; i
++) {
3374 struct lxc_container
*c
;
3376 c
= lxc_container_new(ct_name
[i
], lxcpath
);
3378 WARN("Container %s:%s could not be loaded", lxcpath
, ct_name
[i
]);
3379 remove_from_array(&ct_name
, ct_name
[i
], ct_cnt
--);
3383 if (!add_to_clist(&ct_list
, c
, ct_list_cnt
, false)) {
3384 lxc_container_put(c
);
3403 for (i
= 0; i
< ct_list_cnt
; i
++) {
3404 lxc_container_put(ct_list
[i
]);
3410 for (i
= 0; i
< active_cnt
; i
++) {
3412 free(active_name
[i
]);
3418 for (i
= 0; i
< ct_cnt
; i
++) {