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.
22
#include "lxccontainer.h"
30
#include <sys/types.h>
33
#include <lxc/utils.h>
35
lxc_log_define(lxc_container, lxc);
38
* c->privlock protects the struct lxc_container from multiple threads.
39
* c->slock protects the on-disk container data
40
* NOTHING mutexes two independent programs with their own struct
41
* lxc_container for the same c->name, between API calls. For instance,
42
* c->config_read(); c->start(); Between those calls, data on disk
43
* could change (which shouldn't bother the caller unless for instance
44
* the rootfs get moved). c->config_read(); update; c->config_write();
45
* Two such updaters could race. The callers should therefore check their
46
* results. Trying to prevent that would necessarily expose us to deadlocks
47
* due to hung callers. So I prefer to keep the locks only within our own
48
* functions, not across functions.
50
* If you're going to fork while holding a lxccontainer, increment
51
* c->numthreads (under privlock) before forking. When deleting,
52
* decrement numthreads under privlock, then if it hits 0 you can delete.
53
* Do not ever use a lxccontainer whose numthreads you did not bump.
56
static void lxc_container_free(struct lxc_container *c)
65
if (c->error_string) {
66
free(c->error_string);
67
c->error_string = NULL;
74
sem_destroy(c->privlock);
83
lxc_conf_free(c->lxc_conf);
88
c->config_path = NULL;
93
int lxc_container_get(struct lxc_container *c)
98
if (lxclock(c->privlock, 0))
100
if (c->numthreads < 1) {
101
// bail without trying to unlock, bc the privlock is now probably
106
lxcunlock(c->privlock);
110
int lxc_container_put(struct lxc_container *c)
114
if (lxclock(c->privlock, 0))
116
if (--c->numthreads < 1) {
117
lxcunlock(c->privlock);
118
lxc_container_free(c);
121
lxcunlock(c->privlock);
125
static bool file_exists(char *f)
129
return stat(f, &statbuf) == 0;
132
static bool lxcapi_is_defined(struct lxc_container *c)
141
if (lxclock(c->privlock, 0))
145
statret = stat(c->configfile, &statbuf);
151
lxcunlock(c->privlock);
155
static const char *lxcapi_state(struct lxc_container *c)
162
if (lxclock(c->slock, 0))
164
s = lxc_getstate(c->name, c->config_path);
165
ret = lxc_state2str(s);
171
static bool is_stopped_nolock(struct lxc_container *c)
174
s = lxc_getstate(c->name, c->config_path);
175
return (s == STOPPED);
178
static bool lxcapi_is_running(struct lxc_container *c)
185
if (!s || strcmp(s, "STOPPED") == 0)
190
static bool lxcapi_freeze(struct lxc_container *c)
196
if (lxclock(c->slock, 0))
198
ret = lxc_freeze(c->name);
205
static bool lxcapi_unfreeze(struct lxc_container *c)
211
if (lxclock(c->slock, 0))
213
ret = lxc_unfreeze(c->name);
220
static pid_t lxcapi_init_pid(struct lxc_container *c)
226
if (lxclock(c->slock, 0))
228
ret = get_init_pid(c->name, c->config_path);
233
static bool load_config_locked(struct lxc_container *c, const char *fname)
236
c->lxc_conf = lxc_conf_init();
237
if (c->lxc_conf && !lxc_config_read(fname, c->lxc_conf))
242
static bool lxcapi_load_config(struct lxc_container *c, const char *alt_file)
249
fname = c->configfile;
254
if (lxclock(c->slock, 0))
256
ret = load_config_locked(c, fname);
261
static void lxcapi_want_daemonize(struct lxc_container *c)
268
static bool lxcapi_wait(struct lxc_container *c, const char *state, int timeout)
275
ret = lxc_wait(c->name, state, timeout);
280
static bool wait_on_daemonized_start(struct lxc_container *c)
282
/* we'll probably want to make this timeout configurable? */
283
int timeout = 5, ret, status;
286
* our child is going to fork again, then exit. reap the
290
if (ret == -1 || !WIFEXITED(status) || WEXITSTATUS(status) != 0)
291
DEBUG("failed waiting for first dual-fork child");
292
return lxcapi_wait(c, "RUNNING", timeout);
296
* I can't decide if it'd be more convenient for callers if we accept '...',
297
* or a null-terminated array (i.e. execl vs execv)
299
static bool lxcapi_start(struct lxc_container *c, int useinit, char * const argv[])
302
struct lxc_conf *conf;
304
char *default_args[] = {
309
/* container exists */
312
/* container has been setup */
316
/* is this app meant to be run through lxcinit, as in lxc-execute? */
317
if (useinit && !argv)
320
if (lxclock(c->privlock, 0))
323
daemonize = c->daemonize;
324
lxcunlock(c->privlock);
327
ret = lxc_execute(c->name, argv, 1, conf, c->config_path);
328
return ret == 0 ? true : false;
335
* say, I'm not sure - what locks do we want here? Any?
336
* Is liblxc's locking enough here to protect the on disk
337
* container? We don't want to exclude things like lxc_info
338
* while container is running...
341
if (!lxc_container_get(c))
345
lxc_container_put(c);
349
return wait_on_daemonized_start(c);
350
/* second fork to be reparented by init */
353
SYSERROR("Error doing dual-fork");
358
/* like daemon(), chdir to / and redirect 0,1,2 to /dev/null */
360
SYSERROR("Error chdir()ing to /.");
366
open("/dev/null", O_RDONLY);
367
open("/dev/null", O_RDWR);
368
open("/dev/null", O_RDWR);
373
SYSERROR("failed to clear environment");
374
/* don't error out though */
377
if (putenv("container=lxc")) {
378
fprintf(stderr, "failed to set environment variable");
380
lxc_container_put(c);
389
ret = lxc_start(c->name, argv, conf, c->config_path);
392
INFO("container requested reboot");
398
lxc_container_put(c);
399
exit (ret == 0 ? true : false);
401
return (ret == 0 ? true : false);
406
* note there MUST be an ending NULL
408
static bool lxcapi_startl(struct lxc_container *c, int useinit, ...)
411
char **inargs = NULL, **temp;
415
/* container exists */
419
/* build array of arguments if any */
420
va_start(ap, useinit);
423
arg = va_arg(ap, char *);
427
temp = realloc(inargs, n_inargs * sizeof(*inargs));
431
inargs[n_inargs - 1] = strdup(arg); // not sure if it's safe not to copy
435
/* add trailing NULL */
438
temp = realloc(inargs, n_inargs * sizeof(*inargs));
442
inargs[n_inargs - 1] = NULL;
445
bret = lxcapi_start(c, useinit, inargs);
450
for (i = 0; i < n_inargs; i++) {
460
static bool lxcapi_stop(struct lxc_container *c)
467
ret = lxc_stop(c->name, c->config_path);
472
static bool valid_template(char *t)
477
statret = stat(t, &statbuf);
484
* create the standard expected container dir
486
static bool create_container_dir(struct lxc_container *c)
491
len = strlen(c->config_path) + strlen(c->name) + 2;
495
ret = snprintf(s, len, "%s/%s", c->config_path, c->name);
496
if (ret < 0 || ret >= len) {
500
ret = mkdir(s, 0755);
505
SYSERROR("failed to create container path for %s\n", c->name);
512
* backing stores not (yet) supported
513
* for ->create, argv contains the arguments to pass to the template,
514
* terminated by NULL. If no arguments, you can just pass NULL.
516
static bool lxcapi_create(struct lxc_container *c, char *t, char *const argv[])
528
len = strlen(LXCTEMPLATEDIR) + strlen(t) + strlen("/lxc-") + 1;
532
ret = snprintf(tpath, len, "%s/lxc-%s", LXCTEMPLATEDIR, t);
533
if (ret < 0 || ret >= len)
535
if (!valid_template(tpath)) {
536
ERROR("bad template: %s\n", t);
540
if (!create_container_dir(c))
543
if (!c->save_config(c, NULL)) {
544
ERROR("failed to save starting configuration for %s\n", c->name);
548
/* we're going to fork. but since we'll wait for our child, we
549
don't need to lxc_container_get */
551
if (lxclock(c->slock, 0)) {
552
ERROR("failed to grab global container lock for %s\n", c->name);
558
SYSERROR("failed to fork task for container creation template\n");
562
if (pid == 0) { // child
563
char *patharg, *namearg;
569
open("/dev/null", O_RDONLY);
570
open("/dev/null", O_RDWR);
571
open("/dev/null", O_RDWR);
574
* create our new array, pre-pend the template name and
578
for (; argv[nargs]; nargs++) ;
579
nargs += 3; // template, path and name args
580
newargv = malloc(nargs * sizeof(*newargv));
585
len = strlen(c->config_path) + strlen(c->name) + strlen("--path=") + 2;
586
patharg = malloc(len);
589
ret = snprintf(patharg, len, "--path=%s/%s", c->config_path, c->name);
590
if (ret < 0 || ret >= len)
592
newargv[1] = patharg;
593
len = strlen("--name=") + strlen(c->name) + 1;
594
namearg = malloc(len);
597
ret = snprintf(namearg, len, "--name=%s", c->name);
598
if (ret < 0 || ret >= len)
600
newargv[2] = namearg;
602
/* add passed-in args */
604
for (i = 3; i < nargs; i++)
605
newargv[i] = argv[i-3];
607
/* add trailing NULL */
609
newargv = realloc(newargv, nargs * sizeof(*newargv));
612
newargv[nargs - 1] = NULL;
615
ret = execv(tpath, newargv);
616
SYSERROR("failed to execute template %s", tpath);
621
ret = waitpid(pid, &status, 0);
625
SYSERROR("waitpid failed");
630
if (!WIFEXITED(status)) { // did not exit normally
631
// we could set an error code and string inside the
632
// container_struct here if we like
633
ERROR("container creation template exited abnormally\n");
637
if (WEXITSTATUS(status) != 0) {
638
ERROR("container creation template for %s exited with %d\n",
639
c->name, WEXITSTATUS(status));
643
// now clear out the lxc_conf we have, reload from the created
646
lxc_conf_free(c->lxc_conf);
648
bret = load_config_locked(c, c->configfile);
658
static bool lxcapi_shutdown(struct lxc_container *c, int timeout)
668
if (!c->is_running(c))
670
pid = c->init_pid(c);
674
retv = c->wait(c, "STOPPED", timeout);
675
if (!retv && timeout > 0) {
677
retv = c->wait(c, "STOPPED", 0); // 0 means don't wait
682
static bool lxcapi_createl(struct lxc_container *c, char *t, ...)
685
char **args = NULL, **temp;
693
* since we're going to wait for create to finish, I don't think we
694
* need to get a copy of the arguments.
699
arg = va_arg(ap, char *);
703
temp = realloc(args, (nargs+1) * sizeof(*args));
707
args[nargs - 1] = arg;
712
bret = c->create(c, t, args);
720
static bool lxcapi_clear_config_item(struct lxc_container *c, const char *key)
724
if (!c || !c->lxc_conf)
726
if (lxclock(c->privlock, 0)) {
729
ret = lxc_clear_config_item(c->lxc_conf, key);
730
lxcunlock(c->privlock);
734
static int lxcapi_get_config_item(struct lxc_container *c, const char *key, char *retv, int inlen)
738
if (!c || !c->lxc_conf)
740
if (lxclock(c->privlock, 0)) {
743
ret = lxc_get_config_item(c->lxc_conf, key, retv, inlen);
744
lxcunlock(c->privlock);
748
static int lxcapi_get_keys(struct lxc_container *c, const char *key, char *retv, int inlen)
751
return lxc_listconfigs(retv, inlen);
753
* Support 'lxc.network.<idx>', i.e. 'lxc.network.0'
754
* This is an intelligent result to show which keys are valid given
755
* the type of nic it is
757
if (!c || !c->lxc_conf)
759
if (lxclock(c->privlock, 0))
762
if (strncmp(key, "lxc.network.", 12) == 0)
763
ret = lxc_list_nicconfigs(c->lxc_conf, key, retv, inlen);
764
lxcunlock(c->privlock);
769
/* default config file - should probably come through autoconf */
770
#define LXC_DEFAULT_CONFIG "/etc/lxc/default.conf"
771
static bool lxcapi_save_config(struct lxc_container *c, const char *alt_file)
774
alt_file = c->configfile;
776
return false; // should we write to stdout if no file is specified?
778
if (!c->load_config(c, LXC_DEFAULT_CONFIG)) {
779
ERROR("Error loading default configuration file %s while saving %s\n", LXC_DEFAULT_CONFIG, c->name);
783
FILE *fout = fopen(alt_file, "w");
786
if (lxclock(c->privlock, 0)) {
790
write_config(fout, c->lxc_conf);
792
lxcunlock(c->privlock);
796
static bool lxcapi_destroy(struct lxc_container *c)
807
if (pid == 0) { // child
808
ret = execlp("lxc-destroy", "lxc-destroy", "-n", c->name, NULL);
814
ret = waitpid(pid, &status, 0);
823
if (!WIFEXITED(status)) { // did not exit normally
824
// we could set an error code and string inside the
825
// container_struct here if we like
829
return WEXITSTATUS(status) == 0;
832
static bool lxcapi_set_config_item(struct lxc_container *c, const char *key, const char *v)
836
struct lxc_config_t *config;
841
if (lxclock(c->privlock, 0))
845
c->lxc_conf = lxc_conf_init();
848
config = lxc_getconfig(key);
851
ret = config->cb(key, v, c->lxc_conf);
856
lxcunlock(c->privlock);
860
static char *lxcapi_config_file_name(struct lxc_container *c)
862
if (!c || !c->configfile)
864
return strdup(c->configfile);
867
static const char *lxcapi_get_config_path(struct lxc_container *c)
869
if (!c || !c->config_path)
871
return (const char *)(c->config_path);
876
* Just recalculate the c->configfile based on the
877
* c->config_path, which must be set.
878
* The lxc_container must be locked or not yet public.
880
static bool set_config_filename(struct lxc_container *c)
888
/* $lxc_path + "/" + c->name + "/" + "config" + '\0' */
889
len = strlen(c->config_path) + strlen(c->name) + strlen("config") + 3;
890
newpath = malloc(len);
894
ret = snprintf(newpath, len, "%s/%s/config", c->config_path, c->name);
895
if (ret < 0 || ret >= len) {
896
fprintf(stderr, "Error printing out config file name\n");
903
c->configfile = newpath;
908
static bool lxcapi_set_config_path(struct lxc_container *c, const char *path)
912
char *oldpath = NULL;
917
if (lxclock(c->privlock, 0))
922
ERROR("Out of memory setting new lxc path");
928
oldpath = c->config_path;
931
/* Since we've changed the config path, we have to change the
932
* config file name too */
933
if (!set_config_filename(c)) {
934
ERROR("Out of memory setting new config filename");
936
free(c->config_path);
937
c->config_path = oldpath;
943
lxcunlock(c->privlock);
948
static bool lxcapi_set_cgroup_item(struct lxc_container *c, const char *subsys, const char *value)
956
if (lxclock(c->privlock, 0))
959
if (is_stopped_nolock(c))
962
ret = lxc_cgroup_set(c->name, subsys, value);
966
lxcunlock(c->privlock);
970
static int lxcapi_get_cgroup_item(struct lxc_container *c, const char *subsys, char *retv, int inlen)
974
if (!c || !c->lxc_conf)
977
if (lxclock(c->privlock, 0))
980
if (is_stopped_nolock(c))
983
ret = lxc_cgroup_get(c->name, subsys, retv, inlen);
986
lxcunlock(c->privlock);
990
char *lxc_get_default_config_path(void)
992
return default_lxc_path();
995
struct lxc_container *lxc_container_new(const char *name, const char *configpath)
997
struct lxc_container *c;
999
c = malloc(sizeof(*c));
1001
fprintf(stderr, "failed to malloc lxc_container\n");
1004
memset(c, 0, sizeof(*c));
1007
c->config_path = strdup(configpath);
1009
c->config_path = default_lxc_path();
1011
if (!c->config_path) {
1012
fprintf(stderr, "Out of memory");
1016
c->name = malloc(strlen(name)+1);
1018
fprintf(stderr, "Error allocating lxc_container name\n");
1021
strcpy(c->name, name);
1024
c->slock = lxc_newlock(name);
1026
fprintf(stderr, "failed to create lock\n");
1030
c->privlock = lxc_newlock(NULL);
1032
fprintf(stderr, "failed to alloc privlock\n");
1036
if (!set_config_filename(c)) {
1037
fprintf(stderr, "Error allocating config file pathname\n");
1041
if (file_exists(c->configfile))
1042
lxcapi_load_config(c, NULL);
1044
// assign the member functions
1045
c->is_defined = lxcapi_is_defined;
1046
c->state = lxcapi_state;
1047
c->is_running = lxcapi_is_running;
1048
c->freeze = lxcapi_freeze;
1049
c->unfreeze = lxcapi_unfreeze;
1050
c->init_pid = lxcapi_init_pid;
1051
c->load_config = lxcapi_load_config;
1052
c->want_daemonize = lxcapi_want_daemonize;
1053
c->start = lxcapi_start;
1054
c->startl = lxcapi_startl;
1055
c->stop = lxcapi_stop;
1056
c->config_file_name = lxcapi_config_file_name;
1057
c->wait = lxcapi_wait;
1058
c->set_config_item = lxcapi_set_config_item;
1059
c->destroy = lxcapi_destroy;
1060
c->save_config = lxcapi_save_config;
1061
c->get_keys = lxcapi_get_keys;
1062
c->create = lxcapi_create;
1063
c->createl = lxcapi_createl;
1064
c->shutdown = lxcapi_shutdown;
1065
c->clear_config_item = lxcapi_clear_config_item;
1066
c->get_config_item = lxcapi_get_config_item;
1067
c->get_cgroup_item = lxcapi_get_cgroup_item;
1068
c->set_cgroup_item = lxcapi_set_cgroup_item;
1069
c->get_config_path = lxcapi_get_config_path;
1070
c->set_config_path = lxcapi_set_config_path;
1072
/* we'll allow the caller to update these later */
1073
if (lxc_log_init(NULL, "none", NULL, "lxc_container", 0)) {
1074
fprintf(stderr, "failed to open log\n");
1081
lxc_container_free(c);
1085
int lxc_get_wait_states(const char **states)
1090
for (i=0; i<MAX_STATE; i++)
1091
states[i] = lxc_state2str(i);