]>
git.proxmox.com Git - mirror_lxc.git/blob - src/lxc/lxccontainer.c
3 * Copyright © 2012 Serge Hallyn <serge.hallyn@ubuntu.com>.
4 * Copyright © 2012 Canonical Ltd.
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License version 2, as
8 * published by the Free Software Foundation.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23 #include <sys/types.h>
30 #include "lxccontainer.h"
39 #include <lxc/utils.h>
40 #include <lxc/monitor.h>
43 #include <arpa/inet.h>
46 lxc_log_define(lxc_container
, lxc
);
48 static bool file_exists(char *f
)
52 return stat(f
, &statbuf
) == 0;
56 * A few functions to help detect when a container creation failed.
57 * If a container creation was killed partway through, then trying
58 * to actually start that container could harm the host. We detect
59 * this by creating a 'partial' file under the container directory,
60 * and keeping an advisory lock. When container creation completes,
61 * we remove that file. When we load or try to start a container, if
62 * we find that file, without a flock, we remove the container.
64 int ongoing_create(struct lxc_container
*c
)
66 int len
= strlen(c
->config_path
) + strlen(c
->name
) + 10;
67 char *path
= alloca(len
);
69 ret
= snprintf(path
, len
, "%s/%s/partial", c
->config_path
, c
->name
);
70 if (ret
< 0 || ret
>= len
) {
71 ERROR("Error writing partial pathname");
75 if (!file_exists(path
))
79 if ((fd
= open(path
, O_RDWR
)) < 0) {
80 // give benefit of the doubt
81 SYSERROR("Error opening partial file");
85 if ((ret
= flock(fd
, LOCK_EX
| LOCK_NB
)) == -1 &&
86 errno
== EWOULDBLOCK
) {
87 // create is still ongoing
92 // create completed but partial is still there.
98 int create_partial(struct lxc_container
*c
)
100 // $lxcpath + '/' + $name + '/partial' + \0
101 int len
= strlen(c
->config_path
) + strlen(c
->name
) + 10;
102 char *path
= alloca(len
);
104 ret
= snprintf(path
, len
, "%s/%s/partial", c
->config_path
, c
->name
);
105 if (ret
< 0 || ret
>= len
) {
106 ERROR("Error writing partial pathname");
109 if (process_lock() < 0)
111 if ((fd
=open(path
, O_CREAT
| O_EXCL
, 0755)) < 0) {
112 SYSERROR("Erorr creating partial file");
116 if (flock(fd
, LOCK_EX
) < 0) {
117 SYSERROR("Error locking partial file %s", path
);
127 void remove_partial(struct lxc_container
*c
, int fd
)
129 // $lxcpath + '/' + $name + '/partial' + \0
130 int len
= strlen(c
->config_path
) + strlen(c
->name
) + 10;
131 char *path
= alloca(len
);
135 ret
= snprintf(path
, len
, "%s/%s/partial", c
->config_path
, c
->name
);
136 if (ret
< 0 || ret
>= len
) {
137 ERROR("Error writing partial pathname");
142 if (unlink(path
) < 0)
143 SYSERROR("Error unlink partial file %s", path
);
148 * 1. c->privlock protects the struct lxc_container from multiple threads.
149 * 2. c->slock protects the on-disk container data
150 * 3. thread_mutex protects process data (ex: fd table) from multiple threads
151 * slock is an flock, which does not exclude threads. Therefore slock should
152 * always be wrapped inside privlock.
153 * NOTHING mutexes two independent programs with their own struct
154 * lxc_container for the same c->name, between API calls. For instance,
155 * c->config_read(); c->start(); Between those calls, data on disk
156 * could change (which shouldn't bother the caller unless for instance
157 * the rootfs get moved). c->config_read(); update; c->config_write();
158 * Two such updaters could race. The callers should therefore check their
159 * results. Trying to prevent that would necessarily expose us to deadlocks
160 * due to hung callers. So I prefer to keep the locks only within our own
161 * functions, not across functions.
163 * If you're going to fork while holding a lxccontainer, increment
164 * c->numthreads (under privlock) before forking. When deleting,
165 * decrement numthreads under privlock, then if it hits 0 you can delete.
166 * Do not ever use a lxccontainer whose numthreads you did not bump.
169 static void lxc_container_free(struct lxc_container
*c
)
176 c
->configfile
= NULL
;
178 if (c
->error_string
) {
179 free(c
->error_string
);
180 c
->error_string
= NULL
;
183 lxc_putlock(c
->slock
);
187 lxc_putlock(c
->privlock
);
195 lxc_conf_free(c
->lxc_conf
);
198 if (c
->config_path
) {
199 free(c
->config_path
);
200 c
->config_path
= NULL
;
206 * Consider the following case:
207 freer | racing get()er
208 ==================================================================
209 lxc_container_put() | lxc_container_get()
210 \ lxclock(c->privlock) | c->numthreads < 1? (no)
211 \ c->numthreads = 0 | \ lxclock(c->privlock) -> waits
213 \ lxc_container_free() | \ lxclock() returns
214 | \ c->numthreads < 1 -> return 0
216 \ \ sem_destroy(privlock) |
218 * When the get()er checks numthreads the first time, one of the following
220 * 1. freer has set numthreads = 0. get() returns 0
221 * 2. freer is between lxclock and setting numthreads to 0. get()er will
222 * sem_wait on privlock, get lxclock after freer() drops it, then see
223 * numthreads is 0 and exit without touching lxclock again..
224 * 3. freer has not yet locked privlock. If get()er runs first, then put()er
225 * will see --numthreads = 1 and not call lxc_container_free().
228 int lxc_container_get(struct lxc_container
*c
)
233 // if someone else has already started freeing the container, don't
234 // try to take the lock, which may be invalid
235 if (c
->numthreads
< 1)
238 if (container_mem_lock(c
))
240 if (c
->numthreads
< 1) {
241 // bail without trying to unlock, bc the privlock is now probably
246 container_mem_unlock(c
);
250 int lxc_container_put(struct lxc_container
*c
)
254 if (container_mem_lock(c
))
256 if (--c
->numthreads
< 1) {
257 container_mem_unlock(c
);
258 lxc_container_free(c
);
261 container_mem_unlock(c
);
265 static bool lxcapi_is_defined(struct lxc_container
*c
)
274 if (container_mem_lock(c
))
278 statret
= stat(c
->configfile
, &statbuf
);
284 container_mem_unlock(c
);
288 static const char *lxcapi_state(struct lxc_container
*c
)
295 if (container_disk_lock(c
))
297 s
= lxc_getstate(c
->name
, c
->config_path
);
298 ret
= lxc_state2str(s
);
299 container_disk_unlock(c
);
304 static bool is_stopped_locked(struct lxc_container
*c
)
307 s
= lxc_getstate(c
->name
, c
->config_path
);
308 return (s
== STOPPED
);
311 static bool lxcapi_is_running(struct lxc_container
*c
)
318 if (!s
|| strcmp(s
, "STOPPED") == 0)
323 static bool lxcapi_freeze(struct lxc_container
*c
)
329 if (container_disk_lock(c
))
331 ret
= lxc_freeze(c
->name
, c
->config_path
);
332 container_disk_unlock(c
);
338 static bool lxcapi_unfreeze(struct lxc_container
*c
)
344 if (container_disk_lock(c
))
346 ret
= lxc_unfreeze(c
->name
, c
->config_path
);
347 container_disk_unlock(c
);
353 static pid_t
lxcapi_init_pid(struct lxc_container
*c
)
358 return lxc_cmd_get_init_pid(c
->name
, c
->config_path
);
361 static bool load_config_locked(struct lxc_container
*c
, const char *fname
)
364 c
->lxc_conf
= lxc_conf_init();
365 if (c
->lxc_conf
&& !lxc_config_read(fname
, c
->lxc_conf
))
370 static bool lxcapi_load_config(struct lxc_container
*c
, const char *alt_file
)
377 fname
= c
->configfile
;
382 if (container_disk_lock(c
))
384 ret
= load_config_locked(c
, fname
);
385 container_disk_unlock(c
);
389 static void lxcapi_want_daemonize(struct lxc_container
*c
)
396 static bool lxcapi_wait(struct lxc_container
*c
, const char *state
, int timeout
)
403 ret
= lxc_wait(c
->name
, state
, timeout
, c
->config_path
);
408 static bool wait_on_daemonized_start(struct lxc_container
*c
)
410 /* we'll probably want to make this timeout configurable? */
411 int timeout
= 5, ret
, status
;
414 * our child is going to fork again, then exit. reap the
418 if (ret
== -1 || !WIFEXITED(status
) || WEXITSTATUS(status
) != 0)
419 DEBUG("failed waiting for first dual-fork child");
420 return lxcapi_wait(c
, "RUNNING", timeout
);
424 * I can't decide if it'd be more convenient for callers if we accept '...',
425 * or a null-terminated array (i.e. execl vs execv)
427 static bool lxcapi_start(struct lxc_container
*c
, int useinit
, char * const argv
[])
430 struct lxc_conf
*conf
;
432 char *default_args
[] = {
437 /* container exists */
440 /* container has been setup */
444 if ((ret
= ongoing_create(c
)) < 0) {
445 ERROR("Error checking for incomplete creation");
449 ERROR("Error: %s creation was not completed", c
->name
);
452 } else if (ret
== 1) {
453 ERROR("Error: creation of %s is ongoing", c
->name
);
457 /* is this app meant to be run through lxcinit, as in lxc-execute? */
458 if (useinit
&& !argv
)
461 if (container_mem_lock(c
))
464 daemonize
= c
->daemonize
;
465 container_mem_unlock(c
);
468 ret
= lxc_execute(c
->name
, argv
, 1, conf
, c
->config_path
);
469 return ret
== 0 ? true : false;
476 * say, I'm not sure - what locks do we want here? Any?
477 * Is liblxc's locking enough here to protect the on disk
478 * container? We don't want to exclude things like lxc_info
479 * while container is running...
482 if (!lxc_container_get(c
))
484 lxc_monitord_spawn(c
->config_path
);
490 lxc_container_put(c
);
495 ret
= wait_on_daemonized_start(c
);
500 /* second fork to be reparented by init */
503 SYSERROR("Error doing dual-fork");
508 /* like daemon(), chdir to / and redirect 0,1,2 to /dev/null */
510 SYSERROR("Error chdir()ing to /.");
516 open("/dev/null", O_RDONLY
);
517 open("/dev/null", O_RDWR
);
518 open("/dev/null", O_RDWR
);
524 ret
= lxc_start(c
->name
, argv
, conf
, c
->config_path
);
527 INFO("container requested reboot");
533 lxc_container_put(c
);
534 exit (ret
== 0 ? true : false);
536 return (ret
== 0 ? true : false);
541 * note there MUST be an ending NULL
543 static bool lxcapi_startl(struct lxc_container
*c
, int useinit
, ...)
546 char **inargs
= NULL
, **temp
;
550 /* container exists */
554 /* build array of arguments if any */
555 va_start(ap
, useinit
);
558 arg
= va_arg(ap
, char *);
562 temp
= realloc(inargs
, n_inargs
* sizeof(*inargs
));
568 inargs
[n_inargs
- 1] = strdup(arg
); // not sure if it's safe not to copy
572 /* add trailing NULL */
575 temp
= realloc(inargs
, n_inargs
* sizeof(*inargs
));
579 inargs
[n_inargs
- 1] = NULL
;
582 bret
= lxcapi_start(c
, useinit
, inargs
);
587 for (i
= 0; i
< n_inargs
; i
++) {
597 static bool lxcapi_stop(struct lxc_container
*c
)
604 ret
= lxc_cmd_stop(c
->name
, c
->config_path
);
609 static bool valid_template(char *t
)
614 statret
= stat(t
, &statbuf
);
621 * create the standard expected container dir
623 static bool create_container_dir(struct lxc_container
*c
)
628 len
= strlen(c
->config_path
) + strlen(c
->name
) + 2;
632 ret
= snprintf(s
, len
, "%s/%s", c
->config_path
, c
->name
);
633 if (ret
< 0 || ret
>= len
) {
637 ret
= mkdir(s
, 0755);
642 SYSERROR("failed to create container path for %s\n", c
->name
);
649 * backing stores not (yet) supported
650 * for ->create, argv contains the arguments to pass to the template,
651 * terminated by NULL. If no arguments, you can just pass NULL.
653 static bool lxcapi_create(struct lxc_container
*c
, const char *t
, char *const argv
[])
657 char *tpath
= NULL
, **newargv
;
658 int partial_fd
, ret
, len
, nargs
= 0;
663 len
= strlen(LXCTEMPLATEDIR
) + strlen(t
) + strlen("/lxc-") + 1;
667 ret
= snprintf(tpath
, len
, "%s/lxc-%s", LXCTEMPLATEDIR
, t
);
668 if (ret
< 0 || ret
>= len
)
670 if (!valid_template(tpath
)) {
671 ERROR("bad template: %s\n", t
);
675 if (!c
->save_config(c
, NULL
)) {
676 ERROR("failed to save starting configuration for %s\n", c
->name
);
680 /* container is already created if we have a config and rootfs.path is accessible */
681 if (lxcapi_is_defined(c
) && c
->lxc_conf
&& c
->lxc_conf
->rootfs
.path
&& access(c
->lxc_conf
->rootfs
.path
, F_OK
) == 0)
684 /* Mark that this container is being created */
685 if ((partial_fd
= create_partial(c
)) < 0)
688 /* we're going to fork. but since we'll wait for our child, we
689 * don't need to lxc_container_get */
691 if (container_disk_lock(c
))
696 SYSERROR("failed to fork task for container creation template\n");
700 if (pid
== 0) { // child
701 char *patharg
, *namearg
;
707 open("/dev/null", O_RDONLY
);
708 open("/dev/null", O_RDWR
);
709 open("/dev/null", O_RDWR
);
712 * create our new array, pre-pend the template name and
716 for (; argv
[nargs
]; nargs
++) ;
717 nargs
+= 3; // template, path and name args
718 newargv
= malloc(nargs
* sizeof(*newargv
));
721 newargv
[0] = (char *)t
;
723 len
= strlen(c
->config_path
) + strlen(c
->name
) + strlen("--path=") + 2;
724 patharg
= malloc(len
);
727 ret
= snprintf(patharg
, len
, "--path=%s/%s", c
->config_path
, c
->name
);
728 if (ret
< 0 || ret
>= len
)
730 newargv
[1] = patharg
;
731 len
= strlen("--name=") + strlen(c
->name
) + 1;
732 namearg
= malloc(len
);
735 ret
= snprintf(namearg
, len
, "--name=%s", c
->name
);
736 if (ret
< 0 || ret
>= len
)
738 newargv
[2] = namearg
;
740 /* add passed-in args */
742 for (i
= 3; i
< nargs
; i
++)
743 newargv
[i
] = argv
[i
-3];
745 /* add trailing NULL */
747 newargv
= realloc(newargv
, nargs
* sizeof(*newargv
));
750 newargv
[nargs
- 1] = NULL
;
753 execv(tpath
, newargv
);
754 SYSERROR("failed to execute template %s", tpath
);
758 if (wait_for_pid(pid
) != 0) {
759 ERROR("container creation template for %s failed\n", c
->name
);
763 // now clear out the lxc_conf we have, reload from the created
766 lxc_conf_free(c
->lxc_conf
);
768 bret
= load_config_locked(c
, c
->configfile
);
772 remove_partial(c
, partial_fd
);
773 container_disk_unlock(c
);
780 static bool lxcapi_reboot(struct lxc_container
*c
)
786 if (!c
->is_running(c
))
788 pid
= c
->init_pid(c
);
791 if (kill(pid
, SIGINT
) < 0)
797 static bool lxcapi_shutdown(struct lxc_container
*c
, int timeout
)
807 if (!c
->is_running(c
))
809 pid
= c
->init_pid(c
);
813 retv
= c
->wait(c
, "STOPPED", timeout
);
814 if (!retv
&& timeout
> 0) {
816 retv
= c
->wait(c
, "STOPPED", 0); // 0 means don't wait
821 static bool lxcapi_createl(struct lxc_container
*c
, const char *t
, ...)
824 char **args
= NULL
, **temp
;
832 * since we're going to wait for create to finish, I don't think we
833 * need to get a copy of the arguments.
838 arg
= va_arg(ap
, char *);
842 temp
= realloc(args
, (nargs
+1) * sizeof(*args
));
848 args
[nargs
- 1] = arg
;
854 bret
= c
->create(c
, t
, args
);
862 static bool lxcapi_clear_config_item(struct lxc_container
*c
, const char *key
)
866 if (!c
|| !c
->lxc_conf
)
868 if (container_mem_lock(c
))
870 ret
= lxc_clear_config_item(c
->lxc_conf
, key
);
871 container_mem_unlock(c
);
875 char** lxcapi_get_ips(struct lxc_container
*c
, char* interface
, char* family
, int scope
)
878 struct ifaddrs
*interfaceArray
= NULL
, *tempIfAddr
= NULL
;
879 char addressOutputBuffer
[INET6_ADDRSTRLEN
];
880 void *tempAddrPtr
= NULL
;
881 char **addresses
= NULL
, **temp
;
882 char *address
= NULL
;
883 char new_netns_path
[MAXPATHLEN
];
884 int old_netns
= -1, new_netns
= -1, ret
= 0;
886 if (!c
->is_running(c
))
889 /* Save reference to old netns */
890 old_netns
= open("/proc/self/ns/net", O_RDONLY
);
892 SYSERROR("failed to open /proc/self/ns/net");
896 /* Switch to new netns */
897 ret
= snprintf(new_netns_path
, MAXPATHLEN
, "/proc/%d/ns/net", c
->init_pid(c
));
898 if (ret
< 0 || ret
>= MAXPATHLEN
)
901 new_netns
= open(new_netns_path
, O_RDONLY
);
903 SYSERROR("failed to open %s", new_netns_path
);
907 if (setns(new_netns
, CLONE_NEWNET
)) {
908 SYSERROR("failed to setns");
912 /* Grab the list of interfaces */
913 if (getifaddrs(&interfaceArray
)) {
914 SYSERROR("failed to get interfaces list");
918 /* Iterate through the interfaces */
919 for (tempIfAddr
= interfaceArray
; tempIfAddr
!= NULL
; tempIfAddr
= tempIfAddr
->ifa_next
) {
920 if(tempIfAddr
->ifa_addr
->sa_family
== AF_INET
) {
921 if (family
&& strcmp(family
, "inet"))
923 tempAddrPtr
= &((struct sockaddr_in
*)tempIfAddr
->ifa_addr
)->sin_addr
;
926 if (family
&& strcmp(family
, "inet6"))
929 if (((struct sockaddr_in6
*)tempIfAddr
->ifa_addr
)->sin6_scope_id
!= scope
)
932 tempAddrPtr
= &((struct sockaddr_in6
*)tempIfAddr
->ifa_addr
)->sin6_addr
;
935 if (interface
&& strcmp(interface
, tempIfAddr
->ifa_name
))
937 else if (!interface
&& strcmp("lo", tempIfAddr
->ifa_name
) == 0)
940 address
= (char *)inet_ntop(tempIfAddr
->ifa_addr
->sa_family
,
943 sizeof(addressOutputBuffer
));
948 temp
= realloc(addresses
, count
* sizeof(*addresses
));
954 addresses
[count
- 1] = strdup(address
);
959 freeifaddrs(interfaceArray
);
961 /* Switch back to original netns */
962 if (old_netns
>= 0 && setns(old_netns
, CLONE_NEWNET
))
963 SYSERROR("failed to setns");
969 /* Append NULL to the array */
972 temp
= realloc(addresses
, count
* sizeof(*addresses
));
975 for (i
= 0; i
< count
-1; i
++)
981 addresses
[count
- 1] = NULL
;
987 static int lxcapi_get_config_item(struct lxc_container
*c
, const char *key
, char *retv
, int inlen
)
991 if (!c
|| !c
->lxc_conf
)
993 if (container_mem_lock(c
))
995 ret
= lxc_get_config_item(c
->lxc_conf
, key
, retv
, inlen
);
996 container_mem_unlock(c
);
1000 static int lxcapi_get_keys(struct lxc_container
*c
, const char *key
, char *retv
, int inlen
)
1003 return lxc_listconfigs(retv
, inlen
);
1005 * Support 'lxc.network.<idx>', i.e. 'lxc.network.0'
1006 * This is an intelligent result to show which keys are valid given
1007 * the type of nic it is
1009 if (!c
|| !c
->lxc_conf
)
1011 if (container_mem_lock(c
))
1014 if (strncmp(key
, "lxc.network.", 12) == 0)
1015 ret
= lxc_list_nicconfigs(c
->lxc_conf
, key
, retv
, inlen
);
1016 container_mem_unlock(c
);
1021 /* default config file - should probably come through autoconf */
1022 #define LXC_DEFAULT_CONFIG "/etc/lxc/default.conf"
1023 static bool lxcapi_save_config(struct lxc_container
*c
, const char *alt_file
)
1026 alt_file
= c
->configfile
;
1028 return false; // should we write to stdout if no file is specified?
1030 if (!c
->load_config(c
, LXC_DEFAULT_CONFIG
)) {
1031 ERROR("Error loading default configuration file %s while saving %s\n", LXC_DEFAULT_CONFIG
, c
->name
);
1035 if (!create_container_dir(c
))
1038 FILE *fout
= fopen(alt_file
, "w");
1041 if (container_mem_lock(c
)) {
1045 write_config(fout
, c
->lxc_conf
);
1047 container_mem_unlock(c
);
1051 static const char *lxcapi_get_config_path(struct lxc_container
*c
);
1052 // do we want the api to support --force, or leave that to the caller?
1053 static bool lxcapi_destroy(struct lxc_container
*c
)
1058 /* container is already destroyed if we don't have a config and rootfs.path is not accessible */
1059 if (!c
|| !lxcapi_is_defined(c
) || !c
->lxc_conf
|| !c
->lxc_conf
->rootfs
.path
)
1062 if (lxclock(c
->privlock
, 0))
1064 if (lxclock(c
->slock
, 0)) {
1065 lxcunlock(c
->privlock
);
1069 if (!is_stopped_locked(c
)) {
1070 // we should queue some sort of error - in c->error_string?
1071 ERROR("container %s is not stopped", c
->name
);
1075 r
= bdev_init(c
->lxc_conf
->rootfs
.path
, c
->lxc_conf
->rootfs
.mount
, NULL
);
1077 if (r
->ops
->destroy(r
) < 0) {
1078 ERROR("Error destroying rootfs for %s", c
->name
);
1083 const char *p1
= lxcapi_get_config_path(c
);
1084 char *path
= alloca(strlen(p1
) + strlen(c
->name
) + 2);
1085 sprintf(path
, "%s/%s", p1
, c
->name
);
1086 if (lxc_rmdir_onedev(path
) < 0) {
1087 ERROR("Error destroying container directory for %s", c
->name
);
1093 lxcunlock(c
->privlock
);
1094 lxcunlock(c
->slock
);
1098 static bool lxcapi_set_config_item(struct lxc_container
*c
, const char *key
, const char *v
)
1102 struct lxc_config_t
*config
;
1107 if (container_mem_lock(c
))
1111 c
->lxc_conf
= lxc_conf_init();
1114 config
= lxc_getconfig(key
);
1117 ret
= config
->cb(key
, v
, c
->lxc_conf
);
1122 container_mem_unlock(c
);
1126 static char *lxcapi_config_file_name(struct lxc_container
*c
)
1128 if (!c
|| !c
->configfile
)
1130 return strdup(c
->configfile
);
1133 static const char *lxcapi_get_config_path(struct lxc_container
*c
)
1135 if (!c
|| !c
->config_path
)
1137 return (const char *)(c
->config_path
);
1142 * Just recalculate the c->configfile based on the
1143 * c->config_path, which must be set.
1144 * The lxc_container must be locked or not yet public.
1146 static bool set_config_filename(struct lxc_container
*c
)
1151 if (!c
->config_path
)
1154 /* $lxc_path + "/" + c->name + "/" + "config" + '\0' */
1155 len
= strlen(c
->config_path
) + strlen(c
->name
) + strlen("config") + 3;
1156 newpath
= malloc(len
);
1160 ret
= snprintf(newpath
, len
, "%s/%s/config", c
->config_path
, c
->name
);
1161 if (ret
< 0 || ret
>= len
) {
1162 fprintf(stderr
, "Error printing out config file name\n");
1168 free(c
->configfile
);
1169 c
->configfile
= newpath
;
1174 static bool lxcapi_set_config_path(struct lxc_container
*c
, const char *path
)
1178 char *oldpath
= NULL
;
1183 if (container_mem_lock(c
))
1188 ERROR("Out of memory setting new lxc path");
1194 oldpath
= c
->config_path
;
1197 /* Since we've changed the config path, we have to change the
1198 * config file name too */
1199 if (!set_config_filename(c
)) {
1200 ERROR("Out of memory setting new config filename");
1202 free(c
->config_path
);
1203 c
->config_path
= oldpath
;
1209 container_mem_unlock(c
);
1214 static bool lxcapi_set_cgroup_item(struct lxc_container
*c
, const char *subsys
, const char *value
)
1222 if (container_mem_lock(c
))
1225 if (is_stopped_locked(c
))
1228 ret
= lxc_cgroup_set(c
->name
, subsys
, value
, c
->config_path
);
1232 container_mem_unlock(c
);
1236 static int lxcapi_get_cgroup_item(struct lxc_container
*c
, const char *subsys
, char *retv
, int inlen
)
1240 if (!c
|| !c
->lxc_conf
)
1243 if (container_mem_lock(c
))
1246 if (is_stopped_locked(c
))
1249 ret
= lxc_cgroup_get(c
->name
, subsys
, retv
, inlen
, c
->config_path
);
1252 container_mem_unlock(c
);
1256 const char *lxc_get_default_config_path(void)
1258 return default_lxc_path();
1261 const char *lxc_get_default_lvm_vg(void)
1263 return default_lvm_vg();
1266 const char *lxc_get_default_zfs_root(void)
1268 return default_zfs_root();
1271 const char *lxc_get_version(void)
1273 return lxc_version();
1276 static int copy_file(char *old
, char *new)
1283 if (file_exists(new)) {
1284 ERROR("copy destination %s exists", new);
1287 ret
= stat(old
, &sbuf
);
1289 SYSERROR("stat'ing %s", old
);
1293 in
= open(old
, O_RDONLY
);
1295 SYSERROR("opening original file %s", old
);
1298 out
= open(new, O_CREAT
| O_EXCL
| O_WRONLY
, 0644);
1300 SYSERROR("opening new file %s", new);
1306 len
= read(in
, buf
, 8096);
1308 SYSERROR("reading old file %s", old
);
1313 ret
= write(out
, buf
, len
);
1314 if (ret
< len
) { // should we retry?
1315 SYSERROR("write to new file %s was interrupted", new);
1322 // we set mode, but not owner/group
1323 ret
= chmod(new, sbuf
.st_mode
);
1325 SYSERROR("setting mode on %s", new);
1338 * we're being passed result of two strstrs(x, y). We want to write
1339 * all data up to the first found string, or to end of the string if
1340 * neither string was found.
1341 * This function will return the earliest found string if any, or else
1344 static const char *lowest_nonnull(const char *p1
, const char *p2
)
1350 return p1
< p2
? p1
: p2
;
1353 static int is_word_sep(char c
)
1368 static const char *find_first_wholeword(const char *p
, const char *word
)
1373 while ((p
= strstr(p
, word
)) != NULL
) {
1374 if (is_word_sep(*(p
-1)) && is_word_sep(p
[strlen(word
)]))
1381 static int update_name_and_paths(const char *path
, struct lxc_container
*oldc
,
1382 const char *newname
, const char *newpath
)
1387 const char *p0
, *p1
, *p2
, *end
;
1388 const char *oldpath
= oldc
->get_config_path(oldc
);
1389 const char *oldname
= oldc
->name
;
1391 f
= fopen(path
, "r");
1393 SYSERROR("opening old config");
1396 if (fseek(f
, 0, SEEK_END
) < 0) {
1397 SYSERROR("seeking to end of old config");
1404 SYSERROR("telling size of old config");
1407 if (fseek(f
, 0, SEEK_SET
) < 0) {
1409 SYSERROR("rewinding old config");
1412 contents
= malloc(flen
+1);
1414 SYSERROR("out of memory");
1418 if (fread(contents
, 1, flen
, f
) != flen
) {
1421 SYSERROR("reading old config");
1424 contents
[flen
] = '\0';
1425 if (fclose(f
) < 0) {
1427 SYSERROR("closing old config");
1431 f
= fopen(path
, "w");
1433 SYSERROR("reopening config");
1439 end
= contents
+ flen
;
1441 p1
= find_first_wholeword(p0
, oldpath
);
1442 p2
= find_first_wholeword(p0
, oldname
);
1444 // write the rest and be done
1445 if (fwrite(p0
, 1, (end
-p0
), f
) != (end
-p0
)) {
1446 SYSERROR("writing new config");
1456 const char *p
= lowest_nonnull(p1
, p2
);
1457 const char *new = (p
== p2
) ? newname
: newpath
;
1458 if (fwrite(p0
, 1, (p
-p0
), f
) != (p
-p0
)) {
1459 SYSERROR("writing new config");
1465 // now write the newpath or newname
1466 if (fwrite(new, 1, strlen(new), f
) != strlen(new)) {
1467 SYSERROR("writing new name or path in new config");
1472 p0
+= (p
== p2
) ? strlen(oldname
) : strlen(oldpath
);
1477 static int copyhooks(struct lxc_container
*oldc
, struct lxc_container
*c
)
1481 struct lxc_list
*it
;
1483 for (i
=0; i
<NUM_LXC_HOOKS
; i
++) {
1484 lxc_list_for_each(it
, &c
->lxc_conf
->hooks
[i
]) {
1485 char *hookname
= it
->elem
;
1486 char *fname
= rindex(hookname
, '/');
1487 char tmppath
[MAXPATHLEN
];
1488 if (!fname
) // relative path - we don't support, but maybe we should
1490 // copy the script, and change the entry in confile
1491 ret
= snprintf(tmppath
, MAXPATHLEN
, "%s/%s/%s",
1492 c
->config_path
, c
->name
, fname
+1);
1493 if (ret
< 0 || ret
>= MAXPATHLEN
)
1495 ret
= copy_file(it
->elem
, tmppath
);
1499 it
->elem
= strdup(tmppath
);
1501 ERROR("out of memory copying hook path");
1504 update_name_and_paths(it
->elem
, oldc
, c
->name
, c
->get_config_path(c
));
1508 c
->save_config(c
, NULL
);
1512 static void new_hwaddr(char *hwaddr
)
1514 FILE *f
= fopen("/dev/urandom", "r");
1517 int ret
= fread(&seed
, sizeof(seed
), 1, f
);
1524 snprintf(hwaddr
, 18, "00:16:3e:%02x:%02x:%02x",
1525 rand() % 255, rand() % 255, rand() % 255);
1528 static void network_new_hwaddrs(struct lxc_container
*c
)
1530 struct lxc_list
*it
;
1532 lxc_list_for_each(it
, &c
->lxc_conf
->network
) {
1533 struct lxc_netdev
*n
= it
->elem
;
1535 new_hwaddr(n
->hwaddr
);
1539 static int copy_fstab(struct lxc_container
*oldc
, struct lxc_container
*c
)
1541 char newpath
[MAXPATHLEN
];
1542 char *oldpath
= oldc
->lxc_conf
->fstab
;
1548 char *p
= rindex(oldpath
, '/');
1551 ret
= snprintf(newpath
, MAXPATHLEN
, "%s/%s%s",
1552 c
->config_path
, c
->name
, p
);
1553 if (ret
< 0 || ret
>= MAXPATHLEN
) {
1554 ERROR("error printing new path for %s", oldpath
);
1557 if (file_exists(newpath
)) {
1558 ERROR("error: fstab file %s exists", newpath
);
1562 if (copy_file(oldpath
, newpath
) < 0) {
1563 ERROR("error: copying %s to %s", oldpath
, newpath
);
1566 free(c
->lxc_conf
->fstab
);
1567 c
->lxc_conf
->fstab
= strdup(newpath
);
1568 if (!c
->lxc_conf
->fstab
) {
1569 ERROR("error: allocating pathname");
1576 static int copy_storage(struct lxc_container
*c0
, struct lxc_container
*c
,
1577 const char *newtype
, int flags
, const char *bdevdata
, unsigned long newsize
)
1581 bdev
= bdev_copy(c0
->lxc_conf
->rootfs
.path
, c0
->name
, c
->name
,
1582 c0
->config_path
, c
->config_path
, newtype
, !!(flags
& LXC_CLONE_SNAPSHOT
),
1585 ERROR("error copying storage");
1588 free(c
->lxc_conf
->rootfs
.path
);
1589 c
->lxc_conf
->rootfs
.path
= strdup(bdev
->src
);
1591 if (!c
->lxc_conf
->rootfs
.path
)
1593 // here we could also update all lxc.mount.entries or even
1594 // items in the lxc.mount fstab list. As discussed on m-l,
1595 // we could do either any source paths starting with the
1596 // lxcpath/oldname, or simply anythign which is not a virtual
1597 // fs or a bind mount.
1601 static int clone_update_rootfs(struct lxc_container
*c
, int flags
, char **hookargs
)
1604 char path
[MAXPATHLEN
];
1608 struct lxc_conf
*conf
= c
->lxc_conf
;
1610 /* update hostname in rootfs */
1611 /* we're going to mount, so run in a clean namespace to simplify cleanup */
1617 return wait_for_pid(pid
);
1619 if (unshare(CLONE_NEWNS
) < 0) {
1620 ERROR("error unsharing mounts");
1623 bdev
= bdev_init(c
->lxc_conf
->rootfs
.path
, c
->lxc_conf
->rootfs
.mount
, NULL
);
1626 if (bdev
->ops
->mount(bdev
) < 0)
1629 if (!lxc_list_empty(&conf
->hooks
[LXCHOOK_CLONE
])) {
1630 /* Start of environment variable setup for hooks */
1631 if (setenv("LXC_NAME", c
->name
, 1)) {
1632 SYSERROR("failed to set environment variable for container name");
1634 if (setenv("LXC_CONFIG_FILE", conf
->rcfile
, 1)) {
1635 SYSERROR("failed to set environment variable for config path");
1637 if (setenv("LXC_ROOTFS_MOUNT", conf
->rootfs
.mount
, 1)) {
1638 SYSERROR("failed to set environment variable for rootfs mount");
1640 if (setenv("LXC_ROOTFS_PATH", conf
->rootfs
.path
, 1)) {
1641 SYSERROR("failed to set environment variable for rootfs mount");
1644 if (run_lxc_hooks(c
->name
, "clone", conf
, hookargs
)) {
1645 ERROR("Error executing clone hook for %s", c
->name
);
1650 if (!(flags
& LXC_CLONE_KEEPNAME
)) {
1651 ret
= snprintf(path
, MAXPATHLEN
, "%s/etc/hostname", bdev
->dest
);
1652 if (ret
< 0 || ret
>= MAXPATHLEN
)
1654 if (!(fout
= fopen(path
, "w"))) {
1655 SYSERROR("unable to open %s: ignoring\n", path
);
1658 if (fprintf(fout
, "%s", c
->name
) < 0)
1660 if (fclose(fout
) < 0)
1667 * We want to support:
1668 sudo lxc-clone -o o1 -n n1 -s -L|-fssize fssize -v|--vgname vgname \
1669 -p|--lvprefix lvprefix -t|--fstype fstype -B backingstore
1671 -s [ implies overlayfs]
1675 only rootfs gets converted (copied/snapshotted) on clone.
1678 static int create_file_dirname(char *path
)
1680 char *p
= rindex(path
, '/');
1686 ret
= mkdir(path
, 0755);
1687 if (ret
&& errno
!= EEXIST
)
1688 SYSERROR("creating container path %s\n", path
);
1693 struct lxc_container
*lxcapi_clone(struct lxc_container
*c
, const char *newname
,
1694 const char *lxcpath
, int flags
,
1695 const char *bdevtype
, const char *bdevdata
, unsigned long newsize
,
1698 struct lxc_container
*c2
= NULL
;
1699 char newpath
[MAXPATHLEN
];
1704 if (!c
|| !c
->is_defined(c
))
1707 if (container_mem_lock(c
))
1710 if (c
->is_running(c
)) {
1711 ERROR("error: Original container (%s) is running", c
->name
);
1715 // Make sure the container doesn't yet exist.
1716 n
= newname
? newname
: c
->name
;
1717 l
= lxcpath
? lxcpath
: c
->get_config_path(c
);
1718 ret
= snprintf(newpath
, MAXPATHLEN
, "%s/%s/config", l
, n
);
1719 if (ret
< 0 || ret
>= MAXPATHLEN
) {
1720 SYSERROR("clone: failed making config pathname");
1723 if (file_exists(newpath
)) {
1724 ERROR("error: clone: %s exists", newpath
);
1728 if (create_file_dirname(newpath
) < 0) {
1729 ERROR("Error creating container dir for %s", newpath
);
1733 // copy the configuration, tweak it as needed,
1734 fout
= fopen(newpath
, "w");
1736 SYSERROR("open %s", newpath
);
1739 write_config(fout
, c
->lxc_conf
);
1742 if (update_name_and_paths(newpath
, c
, n
, l
) < 0) {
1743 ERROR("Error updating name in cloned config");
1747 sprintf(newpath
, "%s/%s/rootfs", l
, n
);
1748 if (mkdir(newpath
, 0755) < 0) {
1749 SYSERROR("error creating %s", newpath
);
1753 c2
= lxc_container_new(n
, l
);
1755 ERROR("clone: failed to create new container (%s %s)", n
, l
);
1759 // copy hooks if requested
1760 if (flags
& LXC_CLONE_COPYHOOKS
) {
1761 ret
= copyhooks(c
, c2
);
1763 ERROR("error copying hooks");
1768 if (copy_fstab(c
, c2
) < 0) {
1769 ERROR("error copying fstab");
1774 if (!(flags
& LXC_CLONE_KEEPMACADDR
))
1775 network_new_hwaddrs(c2
);
1777 // copy/snapshot rootfs's
1778 ret
= copy_storage(c
, c2
, bdevtype
, flags
, bdevdata
, newsize
);
1782 if (!c2
->save_config(c2
, NULL
))
1785 if (clone_update_rootfs(c2
, flags
, hookargs
) < 0)
1788 // TODO: update c's lxc.snapshot = count
1789 container_mem_unlock(c
);
1793 container_mem_unlock(c
);
1796 lxc_container_put(c2
);
1802 struct lxc_container
*lxc_container_new(const char *name
, const char *configpath
)
1804 struct lxc_container
*c
;
1806 c
= malloc(sizeof(*c
));
1808 fprintf(stderr
, "failed to malloc lxc_container\n");
1811 memset(c
, 0, sizeof(*c
));
1814 c
->config_path
= strdup(configpath
);
1816 c
->config_path
= strdup(default_lxc_path());
1818 if (!c
->config_path
) {
1819 fprintf(stderr
, "Out of memory");
1823 c
->name
= malloc(strlen(name
)+1);
1825 fprintf(stderr
, "Error allocating lxc_container name\n");
1828 strcpy(c
->name
, name
);
1831 if (!(c
->slock
= lxc_newlock(c
->config_path
, name
))) {
1832 fprintf(stderr
, "failed to create lock\n");
1836 if (!(c
->privlock
= lxc_newlock(NULL
, NULL
))) {
1837 fprintf(stderr
, "failed to alloc privlock\n");
1841 if (!set_config_filename(c
)) {
1842 fprintf(stderr
, "Error allocating config file pathname\n");
1846 if (file_exists(c
->configfile
))
1847 lxcapi_load_config(c
, NULL
);
1849 if (ongoing_create(c
) == 2) {
1850 ERROR("Error: %s creation was not completed", c
->name
);
1855 // assign the member functions
1856 c
->is_defined
= lxcapi_is_defined
;
1857 c
->state
= lxcapi_state
;
1858 c
->is_running
= lxcapi_is_running
;
1859 c
->freeze
= lxcapi_freeze
;
1860 c
->unfreeze
= lxcapi_unfreeze
;
1861 c
->init_pid
= lxcapi_init_pid
;
1862 c
->load_config
= lxcapi_load_config
;
1863 c
->want_daemonize
= lxcapi_want_daemonize
;
1864 c
->start
= lxcapi_start
;
1865 c
->startl
= lxcapi_startl
;
1866 c
->stop
= lxcapi_stop
;
1867 c
->config_file_name
= lxcapi_config_file_name
;
1868 c
->wait
= lxcapi_wait
;
1869 c
->set_config_item
= lxcapi_set_config_item
;
1870 c
->destroy
= lxcapi_destroy
;
1871 c
->save_config
= lxcapi_save_config
;
1872 c
->get_keys
= lxcapi_get_keys
;
1873 c
->create
= lxcapi_create
;
1874 c
->createl
= lxcapi_createl
;
1875 c
->shutdown
= lxcapi_shutdown
;
1876 c
->reboot
= lxcapi_reboot
;
1877 c
->clear_config_item
= lxcapi_clear_config_item
;
1878 c
->get_config_item
= lxcapi_get_config_item
;
1879 c
->get_cgroup_item
= lxcapi_get_cgroup_item
;
1880 c
->set_cgroup_item
= lxcapi_set_cgroup_item
;
1881 c
->get_config_path
= lxcapi_get_config_path
;
1882 c
->set_config_path
= lxcapi_set_config_path
;
1883 c
->clone
= lxcapi_clone
;
1884 c
->get_ips
= lxcapi_get_ips
;
1886 /* we'll allow the caller to update these later */
1887 if (lxc_log_init(NULL
, "none", NULL
, "lxc_container", 0, c
->config_path
)) {
1888 fprintf(stderr
, "failed to open log\n");
1895 lxc_container_free(c
);
1899 int lxc_get_wait_states(const char **states
)
1904 for (i
=0; i
<MAX_STATE
; i
++)
1905 states
[i
] = lxc_state2str(i
);