vps__xenlib.php

Lars Nordseth, 07/27/2010 01:58 am

Download (48.6 kB)

 
1
<?php 
2
3
class vps__xen extends Lxdriverclass {
4
5
6
7
static function find_cpuusage()
8
{
9
        $out = lxshell_output("xm", "list");
10
        $list = explode("\n", $out);
11
12
        foreach($list as $l) {
13
                $l = trimSpaces($l);
14
                $val = explode(" ", $l);
15
16
                if (!cse($val[0], ".vm")) {
17
                        continue;
18
                }
19
                execRrdSingle("cpu", "DERIVE", $val[0], $val[5]);
20
        }
21
}
22
23
static function find_traffic()
24
{
25
        global $gbl, $sgbl, $login, $ghtml; 
26
27
        if (!lxfile_exists("__path_program_etc/xeninterface.list")) {
28
                return;
29
        }
30
        $list = lfile_trim("__path_program_etc/xeninterface.list");
31
32
        if (!lxfile_exists("__path_program_etc/newxeninterfacebw.data")) {
33
                foreach($list as $k) {
34
                        $total[$k] = self::get_bytes_for_interface($k);
35
                }
36
                dprintr($total);
37
                lfile_put_contents("__path_program_etc/newxeninterfacebw.data", serialize($total));
38
                return;
39
        }
40
41
        $data = unserialize(lfile_get_contents("__path_program_etc/newxeninterfacebw.data"));
42
43
        $total = null;
44
45
46
        foreach($list as $k) {
47
                $total[$k] = self::get_bytes_for_interface($k);
48
49
                if (isset($data[$k])) {
50
                        if ($total[$k]['total'] < $data[$k]['total']) {
51
                                $v = $total[$k]['total'];
52
                                $vinc = $total[$k]['incoming'];
53
                                $vout = $total[$k]['outgoing'];
54
                        } else {
55
                                $v =   $total[$k]['total'] - $data[$k]['total'];
56
                                $vinc = $total[$k]['incoming'] - $data[$k]['incoming'];
57
                                $vout = $total[$k]['outgoing'] - $data[$k]['outgoing'];
58
                        }
59
                } else {
60
                        $v = $total[$k]['total'];
61
                        $vinc = $total[$k]['incoming'];
62
                        $vout = $total[$k]['outgoing'];
63
                }
64
65
                execRrdTraffic("xen-$k", $v, "-$vinc", $vout);
66
                $stringa[] = time() . " " . date("d-M-Y:H:i") . " $k $v $vinc $vout";
67
        }
68
69
        dprintr($total);
70
        $string = implode("\n", $stringa);
71
        lfile_put_contents("/var/log/lxinterfacetraffic.log", "$string\n", FILE_APPEND);
72
        lfile_put_contents("__path_program_etc/newxeninterfacebw.data", serialize($total));
73
}
74
75
static function get_bytes_for_interface($l)
76
{
77
        static $net;
78
79
        if (!$net) {
80
                $net = lfile_get_contents("/proc/net/dev");
81
                $net = explode("\n", $net);
82
        }
83
84
        foreach($net as $n) {
85
                $n = trimSpaces($n);
86
                if (!csb($n, "vif$l:")) {
87
                        continue;
88
                }
89
90
                $n = strfrom($n, "vif$l:");
91
                $n = trimSpaces($n);
92
                $b = explode(" ", $n);
93
                $total = $b[0] + $b[8];
94
                // It seems for xen it is the reverse. The input for the vif is the output for the virtual machine.
95
                return array('total' => $total, 'incoming' => $b[8], 'outgoing' => $b[0]);
96
        }
97
        return 0;
98
}
99
100
101
static function execCommand($vpsid, $command)
102
{
103
        global $global_shell_error, $global_shell_ret;
104
}
105
106
static function getOsTemplatelist($type = 'add')
107
{
108
        $list = lscandir_without_dot("__path_program_home/xen/template/");
109
110
        foreach($list as $__l) {
111
                if ($type === 'add') {
112
                        if (!cse($__l, ".tar.gz") && !cse($__l, ".img")) {
113
                                continue;
114
                        }
115
                } else if ($type === 'img') {
116
                        if (!cse($__l, ".img")) {
117
                                continue;
118
                        }
119
                } else if ($type === 'tar.gz') {
120
                        if (!cse($__l, ".tar.gz")) {
121
                                continue;
122
                        }
123
                }
124
125
                if (cse($__l, ".tar.gz")) {
126
                        $size = lxfile_get_uncompressed_size("__path_program_home/xen/template/$__l");
127
                } else {
128
                        $size = lxfile_size("__path_program_home/xen/template/$__l");
129
                }
130
131
                $newlist[strtil($__l, ".tar.gz")] = strtil($__l, ".tar.gz") . " (" . round($size / (1024 * 1024), 2) . "MB)";
132
        }
133
        return $newlist;
134
135
}
136
137
static function checkIfXenOK()
138
{
139
        if (!lxfile_exists("/proc/xen")) {
140
                throw new lxException("no_kernel_support_for_xen._boot_into_the_right_kernel");
141
        }
142
}
143
144
static function getStatus($vmname, $rootdir)
145
{
146
        self::checkIfXenOK();
147
148
149
        if (lx_core_lock_check_only("background.php", "$vmname.create")) {
150
                return 'create';
151
        }
152
153
        if (lxfile_exists("__path_program_root/tmp/$vmname.createfailed")) {
154
                $reason = lfile_get_contents("__path_program_root/tmp/$vmname.createfailed");
155
                return "createfailed: $reason";
156
        }
157
158
        if (!lxfile_exists("$rootdir/$vmname")) {
159
                return "deleted";
160
        }
161
162
        /*
163
        if (lx_core_lock("$vmname.status")) {
164
                throw new lxException("xm_status_locked");
165
        }
166
*/
167
        exec("xm list $vmname", $output, $ret);
168
169
        if (!$ret) {
170
                return 'on';
171
        }
172
173
        return 'off';
174
175
}
176
177
178
static function getDiskUsage($disk, $winflag, $root)
179
{
180
        global $global_dontlogshell;
181
        $global_dontlogshell = true;
182
        if ($winflag) {
183
                $cont = lxfile_get_ntfs_disk_usage($disk, $root);
184
        } else {
185
                $cont = lxfile_get_disk_usage($disk);
186
        }
187
        $global_dontlogshell = false;
188
        return $cont;
189
}
190
191
function initXenVars()
192
{
193
        if ($this->isLvm()) {
194
                $vgname = $this->main->corerootdir;
195
                $vgname = fix_vgname($vgname);
196
                $this->main->maindisk = "/dev/$vgname/{$this->main->maindiskname}";
197
                $this->main->swapdisk = "/dev/$vgname/{$this->main->swapdiskname}";
198
        } else {
199
                $this->main->rootdir = "{$this->main->corerootdir}/{$this->main->nname}/";
200
                $this->main->maindisk = "{$this->main->rootdir}/{$this->main->maindiskname}";
201
                $this->main->swapdisk = "{$this->main->rootdir}/{$this->main->swapdiskname}";
202
        }
203
204
        $this->main->configrootdir = "__path_home_dir/xen/{$this->main->nname}/";
205
}
206
207
function doSyncToSystemPre()
208
{
209
210
        if ($this->main->checkIfOffensive()) {
211
                dprint("Offensive.. Checking...\n");
212
                $this->main->check_and_throw_error_if_some_else_is_using_vps($this->main->nname);
213
        }
214
        $this->initXenVars();
215
}
216
217
function dosyncToSystemPost()
218
{
219
        if ($this->main->dbaction === 'update' && $this->main->__var_custom_exec) {
220
                lxshell_direct($this->main->__var_custom_exec);
221
        }
222
}
223
224
function dbactionAdd()
225
{
226
227
        
228
        global $gbl, $sgbl, $login, $ghtml; 
229
230
        self::checkIfXenOK();
231
232
233
234
        $ret = lxshell_return("xm", "--help");
235
236
        if ($ret == 127) {
237
                throw new lxException("no_xen_at_all");
238
        }
239
240
241
        if (is_unlimited($this->main->priv->disk_usage)) {
242
                $diskusage = 3 * 1024;
243
        } else {
244
                $diskusage = $this->main->priv->disk_usage ;
245
        }
246
247
        if ($this->main->isWindows() && $diskusage < 2 * 1024) {
248
                //throw new lxException("windows_needs_more_than_2GB");
249
        }
250
251
        if ($this->isLVM()) {
252
                $freediskspace = vg_diskfree($this->main->corerootdir);
253
        } else  {
254
                $freediskspace = lxfile_disk_free_space($this->main->corerootdir);
255
        }
256
257
        if (($freediskspace - $diskusage) < 20) {
258
                throw new lxException("not_enough_space");
259
        }
260
261
262
263
        if ($this->main->dbaction === 'syncadd') {
264
                $username = vps::create_user($this->main->username, $this->main->password, $this->main->nname, "/usr/bin/lxxen");
265
                return null;
266
        }
267
268
        if (self::getStatus($this->main->nname, '/home/xen') !== 'deleted') {
269
                throw new lxException("a_virtual_machine_with_the_same_id_exists");
270
        }
271
272
        if ($this->main->isBlankWindows()) {
273
                if (!lxfile_exists("/home/wincd.img")) {
274
                        throw new lxException("windows_installation_image_missing");
275
                }
276
        }
277
278
        /*
279
        if (!lxfile_exists("__path_program_home/xen/template/{$this->main->ostemplate}.tar.gz")) {
280
                throw new lxException("could_not_find_the_osimage", '', $this->main->ostemplate);
281
        }
282
*/
283
284
285
286
        $username = vps::create_user($this->main->username, $this->main->password, $this->main->nname, "/usr/bin/lxxen");
287
288
289
        if (!$this->isLvm()) {
290
                lxfile_mkdir($this->main->rootdir);
291
        }
292
293
        lxfile_mkdir($this->main->configrootdir);
294
        $this->setMemoryUsage();
295
        $this->setCpuUsage();
296
        $this->setSwapUsage();
297
        $this->setDiskUsage();
298
        if ($sgbl->isDebug()) {
299
                $this->doRealCreate();
300
        } else {
301
                callObjectInBackground($this, "doRealCreate");
302
        }
303
304
        $ret = array("__syncv_username" => $username);
305
        return $ret;
306
307
}
308
309
function doRealCreate()
310
{
311
312
        global $gbl, $sgbl, $login, $ghtml; 
313
        $nname = $this->main->nname;
314
        lx_core_lock("$nname.create");
315
316
        if (!$this->isLvm()) {
317
                lxfile_mkdir($this->main->rootdir);
318
        }
319
320
321
        lxfile_mkdir($this->main->configrootdir);
322
323
        $this->setDhCP();
324
325
        if ($this->main->isWindows()) {
326
                $templatefile = "__path_program_home/xen/template/{$this->main->ostemplate}";
327
        } else {
328
                $templatefile = "__path_program_home/xen/template/{$this->main->ostemplate}.tar.gz";
329
        }
330
331
        $this->main->getOsTemplateFromMaster($templatefile);
332
333
        if (!lxfile_real($templatefile)) {
334
                log_error("could not create vm. Could not download $templatefile");
335
                lfile_put_contents("__path_program_root/tmp/$nname.createfailed", "Could not download $templatefile");
336
                exit;
337
        }
338
339
        $size = 0;
340
        if ($this->main->isWindows()) {
341
                $size = lxfile_size($templatefile);
342
                $size = $size / (1024 * 1024);
343
        }
344
345
        try {
346
                $this->createConfig();
347
                $this->setMemoryUsage();
348
                $this->setCpuUsage();
349
                $this->setSwapUsage();
350
                $this->createSwap();
351
                $this->createDisk($size);
352
        } catch (Exception $e) {
353
                log_error("could not create vm. Error was {$e->getMessage()}");
354
                lfile_put_contents("__path_program_root/tmp/$nname.createfailed", "{$e->getMessage()}");
355
                exit;
356
        }
357
358
359
360
        if (!$this->main->isWindows()) {
361
                $mountpoint = $this->mount_this_guy();
362
                lxshell_return("tar", "-C", $mountpoint, "--numeric-owner", "-xpzf", $templatefile);
363
                $this->setInternalParam($mountpoint);
364
                $this->copyKernelModules();
365
                lxfile_cp("../file/sysfile/xen/fstab", "$mountpoint/etc/fstab");
366
                lunlink("$mountpoint/etc/mtab");
367
        } else if (!$this->main->isBlankWindows()) {
368
                $templatefile = expand_real_root($templatefile);
369
                lxshell_return("parted", "-s", $this->main->maindisk, "mklabel", "msdos");
370
                $this->runParted();
371
                $partition = $this->getPartition();
372
                lxshell_return("ntfsfix", $partition);
373
                //lxshell_return("dd", "if=$templatefile", "of={$this->main->maindisk}");
374
                lxshell_return("ntfsclone", "--restore-image", "--force", "-O", $partition, $templatefile);
375
                $this->kpart_remove();
376
                $this->expandPartitionToImage();
377
                //lxshell_return("ntfsclone", "-O", $loop, $templatefile);
378
                //lo_remove($loop);
379
        }
380
381
        $this->main->status = 'On';
382
383
        try {
384
                $this->toggleStatus();
385
        } catch (Exception $e) {
386
        }
387
388
        $this->postCreate();
389
}
390
391
function postCreate()
392
{
393
        if ($this->main->__var_custom_exec) {
394
                lxshell_direct($this->main->__var_custom_exec);
395
        }
396
}
397
398
399
function runParted()
400
{
401
        lxshell_return("parted", "-s", $this->main->maindisk, "--", "unit", "s", "rm", "1");
402
        lxshell_return("parted", "-s", $this->main->maindisk, "--", "unit", "s", "mkpart", "primary", "ntfs", "63", "-1");
403
        lxshell_return("parted", "-s", $this->main->maindisk, "set", "1", "boot", "on");
404
}
405
406
function expandPartitionToImage()
407
{
408
        /*
409
        $out = lxshell_output("parted", $this->main->maindisk, "unit", "s", "print", "free");
410
        $list = explode("\n", $out);
411
        foreach($list as $l) {
412
                if (csb($l, "Disk")) {
413
                        $s = explode(":", $l);
414
                        $s = trim($s[1]);
415
                        $s = strtil($s, "s");
416
                        break;
417
                }
418
        }
419
*/
420
        $this->runParted();
421
        $partition = $this->getPartition();
422
        lxshell_return("ntfsfix", $partition);
423
        //lxshell_expect("ntfsresize", "ntfsresize -f $partition");
424
        lxshell_return("ntfsresize", "-ff", $partition);
425
        $this->kpart_remove();
426
}
427
428
429
function kpart_remove()
430
{
431
        $disk = $this->main->maindisk;
432
        $root = $this->main->corerootdir;
433
        $lv = basename($disk);
434
        $root = fix_vgname($root);
435
        $path = "/dev/mapper/$root-$lv";
436
        lxshell_return("kpartx", "-d", $path);
437
}
438
439
440
441
function copyKernelModules()
442
{
443
        $mountpoint = $this->mount_this_guy();
444
        $kernev = trim(`uname -r`);
445
446
447
        if (!lxfile_exists("$mountpoint/lib/modules/$kernev")) {
448
                lxfile_cp_rec("/lib/modules/$kernev", "$mountpoint/lib/modules/$kernev");
449
        }
450
        if (cse($kernev, "-xen")) {
451
                $nkernev = strtil($kernev, "-xen");
452
                if (!lxfile_exists("$mountpoint/lib/modules/$nkernev")) {
453
                        lxfile_cp_rec("/lib/modules/$kernev", "$mountpoint/lib/modules/$nkernev");
454
                }
455
        }
456
        if (csb($this->main->ostemplate, "centos-")) {
457
                if (lxfile_exists("$mountpoint/lib/tls")) {
458
                        lxfile_rm_rec("$mountpoint/lib/tls.disabled");
459
                        lxfile_mv_rec("$mountpoint/lib/tls", "$mountpoint/lib/tls.disabled");
460
                }
461
        }
462
}
463
464
465
function createDisk($size = 0)
466
{
467
        if (is_unlimited($this->main->priv->disk_usage)) {
468
                $diskusage = 3 * 1024;
469
        } else {
470
                $diskusage = $this->main->priv->disk_usage ;
471
        }
472
473
        if (lxfile_exists($this->main->maindisk)) {
474
                return;
475
        }
476
477
        if ($size && $this->main->isWindows()) {
478
                //$diskusage = $size;
479
        }
480
481
        if ($this->isLVM()) {
482
                $freediskspace = vg_diskfree($this->main->corerootdir);
483
        } else  {
484
                $freediskspace = lxfile_disk_free_space($this->main->corerootdir);
485
        }
486
487
        if (($freediskspace - $diskusage) < 20) {
488
                throw new lxException("not_enough_space");
489
        }
490
491
        if ($this->isLVM()) {
492
                lvm_create($this->main->corerootdir, $this->main->maindiskname, $diskusage);
493
        } else {
494
                lxfile_mkdir($this->main->rootdir);
495
                lxshell_return("dd", "if=/dev/zero", "of={$this->main->maindisk}", "bs=1M", "conv=notrunc", "count=1", "seek=$diskusage");
496
        }
497
498
        if (!$this->main->isWindows()) {
499
                lxshell_return("mkfs.ext3", "-F", $this->main->maindisk);
500
        }
501
502
}
503
504
static function createVpsObject($servername, $input)
505
{
506
507
        $name = "{$input['name']}.vm";
508
        $vpsobject = new Vps(null, $servername, $name);
509
        $vpsobject->parent_clname = createParentName('client', 'admin');
510
        $vpsobject->priv = new priv(null, null, $vpsobject->nname);
511
        $vpsobject->priv->__parent_o = $vpsobject;
512
        $vpsobject->used = new used(null, null, $vpsobject->nname);
513
        $vpsobject->used->__parent_o = $vpsobject;
514
        $vpsobject->vpsipaddress_a = array();
515
        $vpsobject->vpsid = '-';
516
        $vpsobject->password = crypt($name);
517
        $vpsobject->cpstatus = 'on';
518
        $vpsobject->status = 'on';
519
        $vpsobject->ttype = 'xen';
520
        $vpsobject->iid = $name;
521
        $vpsobject->ddate = time();
522
523
        if ($input['type'] === 'file') {
524
                $vpsobject->corerootdir = $input['location'];
525
        } else {
526
                $vpsobject->corerootdir = "lvm:{$input['location']}";
527
        }
528
529
        $vpsobject->maindiskname = $input['maindiskname'];
530
        $vpsobject->swapdiskname = $input['swapdiskname'];
531
532
        if ($input['type'] === 'file') {
533
                $vpsobject->maindisk = "{$vpsobject->corerootdir}/{$vpsobject->maindiskname}";
534
                $vpsobject->swapdisk = "{$vpsobject->corerootdir}/{$vpsobject->swapdiskname}";
535
        } else {
536
                $vgname = $vpsobject->corerootdir;
537
                $vgname = fix_vgname($vgname);
538
                $vpsobject->maindisk = "/dev/$vgname/{$vpsobject->maindiskname}";
539
                $vpsobject->swapdisk = "/dev/$vgname/{$vpsobject->swapdiskname}";
540
        }
541
542
        if (isset($input['gateway'])) {
543
                $vpsobject->networkgateway = $input['gateway'];
544
        }
545
546
        if (isset($input['netmask'])) {
547
                $vpsobject->networknetmask = $input['netmask'];
548
        }
549
550
551
        $vpsobject->priv->realmem_usage = $input['memory'];
552
        $vpsobject->priv->disk_usage = lvm_disksize($vpsobject->maindisk);
553
        $vpsobject->priv->swap_usage = lvm_disksize($vpsobject->swapdisk);
554
        $vpsobject->priv->backup_flag = 'on';
555
        $vpsobject->ostemplate = 'unknown';
556
557
        if (isset($input['ipaddress'])) {
558
                self::importIpaddress($vpsobject, $input['ipaddress']);
559
        }
560
561
        return $vpsobject;
562
563
}
564
565
566
static function importIpaddress($vpsobject, $val)
567
{
568
        $list = explode(" ", $val);
569
        foreach($list as $l) {
570
                $ipadd = new vmipaddress_a(null, $vpsobject->syncserver, $l);
571
                $vpsobject->vmipaddress_a[$ipadd->nname] = $ipadd;
572
        }
573
}
574
575
576
577
function getRealMemory()
578
{
579
        if (is_unlimited($this->main->priv->realmem_usage)) {
580
                $memory = 512;
581
        } else {
582
                $memory = $this->main->priv->realmem_usage;
583
        }
584
        return $memory;
585
}
586
587
588
function getVifString()
589
{
590
        if (!is_unlimited($this->main->priv->uplink_usage) && ($this->main->priv->uplink_usage > 0)) {
591
                $ratestring = "rate = {$this->main->priv->uplink_usage}KB/s,";
592
        } else {
593
                $ratestring = null;
594
        }
595
        if (trim(lxshell_output("uname", "-r")) === "2.6.16.33-xen0") {
596
                $vifnamestring = null;
597
        } else {
598
                $vifnamestring = "vifname=vif{$this->main->vifname},";
599
        }
600
601
        $ipstring = null;
602
        if ($this->main->vmipaddress_a) {
603
                $ilist = get_namelist_from_objectlist($this->main->vmipaddress_a);
604
                $ips = implode(" ", $ilist);
605
                $ipstring = "ip=$ips,";
606
        }
607
608
        $mac = $this->main->macaddress;
609
        if (!csb($mac, "aa:00")) { $mac = "aa:00:$mac"; }
610
        if (strlen($mac) === 14) { $mac = "$mac:01"; }
611
        $bridgestring = null;
612
        if ($this->main->networkbridge && $this->main->networkbridge !== '--automatic--') {
613
                $bridgestring = ",bridge={$this->main->networkbridge}";
614
        }
615
        $string = "vif        = ['$ipstring $vifnamestring $ratestring mac=$mac $bridgestring']\n";
616
        return $string;
617
}
618
619
620
function addVcpu()
621
{
622
        if (is_unlimited($this->main->priv->ncpu_usage)) {
623
                $cpunum = os_getCpuNum();
624
        } else {
625
                $cpunum = $this->main->priv->ncpu_usage;
626
        }
627
628
        if ($cpunum > 0) {
629
                return  "vcpus = $cpunum\n";
630
        }
631
        return null;
632
}
633
634
function createWindowsConfig()
635
{
636
        $memory = $this->getRealMemory();
637
        if (trim(lxshell_output("uname", "-r")) === "2.6.16.33-xen0") {
638
                $vifnamestring = null;
639
        } else {
640
                $vifnamestring = "vifname=vif{$this->main->vifname},";
641
        }
642
        if (!is_unlimited($this->main->priv->uplink_usage) && ($this->main->priv->uplink_usage > 0)) {
643
                $ratestring = "rate = {$this->main->priv->uplink_usage}KB/s,";
644
        } else {
645
                $ratestring = null;
646
        }
647
648
        $mac = $this->main->macaddress;
649
        if (!csb($mac, "aa:00")) { $mac = "aa:00:$mac"; }
650
        $count = count($this->main->vmipaddress_a);
651
        // Big bug workaround. the first vif seems to be ignored. Need to be fixed later.
652
        $vifnamestring = "vifname=vif{$this->main->vifname},";
653
        //$vif[] = "'type=ioemu, $vifnamestring $ratestring mac=$mac:00'";
654
        for ($i = 1; $i <= $count; $i++) {
655
                $hex = get_double_hex($i);
656
                $h = base_convert($i, 10, 36);
657
                $bridgestring = null;
658
                if ($this->main->networkbridge && $this->main->networkbridge !== '--automatic--') {
659
                        $bridgestring = ",bridge={$this->main->networkbridge}";
660
                }
661
                $vifnamestring = "vifname=vif{$this->main->vifname}$h,";
662
                $vif[] = "'type=ioemu, $vifnamestring $ratestring mac=$mac:$hex $bridgestring'";
663
        }
664
        $vif = implode(", ", $vif);
665
        $vif = "vif = [ $vif ]\n";
666
667
                
668
669
        $string = null;
670
        $string .= "import os, re\n";
671
        $string .= "arch = os.uname()[4]\n";
672
        $string .= "if re.search('64', arch):\n";
673
        $string .= "    arch_libdir = 'lib64'\n";
674
        $string .= "else:\n";
675
        $string .= "    arch_libdir = 'lib'\n";
676
        $string .= "name = '{$this->main->nname}'\n";
677
678
        $string .= "kernel = '/usr/lib/xen/boot/hvmloader'\n";
679
        $string .= "builder='hvm'\n";
680
        if ($this->main->isBlankWindows()) {
681
                $string .= "boot='d'\n";
682
        } else {
683
                $string .= "boot='c'\n";
684
        }
685
        $string .= "memory = $memory\n";
686
        $string .= $vif;
687
        $string .= "device_model = '/usr/' + arch_libdir + '/xen/bin/qemu-dm'\n";
688
        $string .= "vnc=1\n";
689
        $string .= "sdl=0\n";
690
691
        $string .= $this->addVcpu();
692
693
        $string .= "vnclisten='0.0.0.0'\n";
694
        $string .= "vncpasswd='{$this->main->realpass}'\n";
695
        if ($this->main->isBlankWindows()) {
696
                $string .= "disk = [ 'file:/home/wincd.img,hdc:cdrom,r', 'phy:{$this->main->maindisk},ioemu:hda,w']\n";
697
                $string .= "acpi=1\n";
698
        } else {
699
                $string .= "disk = [ 'phy:{$this->main->maindisk},ioemu:hda,w']\n";
700
                $string .= "acpi=1\n";
701
        }
702
        $string .= "vncunused=0\n";
703
        $string .= "vncdisplay={$this->main->vncdisplay}\n";
704
705
        if ($this->main->text_xen_config) {
706
                $string .= "{$this->main->text_xen_config}\n";
707
        }
708
709
710
        lxfile_mkdir($this->main->configrootdir);
711
        lfile_put_contents("{$this->main->configrootdir}/{$this->main->nname}.cfg", $string);
712
}
713
714
715
function createConfig()
716
{
717
        global $gbl, $sgbl, $login, $ghtml; 
718
719
        if ($this->main->isOn('nosaveconfig_flag')) {
720
                return;
721
        }
722
723
        if ($this->main->isWindows()) {
724
                $this->createWindowsConfig();
725
                return;
726
        }
727
728
        $memory = $this->getRealMemory();
729
730
        if ($this->isLVM()) { $loc = "phy"; } 
731
        else { $loc = "file"; }
732
733
        $string  = null;
734
735
        $sk = "/boot/hypervm-xen-vmlinuz-{$this->main->nname}";
736
737
        if (lxfile_exists($sk)) {
738
                $kern = $sk;
739
        } else {
740
                $kern = "/boot/hypervm-xen-vmlinuz";
741
        }
742
        $string .= "kernel     = '$kern'\n";
743
744
745
        $customram = "/boot/hypervm-xen-initrd-{$this->main->nname}.img";
746
747
        if (lxfile_exists($customram)) {
748
                $string .= "ramdisk    = '$customram'\n";
749
        } else if (lxfile_exists('/boot/hypervm-xen-initrd.img')) {
750
                $string .= "ramdisk    = '/boot/hypervm-xen-initrd.img'\n";
751
        }
752
753
        if (is_unlimited($this->main->priv->cpu_usage)) {
754
                $cpu = "100" * os_getCpuNum();;
755
        } else {
756
                $cpu = $this->main->priv->cpu_usage;
757
        }
758
759
        if (is_unlimited($this->main->priv->cpuunit_usage)) {
760
                $cpuunit = "1000";
761
        } else {
762
                $cpuunit = $this->main->priv->cpuunit_usage;
763
        }
764
765
        if (!is_numeric($cpuunit)) { $cpuunit = '1000'; }
766
        if (!is_numeric($cpu)) { $cpu = "100" * os_getCpuNum(); }
767
768
        $string .= "memory     = $memory\n";
769
        //$string .= "cpu_cap     = $cpu\n";
770
        $string .= "cpu_weight     = $cpuunit\n";
771
        $string .= "name       = '{$this->main->nname}'\n";
772
        $string .= $this->getVifString();
773
        $string .= "vnc        = 0\n";
774
775
        $string .= $this->addVcpu();
776
777
        $string .= "vncviewer  = 0\n";
778
        $string .= "serial     = 'pty'\n";
779
        $string .= "disk       = ['$loc:{$this->main->maindisk},sda1,w', '$loc:{$this->main->swapdisk},sda2,w']\n";
780
        $string .= "root = '/dev/sda1 ro'\n";
781
782
        if ($this->main->text_xen_config) {
783
                $string .= "{$this->main->text_xen_config}\n";
784
        }
785
786
        lxfile_mkdir($this->main->configrootdir);
787
        lfile_put_contents("{$this->main->configrootdir}/{$this->main->nname}.cfg", $string);
788
789
790
}
791
792
function getValueFromFile($file)
793
{
794
        $vfile = "{$this->main->configrootdir}/$file";
795
        if (!lxfile_exists($vfile)) {
796
                return ;
797
        }
798
        $v = lfile_get_contents($vfile);
799
        lunlink($vfile);
800
        $v = trim($v);
801
        return $v;
802
}
803
804
function resizeRootImage()
805
{
806
807
        $v = $this->getValueFromFile("disk.value");
808
        if (!$v) { return; }
809
810
        $this->stop();
811
812
        $this->umountThis();
813
814
        if ($this->isLVM()) {
815
                lvm_extend($this->main->maindisk, $v);
816
                $disk = $this->main->maindisk;
817
        } else {
818
                lxshell_return("dd", "if=/dev/zero", "of={$this->main->maindisk}", "bs=1M", "conv=notrunc", "count=1", "seek=$v");
819
                $disk = $this->main->maindisk;
820
                //$disk = $this->get_free_loop();
821
                //$ret = lxshell_return("losetup", $disk, $this->main->maindisk);
822
        }
823
824
825
        if ($this->main->isWindows()) {
826
                $this->expandPartitionToImage();
827
        } else {
828
                lxshell_return("e2fsck", "-f", "-y", $disk);
829
                lxshell_return("resize2fs", $disk);
830
        }
831
        if (!$this->isLVM()) {
832
                //lo_remove($disk);
833
        }
834
835
}
836
837
838
function getPartition()
839
{
840
        return get_partition($this->main->maindisk, $this->main->corerootdir);
841
}
842
843
function get_free_loop()
844
{
845
        return get_free_loop();
846
}
847
848
849
function isLvm()
850
{
851
        return csb($this->main->corerootdir, "lvm:");
852
}
853
854
function createSwap()
855
{
856
        global $gbl, $sgbl, $login, $ghtml; 
857
        global $global_shell_error, $global_shell_ret;
858
859
        if ($this->main->isWindows()) {
860
                return;
861
        }
862
863
        $v = $this->getValueFromFile("swap.value");
864
865
        if (!$v) { return ; }
866
867
        if ($this->isLVM()) {
868
                lvm_remove($this->main->swapdisk);
869
                $ret = lvm_create($this->main->corerootdir, $this->main->swapdiskname, $v);
870
                if ($ret) {
871
                        throw new lxException("failed_to_create_swap", '', $global_shell_error);
872
                }
873
        } else {
874
                lunlink($this->main->swapdisk);
875
                lxshell_return("dd", "if=/dev/zero", "of={$this->main->swapdisk}", "bs=1M", "count=1", "seek=$v");
876
        }
877
878
        lxshell_return("mkswap", $this->main->swapdisk);
879
}
880
881
882
function setvif()
883
{
884
        $filelist = lfile_trim("__path_program_etc/xeninterface.list");
885
        $list = $this->main->getViflist();
886
        foreach($list as $l) {
887
                $filelist = array_push_unique($filelist, $l);
888
        }
889
        dprintr($filelist);
890
        lfile_put_contents("__path_program_etc/xeninterface.list", implode("\n", $filelist));
891
}
892
893
function deletevif()
894
{
895
        $filelist = lfile_trim("__path_program_etc/xeninterface.list");
896
        $list = $this->main->getViflist();
897
        foreach($list as $l) {
898
                $filelist = array_remove($filelist, $l);
899
        }
900
        dprintr($filelist);
901
        if ($filelist) {
902
                lfile_put_contents("__path_program_etc/xeninterface.list", implode("\n", $filelist));
903
        }
904
}
905
906
function dbactionDelete()
907
{
908
        global $gbl, $sgbl, $login, $ghtml; 
909
        $this->deletevif();
910
        $this->hardstop();
911
        $this->umountThis();
912
913
        if ($this->isLVM()) {
914
                if ($this->main->isWindows()) {
915
                        lxshell_return("parted", "-s", $this->main->maindisk, "--", "unit", "s", "rm", "1");
916
                        lxshell_return("parted", "-s", $this->main->maindisk, "--", "mklabel", "msdos");
917
                }
918
                lvm_remove($this->main->maindisk);
919
                if (!$this->main->isWindows()) {
920
                        lvm_remove($this->main->swapdisk);
921
                }
922
        } else {
923
                lxfile_rm_rec($this->main->rootdir);
924
        }
925
926
        @ lunlink("__path_program_root/tmp/{$this->main->nname}.createfailed");
927
        lxfile_rm_rec($this->main->configrootdir);
928
        lxshell_return("userdel", "-r", $this->main->username);
929
        lunlink("/etc/xen/auto/{$this->main->nname}.cfg");
930
}
931
932
933
function toggleStatus()
934
{
935
        global $global_shell_out, $global_shell_error, $global_shell_ret;
936
937
        if ($this->main->isOn('status')) {
938
                $ret = $this->start();
939
                if ($ret) {
940
                        throw new lxException("could_not_start_vps", '', str_replace("\n", ": ", $global_shell_error));
941
                }
942
                $ret = lxfile_symlink("{$this->main->configrootdir}/{$this->main->nname}.cfg", "/etc/xen/auto");
943
        } else {
944
                $ret = $this->stop();
945
                lunlink("/etc/xen/auto/{$this->main->nname}.cfg");
946
        }
947
948
        if($ret)
949
                log_message($ret);
950
}
951
952
function setRootPassword()
953
{
954
955
}
956
957
958
959
function mount_this_guy()
960
{
961
        $this->stop();
962
963
        if ($this->main->isWindows()) {
964
                return;
965
                throw new lxException("trying_to_mount_windows_image", '', '');
966
        }
967
968
        $mountpoint = "{$this->main->configrootdir}/mnt";
969
        if ($this->isMounted()) {
970
                return $mountpoint;
971
        }
972
973
        lxfile_mkdir($mountpoint);
974
975
976
        $loop = $this->main->maindisk;
977
        lxshell_return("e2fsck", "-y", $loop);
978
979
        if ($this->isLVM()) {
980
                $ret = lxshell_return("mount", $loop, $mountpoint);
981
        } else {
982
                $ret = lxshell_return("mount", "-o", "loop", $loop, $mountpoint);
983
        }
984
985
        if ($ret) {
986
                throw new lxException("could_not_mount_the_root_image");
987
        }
988
        return $mountpoint;
989
}
990
991
function takeSnapshot()
992
{
993
        lxshell_return("modprobe", "dm-snapshot");
994
        $tmp = "{$this->main->configrootdir}/snapshot_mount";
995
        lxfile_mkdir($tmp);
996
        $tmp = expand_real_root($tmp);
997
        $size = lvm_disksize($this->main->maindisk);
998
        $size = $size/3;
999
        $size = 10000;
1000
        $size = round($size);
1001
        $vgname = $this->main->corerootdir;
1002
        $vgname = fix_vgname($vgname);
1003
1004
1005
        $sfpath = "/dev/$vgname/{$this->main->nname}_snapshot";
1006
        $out = exec_with_all_closed_output("lvdisplay -c $sfpath");
1007
1008
        if (csa($out, ":")) {
1009
                lxshell_return("umount", $sfpath);
1010
                lvm_remove($sfpath);
1011
        }
1012
1013
1014
        $out = exec_with_all_closed_output("lvdisplay -c $sfpath");
1015
1016
        if (csa($out, ":")) {
1017
                throw new lxException("old_snapshot_exists_and_cant_remove");
1018
        }
1019
1020
        $ret = lxshell_return("lvcreate", "-L{$size}M", "-s",  "-n", "{$this->main->nname}_snapshot", $this->main->maindisk);
1021
1022
        if ($ret) {
1023
                throw new lxException("could_not_create_snapshot_lack_of_space");
1024
        }
1025
1026
        if (!$this->main->isWindows()) {
1027
                lxshell_return("e2fsck", "-f", "-y", $sfpath);
1028
                lxshell_return("mount", "-o", "ro", $sfpath, $tmp);
1029
        } else {
1030
                $tmp = $sfpath;
1031
        }
1032
1033
1034
        return $tmp;
1035
}
1036
1037
function changeLocation()
1038
{
1039
        if ($this->main->newlocation === $this->main->corerootdir) {
1040
                throw new lxException("old_new_location_same");
1041
        }
1042
1043
        $this->stop();
1044
        $this->umountThis();
1045
        $this->setMemoryUsage();
1046
        $this->setCpuUsage();
1047
        $this->setDiskUsage();
1048
        $this->__oldlocation = $this->main->corerootdir;
1049
        $this->main->corerootdir = $this->main->newlocation;
1050
        $name = strtil($this->main->nname, ".vm");
1051
        $this->main->maindiskname = "{$name}_rootimg";
1052
        $this->main->swapdiskname = "{$name}_vmswap";
1053
        $this->initXenVars();
1054
        $this->createDisk();
1055
        $this->setSwapUsage();
1056
        $this->createSwap();
1057
        //$this->mount_this_guy();
1058
1059
        if (csb($this->__oldlocation, "lvm:")) {
1060
                $vgname = fix_vgname($this->__oldlocation);
1061
                $oldimage = "/dev/$vgname/{$this->main->maindiskname}";
1062
        } else {
1063
                $oldimage = "{$this->__oldlocation}/{$this->main->nname}/root.img";
1064
        }
1065
1066
        $ret = lxshell_return("dd", "if=$oldimage", "of={$this->main->maindisk}");
1067
        if ($ret) {
1068
                throw new lxException("could_not_clone");
1069
        }
1070
1071
1072
        // Don't do this at all. The saved space is not going to be very important for the short period.
1073
        //lunlink("$this->__oldlocation/{$this->main->nname}/root.img");
1074
        /*
1075
        if (csb($this->__oldlocation, "lvm:")) {
1076
                $vg = fix_vgname($this->__oldlocation);
1077
                lvm_remove("/dev/$vg/{$this->main->swapdiskname}");
1078
        } else {
1079
                lunlink("$this->__oldlocation/{$this->main->nname}/vm.swap");
1080
        }
1081
        */
1082
        $this->start();
1083
1084
        $ret = array("__syncv_corerootdir" => $this->main->newlocation, "__syncv_maindiskname" => $this->main->maindiskname, "__syncv_swapdiskname" => $this->main->swapdiskname);
1085
        return $ret;
1086
1087
}
1088
1089
function saveXen()
1090
{
1091
        if (self::getStatus($this->main->nname, '/home/xen') !== 'on') {
1092
                return null;
1093
        }
1094
        $tmp = lx_tmp_file("{$this->main->nname}_ram");
1095
        lxshell_return("xm", "save", $this->main->nname, $tmp);
1096
        return $tmp;
1097
}
1098
1099
function restoreXen($file)
1100
{
1101
        if (!$file) {
1102
                return;
1103
        }
1104
        lxshell_return("xm", "restore", $file);
1105
}
1106
1107
1108
function do_backup()
1109
{
1110
        global $gbl, $sgbl, $login, $ghtml; 
1111
1112
        $tmpbasedir = $this->main->__var_tmp_base_dir;
1113
1114
        if ($this->isLVM()) {
1115
                //$file = $this->saveXen();
1116
1117
                if ($this->main->isOn('__var_bc_backupextra_stopvpsflag')) {
1118
                        $this->stop();
1119
                }
1120
1121
                try {
1122
                        $mountpoint = $this->takeSnapshot();
1123
                } catch (Exception $e) {
1124
                        //$this->restoreXen($file);
1125
                        $this->start();
1126
                        throw $e;
1127
                }
1128
1129
1130
                if ($this->main->isOn('__var_bc_backupextra_stopvpsflag')) {
1131
                        $this->start();
1132
                }
1133
1134
                $this->main->__snapshotmount = $mountpoint;
1135
                $this->main->__save_variable['__snapshotmount'] = $mountpoint;
1136
1137
        } else {
1138
                $this->stop();
1139
                $mountpoint = $this->mount_this_guy();
1140
        }
1141
1142
        if (!$this->main->isWindows()) {
1143
                $mountpoint = expand_real_root($mountpoint);
1144
                $list = lscandir_without_dot($mountpoint);
1145
                $list = array_remove($list, "proc");
1146
                if (count($list) < 6) {
1147
                        throw new lxException("not_enough_directories_in_vps_root,_possibly_wrong_location", '', '');
1148
                }
1149
1150
        } else {
1151
                if ($this->main->isCentralBackup) {
1152
                        // 2010-07-26 LN: Code for central backup of Windows VPS's
1153
                        //---------------------------------------------------------
1154
                        // Get partitions in snapshot
1155
                        $vgname = fix_vgname($this->main->corerootdir);
1156
                        $snapshot = "/dev/$vgname/{$this->main->nname}_snapshot";
1157
                        $out = lxshell_output("kpartx", "-l", $snapshot);
1158
                        $partitions = explode("\n", trim($out, " \n"));
1159
                        $partitions = preg_replace('/^([^ ]+).*$/', "/dev/mapper/$1", $partitions);
1160
                        lxshell_return("kpartx", "-a", $snapshot);
1161
                        // Return snapshot and partitions to the mothership
1162
                        $res = new stdClass();
1163
                        $res->snapshot = $snapshot;
1164
                        $res->partitions = $partitions;
1165
                        return $res;
1166
                } else {
1167
                        // 2010-07-26 LN: Original code, it was never called for central Windows backup
1168
                        //------------------------------------------------------------------------------
1169
                        $tmpdir = createTempDir($tmpbasedir, "lx_{$this->main->nname}_backup");
1170
                        $vgname = fix_vgname($this->main->corerootdir);
1171
                        $snapshot = "/dev/$vgname/{$this->main->nname}_snapshot";
1172
                        $partition = get_partition($snapshot, $this->main->corerootdir);
1173
                        lxshell_return("ntfsfix", $partition);
1174
                        $ret = lxshell_return("ntfsclone", "--force", "--save-image", "-O", "$tmpdir/backup.img", $partition);
1175
                        if ($ret) { 
1176
                                kpart_remove("/dev/mapper/$vgname-{$this->main->nname}_snapshot");
1177
                                lvm_remove($snapshot);
1178
                                throw new lxException("could_not_clone");
1179
                        }
1180
                        kpart_remove("/dev/mapper/$vgname-{$this->main->nname}_snapshot");
1181
                        $list = array("backup.img");
1182
                        $mountpoint = $tmpdir;
1183
                        $this->main->__windows_tmpdir = $tmpdir;
1184
                        lvm_remove($snapshot);
1185
                }
1186
        }
1187
                
1188
        return array($mountpoint, $list);
1189
}
1190
1191
1192
1193
function do_backup_cleanup($bc)
1194
{
1195
        // I had commented out the starting of the vps after backup. I don't know why. Why is this not done.. The vps should be started after the backup is done.
1196
        $mountpoint = "{$this->main->configrootdir}/mnt";
1197
1198
        if ($this->main->isWindows()) {
1199
                // 2010-07-26 LN: Cleanup for Windows VPS's
1200
                //------------------------------------------
1201
                if ($this->main->isCentralBackup) {
1202
                        $snapshot = $this->main->__save_bc->snapshot;
1203
                        $out = lxshell_output("kpartx", "-d", $snapshot);
1204
                        lvm_remove($snapshot);
1205
                } else {
1206
                        // Original code kept for now
1207
                        lxfile_rm("{$this->main->__windows_tmpdir}/backup.img");
1208
                        lxfile_rm($this->main->__windows_tmpdir);
1209
                }
1210
                return;
1211
        }
1212
        if ($this->isLVM()) {
1213
                lxshell_return("umount", $this->main->__snapshotmount);
1214
                lxfile_rm($this->main->__snapshotmount);
1215
                $vglocation = fix_vgname($this->main->corerootdir);
1216
                $snapshotlvm = "/dev/$vglocation/{$this->main->nname}_snapshot";
1217
                lvm_remove($snapshotlvm);
1218
        } else {
1219
                $this->start();
1220
        }
1221
}
1222
1223
1224
function do_restore($docd)
1225
{
1226
        global $gbl, $sgbl, $login, $ghtml;
1227
1228
        $this->hardstop();
1229
        $this->createDisk();
1230
1231
        $tmpbasedir = $this->main->__var_tmp_base_dir;
1232
1233
        if ($this->checkForSnapshot()) {
1234
                lvm_remove($this->getSnapshotName());
1235
                if ($this->checkForSnapshot()) {
1236
                        throw new lxException("snapshot_for_this_exists_and_coudnt_remove");
1237
                }
1238
        }
1239
1240
        if (!$this->main->isWindows()) {
1241
                $mountpoint = $this->mount_this_guy();
1242
                lxshell_unzip_numeric_with_throw($mountpoint, $docd);
1243
                //lxshell_return("tar", "-C", "$mountpoint/dev", "-xzf", "__path_program_root/file/vps-dev.tgz");
1244
1245
                if ($this->main->__old_driver !== 'xen') {
1246
                        log_restore("Restoring {$this->main->nname} from a different driver {$this->main->__old_driver} to xen");
1247
1248
                        /*
1249
                        if (!lxfile_exists("__path_program_home/xen/template/{$this->main->ostemplate}.tar.gz")) {
1250
                                throw new lxException("migrating_from_{$this->main->__old_driver}_needs_osImage");
1251
                }
1252
                */
1253
                        //lxshell_return("tar", "-C", $mountpoint, "-xzf", "__path_program_home/xen/template/{$this->main->ostemplate}.tar.gz", "etc/rc.d", "sbin", "etc/hotplug.d", "etc/dev.d", "etc/udev", "lib", "usr", "bin", "etc/inittab", "etc/sysconfig");
1254
                        //lxshell_return("tar", "-C", $mountpoint, "-xzf", "__path_program_home/xen/template/{$this->main->ostemplate}.tar.gz", "etc/rc.d", "sbin", "etc/hotplug.d", "etc/dev.d", "etc/udev", "lib", "usr", "bin", "etc/inittab");
1255
                        lxfile_cp("../file/sysfile/xen/fstab", "$mountpoint/etc/fstab");
1256
                        lxfile_cp("__path_program_root/file/sysfile/xen/inittab", "$mountpoint/etc/inittab");
1257
                        lunlink("$mountpoint/etc/mtab");
1258
                        lunlink("$mountpoint/etc/init.d/vzquota");
1259
                        $this->copyKernelModules();
1260
                }
1261
1262
                lxfile_mkdir("$mountpoint/proc");
1263
                $this->createConfig();
1264
                $this->setMemoryUsage();
1265
                $this->setCpuUsage();
1266
                $this->setSwapUsage();
1267
        } else {
1268
                $tmpdir = createTempDir($tmpbasedir, "lx_{$this->main->nname}_backup");
1269
                lxshell_unzip_with_throw($tmpdir, $docd);
1270
                $partition = $this->getPartition();
1271
                lxshell_return("ntfsclone", "--restore-image", "--force", "-O", $partition, "$tmpdir/backup.img");
1272
                lxfile_tmp_rm_rec("$tmpdir");
1273
                $this->kpart_remove();
1274
        }
1275
1276
        $this->main->status = 'on';
1277
1278
        try {
1279
                $this->toggleStatus();
1280
        } catch (Exception $e) {
1281
        }
1282
1283
        $this->start();
1284
1285
        // Saving state doesn't seem to be an option. The thing is, it is the file system itself that's left in an inconsistent state, and there's little we can do about it.
1286
1287
        /*
1288
        $statefile = "$mountpoint/__hypervm_xensavestate";
1289
        if (lxfile_exists($statefile)) {
1290
                $tmp = lx_tmp_file("/tmp", "xen_ram");
1291
                lxfile_mv($statefile, $tmp);
1292
                $this->umountThis();
1293
                $this->restoreXen($tmp);
1294
                lunlink($tmp);
1295
        } else {
1296
                $this->start();
1297
        }
1298
*/
1299
}
1300
1301
1302
1303
function setCpuUsage()
1304
{
1305
        if (is_unlimited($this->main->priv->cpu_usage)) {
1306
                $cpu = "100" * os_getCpuNum();;
1307
        } else {
1308
                $cpu = $this->main->priv->cpu_usage;
1309
        }
1310
        lxshell_return("xm", "sched-credit", "-d", $this->main->nname, "-c", $cpu);
1311
}
1312
1313
function setMemoryUsage()
1314
{
1315
        if (is_unlimited($this->main->priv->realmem_usage)) {
1316
                $memory = 512;
1317
        } else {
1318
                $memory = $this->main->priv->realmem_usage;
1319
        }
1320
1321
        $this->createConfig();
1322
        lxshell_return("xm", "mem-set", $this->main->nname, $memory);
1323
        lfile_put_contents("{$this->main->configrootdir}/memory.value", $memory);
1324
}
1325
1326
function setSwapUsage()
1327
{
1328
1329
        if ($this->main->isWindows()) {
1330
                return;
1331
        }
1332
1333
        if (is_unlimited($this->main->priv->swap_usage)) {
1334
                $memory = 512;
1335
        } else {
1336
                $memory = $this->main->priv->swap_usage;
1337
        }
1338
1339
        lfile_put_contents("{$this->main->configrootdir}/swap.value", $memory);
1340
}
1341
1342
function setDiskUsage()
1343
{
1344
        if (is_unlimited($this->main->priv->disk_usage)) {
1345
                $diskusage = 3 * 1024;
1346
        } else {
1347
                $diskusage = $this->main->priv->disk_usage ;
1348
        }
1349
1350
        lfile_put_contents("{$this->main->configrootdir}/disk.value", $diskusage);
1351
        
1352
}
1353
1354
1355
function reboot()
1356
{
1357
        global $global_shell_out, $global_shell_error, $global_shell_ret;
1358
        $this->stop();
1359
        $ret = $this->start();
1360
1361
        if ($ret) {
1362
                throw new lxException("could_not_start_vps", '', str_replace("\n", ": ", $global_shell_error));
1363
        }
1364
}
1365
1366
1367
function rebuild()
1368
{
1369
1370
        if (!$this->main->isOn('rebuild_confirm_f')) {
1371
                throw new lxException("need_confirm_rebuild", 'rebuild_confirm_f');
1372
        }
1373
1374
1375
        if ($this->main->isWindows()) {
1376
                $templatefile = "__path_program_home/xen/template/{$this->main->ostemplate}";
1377
        } else {
1378
                $templatefile = "__path_program_home/xen/template/{$this->main->ostemplate}.tar.gz";
1379
        }
1380
1381
        if(!lxfile_nonzero($templatefile)) {
1382
                $this->main->getOsTemplateFromMaster($templatefile);
1383
        }
1384
1385
        if (!lxfile_nonzero($templatefile)) {
1386
                throw new lxException("no_template_and_could_not_download", 'rebuild_confirm_f');
1387
        }
1388
1389
        $this->stop();
1390
1391
        if ($this->main->isNotWindows()) {
1392
                $mountpoint = $this->mount_this_guy();
1393
                if ($this->main->isOn('rebuild_backup_f')) {
1394
                        lxfile_mkdir("/home/hypervm/vps/{$this->main->nname}/__backup/");
1395
                        $date = date('Y-m-d-') . time();
1396
                        $dir = "/home/hypervm/vps/{$this->main->nname}/__backup/rebuild-backup.$date";
1397
                        lxfile_cp_rec($mountpoint, $dir);
1398
                }
1399
        }
1400
1401
        $this->umountThis();
1402
1403
        if ($this->main->isNotWindows()) {
1404
                if ($this->isLvm()) {
1405
                        lxshell_return("mkfs.ext3", "-F", $this->main->maindisk);
1406
                } else {
1407
                        lxfile_rm_rec($this->main->maindisk);
1408
                        $this->createDisk();
1409
                }
1410
1411
                $mountpoint = $this->mount_this_guy();
1412
                $ret = lxshell_return("tar", "-C", $mountpoint, '--numeric-owner', "-xpzf", $templatefile);
1413
1414
                if ($ret) {
1415
                        throw new lxException("rebuild_failed_could_not_untar");
1416
                }
1417
        } else {
1418
                $templatefile = expand_real_root($templatefile);
1419
                lxshell_return("parted", "-s", $this->main->maindisk, "mklabel", "msdos");
1420
                $this->runParted();
1421
                $partition = $this->getPartition();
1422
                //lxshell_return("dd", "if=$templatefile", "of={$this->main->maindisk}");
1423
                lxshell_return("ntfsclone", "--restore-image", "-O", $partition, $templatefile);
1424
                $this->kpart_remove();
1425
                $this->expandPartitionToImage();
1426
        }
1427
1428
1429
        $this->start();
1430
}
1431
1432
1433
function installkloxo()
1434
{
1435
        $this->rebuild();
1436
}
1437
1438
function recoverVps()
1439
{
1440
        if (!$this->main->isOn('recover_confirm_f')) {
1441
                throw new lxException("need_confirm_recover", 'recover_confirm_f');
1442
        }
1443
        $this->stop();
1444
        $mountpoint = $this->mount_this_guy();
1445
        $this->main->coreRecoverVps($mountpoint);
1446
        $this->start();
1447
}
1448
1449
function setInformation()
1450
{
1451
        //lxshell_return("vzctl", "set", $this->main->vpsid, "--hostname", $this->main->hostname);
1452
}
1453
1454
function createTemplate()
1455
{
1456
1457
        $stem = explode("-", $this->main->ostemplate);
1458
        if ($this->main->isWindows()) {
1459
                $name = "{$stem[0]}-";
1460
        } else {
1461
                $name = "{$stem[0]}-{$stem[1]}-{$stem[2]}-";
1462
        }
1463
1464
1465
        $templatename = "$name{$this->main->newostemplate_name_f}";
1466
        if ($this->main->isWindows()) {
1467
                $tempfpath = "__path_program_home/xen/template/$templatename.img";
1468
        } else {
1469
                $tempfpath = "__path_program_home/xen/template/$templatename.tar.gz";
1470
        }
1471
1472
1473
        $this->stop();
1474
1475
        if ($this->main->isWindows()) {
1476
                $partition = $this->getPartition();
1477
                lxshell_return("ntfsfix", $partition);
1478
                lxshell_return("ntfsclone", "--save-image", "--force", "-O", $tempfpath, $partition);
1479
                $this->kpart_remove();
1480
        } else {
1481
                $list = lscandir_without_dot("{$this->main->configrootdir}/mnt");
1482
                $ret = lxshell_return("tar", "-C", "{$this->main->configrootdir}/mnt", '--numeric-owner', "-czf", $tempfpath, $list);
1483
        }
1484
        $this->start();
1485
1486
        $filepass = cp_fileserv($tempfpath);
1487
        $ret = array("__syncv___ostemplate_filepass" => $filepass, "__syncv___ostemplate_filename" => basename($tempfpath));
1488
        return $ret;
1489
1490
}
1491
1492
function hardstop()
1493
{
1494
        if (self::getStatus($this->main->nname, '/home/xen') !== 'on') {
1495
                //$this->mount_this_guy();
1496
                return;
1497
        }
1498
1499
        lxshell_return("xm", "shutdown", $this->main->nname);
1500
1501
        $count = 0;
1502
        while (self::getStatus($this->main->nname, '/home/xen') === 'on') {
1503
                $count++;
1504
                sleep(5);
1505
                if ($count === 3) {
1506
                        lxshell_return("xm", "destroy", $this->main->nname);
1507
                        break;
1508
                }
1509
        }
1510
1511
        while (self::getStatus($this->main->nname, '/home/xen') === 'on') {
1512
                sleep(5);
1513
        }
1514
1515
        usleep(100 * 1000);
1516
        sleep(10);
1517
1518
1519
}
1520
1521
function stop()
1522
{
1523
        if (self::getStatus($this->main->nname, '/home/xen') !== 'on') {
1524
                //$this->mount_this_guy();
1525
                return;
1526
        }
1527
1528
        lxshell_return("xm", "shutdown", $this->main->nname);
1529
1530
        sleep(40);
1531
1532
        if (self::getStatus($this->main->nname, '/home/xen') === 'on') {
1533
                lxshell_return("xm", "destroy", $this->main->nname);
1534
        }
1535
1536
1537
        sleep(3);
1538
1539
        if (self::getStatus($this->main->nname, '/home/xen') === 'on') {
1540
                throw new lxException("could_not_stop_vps");
1541
        }
1542
1543
        $this->mount_this_guy();
1544
}
1545
1546
function isMounted()
1547
{
1548
        $mountpoint = "{$this->main->configrootdir}/mnt";
1549
        $mountpoint = expand_real_root($mountpoint);
1550
        $cont = lfile_get_contents("/proc/mounts");
1551
        if (csa($cont, $mountpoint)) {
1552
                return true;
1553
        }
1554
        dprint("$mountpoint is not in /proc/mounts\n");
1555
        return false;
1556
}
1557
1558
function umountThis()
1559
{
1560
        $mountpoint = "{$this->main->configrootdir}/mnt";
1561
        lxshell_return("sync");
1562
        $count = 0;
1563
        while (true) {
1564
                $count++;
1565
                if ($count > 10) {
1566
                        throw new lxException("cannot_unmount_after_10_attempts");
1567
                }
1568
                if (!$this->isMounted()) {
1569
                        break;
1570
                }
1571
1572
                $ret = lxshell_return("umount", $mountpoint);
1573
                if ($ret) {
1574
                        //lxshell_return("umount", "-l", $mountpoint);
1575
                        throw new lxException("umounting_file_system_failed");
1576
                }
1577
        }
1578
}
1579
1580
function checkForSnapshot()
1581
{
1582
        if ($this->isLvm()) {
1583
                if (lxfile_exists($this->getSnapshotName())) {
1584
                        log_log("critical_snapshot", "Found snapshot for {$this->main->nname} removing...");
1585
                        return true;
1586
                }
1587
        }
1588
1589
        return false;
1590
}
1591
1592
function getSnapshotName()
1593
{
1594
        $vgname = fix_vgname($this->main->corerootdir);
1595
        $snap = "/dev/$vgname/{$this->main->nname}_snapshot";
1596
        return $snap;
1597
}
1598
1599
1600
function start() 
1601
{
1602
1603
        if (self::getStatus($this->main->nname, '/home/xen') === 'on') {
1604
                return;
1605
        }
1606
1607
        $this->createConfig();
1608
        $this->createSwap();
1609
        $this->setvif();
1610
        $this->resizeRootImage();
1611
1612
        if ($this->checkForSnapshot()) {
1613
                //lvm_remove($this->getSnapshotName());
1614
        }
1615
1616
        if (!$this->main->isWindows()) {
1617
                $mountpoint = $this->mount_this_guy();
1618
                $this->setInternalParam($mountpoint);
1619
                $this->copyKernelModules();
1620
                $this->umountThis();
1621
        }
1622
1623
        return lxshell_return("xm", "create", "{$this->main->configrootdir}/{$this->main->nname}.cfg"); 
1624
}
1625
1626
1627
function setInternalParam($mountpoint)
1628
{
1629
        $name = $this->main->ostemplate;
1630
1631
        if ($this->main->isWindows()) { return; } 
1632
1633
        if (!$mountpoint) { return; }
1634
1635
        if ($name === 'unknown') { return; }
1636
1637
1638
1639
        $name = strtolower($name);
1640
        $mountpoint = expand_real_root($mountpoint);
1641
        $result = $this->getScriptS($name);
1642
        dprint("Distro Name $name, Scripts: \n");
1643
        dprintr($result);
1644
1645
        $init = strtilfirst($name, "-");
1646
1647
        dprint("File is  $init.inittab\n");
1648
        if (lxfile_exists("../file/sysfile/inittab/$init.inittab")) {
1649
                dprint("Copying $init.inittab\n");
1650
                $content = lfile_get_contents("../file/sysfile/inittab/$init.inittab");
1651
                if ($this->main->text_inittab) {
1652
                        $content .= "\n{$this->main->text_inittab}";
1653
                }
1654
                lfile_put_contents("$mountpoint/etc/inittab", $content);
1655
        }
1656
1657
        $iplist = get_namelist_from_objectlist($this->main->vmipaddress_a);
1658
        if ($this->main->mainipaddress) {
1659
                $main_ip = $this->main->mainipaddress;
1660
                $iplist = array_remove($iplist, $main_ip);
1661
        } else {
1662
                $main_ip = array_shift($iplist);
1663
        }
1664
1665
        if ($this->main->networknetmask) {
1666
                $main_netmask = $this->main->networknetmask;
1667
        } else {
1668
                $main_netmask = "255.255.255.0";
1669
        }
1670
1671
        $iplist = implode(" ", $iplist);
1672
1673
        $ipadd = $result['ADD_IP'];
1674
        $sethostname = $result['SET_HOSTNAME'];
1675
        $setuserpass = $result['SET_USERPASS'];
1676
        $ipdel = $result['DEL_IP'];
1677
1678
        $name = createTempDir("$mountpoint/tmp", "xen-scripts");
1679
        lxfile_cp_rec("__path_program_root/bin/xen-dists/scripts/functions", $name);
1680
        lxfile_cp_rec("__path_program_root/bin/xen-dists/scripts/$ipadd", $name);
1681
        lxfile_cp_rec("__path_program_root/bin/xen-dists/scripts/$sethostname", $name);
1682
        lxfile_cp_rec("__path_program_root/bin/xen-dists/scripts/$setuserpass", $name);
1683
        lxfile_cp_rec("__path_program_root/bin/xen-dists/scripts/$ipdel", $name);
1684
1685
1686
        $basepath = strfrom($name, $mountpoint);
1687
        lfile_put_contents("$name/tmpfile.sh", "source /$basepath/functions\nsource /$basepath/$ipdel\n");
1688
        $delipstring = "IPDELALL=yes chroot $mountpoint bash /$basepath/tmpfile.sh";
1689
1690
        if ($this->main->networkgateway) {
1691
                $gw = $this->main->networkgateway;
1692
        } else {
1693
                $gw = os_get_network_gateway();
1694
        }
1695
1696
        log_shell($delipstring);
1697
        system($delipstring);
1698
1699
        $gwn = strtil($gw, ".") . ".0";
1700
        putenv("VE_STATE=stopped");
1701
        lfile_put_contents("$name/tmpfile.sh", "source /$basepath/functions\n source /$basepath/$ipadd\n");
1702
        $string = "IPDELALL=yes MAIN_NETMASK=$main_netmask MAIN_IP_ADDRESS=$main_ip IP_ADDR=\"$iplist\" NETWORK_GATEWAY=$gw NETWORK_GATEWAY_NET=$gwn chroot $mountpoint bash /$basepath/tmpfile.sh";
1703
1704
        log_shell($string);
1705
        system($string); 
1706
1707
        $hostname = $this->main->hostname;
1708
        if (!$hostname) { $hostname = os_get_hostname(); }
1709
1710
        lfile_put_contents("$name/tmpfile.sh", "source /$basepath/functions\n source /$basepath/$sethostname\n");
1711
        $string = "HOSTNM=$hostname chroot $mountpoint bash /$basepath/tmpfile.sh";
1712
        log_shell($string);
1713
        system($string);
1714
1715
        if (($this->main->subaction === 'rebuild') || ($this->main->dbaction === 'add') || ($this->main->isOn('__var_rootpassword_changed') && $this->main->rootpassword)) {
1716
                $rootpass = "root:{$this->main->rootpassword}";
1717
                lfile_put_contents("$name/tmpfile.sh", "source /$basepath/functions\n source /$basepath/$setuserpass\n");
1718
                $string = "USERPW=$rootpass chroot $mountpoint bash /$basepath/tmpfile.sh";
1719
                log_shell($string);
1720
                system($string);
1721
        }
1722
1723
1724
        lxfile_rm_rec($name);
1725
1726
        if ($this->main->nameserver) {
1727
                $nlist = explode(" ", $this->main->nameserver);
1728
                $nstring = null;
1729
                foreach($nlist as $l) {
1730
                        $nstring .= "nameserver $l\n";
1731
                }
1732
                lfile_put_contents("$mountpoint/etc/resolv.conf", $nstring);
1733
        }
1734
1735
        if ($this->main->timezone) {
1736
                lxfile_rm("$mountpoint/etc/localtime");
1737
1738
                $cmdstring = "ln -sf ../usr/share/zoneinfo/{$this->main->timezone} $mountpoint/etc/localtime";
1739
                log_log("localtime", $cmdstring);
1740
                do_exec_system('__system__', "/", $cmdstring, $out, $err, $ret, null);
1741
                //lxfile_cp("/usr/share/zoneinfo/{$this->main->timezone}", "$mountpoint/etc/localtime");
1742
        }
1743
1744
        if (csb($this->main->ostemplate, "centos")) {
1745
                //addLineIfNotExistInside("$mountpoint/etc/rc.local", 
1746
                //addLineIfNotExistInside("$mountpoint/etc/rc.local", "depmod", "#added by hyperVM since the kernel can change without notice");
1747
        } else {
1748
        }
1749
1750
        $content = "#added by hyperVM to kill the runaway nash\n";
1751
        $content .= "pkill -f nash\n";
1752
        lfile_put_contents("$mountpoint/etc/init.d/killnash", $content);
1753
        lxfile_unix_chmod("$mountpoint/etc/init.d/killnash", "0755");
1754
1755
        /*
1756
        if (lxfile_exists("$mountpoint/etc/rc0.d")) {
1757
                foreach(range(2, 6) as $ii) {
1758
                        lxshell_return("ln", "-sf", "../init.d/killnash", "$mountpoint/etc/init.d/rc$ii.d/S99killnash");
1759
                }
1760
        } else {
1761
        }
1762
*/
1763
1764
        foreach(range(2, 6) as $ii) {
1765
                lxshell_return("ln", "-sf", "../init.d/killnash", "$mountpoint/etc/rc$ii.d/S99killnash");
1766
        }
1767
1768
        if (lxfile_exists("$mountpoint/etc/runlevels/default")) {
1769
                lxshell_return("ln", "-sf", "../../init.d/killnash", "$mountpoint/etc/runlevels/default/killnash");
1770
        }
1771
1772
        lunlink("$mountpoint/etc/sysconfig/network-scripts/ifcfg-venet0");
1773
        lunlink("$mountpoint/etc/sysconfig/network-scripts/ifcfg-venet0:0");
1774
1775
        $this->main->doKloxoInit($mountpoint);
1776
1777
}
1778
1779
function getScriptS($name)
1780
{
1781
        $v = $name;
1782
        while (true) {
1783
                $v = strtil($v, "-");
1784
                if (!$v) {
1785
                        $v = 'default';
1786
                        break;
1787
                }
1788
                dprint("Checking for conf $v\n");
1789
                if (lxfile_exists("__path_program_root/bin/xen-dists/$v.conf")) {
1790
                        break;
1791
                }
1792
1793
                if (!csa($v, "-")) {
1794
                        $v = "default";
1795
                        break;
1796
                }
1797
1798
        }
1799
        $file = "__path_program_root/bin/xen-dists/$v.conf";
1800
        $list = lfile_trim($file);
1801
1802
        foreach($list as $l) {
1803
                if (csb($l, "#")) {
1804
                        continue;
1805
                }
1806
1807
                if (csa($l, "=")) {
1808
                        $v = explode("=", $l);
1809
                        $result[$v[0]] = $v[1];
1810
                }
1811
        }
1812
        return $result;
1813
}
1814
1815
1816
function changeUserPassword()
1817
{
1818
        $pass = $this->main->password;
1819
        lxshell_return("usermod", "-p", $pass, $this->main->username);
1820
}
1821
1822
1823
1824
function dbactionUpdate($subaction)
1825
{
1826
1827
        global $gbl, $sgbl, $login, $ghtml; 
1828
1829
1830
1831
        switch($subaction) {
1832
                case "changelocation":
1833
                        return $this->changelocation();
1834
                        break;
1835
1836
                case "rebuild":
1837
                        $this->rebuild();
1838
                        break;
1839
1840
                case "recovervps":
1841
                        $this->recovervps();
1842
                        break;
1843
1844
1845
                case "mount":
1846
                        $this->mount_this_guy();
1847
                        break;
1848
1849
                case "createuser":
1850
                        return $this->main->syncCreateUser();
1851
                        break;
1852
1853
1854
                case "full_update":
1855
                        $this->setDiskUsage();
1856
                        $this->setMemoryUsage();
1857
                        $this->setCpuUsage();
1858
                        $this->setSwapUsage();
1859
                        $this->toggleStatus();
1860
                        break;
1861
1862
1863
                case "password":
1864
                        $this->changeUserPassword();
1865
                        break;
1866
1867
                case "createtemplate":
1868
                        return $this->createTemplate();
1869
                        break;
1870
1871
                case "disable":
1872
                case "enable":
1873
                case "toggle_status":
1874
                        $this->toggleStatus();
1875
                        break;
1876
1877
1878
                case "change_disk_usage":
1879
                        $this->setDiskUsage();
1880
                        break;
1881
1882
                case "change_realmem_usage":
1883
                        $this->setMemoryUsage();
1884
                        break;
1885
1886
1887
                case "change_swap_usage":
1888
                        $this->setSwapUsage();
1889
                        break;
1890
1891
                case "change_process_usage":
1892
                        //$this->setProcessUsage();
1893
                        break;
1894
                        
1895
                case "rootpassword":
1896
                        $this->setRootPassword();
1897
                        break;
1898
1899
                case "installkloxo":
1900
                        $this->installKloxo();
1901
                        break;
1902
1903
                case "network":
1904
                case "information":
1905
                        $this->setInformation();
1906
                        $this->setDhCP();
1907
                        break;
1908
1909
                case "add_vmipaddress_a":
1910
                        $this->setDhCP();
1911
                        break;
1912
1913
                case "delete_vmipaddress_a":
1914
                        $this->setDhCP();
1915
                        break;
1916
1917
                case "boot":
1918
                        $this->start();
1919
                        break;
1920
1921
                case "poweroff":
1922
                        $this->stop();
1923
                        $this->mount_this_guy();
1924
                        break;
1925
1926
1927
                case "reboot":
1928
                        $this->reboot();
1929
                        break;
1930
1931
                case "change_cpu_usage":
1932
                        $this->setCpuUsage();
1933
                        break;
1934
1935
                case "hardpoweroff":
1936
                        $this->hardstop();
1937
                        break;
1938
1939
1940
                case "createconfig":
1941
                        $this->createConfig();
1942
                        $ret = lxfile_symlink("{$this->main->configrootdir}/{$this->main->nname}.cfg", "/etc/xen/auto");
1943
                        break;
1944
1945
                case "graph_traffic":
1946
                        return rrd_graph_vps("traffic", "xen-{$this->main->vifname}.rrd", $this->main->rrdtime);
1947
                        break;
1948
1949
                case "graph_cpuusage":
1950
                        return rrd_graph_vps("cpu", "{$this->main->nname}.rrd", $this->main->rrdtime);
1951
                        break;
1952
1953
1954
        }
1955
}
1956
1957
function setDhCP()
1958
{
1959
        if (!$this->main->isWindows()) {
1960
                return;
1961
        }
1962
1963
        $this->main->iplist = get_namelist_from_objectlist($this->main->vmipaddress_a);
1964
        $res = merge_array_object_not_deleted($this->main->__var_win_iplist, $this->main);
1965
        dhcp__dhcpd::createDhcpConfFile($res);
1966
}
1967
1968
function setProcessUsage()
1969
{
1970
}
1971
1972
static function getCompleteStatus($list)
1973
{
1974
        foreach($list as $l) {
1975
                $r['status'] = self::getStatus($l['nname'], '/home/xen');
1976
                $disk = self::getDiskUsage($l['diskname'], $l['winflag'], $l['corerootdir']);
1977
                $r['ldiskusage_f'] = $disk['used'];
1978
                $res[$l['nname']] = $r;
1979
        }
1980
        return $res;
1981
}
1982
1983
}