/
xenops_server_xen.ml
1958 lines (1778 loc) · 71.7 KB
/
xenops_server_xen.ml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
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
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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(*
* Copyright (C) Citrix Systems Inc.
*
* This program 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; version 2.1 only. with the special
* exception on linking described in file LICENSE.
*
* This program 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.
*)
open Xenops_interface
open Xenops_utils
open Xenops_server_plugin
open Xenops_helpers
open Xenstore
open Pervasiveext
open Listext
open Threadext
open Stringext
open Fun
module D = Debug.Debugger(struct let name = service_name end)
open D
let _qemu_dm = "/opt/xensource/libexec/qemu-dm-wrapper"
let _tune2fs = "/sbin/tune2fs"
let _mkfs = "/sbin/mkfs"
let _mount = "/bin/mount"
let _umount = "/bin/umount"
let _ionice = "/usr/bin/ionice"
let run cmd args =
debug "%s %s" cmd (String.concat " " args);
fst(Forkhelpers.execute_command_get_output cmd args)
type qemu_frontend =
| Name of string (* block device path or bridge name *)
| Device of Device_common.device
with rpc
type attached_vdi = {
domid: int;
attach_info: Storage_interface.attach_info;
}
module VmExtra = struct
(** Extra data we store per VM. This is preserved when the domain is
suspended so it can be re-used in the following 'create' which is
part of 'resume'. When a VM is shutdown for other reasons (eg reboot)
we throw this information away and generate fresh data on the
following 'create' *)
type t = {
create_info: Domain.create_info;
build_info: Domain.build_info option;
vcpu_max: int;
vcpus: int;
shadow_multiplier: float;
memory_static_max: int64;
suspend_memory_bytes: int64;
ty: Vm.builder_info option;
vbds: Vbd.t list; (* needed to regenerate qemu IDE config *)
qemu_vbds: (Vbd.id * (int * qemu_frontend)) list;
qemu_vifs: (Vif.id * (int * qemu_frontend)) list;
vifs: Vif.t list;
last_create_time: float;
pci_msitranslate: bool;
pci_power_mgmt: bool;
} with rpc
end
module DB = struct
include TypedTable(struct
include VmExtra
let namespace = "extra"
type key = string
let key vm = [ vm ]
end)
end
(* Used to signal when work needs to be done on a VM *)
let updates = Updates.empty ()
let event_wait task timeout p =
let finished = ref false in
let success = ref false in
let event_id = ref None in
while not !finished do
let deltas, next_id = Updates.get (Printf.sprintf "event_wait task %s" task.Xenops_task.id) !event_id timeout updates in
if deltas = [] then finished := true;
List.iter (fun d -> if p d then (success := true; finished := true)) deltas;
event_id := next_id;
done;
!success
let this_domid ~xs = int_of_string (xs.Xs.read "domid")
let uuid_of_vm vm = Uuid.uuid_of_string vm.Vm.id
let uuid_of_di di = Uuid.uuid_of_int_array di.Xenctrl.handle
(* During a live migrate, there will be multiple domains with the same uuid.
The convention is: we construct things on the newest domain (e.g. VBD.plug)
and we destroy things on the oldest domain (e.g. VBD.unplug). In the normal
case there is only one domain, so oldest = newest *)
type domain_selection =
| Oldest (* operate on the oldest domain *)
| Newest (* operate on the newest domain *)
| Expect_only_one
let di_of_uuid ~xc ~xs domain_selection uuid =
let open Xenctrl in
let uuid' = Uuid.string_of_uuid uuid in
let all = domain_getinfolist xc 0 in
let possible = List.filter (fun x -> uuid_of_di x = uuid) all in
let oldest_first = List.sort
(fun a b ->
let has_run x = x.cpu_time <> 0L in
match has_run a, has_run b with
| true, false -> -1 (* a is older than b *)
| false, true -> 1
| _, _ ->
warn "VM %s: unable to tell which of domid %d and %d is newer" uuid' a.domid b.domid;
compare a.domid b.domid
) possible in
let domid_list = String.concat ", " (List.map (fun x -> string_of_int x.domid) oldest_first) in
if List.length oldest_first > 2
then warn "VM %s: there are %d domains (%s) with the same uuid: one or more have leaked" uuid' (List.length oldest_first) domid_list;
if domain_selection = Expect_only_one && (List.length oldest_first > 1)
then raise (Internal_error (Printf.sprintf "More than one domain with uuid (%s): %s" uuid' domid_list));
match (if domain_selection = Oldest then oldest_first else List.rev oldest_first) with
| [] -> None
| x :: [] ->
Some x
| x :: rest ->
debug "VM = %s; domids = [ %s ]; we will operate on %d" uuid' domid_list x.domid;
Some x
let domid_of_uuid ~xc ~xs domain_selection uuid =
Opt.map (fun di -> di.Xenctrl.domid) (di_of_uuid ~xc ~xs domain_selection uuid)
let get_uuid ~xc domid = uuid_of_di (Xenctrl.domain_getinfo xc domid)
let create_vbd_frontend ~xc ~xs task frontend_domid vdi =
let frontend_vm_id = get_uuid ~xc frontend_domid |> Uuid.string_of_uuid in
let backend_vm_id = get_uuid ~xc vdi.domid |> Uuid.string_of_uuid in
match domid_of_uuid ~xc ~xs Expect_only_one (Uuid.uuid_of_string backend_vm_id) with
| None ->
error "VM = %s; domid = %d; Failed to determine domid of backend VM id: %s" frontend_vm_id frontend_domid backend_vm_id;
raise (Does_not_exist("domain", backend_vm_id))
| Some backend_domid when backend_domid = frontend_domid ->
(* There's no need to use a PV disk if we're in the same domain *)
Name vdi.attach_info.Storage_interface.params
| Some backend_domid ->
let t = {
Device.Vbd.mode = Device.Vbd.ReadOnly;
device_number = None; (* we don't mind *)
phystype = Device.Vbd.Phys;
params = vdi.attach_info.Storage_interface.params;
dev_type = Device.Vbd.Disk;
unpluggable = true;
protocol = None;
extra_backend_keys = List.map (fun (k, v) -> "sm-data/" ^ k, v) (vdi.attach_info.Storage_interface.xenstore_data);
extra_private_keys = [];
backend_domid = backend_domid;
} in
let device = Xenops_task.with_subtask task "Vbd.add"
(fun () -> Device.Vbd.add task ~xs ~hvm:false t frontend_domid) in
Device device
let block_device_of_vbd_frontend = function
| Name x -> x
| Device device ->
let open Device_common in
device.frontend.devid |> Device_number.of_xenstore_key |> Device_number.to_linux_device |> (fun x -> "/dev/" ^ x)
let destroy_vbd_frontend ~xc ~xs task disk =
match disk with
| Name _ -> ()
| Device device ->
Xenops_task.with_subtask task "Vbd.clean_shutdown"
(fun () ->
let open Device_common in
let me = this_domid ~xs in
(* To avoid having two codepaths: a 99% "normal" codepath and a 1%
"transient failure" codepath we deliberately trigger a "transient
failure" in 100% of cases by opening the device ourselves.
NB this only works when we're in the same domain as the frontend. *)
let f = ref (
if device.frontend.domid = me
then Some (Unix.openfile (block_device_of_vbd_frontend disk) [ Unix.O_RDONLY ] 0o0)
else None
) in
let close () = Opt.iter (fun fd -> Unix.close fd; f := None) !f in
finally
(fun () ->
Device.Vbd.clean_shutdown_async ~xs device;
try
Device.Vbd.clean_shutdown_wait task ~xs device
with Device_error(_, x) ->
debug "Caught transient Device_error %s" x;
close ();
Device.Vbd.clean_shutdown_wait task ~xs device
) (fun () -> close ())
)
module Storage = struct
open Storage_interface
module Client = Client(struct
let rec retry_econnrefused upto f =
try
f ()
with
| Unix.Unix_error(Unix.ECONNREFUSED, "connect", _) as e ->
if upto = 0 then raise e;
debug "Caught ECONNREFUSED; retrying in 5s";
Thread.delay 5.;
retry_econnrefused (upto - 1) f
| e ->
error "Caught %s: does the storage service need restarting?" (Printexc.to_string e);
raise e
let rpc call =
let open Xmlrpc_client in
retry_econnrefused 10
(fun () ->
XMLRPC_protocol.rpc ~srcstr:"xenops" ~dststr:"smapiv2" ~transport:(Unix "/var/xapi/storage") ~http:(xmlrpc ~version:"1.0" "/") call
)
end)
let transform_exception f x =
try f x
with
| Backend_error(code, params) -> raise (Storage_backend_error(code, params))
| e -> raise e
(* Used to identify this VBD to the storage layer *)
let id_of frontend_domid vbd = Printf.sprintf "vbd/%d/%s" frontend_domid (snd vbd)
let attach_and_activate task dp sr vdi read_write =
let result =
Xenops_task.with_subtask task (Printf.sprintf "VDI.attach %s" dp)
(transform_exception (fun () -> Client.VDI.attach "attach_and_activate" dp sr vdi read_write)) in
Xenops_task.with_subtask task (Printf.sprintf "VDI.activate %s" dp)
(transform_exception (fun () -> Client.VDI.activate "attach_and_activate" dp sr vdi));
(* XXX: we need to find out the backend domid *)
{ domid = 0; attach_info = result }
let deactivate task dp sr vdi =
debug "Deactivating disk %s %s" sr vdi;
Xenops_task.with_subtask task (Printf.sprintf "VDI.deactivate %s" dp)
(transform_exception (fun () -> Client.VDI.deactivate "deactivate" dp sr vdi))
let deactivate_and_detach task dp =
Xenops_task.with_subtask task (Printf.sprintf "DP.destroy %s" dp)
(transform_exception (fun () ->
Client.DP.destroy "deactivate_and_detach" dp false))
let get_disk_by_name task path =
debug "Storage.get_disk_by_name %s" path;
Xenops_task.with_subtask task (Printf.sprintf "get_by_name %s" path)
(transform_exception (fun () ->
let vdi = Client.get_by_name "get_by_name" path in
vdi.sr, vdi.vdi
))
end
let with_disk ~xc ~xs task disk write f = match disk with
| Local path -> f path
| VDI path ->
let open Storage_interface in
let open Storage in
let sr, vdi = get_disk_by_name task path in
let dp = Client.DP.create "with_disk" (Printf.sprintf "xenopsd/task/%s" task.Xenops_task.id) in
finally
(fun () ->
let vdi = attach_and_activate task dp sr vdi write in
let frontend_domid = this_domid ~xs in
let device = create_vbd_frontend ~xc ~xs task frontend_domid vdi in
finally
(fun () ->
device |> block_device_of_vbd_frontend |> f
)
(fun () ->
destroy_vbd_frontend ~xc ~xs task device
)
)
(fun () -> deactivate_and_detach task dp)
module Mem = struct
let call_daemon xs fn args = Squeezed_rpc.Rpc.client ~xs ~service:Squeezed_rpc._service ~fn ~args
let ignore_results (_: (string * string) list) = ()
let wrap f =
try Some (f ())
with
| Squeezed_rpc.Error(code, descr) when code = Squeezed_rpc._error_cannot_free_this_much_memory_code ->
debug "Got error_cannot_free_this_much_memory(%s) from ballooning daemon" descr;
begin match Stringext.String.split ',' descr with
| [ needed; free ] ->
let needed = Memory.bytes_of_kib (Int64.of_string needed) in
let free = Memory.bytes_of_kib (Int64.of_string free) in
raise (Cannot_free_this_much_memory(needed, free))
| _ ->
error "Failed to parse cannot_free_this_much_memory_error (old ballooning daemon?)";
raise (Ballooning_error(code, descr))
end
| Squeezed_rpc.Error(code, descr) when code = Squeezed_rpc._error_domains_refused_to_cooperate_code ->
debug "Got error_domains_refused_to_cooperate_code from ballooning daemon";
Xenctrl.with_intf
(fun xc ->
let domids = List.map int_of_string (Stringext.String.split ',' descr) in
let vms = List.map (get_uuid ~xc) domids |> List.map Uuid.string_of_uuid in
raise (Vms_failed_to_cooperate(vms))
)
| Squeezed_rpc.Server_not_registered ->
error "The ballooning daemon is not running";
None (* Keep going anyway *)
| Squeezed_rpc.Error(code, descr) -> raise (Ballooning_error(code, descr))
let do_login_exn ~xs =
let args = [ Squeezed_rpc._service_name, "xenopsd" ] in
let results = call_daemon xs Squeezed_rpc._login args in
List.assoc Squeezed_rpc._session_id results
let do_login ~xs = wrap (fun () -> do_login_exn ~xs)
(** Maintain a cached login session with the ballooning service; return the cached value on demand *)
let get_session_id =
let session_id = ref None in
let m = Mutex.create () in
fun ~xs ->
Mutex.execute m
(fun () ->
match !session_id with
| Some x -> x
| None ->
let s = do_login ~xs in
session_id := Some s;
s
)
(** If we fail to allocate because VMs either failed to co-operate or because they are still booting
and haven't written their feature-balloon flag then retry for a while before finally giving up.
In particular this should help smooth over the period when VMs are booting and haven't loaded their balloon
drivers yet. *)
let retry f =
let start = Unix.gettimeofday () in
let interval = 10. in
let timeout = 0. in
let rec loop () =
try
f ()
with
| Squeezed_rpc.Error(code, descr) as e when
false
|| code = Squeezed_rpc._error_domains_refused_to_cooperate_code
|| code = Squeezed_rpc._error_cannot_free_this_much_memory_code ->
let now = Unix.gettimeofday () in
if now -. start > timeout then raise e else begin
debug "Sleeping %.0f before retrying" interval;
Thread.delay interval;
loop ()
end in
loop ()
(** Reserve a particular amount of memory and return a reservation id *)
let reserve_memory_range_exn ~xc ~xs ~min ~max =
Opt.map
(fun session_id ->
let reserved_memory, reservation_id =
retry
(fun () ->
debug "Requesting a host memory reservation between %Ld and %Ld" min max;
let args = [ Squeezed_rpc._session_id, session_id; Squeezed_rpc._min, Int64.to_string min; Squeezed_rpc._max, Int64.to_string max ] in
let results = call_daemon xs Squeezed_rpc._reserve_memory_range args in
let kib = List.assoc Squeezed_rpc._kib results
and reservation_id = List.assoc Squeezed_rpc._reservation_id results in
debug "Memory reservation size = %s (reservation_id = %s)" kib reservation_id;
Int64.of_string kib, reservation_id
)
in
(* Post condition: *)
assert (reserved_memory >= min);
assert (reserved_memory <= max);
reserved_memory, (reservation_id, reserved_memory)
) (get_session_id ~xs)
let reserve_memory_range ~xc ~xs ~min ~max : (int64 * (string * int64)) option =
wrap (fun () -> reserve_memory_range_exn ~xc ~xs ~min ~max) |> Opt.join
(** Delete a reservation given by [reservation_id] *)
let delete_reservation_exn ~xs (reservation_id, _) =
Opt.map
(fun session_id ->
debug "delete_reservation %s" reservation_id;
let args = [ Squeezed_rpc._session_id, session_id; Squeezed_rpc._reservation_id, reservation_id ] in
ignore_results (call_daemon xs Squeezed_rpc._delete_reservation args)
) (get_session_id ~xs)
let delete_reservation ~xs r =
let (_: unit option option) = wrap (fun () -> delete_reservation_exn ~xs r) in
()
(** Reserves memory, passes the id to [f] and cleans up afterwards. If the user
wants to keep the memory, then call [transfer_reservation_to_domain]. *)
let with_reservation ~xc ~xs ~min ~max f =
let amount, id = Opt.default (min, ("none", min)) (reserve_memory_range ~xc ~xs ~min ~max) in
finally
(fun () -> f amount id)
(fun () -> delete_reservation ~xs id)
(** Transfer this 'reservation' to the given domain id *)
let transfer_reservation_to_domain_exn ~xc ~xs ~domid (reservation_id, amount) =
match get_session_id ~xs with
| Some session_id ->
let uuid = get_uuid ~xc domid in
debug "VM = %s; domid = %d; transfer_reservation_to_domain %s" (Uuid.to_string uuid) domid reservation_id;
let args = [ Squeezed_rpc._session_id, session_id; Squeezed_rpc._reservation_id, reservation_id; Squeezed_rpc._domid, string_of_int domid ] in
ignore_results (call_daemon xs Squeezed_rpc._transfer_reservation_to_domain args)
| None ->
info "No ballooning daemon. Manually setting domain maxmem for domid = %d to %Ld KiB" domid amount;
Xenctrl.domain_setmaxmem xc domid amount
let transfer_reservation_to_domain ~xc ~xs ~domid r =
let (_: unit option) = wrap (fun () -> transfer_reservation_to_domain_exn ~xc ~xs ~domid r) in
()
(** After an event which frees memory (eg a domain destruction), perform a one-off memory rebalance *)
let balance_memory ~xc ~xs =
debug "rebalance_memory";
ignore_results (call_daemon xs Squeezed_rpc._balance_memory [])
end
(* We store away the device name so we can lookup devices by name later *)
let _device_id kind = Device_common.string_of_kind kind ^ "-id"
(* Return the xenstore device with [kind] corresponding to [id] *)
let device_by_id xc xs vm kind domain_selection id =
match vm |> Uuid.uuid_of_string |> domid_of_uuid ~xc ~xs domain_selection with
| None ->
debug "VM = %s; does not exist in domain list" vm;
raise (Does_not_exist("domain", vm))
| Some frontend_domid ->
let devices = Device_common.list_frontends ~xs frontend_domid in
let key = _device_id kind in
let id_of_device device =
let path = Hotplug.get_private_data_path_of_device device in
try Some (xs.Xs.read (Printf.sprintf "%s/%s" path key))
with _ -> None in
let ids = List.map id_of_device devices in
try
List.assoc (Some id) (List.combine ids devices)
with Not_found ->
debug "VM = %s; domid = %d; Device is not active: kind = %s; id = %s; active devices = [ %s ]" vm frontend_domid (Device_common.string_of_kind kind) id (String.concat ", " (List.map (Opt.default "None") ids));
raise (Device_not_connected)
let set_stubdom ~xs domid domid' =
xs.Xs.write (Printf.sprintf "/local/domain/%d/stub-domid" domid) (string_of_int domid')
let get_stubdom ~xs domid =
try Some (int_of_string (xs.Xs.read (Printf.sprintf "/local/domain/%d/stub-domid" domid))) with _ -> None
module HOST = struct
let get_console_data () =
with_xc_and_xs
(fun xc xs ->
let raw = Xenctrl.readconsolering xc in
(* There may be invalid XML characters in the buffer, so remove them *)
let is_printable chr =
let x = int_of_char chr in
x >= 0x20 && x <= 0x7e in
for i = 0 to String.length raw - 1 do
if not(is_printable raw.[i])
then raw.[i] <- ' '
done;
raw
)
let get_total_memory_mib () =
with_xc_and_xs
(fun xc xs ->
let pages_per_mib = 256L in
Int64.(div ((Xenctrl.physinfo xc).Xenctrl.total_pages |> of_nativeint) pages_per_mib)
)
let send_debug_keys keys =
with_xc_and_xs
(fun xc xs ->
Xenctrl.send_debug_keys xc keys
)
end
module VM = struct
open Vm
let will_be_hvm vm = match vm.ty with HVM _ -> true | _ -> false
let compute_overhead domain =
let static_max_mib = Memory.mib_of_bytes_used domain.VmExtra.memory_static_max in
let memory_overhead_mib =
(if domain.VmExtra.create_info.Domain.hvm then Memory.HVM.overhead_mib else Memory.Linux.overhead_mib)
static_max_mib domain.VmExtra.vcpu_max domain.VmExtra.shadow_multiplier in
Memory.bytes_of_mib memory_overhead_mib
let shutdown_reason = function
| Reboot -> Domain.Reboot
| PowerOff -> Domain.PowerOff
| Suspend -> Domain.Suspend
| Halt -> Domain.Halt
| S3Suspend -> Domain.S3Suspend
(* We compute our initial target at memory reservation time, done before the domain
is created. We consume this information later when the domain is built. *)
let set_initial_target ~xs domid initial_target =
xs.Xs.write (Printf.sprintf "/local/domain/%d/memory/initial-target" domid)
(Int64.to_string initial_target)
let get_initial_target ~xs domid =
Int64.of_string (xs.Xs.read (Printf.sprintf "/local/domain/%d/memory/initial-target" domid))
let create_exn (task: Xenops_task.t) vm =
let k = vm.Vm.id in
with_xc_and_xs
(fun xc xs ->
let vmextra =
match DB.read k with
| Some x ->
debug "VM = %s; reloading stored domain-level configuration" vm.Vm.id;
{ x with
VmExtra.last_create_time = Unix.gettimeofday ()
}
| None -> begin
debug "VM = %s; has no stored domain-level configuration, regenerating" vm.Vm.id;
let hvm = match vm.ty with HVM _ -> true | _ -> false in
(* XXX add per-vcpu information to the platform data *)
(* VCPU configuration *)
let pcpus = Xenctrlext.get_max_nr_cpus xc in
let all_pcpus = pcpus |> Range.make 0 |> Range.to_list in
let all_vcpus = vm.vcpu_max |> Range.make 0 |> Range.to_list in
let masks = match vm.scheduler_params.affinity with
| [] ->
(* Every vcpu can run on every pcpu *)
List.map (fun _ -> all_pcpus) all_vcpus
| m :: ms ->
(* Treat the first as the template for the rest *)
let defaults = List.map (fun _ -> m) all_vcpus in
List.take vm.vcpu_max (m :: ms @ defaults) in
(* convert a mask into a binary string, one char per pCPU *)
let bitmap cpus: string =
let cpus = List.filter (fun x -> x >= 0 && x < pcpus) cpus in
let result = String.make pcpus '0' in
List.iter (fun cpu -> result.[cpu] <- '1') cpus;
result in
let affinity =
List.mapi (fun idx mask ->
Printf.sprintf "vcpu/%d/affinity" idx, bitmap mask
) masks in
let weight = Opt.default [] (Opt.map
(fun (w, c) -> [
"vcpu/weight", string_of_int w;
"vcpu/cap", string_of_int c
])
vm.scheduler_params.priority
) in
let vcpus = [
"vcpu/number", string_of_int vm.vcpu_max;
"vcpu/current", string_of_int vm.vcpus;
] @ affinity @ weight in
let create_info = {
Domain.ssidref = vm.ssidref;
hvm = hvm;
hap = hvm;
name = vm.name;
xsdata = vm.xsdata;
platformdata = vm.platformdata @ vcpus;
bios_strings = vm.bios_strings;
} in {
VmExtra.create_info = create_info;
build_info = None;
vcpu_max = vm.vcpu_max;
vcpus = vm.vcpus;
shadow_multiplier = (match vm.Vm.ty with Vm.HVM { Vm.shadow_multiplier = sm } -> sm | _ -> 1.);
memory_static_max = vm.memory_static_max;
suspend_memory_bytes = 0L;
ty = None;
vbds = [];
qemu_vbds = [];
qemu_vifs = [];
vifs = [];
last_create_time = Unix.gettimeofday ();
pci_msitranslate = vm.Vm.pci_msitranslate;
pci_power_mgmt = vm.Vm.pci_power_mgmt;
}
end in
let open Memory in
let overhead_bytes = compute_overhead vmextra in
(* If we are resuming then we know exactly how much memory is needed *)
let resuming = vmextra.VmExtra.suspend_memory_bytes <> 0L in
let min_kib = kib_of_bytes_used (if resuming then vmextra.VmExtra.suspend_memory_bytes else (vm.memory_dynamic_min +++ overhead_bytes)) in
let max_kib = kib_of_bytes_used (if resuming then vmextra.VmExtra.suspend_memory_bytes else (vm.memory_dynamic_max +++ overhead_bytes)) in
(* XXX: we would like to be able to cancel an in-progress with_reservation *)
Mem.with_reservation ~xc ~xs ~min:min_kib ~max:max_kib
(fun target_plus_overhead_kib reservation_id ->
DB.write k vmextra;
let domid = Domain.make ~xc ~xs vmextra.VmExtra.create_info (uuid_of_vm vm) in
Mem.transfer_reservation_to_domain ~xc ~xs ~domid reservation_id;
begin match vm.Vm.ty with
| Vm.HVM { Vm.qemu_stubdom = true } ->
Mem.with_reservation ~xc ~xs ~min:Stubdom.memory_kib ~max:Stubdom.memory_kib
(fun _ reservation_id ->
let stubdom_domid = Stubdom.create ~xc ~xs domid in
Mem.transfer_reservation_to_domain ~xc ~xs ~domid:stubdom_domid reservation_id;
set_stubdom ~xs domid stubdom_domid;
)
| _ ->
()
end;
let initial_target =
let target_plus_overhead_bytes = bytes_of_kib target_plus_overhead_kib in
let target_bytes = target_plus_overhead_bytes --- overhead_bytes in
min vm.memory_dynamic_max target_bytes in
set_initial_target ~xs domid initial_target;
if vm.suppress_spurious_page_faults
then Domain.suppress_spurious_page_faults ~xc domid;
Domain.set_machine_address_size ~xc domid vm.machine_address_size;
for i = 0 to vm.vcpu_max - 1 do
Device.Vcpu.add ~xs ~devid:i domid
done
);
)
let create = create_exn
let on_domain f domain_selection (task: Xenops_task.t) vm =
let uuid = uuid_of_vm vm in
with_xc_and_xs
(fun xc xs ->
match di_of_uuid ~xc ~xs domain_selection uuid with
| None -> raise (Does_not_exist("domain", vm.Vm.id))
| Some di -> f xc xs task vm di
)
let log_exn_continue msg f x = try f x with e -> debug "Safely ignoring exception: %s while %s" (Printexc.to_string e) msg
let destroy_device_model = on_domain (fun xc xs task vm di ->
let domid = di.Xenctrl.domid in
log_exn_continue "Error stoping device-model, already dead ?"
(fun () -> Device.Dm.stop ~xs domid) ();
log_exn_continue "Error stoping vncterm, already dead ?"
(fun () -> Device.PV_Vnc.stop ~xs domid) ();
(* If qemu is in a different domain to storage, detach disks *)
) Oldest
let destroy = on_domain (fun xc xs task vm di ->
let domid = di.Xenctrl.domid in
(* We need to clean up the stubdom before the primary otherwise we deadlock *)
Opt.iter
(fun stubdom_domid ->
Domain.destroy task ~preserve_xs_vm:false ~xc ~xs stubdom_domid
) (get_stubdom ~xs domid);
let vbds = Opt.default [] (Opt.map (fun d -> d.VmExtra.vbds) (DB.read vm.Vm.id)) in
(* Normally we throw-away our domain-level information. If the domain
has suspended then we preserve it. *)
if di.Xenctrl.shutdown && (Domain.shutdown_reason_of_int di.Xenctrl.shutdown_code = Domain.Suspend)
then debug "VM = %s; domid = %d; domain has suspended; preserving domain-level information" vm.Vm.id di.Xenctrl.domid
else begin
debug "VM = %s; domid = %d; will not have domain-level information preserved" vm.Vm.id di.Xenctrl.domid;
if DB.exists vm.Vm.id then DB.remove vm.Vm.id;
end;
Domain.destroy task ~preserve_xs_vm:false ~xc ~xs domid;
(* Detach any remaining disks *)
List.iter (fun vbd -> Storage.deactivate_and_detach task (Storage.id_of domid vbd.Vbd.id)) vbds
) Oldest
let pause = on_domain (fun xc xs _ _ di ->
if di.Xenctrl.total_memory_pages = 0n then raise (Domain_not_built);
Domain.pause ~xc di.Xenctrl.domid
) Newest
let unpause = on_domain (fun xc xs _ _ di ->
if di.Xenctrl.total_memory_pages = 0n then raise (Domain_not_built);
Domain.unpause ~xc di.Xenctrl.domid;
Opt.iter
(fun stubdom_domid ->
Domain.unpause ~xc stubdom_domid
) (get_stubdom ~xs di.Xenctrl.domid)
) Newest
let set_xsdata task vm xsdata = on_domain (fun xc xs _ _ di ->
Domain.set_xsdata ~xs di.Xenctrl.domid xsdata
) Newest task vm
let set_vcpus task vm target = on_domain (fun xc xs _ _ di ->
if di.Xenctrl.hvm_guest then raise (Unimplemented("vcpu hotplug for HVM domains"));
let domid = di.Xenctrl.domid in
(* Returns the instantaneous CPU number from xenstore *)
let current =
let n = ref (-1) in
for i = 0 to vm.Vm.vcpu_max - 1
do if Device.Vcpu.status ~xs ~devid:i domid then n := i
done;
!n + 1 in
if current > target then (
(* need to deplug cpus *)
for i = current - 1 downto target
do
Device.Vcpu.set ~xs ~devid:i domid false
done
) else if current < target then (
(* need to plug cpus *)
for i = current to (target - 1)
do
Device.Vcpu.set ~xs ~devid:i domid true
done
)
) Newest task vm
let set_shadow_multiplier task vm target = on_domain (fun xc xs _ _ di ->
if not di.Xenctrl.hvm_guest then raise (Unimplemented "shadow_multiplier for PV domains");
let domid = di.Xenctrl.domid in
let static_max_mib = Memory.mib_of_bytes_used vm.Vm.memory_static_max in
let newshadow = Int64.to_int (Memory.HVM.shadow_mib static_max_mib vm.Vm.vcpu_max target) in
let curshadow = Xenctrl.shadow_allocation_get xc domid in
let needed_mib = newshadow - curshadow in
debug "VM = %s; domid = %d; Domain has %d MiB shadow; an increase of %d MiB requested" vm.Vm.id domid curshadow needed_mib;
if not(Domain.wait_xen_free_mem xc (Int64.mul (Int64.of_int needed_mib) 1024L)) then begin
error "VM = %s; domid = %d; Failed waiting for Xen to free %d MiB: some memory is not properly accounted" vm.Vm.id domid needed_mib;
raise (Not_enough_memory (Memory.bytes_of_mib (Int64.of_int needed_mib)))
end;
debug "VM = %s; domid = %d; shadow_allocation_setto %d MiB" vm.Vm.id domid newshadow;
Xenctrl.shadow_allocation_set xc domid newshadow;
) Newest task vm
let set_memory_dynamic_range task vm min max = on_domain (fun xc xs _ _ di ->
let domid = di.Xenctrl.domid in
Domain.set_memory_dynamic_range ~xc ~xs
~min:(Int64.to_int (Int64.div min 1024L))
~max:(Int64.to_int (Int64.div max 1024L))
domid;
) Newest task vm
(* NB: the arguments which affect the qemu configuration must be saved and
restored with the VM. *)
let create_device_model_config = function
| { VmExtra.build_info = None }
| { VmExtra.ty = None } -> raise (Domain_not_built)
| {
VmExtra.ty = Some ty; build_info = Some build_info;
vifs = vifs;
vbds = vbds; qemu_vbds = qemu_vbds
} ->
let make ?(boot_order="cd") ?(serial="pty") ?(monitor="pty")
?(nics=[])
?(disks=[]) ?(pci_emulations=[]) ?(usb=["tablet"])
?(acpi=true) ?(video=Cirrus) ?(keymap="en-us")
?vnc_ip ?(pci_passthrough=false) ?(hvm=true) ?(video_mib=4) () =
let video = match video with
| Cirrus -> Device.Dm.Cirrus
| Standard_VGA -> Device.Dm.Std_vga in
let open Device.Dm in {
memory = build_info.Domain.memory_max;
boot = boot_order;
serial = Some serial;
monitor = Some monitor;
vcpus = build_info.Domain.vcpus;
nics = nics;
disks = disks;
pci_emulations = pci_emulations;
usb = usb;
acpi = acpi;
disp = VNC (video, vnc_ip, true, 0, keymap);
pci_passthrough = pci_passthrough;
xenclient_enabled=false;
hvm=hvm;
sound=None;
power_mgmt=None;
oem_features=None;
inject_sci = None;
video_mib=video_mib;
extras = [];
} in
let bridge_of_network = function
| Network.Local b -> b
| Network.Remote (_, _) -> failwith "Need to create a VIF frontend" in
let nics = List.map (fun vif ->
vif.Vif.mac,
bridge_of_network vif.Vif.backend,
vif.Vif.position
) vifs in
match ty with
| PV { framebuffer = false } -> None
| PV { framebuffer = true } ->
Some (make ~hvm:false ())
| HVM hvm_info ->
let disks = List.filter_map (fun vbd ->
let id = vbd.Vbd.id in
if hvm_info.Vm.qemu_disk_cmdline && (List.mem_assoc id qemu_vbds)
then
let index, bd = List.assoc id qemu_vbds in
let path = block_device_of_vbd_frontend bd in
let media =
if vbd.Vbd.ty = Vbd.Disk
then Device.Dm.Disk else Device.Dm.Cdrom in
Some (index, path, media)
else None
) vbds in
Some (make ~video_mib:hvm_info.video_mib
~video:hvm_info.video ~acpi:hvm_info.acpi
?serial:hvm_info.serial ?keymap:hvm_info.keymap
?vnc_ip:hvm_info.vnc_ip
~pci_emulations:hvm_info.pci_emulations
~pci_passthrough:hvm_info.pci_passthrough
~boot_order:hvm_info.boot_order ~nics ~disks ())
let build_domain_exn xc xs domid task vm vbds vifs =
let open Memory in
let initial_target = get_initial_target ~xs domid in
let make_build_info kernel priv = {
Domain.memory_max = vm.memory_static_max /// 1024L;
memory_target = initial_target /// 1024L;
kernel = kernel;
vcpus = vm.vcpu_max;
priv = priv;
} in
(* We should prevent leaking files in our filesystem *)
let kernel_to_cleanup = ref None in
finally (fun () ->
let build_info =
match vm.ty with
| HVM hvm_info ->
let builder_spec_info = Domain.BuildHVM {
Domain.shadow_multiplier = hvm_info.shadow_multiplier;
timeoffset = hvm_info.timeoffset;
video_mib = hvm_info.video_mib;
} in
make_build_info Domain.hvmloader builder_spec_info
| PV { boot = Direct direct } ->
let builder_spec_info = Domain.BuildPV {
Domain.cmdline = direct.cmdline;
ramdisk = direct.ramdisk;
} in
make_build_info direct.kernel builder_spec_info
| PV { boot = Indirect { devices = [] } } ->
raise (No_bootable_device)
| PV { boot = Indirect ( { devices = d :: _ } as i ) } ->
with_disk ~xc ~xs task d false
(fun dev ->
let b = Bootloader.extract task ~bootloader:i.bootloader
~legacy_args:i.legacy_args ~extra_args:i.extra_args
~pv_bootloader_args:i.bootloader_args
~disk:dev ~vm:vm.Vm.id () in
kernel_to_cleanup := Some b;
let builder_spec_info = Domain.BuildPV {
Domain.cmdline = b.Bootloader.kernel_args;
ramdisk = b.Bootloader.initrd_path;
} in
make_build_info b.Bootloader.kernel_path builder_spec_info
) in
let arch = Domain.build task ~xc ~xs build_info domid in
Domain.cpuid_apply ~xc ~hvm:(will_be_hvm vm) domid;
debug "VM = %s; domid = %d; Domain built with architecture %s" vm.Vm.id domid (Domain.string_of_domarch arch);
let k = vm.Vm.id in
let d = DB.read_exn vm.Vm.id in
DB.write k { d with
VmExtra.build_info = Some build_info;
ty = Some vm.ty;
vbds = vbds;
vifs = vifs;
}
) (fun () -> Opt.iter Bootloader.delete !kernel_to_cleanup)
let build_domain vm vbds vifs xc xs task _ di =
let domid = di.Xenctrl.domid in
try
build_domain_exn xc xs domid task vm vbds vifs
with
| Bootloader.Bad_sexpr x ->
let m = Printf.sprintf "VM = %s; domid = %d; Bootloader.Bad_sexpr %s" vm.Vm.id domid x in
debug "%s" m;
raise (Internal_error m)
| Bootloader.Bad_error x ->
let m = Printf.sprintf "VM = %s; domid = %d; Bootloader.Bad_error %s" vm.Vm.id domid x in
debug "%s" m;
raise (Internal_error m)
| Bootloader.Unknown_bootloader x ->
let m = Printf.sprintf "VM = %s; domid = %d; Bootloader.Unknown_bootloader %s" vm.Vm.id domid x in
debug "%s" m;
raise (Internal_error m)
| Bootloader.Error_from_bootloader (a, b) ->
let m = Printf.sprintf "VM = %s; domid = %d; Bootloader.Error_from_bootloader (%s, [ %s ])" vm.Vm.id domid a (String.concat "; " b) in
debug "%s" m;
raise (Bootloader_error (a, b))
| e ->
let m = Printf.sprintf "VM = %s; domid = %d; Bootloader error: %s" vm.Vm.id domid (Printexc.to_string e) in
debug "%s" m;
raise e
let build task vm vbds vifs = on_domain (build_domain vm vbds vifs) Newest task vm
let create_device_model_exn saved_state xc xs task vm di =
let vmextra = DB.read_exn vm.Vm.id in
Opt.iter (fun info ->
match vm.Vm.ty with
| Vm.HVM { Vm.qemu_stubdom = true } ->
if saved_state then failwith "Cannot resume with stubdom yet";
Opt.iter
(fun stubdom_domid ->
Stubdom.build task ~xc ~xs info di.Xenctrl.domid stubdom_domid;
Device.Dm.start_vnconly task ~xs ~dmpath:_qemu_dm info stubdom_domid
) (get_stubdom ~xs di.Xenctrl.domid);
| _ ->
(if saved_state then Device.Dm.restore else Device.Dm.start)
task ~xs ~dmpath:_qemu_dm info di.Xenctrl.domid
) (vmextra |> create_device_model_config);
match vm.Vm.ty with
| Vm.PV { vncterm = true; vncterm_ip = ip } -> Device.PV_Vnc.start ~xs ?ip di.Xenctrl.domid
| _ -> ()
let create_device_model task vm saved_state = on_domain (create_device_model_exn saved_state) Newest task vm
let request_shutdown task vm reason ack_delay =
let reason = shutdown_reason reason in
on_domain
(fun xc xs task vm di ->
let domid = di.Xenctrl.domid in
try
Domain.shutdown ~xc ~xs domid reason;
Domain.shutdown_wait_for_ack task ~timeout:ack_delay ~xc ~xs domid reason;
true
with Watch.Timeout _ ->
false
) Oldest task vm
let wait_shutdown task vm reason timeout =
event_wait task (Some (timeout |> ceil |> int_of_float))
(function
| Dynamic.Vm id when id = vm.Vm.id ->
debug "EVENT on our VM: %s" id;
on_domain (fun xc xs _ vm di -> di.Xenctrl.shutdown) Oldest task vm
| Dynamic.Vm id ->
debug "EVENT on other VM: %s" id;
false
| _ ->
debug "OTHER EVENT";
false)
(* Create an ext2 filesystem without maximal mount count and
checking interval. *)
let mke2fs device =
run _mkfs ["-t"; "ext2"; device] |> ignore_string;
run _tune2fs ["-i"; "0"; "-c"; "0"; device] |> ignore_string
(* Mount a filesystem somewhere, with optional type *)
let mount ?ty:(ty = None) src dest =
let ty = match ty with None -> [] | Some ty -> [ "-t"; ty ] in
run _mount (ty @ [ src; dest ]) |> ignore_string
let timeout = 300. (* 5 minutes: something is seriously wrong if we hit this timeout *)
exception Umount_timeout
(** Unmount a mountpoint. Retries every 5 secs for a total of 5mins before returning failure *)
let umount ?(retry=true) dest =
let finished = ref false in
let start = Unix.gettimeofday () in
while not(!finished) && (Unix.gettimeofday () -. start < timeout) do
try
run _umount [dest] |> ignore_string;
finished := true
with e ->
if not(retry) then raise e;
debug "Caught exception (%s) while unmounting %s: pausing before retrying"
(Printexc.to_string e) dest;
Thread.delay 5.
done;
if not(!finished) then raise Umount_timeout
let with_mounted_dir device f =
let mount_point = Filename.temp_file "xenops_mount_" "" in
Unix.unlink mount_point;
Unix.mkdir mount_point 0o640;
finally
(fun () ->
mount ~ty:(Some "ext2") device mount_point;
f mount_point)
(fun () ->
(try umount mount_point with e -> debug "Caught %s" (Printexc.to_string e));
(try Unix.rmdir mount_point with e -> debug "Caught %s" (Printexc.to_string e))
)
let with_data ~xc ~xs task data write f = match data with