forked from xapi-project/xen-api
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathxapi_host.ml
More file actions
3247 lines (3023 loc) · 124 KB
/
xapi_host.ml
File metadata and controls
3247 lines (3023 loc) · 124 KB
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) 2006-2009 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.
*)
module Rrdd = Rrd_client.Client
module Date = Clock.Date
module Pervasiveext = Xapi_stdext_pervasives.Pervasiveext
let with_lock = Xapi_stdext_threads.Threadext.Mutex.execute
module Unixext = Xapi_stdext_unix.Unixext
open Xapi_host_helpers
open Xapi_pif_helpers
open Xapi_database.Db_filter_types
open Workload_balancing
module D = Debug.Make (struct let name = "xapi_host" end)
open D
(* [take n xs] returns the first [n] elements of [xs] and the remaining
tail. Similar to Listext.chop but never raises an exception even if
n <= 0 or n > |xs|. *)
let take n xs =
let rec loop n head tail =
match tail with
| [] ->
(List.rev head, tail)
| tail when n <= 0 ->
(List.rev head, tail)
| t :: ts ->
loop (n - 1) (t :: head) ts
in
loop n [] xs
let get_servertime ~__context ~host:_ = Date.now ()
let get_server_localtime ~__context ~host:_ = Date.localtime ()
let set_emergency_mode_error code params =
Xapi_globs.emergency_mode_error := Api_errors.Server_error (code, params)
let local_assert_healthy ~__context =
match Pool_role.get_role () with
| Pool_role.Master ->
()
| Pool_role.Broken ->
raise !Xapi_globs.emergency_mode_error
| Pool_role.Slave _ ->
if !Xapi_globs.slave_emergency_mode then
raise !Xapi_globs.emergency_mode_error
let set_power_on_mode ~__context ~self ~power_on_mode ~power_on_config =
Db.Host.set_power_on_mode ~__context ~self ~value:power_on_mode ;
let current_config = Db.Host.get_power_on_config ~__context ~self in
Db.Host.set_power_on_config ~__context ~self ~value:power_on_config ;
Xapi_secret.clean_out_passwds ~__context current_config ;
Xapi_host_helpers.update_allowed_operations ~__context ~self
(** Before we re-enable this host we make sure it's safe to do so. It isn't if:
+ there are pending mandatory guidances on the host
+ we're in the middle of an HA shutdown/reboot and have our fencing temporarily disabled.
+ xapi hasn't properly started up yet.
+ HA is enabled and this host has broken storage or networking which would cause protected VMs
to become non-agile
*)
let assert_safe_to_reenable ~__context ~self =
assert_startup_complete () ;
Repository_helpers.assert_no_host_pending_mandatory_guidance ~__context
~host:self ;
let host_disabled_until_reboot =
try bool_of_string (Localdb.get Constants.host_disabled_until_reboot)
with _ -> false
in
if host_disabled_until_reboot then
raise
(Api_errors.Server_error
(Api_errors.host_disabled_until_reboot, [Ref.string_of self])
) ;
if Db.Pool.get_ha_enabled ~__context ~self:(Helpers.get_pool ~__context) then (
let pbds = Db.Host.get_PBDs ~__context ~self in
let unplugged_pbds =
List.filter
(fun pbd -> not (Db.PBD.get_currently_attached ~__context ~self:pbd))
pbds
in
(* Make sure it is 'ok' to have these PBDs remain unplugged *)
List.iter
(fun self ->
Xapi_pbd.abort_if_storage_attached_to_protected_vms ~__context ~self
)
unplugged_pbds ;
let pifs = Db.Host.get_PIFs ~__context ~self in
let unplugged_pifs =
List.filter
(fun pif -> not (Db.PIF.get_currently_attached ~__context ~self:pif))
pifs
in
(* Make sure it is 'ok' to have these PIFs remain unplugged *)
List.iter
(fun self ->
Xapi_pif.abort_if_network_attached_to_protected_vms ~__context ~self
)
unplugged_pifs
)
(* The maximum pool size allowed must be restricted to 3 hosts for the pool which does not have Pool_size feature *)
let pool_size_is_restricted ~__context =
not (Pool_features.is_enabled ~__context Features.Pool_size)
let bugreport_upload ~__context ~host:_ ~url ~options =
let proxy =
if List.mem_assoc "http_proxy" options then
List.assoc "http_proxy" options
else
Option.value (Sys.getenv_opt "http_proxy") ~default:""
in
let cmd =
Printf.sprintf "%s %s %s"
!Xapi_globs.host_bugreport_upload
"(url filtered)" proxy
in
try
let env = Helpers.env_with_path [("INPUT_URL", url); ("PROXY", proxy)] in
let stdout, stderr =
Forkhelpers.execute_command_get_output ~env
!Xapi_globs.host_bugreport_upload
[]
in
debug "%s succeeded with stdout=[%s] stderr=[%s]" cmd stdout stderr
with Forkhelpers.Spawn_internal_error (stderr, stdout, status) as e -> (
debug "%s failed with stdout=[%s] stderr=[%s]" cmd stdout stderr ;
(* Attempt to interpret curl's exit code (from curl(1)) *)
match status with
| Unix.WEXITED (1 | 3 | 4) ->
failwith "URL not recognised"
| Unix.WEXITED (5 | 6) ->
failwith "Failed to resolve proxy or host"
| Unix.WEXITED 7 ->
failwith "Failed to connect to host"
| Unix.WEXITED 9 ->
failwith "FTP access denied"
| _ ->
raise e
)
(** Check that a) there are no running VMs present on the host, b) there are no VBDs currently
attached to dom0, c) host is disabled.
This is approximately maintainance mode as defined by the gui. However, since
we haven't agreed on an exact definition of this mode, we'll not call this maintainance mode here, but we'll
use a synonym. According to http://thesaurus.com/browse/maintenance, bacon is a synonym
for maintainance, hence the name of the following function.
*)
let assert_bacon_mode ~__context ~host =
if Db.Host.get_enabled ~__context ~self:host then
raise (Api_errors.Server_error (Api_errors.host_not_disabled, [])) ;
let selfref = Ref.string_of host in
let vms =
Db.VM.get_refs_where ~__context
~expr:
(And
( Eq (Field "resident_on", Literal (Ref.string_of host))
, Eq (Field "power_state", Literal "Running")
)
)
in
(* We always expect a control domain to be resident on a host *)
( match
List.filter
(fun vm -> not (Db.VM.get_is_control_domain ~__context ~self:vm))
vms
with
| [] ->
()
| guest_vms ->
let vm_data = [selfref; "vm"; Ref.string_of (List.hd guest_vms)] in
raise (Api_errors.Server_error (Api_errors.host_in_use, vm_data))
) ;
debug "Bacon test: VMs OK - %d running VMs" (List.length vms) ;
let control_domain_vbds =
List.filter
(fun vm ->
Db.VM.get_resident_on ~__context ~self:vm = host
&& Db.VM.get_is_control_domain ~__context ~self:vm
)
(Db.VM.get_all ~__context)
|> List.concat_map (fun self -> Db.VM.get_VBDs ~__context ~self)
|> List.filter (fun self -> Db.VBD.get_currently_attached ~__context ~self)
in
if control_domain_vbds <> [] then
raise
(Api_errors.Server_error
( Api_errors.host_in_use
, [
selfref; "vbd"; List.hd (List.map Ref.string_of control_domain_vbds)
]
)
) ;
debug "Bacon test: VBDs OK"
let signal_networking_change = Xapi_mgmt_iface.on_dom0_networking_change
let signal_cdrom_event ~__context params =
let find_vdi_name sr name =
let ret = ref None in
let vdis = Db.SR.get_VDIs ~__context ~self:sr in
List.iter
(fun vdi ->
if Db.VDI.get_location ~__context ~self:vdi = name then ret := Some vdi
)
vdis ;
!ret
in
let find_vdis name =
let srs =
List.filter
(fun sr ->
let ty = Db.SR.get_type ~__context ~self:sr in
ty = "local" || ty = "udev"
)
(Db.SR.get_all ~__context)
in
List.fold_left
(fun acc o -> match o with Some x -> x :: acc | None -> acc)
[]
(List.map (fun sr -> find_vdi_name sr name) srs)
in
let insert dev =
let vdis = find_vdis dev in
if List.length vdis = 1 then (
let vdi = List.hd vdis in
debug "cdrom inserted notification in vdi %s" (Ref.string_of vdi) ;
let vbds = Db.VDI.get_VBDs ~__context ~self:vdi in
List.iter
(fun vbd -> Xapi_xenops.vbd_insert ~__context ~self:vbd ~vdi)
vbds
) else
()
in
try
match String.split_on_char ':' params with
| ["inserted"; dev] ->
insert dev
| "ejected" :: _ ->
()
| _ ->
()
with _ -> ()
let notify ~__context ~ty ~params =
match ty with "cdrom" -> signal_cdrom_event ~__context params | _ -> ()
(* A host evacuation plan consists of a hashtable mapping VM refs to instances of per_vm_plan: *)
type per_vm_plan = Migrate of API.ref_host | Error of (string * string list)
let string_of_per_vm_plan p =
match p with
| Migrate h ->
Ref.string_of h
| Error (e, t) ->
String.concat "," (e :: t)
(** Return a table mapping VMs to 'per_vm_plan' types indicating either a target
Host or a reason why the VM cannot be migrated. *)
let compute_evacuation_plan_no_wlb ~__context ~host ?(ignore_ha = false) () =
let all_hosts = Db.Host.get_all ~__context in
let enabled_hosts =
List.filter (fun self -> Db.Host.get_enabled ~__context ~self) all_hosts
in
(* Only consider migrating to other enabled hosts (not this one obviously) *)
let target_hosts = List.filter (fun self -> self <> host) enabled_hosts in
(* PR-1007: During a rolling pool upgrade, we are only allowed to
migrate VMs to hosts that have the same or higher version as
the source host. So as long as host versions aren't decreasing,
we're allowed to migrate VMs between hosts. *)
debug "evacuating host version: %s"
(Helpers.version_string_of ~__context (Helpers.LocalObject host)) ;
let target_hosts =
List.filter
(fun target ->
debug "host %s version: %s"
(Db.Host.get_hostname ~__context ~self:target)
(Helpers.version_string_of ~__context (Helpers.LocalObject target)) ;
Helpers.host_versions_not_decreasing ~__context
~host_from:(Helpers.LocalObject host)
~host_to:(Helpers.LocalObject target)
)
target_hosts
in
debug "evacuation target hosts are [%s]"
(String.concat "; "
(List.map (fun h -> Db.Host.get_hostname ~__context ~self:h) target_hosts)
) ;
let all_vms = Db.Host.get_resident_VMs ~__context ~self:host in
let all_vms =
List.map (fun self -> (self, Db.VM.get_record ~__context ~self)) all_vms
in
let all_user_vms =
List.filter (fun (_, record) -> not record.API.vM_is_control_domain) all_vms
in
let plans = Hashtbl.create 10 in
if target_hosts = [] then (
List.iter
(fun (vm, _) ->
Hashtbl.replace plans vm
(Error (Api_errors.no_hosts_available, [Ref.string_of vm]))
)
all_user_vms ;
plans
) else
(* If HA is enabled we require that non-protected VMs are suspended. This gives us the property that
the result obtained by executing the evacuation plan and disabling the host looks the same (from the HA
planner's PoV) to the result obtained following a host failure and VM restart. *)
let pool = Helpers.get_pool ~__context in
let protected_vms, unprotected_vms =
if Db.Pool.get_ha_enabled ~__context ~self:pool && not ignore_ha then
List.partition
(fun (_, record) ->
Helpers.vm_should_always_run record.API.vM_ha_always_run
record.API.vM_ha_restart_priority
)
all_user_vms
else
(all_user_vms, [])
in
List.iter
(fun (vm, _) ->
Hashtbl.replace plans vm
(Error (Api_errors.host_not_enough_free_memory, [Ref.string_of vm]))
)
unprotected_vms ;
let migratable_vms, _ =
List.partition
(fun (vm, record) ->
try
List.iter
(fun host ->
Xapi_vm_helpers.assert_can_boot_here ~__context ~self:vm ~host
~snapshot:record ~do_memory_check:false ~do_cpuid_check:true
()
)
target_hosts ;
true
with Api_errors.Server_error (code, params) ->
Hashtbl.replace plans vm (Error (code, params)) ;
false
)
protected_vms
in
(* Check for impediments before attempting to perform pool_migrate *)
List.iter
(fun (vm, _) ->
match
Xapi_vm_lifecycle.get_operation_error ~__context ~self:vm
~op:`pool_migrate ~strict:true
with
| None ->
()
| Some (a, b) ->
Hashtbl.replace plans vm (Error (a, b))
)
all_user_vms ;
(* Compute the binpack which takes only memory size into account. We will check afterwards for storage
and network availability. *)
let plan =
Xapi_ha_vm_failover.compute_evacuation_plan ~__context
(List.length all_hosts) target_hosts migratable_vms
in
(* Check if the plan was actually complete: if some VMs are missing it means there wasn't enough memory *)
let vms_handled = List.map fst plan in
let vms_missing =
List.filter
(fun x -> not (List.mem x vms_handled))
(List.map fst migratable_vms)
in
List.iter
(fun vm ->
Hashtbl.replace plans vm
(Error (Api_errors.host_not_enough_free_memory, [Ref.string_of vm]))
)
vms_missing ;
(* Now for each VM we did place, verify storage and network visibility. *)
List.iter
(fun (vm, host) ->
let snapshot = List.assoc vm all_vms in
( try
Xapi_vm_helpers.assert_can_boot_here ~__context ~self:vm ~host
~snapshot ~do_memory_check:false ~do_cpuid_check:true ()
with Api_errors.Server_error (code, params) ->
Hashtbl.replace plans vm (Error (code, params))
) ;
if not (Hashtbl.mem plans vm) then
Hashtbl.replace plans vm (Migrate host)
)
plan ;
plans
(* Old Miami style function with the strange error encoding *)
let assert_can_evacuate ~__context ~host =
(* call no_wlb function as we only care about errors, and wlb only provides recs for moveable vms *)
let plans = compute_evacuation_plan_no_wlb ~__context ~host () in
let errors =
Hashtbl.fold
(fun _ plan acc ->
match plan with
| Error (code, params) ->
String.concat "," (code :: params) :: acc
| _ ->
acc
)
plans []
in
if errors <> [] then
raise
(Api_errors.Server_error
(Api_errors.cannot_evacuate_host, [String.concat "|" errors])
)
let get_vms_which_prevent_evacuation_internal ~__context ~self ~ignore_ha =
let plans =
compute_evacuation_plan_no_wlb ~__context ~host:self ~ignore_ha ()
in
Hashtbl.fold
(fun vm plan acc ->
match plan with
| Error (code, params) ->
(vm, code :: params) :: acc
| _ ->
acc
)
plans []
(* New Orlando style function which returns a Map *)
let get_vms_which_prevent_evacuation ~__context ~self =
let vms =
get_vms_which_prevent_evacuation_internal ~__context ~self ~ignore_ha:false
in
let log (vm, reasons) =
debug "%s: VM %s preventing evacuation of host %s: %s" __FUNCTION__
(Db.VM.get_uuid ~__context ~self:vm)
(Db.Host.get_uuid ~__context ~self)
(String.concat "; " reasons)
in
List.iter log vms ; vms
let compute_evacuation_plan_wlb ~__context ~self =
(* We treat xapi as primary when it comes to "hard" errors, i.e. those that aren't down to memory constraints. These are things like
VM_REQUIRES_SR or VM_LACKS_FEATURE_SUSPEND.
We treat WLB as primary when it comes to placement of things that can actually move. WLB will return a list of migrations to perform,
and we pass those on. WLB will only return a partial set of migrations -- if there's not enough memory available, or if the VM can't
move, then it will simply omit that from the results.
So the algorithm is:
Record all the recommendations made by WLB.
Record all the non-memory errors from compute_evacuation_plan_no_wlb. These might overwrite recommendations by WLB, which is the
right thing to do because WLB doesn't know about all the HA corner cases (for example), but xapi does.
If there are any VMs left over, record them as HOST_NOT_ENOUGH_FREE_MEMORY, because we assume that WLB thinks they don't fit.
*)
let error_vms = compute_evacuation_plan_no_wlb ~__context ~host:self () in
let vm_recoms =
get_evacuation_recoms ~__context ~uuid:(Db.Host.get_uuid ~__context ~self)
in
let recs = Hashtbl.create 31 in
List.iter
(fun (v, detail) ->
debug "WLB recommends VM evacuation: %s to %s"
(Db.VM.get_name_label ~__context ~self:v)
(String.concat "," detail) ;
(* Sanity check
Note: if the vm being moved is dom0 then this is a power management rec and this check does not apply
*)
let resident_h = Db.VM.get_resident_on ~__context ~self:v in
let target_uuid = List.hd (List.tl detail) in
let target_host = Db.Host.get_by_uuid ~__context ~uuid:target_uuid in
if
Db.Host.get_control_domain ~__context ~self:target_host <> v
&& Db.Host.get_uuid ~__context ~self:resident_h = target_uuid
then (* resident host and migration host are the same. Reject this plan *)
raise
(Api_errors.Server_error
( Api_errors.wlb_malformed_response
, [
Printf.sprintf
"WLB recommends migrating VM %s to the same server it is \
being evacuated from."
(Db.VM.get_name_label ~__context ~self:v)
]
)
) ;
match detail with
| ["WLB"; host_uuid; _] ->
Hashtbl.replace recs v
(Migrate (Db.Host.get_by_uuid ~__context ~uuid:host_uuid))
| _ ->
raise
(Api_errors.Server_error
( Api_errors.wlb_malformed_response
, ["WLB gave malformed details for VM evacuation."]
)
)
)
vm_recoms ;
Hashtbl.iter
(fun v detail ->
match detail with
| Migrate _ ->
(* Skip migrations -- WLB is providing these *)
()
| Error (e, _) when e = Api_errors.host_not_enough_free_memory ->
(* Skip errors down to free memory -- we're letting WLB decide this *)
()
| Error _ as p ->
debug "VM preventing evacuation: %s because %s"
(Db.VM.get_name_label ~__context ~self:v)
(string_of_per_vm_plan p) ;
Hashtbl.replace recs v detail
)
error_vms ;
let resident_vms =
List.filter
(fun v ->
(not (Db.VM.get_is_control_domain ~__context ~self:v))
&& not (Db.VM.get_is_a_template ~__context ~self:v)
)
(Db.Host.get_resident_VMs ~__context ~self)
in
List.iter
(fun vm ->
if not (Hashtbl.mem recs vm) then
(* Anything for which we don't have a recommendation from WLB, but which is agile, we treat as "not enough memory" *)
Hashtbl.replace recs vm
(Error (Api_errors.host_not_enough_free_memory, [Ref.string_of vm]))
)
resident_vms ;
Hashtbl.iter
(fun vm detail ->
debug "compute_evacuation_plan_wlb: Key: %s Value %s"
(Db.VM.get_name_label ~__context ~self:vm)
(string_of_per_vm_plan detail)
)
recs ;
recs
let compute_evacuation_plan ~__context ~host =
let oc =
Db.Pool.get_other_config ~__context ~self:(Helpers.get_pool ~__context)
in
if
List.exists
(fun (k, v) ->
k = "wlb_choose_host_disable" && String.lowercase_ascii v = "true"
)
oc
|| not (Workload_balancing.check_wlb_enabled ~__context)
then (
debug
"Using wlb recommendations for choosing a host has been disabled or wlb \
is not available. Using original algorithm" ;
compute_evacuation_plan_no_wlb ~__context ~host ()
) else
try
debug "Using WLB recommendations for host evacuation." ;
compute_evacuation_plan_wlb ~__context ~self:host
with
| Api_errors.Server_error (error_type, error_detail) ->
debug
"Encountered error when using wlb for choosing host \"%s: %s\". \
Using original algorithm"
error_type
(String.concat "" error_detail) ;
( try
let uuid = Db.Host.get_uuid ~__context ~self:host in
let message_body =
Printf.sprintf
"Wlb consultation for Host '%s' failed (pool uuid: %s)"
(Db.Host.get_name_label ~__context ~self:host)
(Db.Pool.get_uuid ~__context ~self:(Helpers.get_pool ~__context))
in
let name, priority = Api_messages.wlb_failed in
ignore
(Xapi_message.create ~__context ~name ~priority ~cls:`Host
~obj_uuid:uuid ~body:message_body
)
with _ -> ()
) ;
compute_evacuation_plan_no_wlb ~__context ~host ()
| _ ->
debug
"Encountered an unknown error when using wlb for choosing host. \
Using original algorithm" ;
compute_evacuation_plan_no_wlb ~__context ~host ()
let evacuate ~__context ~host ~network ~evacuate_batch_size =
let plans = compute_evacuation_plan ~__context ~host in
let plans_length = float (Hashtbl.length plans) in
(* Check there are no errors in this list *)
Hashtbl.iter
(fun _ plan ->
match plan with
| Error (code, params) ->
raise (Api_errors.Server_error (code, params))
| _ ->
()
)
plans ;
(* check all hosts that show up as destinations *)
let assert_valid_networks plans =
plans
|> Hashtbl.to_seq
|> Seq.filter_map (function _, Migrate host -> Some host | _ -> None)
|> List.of_seq
|> List.sort_uniq compare
|> List.iter (fun host ->
ignore
@@ Xapi_network_attach_helpers
.assert_valid_ip_configuration_on_network_for_host ~__context
~self:network ~host
)
in
let options =
match network with
| network when network = Ref.null ->
[("live", "true")]
| network ->
assert_valid_networks plans ;
[("network", Ref.string_of network); ("live", "true")]
in
let migrate_vm ~rpc ~session_id (vm, plan) =
match plan with
| Migrate host ->
Client.Client.Async.VM.pool_migrate ~rpc ~session_id ~vm ~host ~options
| Error (code, params) ->
(* should never happen *)
raise (Api_errors.Server_error (code, params))
in
(* execute [n] asynchronous API calls [api_fn] for [xs] and wait for them to
finish before executing the next batch. *)
let batch ~__context n api_fn xs =
let finally = Xapi_stdext_pervasives.Pervasiveext.finally in
let destroy = Client.Client.Task.destroy in
let fail task msg =
Helpers.internal_error "%s, %s" (Ref.string_of task) msg
in
let assert_success task =
match Db.Task.get_status ~__context ~self:task with
| `success ->
()
| `failure -> (
match Db.Task.get_error_info ~__context ~self:task with
| [] ->
fail task "couldn't extract error result from task"
| code :: _ when code = Api_errors.vm_bad_power_state ->
()
| code :: params ->
raise (Api_errors.Server_error (code, params))
)
| _ ->
fail task "unexpected status of migration task"
in
let rec loop xs =
match take n xs with
| [], _ ->
()
| head, tail ->
Helpers.call_api_functions ~__context @@ fun rpc session_id ->
let tasks = List.map (api_fn ~rpc ~session_id) head in
finally
(fun () ->
Tasks.wait_for_all ~rpc ~session_id ~tasks ;
List.iter assert_success tasks ;
let tail_length = List.length tail |> float in
let progress = 1.0 -. (tail_length /. plans_length) in
TaskHelper.set_progress ~__context progress
)
(fun () ->
List.iter (fun self -> destroy ~rpc ~session_id ~self) tasks
) ;
loop tail
in
loop xs ;
TaskHelper.set_progress ~__context 1.0
in
let batch_size =
match evacuate_batch_size with
| size when size > 0L ->
Int64.to_int size
| _ ->
!Xapi_globs.evacuation_batch_size
in
(* avoid edge cases from meaningless batch sizes *)
let batch_size = Int.(max 1 (abs batch_size)) in
info "Host.evacuate: migrating VMs in batches of %d" batch_size ;
(* execute evacuation plan in batches *)
plans
|> Hashtbl.to_seq
|> List.of_seq
|> batch ~__context batch_size migrate_vm ;
(* Now check there are no VMs left *)
let vms = Db.Host.get_resident_VMs ~__context ~self:host in
let vms =
List.filter
(fun vm -> not (Db.VM.get_is_control_domain ~__context ~self:vm))
vms
in
let remainder = List.length vms in
if not (remainder = 0) then
Helpers.internal_error "evacuate: %d VMs are still resident on %s" remainder
(Ref.string_of host)
let retrieve_wlb_evacuate_recommendations ~__context ~self =
let plans = compute_evacuation_plan_wlb ~__context ~self in
Hashtbl.fold
(fun vm detail acc ->
let plan =
match detail with
| Error (e, t) ->
e :: t
| Migrate h ->
["WLB"; Db.Host.get_uuid ~__context ~self:h]
in
(vm, plan) :: acc
)
plans []
let restart_agent ~__context ~host:_ =
(* Spawn a thread to call the restarting script so that this call could return
* successfully before its stunnel connection being terminated by the restarting.
*)
ignore
(Thread.create
(fun () ->
Thread.delay 1. ;
let syslog_stdout = Forkhelpers.Syslog_WithKey "Host.restart_agent" in
let pid =
Forkhelpers.safe_close_and_exec None None None [] ~syslog_stdout
!Xapi_globs.xe_toolstack_restart
[]
in
debug "Created process with pid: %d to perform xe-toolstack-restart"
(Forkhelpers.getpid pid)
)
()
)
let shutdown_agent ~__context =
debug "Host.restart_agent: Host agent will shutdown in 1s!!!!" ;
let localhost = Helpers.get_localhost ~__context in
Xapi_hooks.xapi_pre_shutdown ~__context ~host:localhost
~reason:Xapi_hooks.reason__clean_shutdown ;
Xapi_fuse.light_fuse_and_dont_restart ~fuse_length:1. ()
let disable ~__context ~host =
if Db.Host.get_enabled ~__context ~self:host then (
info
"Host.enabled: setting host %s (%s) to disabled because of user request"
(Ref.string_of host)
(Db.Host.get_hostname ~__context ~self:host) ;
Db.Host.set_enabled ~__context ~self:host ~value:false ;
Xapi_host_helpers.user_requested_host_disable := true
)
let enable ~__context ~host =
if not (Db.Host.get_enabled ~__context ~self:host) then (
assert_safe_to_reenable ~__context ~self:host ;
Xapi_host_helpers.user_requested_host_disable := false ;
info "Host.enabled: setting host %s (%s) to enabled because of user request"
(Ref.string_of host)
(Db.Host.get_hostname ~__context ~self:host) ;
Db.Host.set_enabled ~__context ~self:host ~value:true ;
(* Normally we schedule a plan recomputation when we successfully plug in our storage. In the case
when some of our storage was broken and required maintenance, we end up here, manually re-enabling
the host. If we're overcommitted then this might fix the problem. *)
let pool = Helpers.get_pool ~__context in
if
Db.Pool.get_ha_enabled ~__context ~self:pool
&& Db.Pool.get_ha_overcommitted ~__context ~self:pool
then
Helpers.call_api_functions ~__context (fun rpc session_id ->
Client.Client.Pool.ha_schedule_plan_recomputation ~rpc ~session_id
)
)
let prepare_for_poweroff_precheck ~__context ~host =
Xapi_host_helpers.assert_host_disabled ~__context ~host
let prepare_for_poweroff ~__context ~host =
(* Do not run assert_host_disabled here, continue even if the host is
enabled: the host is already shutting down when this function gets called *)
let i_am_master = Pool_role.is_master () in
if i_am_master then
(* We are the master and we are about to shutdown HA and redo log:
prevent slaves from sending (DB) requests.
If we are the slave we cannot shutdown the request thread yet
because we might need it when unplugging the PBDs
*)
Remote_requests.stop_request_thread () ;
Vm_evacuation.ensure_no_vms ~__context ~evacuate_timeout:0. ;
Xapi_ha.before_clean_shutdown_or_reboot ~__context ~host ;
Xapi_pbd.unplug_all_pbds ~__context ;
if not i_am_master then
Remote_requests.stop_request_thread () ;
(* Push the Host RRD to the master. Note there are no VMs running here so we don't have to worry about them. *)
if not (Pool_role.is_master ()) then
log_and_ignore_exn (fun () ->
Rrdd.send_host_rrd_to_master (Pool_role.get_master_address ())
) ;
(* Also save the Host RRD to local disk for us to pick up when we return. Note there are no VMs running at this point. *)
log_and_ignore_exn (Rrdd.backup_rrds None) ;
(* This prevents anyone actually re-enabling us until after reboot *)
Localdb.put Constants.host_disabled_until_reboot "true" ;
(* This helps us distinguish between an HA fence and a reboot *)
Localdb.put Constants.host_restarted_cleanly "true"
let shutdown_and_reboot_common ~__context ~host label description operation cmd
=
(* The actual shutdown actions are done asynchronously, in a call to
prepare_for_poweroff, so the API user will not be notified of any errors
that happen during that operation.
Therefore here we make an additional call to the prechecks of every
operation that gets called from prepare_for_poweroff, either directly or
indirectly, to fail early and ensure that a suitable error is returned to
the XenAPI user. *)
let shutdown_precheck () =
prepare_for_poweroff_precheck ~__context ~host ;
Xapi_ha.before_clean_shutdown_or_reboot_precheck ~__context ~host
in
shutdown_precheck () ;
(* This tells the master that the shutdown is still ongoing: it can be used to continue
masking other operations even after this call return.
If xapi restarts then this task will be reset by the startup code, which is unfortunate
but the host will stay disabled provided host_disabled_until_reboot is still set... so
safe but ugly. *)
Server_helpers.exec_with_new_task ~subtask_of:(Context.get_task_id __context)
~task_description:description ~task_in_database:true label
(fun __newcontext ->
Db.Host.add_to_current_operations ~__context ~self:host
~key:(Ref.string_of (Context.get_task_id __newcontext))
~value:operation ;
(* Do the shutdown in a background thread with a delay to give this API call
a reasonable chance of succeeding. *)
ignore
(Thread.create
(fun () ->
Thread.delay 10. ;
ignore (Sys.command cmd)
)
()
)
)
let shutdown ~__context ~host =
shutdown_and_reboot_common ~__context ~host "Host is shutting down"
"Host is shutting down" `shutdown "/sbin/shutdown -h now"
let reboot ~__context ~host =
shutdown_and_reboot_common ~__context ~host "Host is rebooting"
"Host is rebooting" `shutdown "/sbin/shutdown -r now"
let power_on ~__context ~host =
let result =
Xapi_plugins.call_plugin
(Context.get_session_id __context)
Constants.power_on_plugin Constants.power_on_fn
[("remote_host_uuid", Db.Host.get_uuid ~__context ~self:host)]
in
if result <> "True" then
failwith (Printf.sprintf "The host failed to power on.")
let dmesg ~__context ~host:_ =
let dbg = Context.string_of_task __context in
let open Xapi_xenops_queue in
let module Client = (val make_client (default_xenopsd ()) : XENOPS) in
Client.HOST.get_console_data dbg
let dmesg_clear ~__context ~host:_ =
raise (Api_errors.Server_error (Api_errors.not_implemented, ["dmesg_clear"]))
let get_log ~__context ~host:_ =
raise (Api_errors.Server_error (Api_errors.not_implemented, ["get_log"]))
let send_debug_keys ~__context ~host:_ ~keys =
let open Xapi_xenops_queue in
let module Client = (val make_client (default_xenopsd ()) : XENOPS) in
let dbg = Context.string_of_task __context in
Client.HOST.send_debug_keys dbg keys
let list_methods ~__context =
raise (Api_errors.Server_error (Api_errors.not_implemented, ["list_method"]))
let is_slave ~__context ~host:_ = not (Pool_role.is_master ())
let ask_host_if_it_is_a_slave ~__context ~host =
let ask_and_warn_when_slow ~__context =
let local_fn = is_slave ~host in
let remote_fn = Client.Client.Pool.is_slave ~host in
let timeout = 10. in
let task_name = Context.get_task_id __context |> Ref.string_of in
let ip, uuid =
( Db.Host.get_address ~__context ~self:host
, Db.Host.get_uuid ~__context ~self:host
)
in
let rec log_host_slow_to_respond timeout () =
D.warn
"ask_host_if_it_is_a_slave: host taking a long time to respond - IP: \
%s; uuid: %s"
ip uuid ;
Xapi_stdext_threads_scheduler.Scheduler.add_to_queue task_name
Xapi_stdext_threads_scheduler.Scheduler.OneShot timeout
(log_host_slow_to_respond (min (2. *. timeout) 300.))
in
Xapi_stdext_threads_scheduler.Scheduler.add_to_queue task_name
Xapi_stdext_threads_scheduler.Scheduler.OneShot timeout
(log_host_slow_to_respond timeout) ;
let res =
Message_forwarding.do_op_on_localsession_nolivecheck ~local_fn ~__context
~host ~remote_fn
in
Xapi_stdext_threads_scheduler.Scheduler.remove_from_queue task_name ;
res
in
Server_helpers.exec_with_subtask ~__context "host.ask_host_if_it_is_a_slave"
ask_and_warn_when_slow
let is_host_alive ~__context ~host =
(* If the host is marked as not-live then assume we don't need to contact it to verify *)
let should_contact_host =
try
let hm = Db.Host.get_metrics ~__context ~self:host in
Db.Host_metrics.get_live ~__context ~self:hm
with _ -> true
in
if should_contact_host then (
debug
"is_host_alive host=%s is marked as live in the database; asking host to \
make sure"
(Ref.string_of host) ;
try
ignore (ask_host_if_it_is_a_slave ~__context ~host) ;
true
with e ->
warn
"is_host_alive host=%s caught %s while querying host liveness: \
assuming dead"
(Ref.string_of host)
(ExnHelper.string_of_exn e) ;
false
) else (
debug
"is_host_alive host=%s is marked as dead in the database; treating this \
as definitive."
(Ref.string_of host) ;
false
)
let create ~__context ~uuid ~name_label ~name_description:_ ~hostname ~address
~external_auth_type ~external_auth_service_name ~external_auth_configuration
~license_params ~edition ~license_server ~local_cache_sr ~chipset_info
~ssl_legacy:_ ~last_software_update ~last_update_hash =
(* fail-safe. We already test this on the joining host, but it's racy, so multiple concurrent
pool-join might succeed. Note: we do it in this order to avoid a problem checking restrictions during
the initial setup of the database *)
if
List.length (Db.Host.get_all ~__context) >= Xapi_globs.restricted_pool_size
&& pool_size_is_restricted ~__context
then
raise
(Api_errors.Server_error
( Api_errors.license_restriction
, [Features.name_of_feature Features.Pool_size]
)
) ;
let make_new_metrics_object ref =
Db.Host_metrics.create ~__context ~ref
~uuid:(Uuidx.to_string (Uuidx.make ()))
~live:false ~memory_total:0L ~memory_free:0L ~last_updated:Date.epoch
~other_config:[]
in