openvz_conf.c 11.4 KB
Newer Older
1 2 3 4 5
/*
 * openvz_conf.c: config functions for managing OpenVZ VEs
 *
 * Copyright (C) 2006, 2007 Binary Karma
 * Copyright (C) 2006 Shuveb Hussain
6
 * Copyright (C) 2007 Anoop Joe Cyriac
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
 *
22
 * Authors:
23 24 25
 * Shuveb Hussain <shuveb@binarykarma.com>
 * Anoop Joe Cyriac <anoop@binarykarma.com>
 *
26 27
 */

28
#include <config.h>
J
Jim Meyering 已提交
29

30 31 32 33 34 35 36 37
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <dirent.h>
#include <strings.h>
#include <time.h>
38 39 40 41
#include <sys/stat.h>
#include <unistd.h>
#include <limits.h>
#include <errno.h>
D
Daniel P. Berrange 已提交
42
#include <string.h>
43
#include <sys/utsname.h>
44

45
#include "openvz_conf.h"
46 47
#include "uuid.h"
#include "buf.h"
48
#include "memory.h"
49
#include "util.h"
50

51 52
static char *openvzLocateConfDir(void);
static int openvzGetVPSUUID(int vpsid, char *uuidstr);
53
static int openvzLocateConfFile(int vpsid, char *conffile, int maxlen);
54
static int openvzAssignUUIDs(void);
55

56
void
D
Daniel Veillard 已提交
57
openvzError (virConnectPtr conn, virErrorNumber code, const char *fmt, ...)
58
{
59
    va_list args;
60
    char errorMessage[1024];
61 62
    const char *errmsg;

63 64
    if (fmt) {
        va_start(args, fmt);
65
        vsnprintf(errorMessage, sizeof(errorMessage)-1, fmt, args);
66 67 68 69 70 71
        va_end(args);
    } else {
        errorMessage[0] = '\0';
    }

    errmsg = __virErrorMsg(code, (errorMessage[0] ? errorMessage : NULL));
72
    __virRaiseError (conn, NULL, NULL, VIR_FROM_OPENVZ,
73 74
                     code, VIR_ERR_ERROR, errmsg, errorMessage, NULL, 0, 0,
                     errmsg, errorMessage);
75 76 77
}


78
int
79
strtoI(const char *str)
80 81 82
{
    int val;

83 84
    if (virStrToLong_i(str, NULL, 10, &val) < 0)
        return 0 ;
85

86 87 88
    return val;
}

89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
virCapsPtr openvzCapsInit(void)
{
    struct utsname utsname;
    virCapsPtr caps;
    virCapsGuestPtr guest;

    uname(&utsname);

    if ((caps = virCapabilitiesNew(utsname.machine,
                                   0, 0)) == NULL)
        goto no_memory;

    if ((guest = virCapabilitiesAddGuest(caps,
                                         "exe",
                                         utsname.machine,
                                         sizeof(int) == 4 ? 32 : 8,
                                         NULL,
                                         NULL,
                                         0,
                                         NULL)) == NULL)
        goto no_memory;

    if (virCapabilitiesAddGuestDomain(guest,
                                      "openvz",
                                      NULL,
                                      NULL,
                                      0,
                                      NULL) == NULL)
        goto no_memory;
    return caps;

no_memory:
    virCapabilitiesFree(caps);
    return NULL;
}


D
Daniel Veillard 已提交
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
/* function checks MAC address is empty
   return 0 - empty
          1 - not
*/
int openvzCheckEmptyMac(const unsigned char *mac)
{
    int i;
    for (i = 0; i < VIR_DOMAIN_NET_MAC_SIZE; i++)
        if (mac[i] != 0x00)
            return 1;

    return 0;
}

/* convert mac address to string
   return pointer to string or NULL
*/
char *openvzMacToString(const unsigned char *mac)
{
    char str[20];
    if (snprintf(str, 18, "%02X:%02X:%02X:%02X:%02X:%02X",
                      mac[0], mac[1], mac[2],
                      mac[3], mac[4], mac[5]) >= 18)
        return NULL;

    return strdup(str);
}

154 155 156 157
/* Free all memory associated with a openvz_driver structure */
void
openvzFreeDriver(struct openvz_driver *driver)
{
158 159
    virDomainObjPtr dom;
  
160 161
    if (!driver)
        return;
162 163 164 165 166 167
 
    dom = driver->domains;
    while (dom) {
        virDomainObjPtr tmp = dom->next;
        virDomainObjFree(dom);
        dom = tmp;
D
Daniel Veillard 已提交
168
    }
169 170 171
 
    virCapabilitiesFree(driver->caps);
} 
D
Daniel Veillard 已提交
172 173 174



175
int openvzLoadDomains(struct openvz_driver *driver) {
176 177 178
    FILE *fp;
    int veid, ret;
    char status[16];
179
    char uuidstr[VIR_UUID_STRING_BUFLEN];
180 181
    virDomainObjPtr dom = NULL, prev = NULL;
    char temp[50];
182

183 184
    if (openvzAssignUUIDs() < 0)
        return -1;
185

186 187 188 189 190 191
    if ((fp = popen(VZLIST " -a -ovpsid,status -H 2>/dev/null", "r")) == NULL) {
        openvzError(NULL, VIR_ERR_INTERNAL_ERROR, _("popen failed"));
        return -1;
    }

    while(!feof(fp)) {
192
        if (fscanf(fp, "%d %s\n", &veid, status) != 2) {
193 194
            if (feof(fp))
                break;
195 196 197 198
  
            openvzError(NULL, VIR_ERR_INTERNAL_ERROR,
                        _("Failed to parse vzlist output"));
            goto cleanup;
199
        }
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
 
        if (VIR_ALLOC(dom) < 0 ||
            VIR_ALLOC(dom->def) < 0)
            goto no_memory;
 
        if (STREQ(status, "stopped"))
            dom->state = VIR_DOMAIN_SHUTOFF;
        else
            dom->state = VIR_DOMAIN_RUNNING;
 
        dom->pid = veid;
        dom->def->id = dom->state == VIR_DOMAIN_SHUTOFF ? -1 : veid;
 
        if (asprintf(&dom->def->name, "%i", veid) < 0) {
            dom->def->name = NULL;
            goto no_memory;
216
        }
217
 
218
        openvzGetVPSUUID(veid, uuidstr);
219 220 221 222 223 224
        ret = virUUIDParse(uuidstr, dom->def->uuid);
 
        if (ret == -1) {
            openvzError(NULL, VIR_ERR_INTERNAL_ERROR,
                        _("UUID in config file malformed"));
            goto cleanup;
225
        }
226 227 228 229 230
 
        if (!(dom->def->os.type = strdup("exe")))
            goto no_memory;
        if (!(dom->def->os.init = strdup("/sbin/init")))
            goto no_memory;
231

232 233
        ret = openvzReadConfigParam(veid, "CPUS", temp, sizeof(temp));
        if (ret < 0) {
234 235 236 237
            openvzError(NULL, VIR_ERR_INTERNAL_ERROR,
                        _("Cound not read config for container %d"), 
                        veid);
            goto cleanup;
238
        } else if (ret > 0) {
239 240 241
            dom->def->vcpus = strtoI(temp);
        } else {
            dom->def->vcpus = 1;
242 243
        }

244 245 246 247 248 249 250 251
        /* XXX load rest of VM config data .... */
 
        if (prev) {
            prev->next = dom;
        } else {
            driver->domains = dom;
        }
        prev = dom;
252
    }
253 254 255 256 257 258 259 260 261 262 263 264
 
    fclose(fp);
 
    return 0;
 
 no_memory:
    openvzError(NULL, VIR_ERR_NO_MEMORY, NULL);
 
 cleanup:
    fclose(fp);
    virDomainObjFree(dom);
    return -1;
265 266
}

267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
/*
* Read parameter from container config
* sample: 133, "OSTEMPLATE", value, 1024
* return: -1 - error
*	   0 - don't found
*          1 - OK
*/
int
openvzReadConfigParam(int vpsid ,const char * param, char *value, int maxlen)
{
    char conf_file[PATH_MAX] ;
    char line[PATH_MAX] ;
    int ret, found = 0;
    int fd ;
    char * sf, * token;
    char *saveptr = NULL;

284
    if (openvzLocateConfFile(vpsid, conf_file, PATH_MAX)<0)
285 286 287 288 289
        return -1;

    value[0] = 0;

    fd = open(conf_file, O_RDONLY);
D
Daniel Veillard 已提交
290
    if (fd == -1)
291 292 293 294 295 296 297
        return -1;

    while(1) {
        ret = openvz_readline(fd, line, sizeof(line));
        if(ret <= 0)
            break;
        saveptr = NULL;
D
Daniel Veillard 已提交
298
        if (STREQLEN(line, param, strlen(param))) {
299 300 301 302 303 304 305
            sf = line;
            sf += strlen(param);
            if (sf[0] == '=' && (token = strtok_r(sf,"\"\t=\n", &saveptr)) != NULL) {
                strncpy(value, token, maxlen) ;
                value[maxlen-1] = '\0';
                found = 1;
            }
D
Daniel Veillard 已提交
306
       }
307 308 309 310 311 312 313 314 315
    }
    close(fd);

    if (ret == 0 && found)
        ret = 1;

    return ret ;
}

316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336
/* Locate config file of container
* return -1 - error
*         0 - OK
*/
static int
openvzLocateConfFile(int vpsid, char *conffile, int maxlen)
{
    char * confdir;
    int ret = 0;

    confdir = openvzLocateConfDir();
    if (confdir == NULL)
        return -1;

    if (snprintf(conffile, maxlen, "%s/%d.conf", confdir, vpsid) >= maxlen)
        ret = -1;

    VIR_FREE(confdir);
    return ret;
}

337
static char
338
*openvzLocateConfDir(void)
339 340 341 342 343 344
{
    const char *conf_dir_list[] = {"/etc/vz/conf", "/usr/local/etc/conf", NULL};
    int i=0;

    while(conf_dir_list[i]) {
        if(!access(conf_dir_list[i], F_OK))
345
            return strdup(conf_dir_list[i]);
346 347 348 349 350 351 352
        i ++;
    }

    return NULL;
}

/* Richard Steven's classic readline() function */
353
int
354
openvz_readline(int fd, char *ptr, int maxlen)
355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
{
    int n, rc;
    char c;

    for(n = 1; n < maxlen; n ++) {
        if( (rc = read(fd, &c, 1)) == 1) {
            *ptr++ = c;
            if(c == '\n')
                break;
        }
        else if(rc == 0) {
            if(n == 1)
                return 0; /* EOF condition */
            else
                break;
        }
        else
            return -1; /* error */
    }
    *ptr = 0;
    return n;
}

378
static int
379
openvzGetVPSUUID(int vpsid, char *uuidstr)
380 381 382
{
    char conf_file[PATH_MAX];
    char line[1024];
383
    char uuidbuf[1024];
384 385 386
    char iden[1024];
    int fd, ret;

387 388
   if (openvzLocateConfFile(vpsid, conf_file, PATH_MAX)<0)
       return -1;
389

390
    fd = open(conf_file, O_RDONLY);
391 392 393 394 395 396 397 398 399
    if(fd == -1)
        return -1;

    while(1) {
        ret = openvz_readline(fd, line, sizeof(line));
        if(ret == -1)
            return -1;

        if(ret == 0) { /* EoF, UUID was not found */
400
            uuidstr[0] = 0;
401 402 403
            break;
        }

404
        sscanf(line, "%s %s\n", iden, uuidbuf);
405
        if(STREQ(iden, "#UUID:")) {
406
            strncpy(uuidstr, uuidbuf, VIR_UUID_STRING_BUFLEN);
407 408 409
            break;
        }
    }
410 411
    close(fd);

412 413 414 415 416 417
    return 0;
}

/* Do actual checking for UUID presence in conf file,
 * assign if not present.
 */
418 419
int
openvzSetDefinedUUID(int vpsid, unsigned char *uuid)
420 421
{
    char conf_file[PATH_MAX];
422
    char uuidstr[VIR_UUID_STRING_BUFLEN];
423 424 425

    if (uuid == NULL)
        return -1;
426

427 428
   if (openvzLocateConfFile(vpsid, conf_file, PATH_MAX)<0)
       return -1;
429

J
Jim Meyering 已提交
430
    if (openvzGetVPSUUID(vpsid, uuidstr))
431 432
        return -1;

J
Jim Meyering 已提交
433
    if (uuidstr[0] == 0) {
434 435 436
        FILE *fp = fopen(conf_file, "a"); /* append */
        if (fp == NULL)
          return -1;
437

438 439
        virUUIDFormat(uuid, uuidstr);

440 441 442 443 444
        /* Record failure if fprintf or fclose fails,
           and be careful always to close the stream.  */
        if ((fprintf(fp, "\n#UUID: %s\n", uuidstr) < 0)
            + (fclose(fp) == EOF))
            return -1;
445 446 447 448 449
    }

    return 0;
}

450 451 452 453 454 455 456 457 458
static int
openvzSetUUID(int vpsid){
    unsigned char uuid[VIR_UUID_BUFLEN];

    virUUIDGenerate(uuid);

    return openvzSetDefinedUUID(vpsid, uuid);
}

459 460 461 462 463 464 465
/*
 * Scan VPS config files and see if they have a UUID.
 * If not, assign one. Just append one to the config
 * file as comment so that the OpenVZ tools ignore it.
 *
 */

466
static int openvzAssignUUIDs(void)
467 468 469 470 471 472 473 474
{
    DIR *dp;
    struct dirent *dent;
    char *conf_dir;
    int vpsid, res;
    char ext[8];

    conf_dir = openvzLocateConfDir();
475 476
    if (conf_dir == NULL)
        return -1;
477 478 479

    dp = opendir(conf_dir);
    if(dp == NULL) {
480
        VIR_FREE(conf_dir);
481 482 483 484 485
        return 0;
    }

    while((dent = readdir(dp))) {
        res = sscanf(dent->d_name, "%d.%5s", &vpsid, ext);
486
        if(!(res == 2 && STREQ(ext, "conf")))
487 488 489 490 491
            continue;
        if(vpsid > 0) /* '0.conf' belongs to the host, ignore it */
            openvzSetUUID(vpsid);
    }
    closedir(dp);
492
    VIR_FREE(conf_dir);
493 494 495
    return 0;
}