forked from apache/cloudstack
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathUserVmManagerImpl.java
7948 lines (6937 loc) · 410 KB
/
UserVmManagerImpl.java
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
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package com.cloud.vm;
import static com.cloud.utils.NumbersUtil.toHumanReadableSize;
import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.inject.Inject;
import javax.naming.ConfigurationException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import com.cloud.network.router.CommandSetupHelper;
import com.cloud.network.router.NetworkHelper;
import org.apache.cloudstack.acl.ControlledEntity;
import org.apache.cloudstack.acl.ControlledEntity.ACLType;
import org.apache.cloudstack.acl.SecurityChecker.AccessType;
import org.apache.cloudstack.affinity.AffinityGroupService;
import org.apache.cloudstack.affinity.AffinityGroupVMMapVO;
import org.apache.cloudstack.affinity.AffinityGroupVO;
import org.apache.cloudstack.affinity.dao.AffinityGroupDao;
import org.apache.cloudstack.affinity.dao.AffinityGroupVMMapDao;
import org.apache.cloudstack.annotation.AnnotationService;
import org.apache.cloudstack.annotation.dao.AnnotationDao;
import org.apache.cloudstack.api.ApiConstants;
import org.apache.cloudstack.api.BaseCmd.HTTPMethod;
import org.apache.cloudstack.api.command.admin.vm.AssignVMCmd;
import org.apache.cloudstack.api.command.admin.vm.DeployVMCmdByAdmin;
import org.apache.cloudstack.api.command.admin.vm.RecoverVMCmd;
import org.apache.cloudstack.api.command.user.vm.AddNicToVMCmd;
import org.apache.cloudstack.api.command.user.vm.DeployVMCmd;
import org.apache.cloudstack.api.command.user.vm.DestroyVMCmd;
import org.apache.cloudstack.api.command.user.vm.RebootVMCmd;
import org.apache.cloudstack.api.command.user.vm.RemoveNicFromVMCmd;
import org.apache.cloudstack.api.command.user.vm.ResetVMPasswordCmd;
import org.apache.cloudstack.api.command.user.vm.ResetVMSSHKeyCmd;
import org.apache.cloudstack.api.command.user.vm.RestoreVMCmd;
import org.apache.cloudstack.api.command.user.vm.ScaleVMCmd;
import org.apache.cloudstack.api.command.user.vm.SecurityGroupAction;
import org.apache.cloudstack.api.command.user.vm.StartVMCmd;
import org.apache.cloudstack.api.command.user.vm.UpdateDefaultNicForVMCmd;
import org.apache.cloudstack.api.command.user.vm.UpdateVMCmd;
import org.apache.cloudstack.api.command.user.vm.UpdateVmNicIpCmd;
import org.apache.cloudstack.api.command.user.vm.UpgradeVMCmd;
import org.apache.cloudstack.api.command.user.vmgroup.CreateVMGroupCmd;
import org.apache.cloudstack.api.command.user.vmgroup.DeleteVMGroupCmd;
import org.apache.cloudstack.api.command.user.volume.ResizeVolumeCmd;
import org.apache.cloudstack.backup.Backup;
import org.apache.cloudstack.backup.BackupManager;
import org.apache.cloudstack.backup.dao.BackupDao;
import org.apache.cloudstack.context.CallContext;
import org.apache.cloudstack.engine.cloud.entity.api.VirtualMachineEntity;
import org.apache.cloudstack.engine.cloud.entity.api.db.dao.VMNetworkMapDao;
import org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService;
import org.apache.cloudstack.engine.orchestration.service.VolumeOrchestrationService;
import org.apache.cloudstack.engine.service.api.OrchestrationService;
import org.apache.cloudstack.engine.subsystem.api.storage.DataStore;
import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreDriver;
import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager;
import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreProvider;
import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreProviderManager;
import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStore;
import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreDriver;
import org.apache.cloudstack.engine.subsystem.api.storage.VolumeDataFactory;
import org.apache.cloudstack.engine.subsystem.api.storage.VolumeInfo;
import org.apache.cloudstack.engine.subsystem.api.storage.VolumeService;
import org.apache.cloudstack.engine.subsystem.api.storage.VolumeService.VolumeApiResult;
import org.apache.cloudstack.framework.async.AsyncCallFuture;
import org.apache.cloudstack.framework.config.ConfigKey;
import org.apache.cloudstack.framework.config.Configurable;
import org.apache.cloudstack.framework.config.dao.ConfigurationDao;
import org.apache.cloudstack.managed.context.ManagedContextRunnable;
import org.apache.cloudstack.query.QueryService;
import org.apache.cloudstack.storage.command.DeleteCommand;
import org.apache.cloudstack.storage.command.DettachCommand;
import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao;
import org.apache.cloudstack.storage.datastore.db.StoragePoolVO;
import org.apache.cloudstack.storage.datastore.db.TemplateDataStoreDao;
import org.apache.cloudstack.storage.datastore.db.TemplateDataStoreVO;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import com.cloud.agent.AgentManager;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.Command;
import com.cloud.agent.api.GetVmDiskStatsAnswer;
import com.cloud.agent.api.GetVmDiskStatsCommand;
import com.cloud.agent.api.GetVmIpAddressCommand;
import com.cloud.agent.api.GetVmNetworkStatsAnswer;
import com.cloud.agent.api.GetVmNetworkStatsCommand;
import com.cloud.agent.api.GetVmStatsAnswer;
import com.cloud.agent.api.GetVmStatsCommand;
import com.cloud.agent.api.GetVolumeStatsAnswer;
import com.cloud.agent.api.GetVolumeStatsCommand;
import com.cloud.agent.api.ModifyTargetsCommand;
import com.cloud.agent.api.PvlanSetupCommand;
import com.cloud.agent.api.RestoreVMSnapshotAnswer;
import com.cloud.agent.api.RestoreVMSnapshotCommand;
import com.cloud.agent.api.StartAnswer;
import com.cloud.agent.api.VmDiskStatsEntry;
import com.cloud.agent.api.VmNetworkStatsEntry;
import com.cloud.agent.api.VmStatsEntry;
import com.cloud.agent.api.VolumeStatsEntry;
import com.cloud.agent.api.to.DiskTO;
import com.cloud.agent.api.to.NicTO;
import com.cloud.agent.api.to.VirtualMachineTO;
import com.cloud.agent.api.to.deployasis.OVFNetworkTO;
import com.cloud.agent.api.to.deployasis.OVFPropertyTO;
import com.cloud.agent.manager.Commands;
import com.cloud.alert.AlertManager;
import com.cloud.api.ApiDBUtils;
import com.cloud.api.query.dao.ServiceOfferingJoinDao;
import com.cloud.api.query.vo.ServiceOfferingJoinVO;
import com.cloud.capacity.Capacity;
import com.cloud.capacity.CapacityManager;
import com.cloud.configuration.Config;
import com.cloud.configuration.ConfigurationManager;
import com.cloud.configuration.ConfigurationManagerImpl;
import com.cloud.configuration.Resource.ResourceType;
import com.cloud.dc.DataCenter;
import com.cloud.dc.DataCenter.NetworkType;
import com.cloud.dc.DataCenterVO;
import com.cloud.dc.DedicatedResourceVO;
import com.cloud.dc.HostPodVO;
import com.cloud.dc.Pod;
import com.cloud.dc.Vlan;
import com.cloud.dc.Vlan.VlanType;
import com.cloud.dc.VlanVO;
import com.cloud.dc.dao.ClusterDao;
import com.cloud.dc.dao.DataCenterDao;
import com.cloud.dc.dao.DedicatedResourceDao;
import com.cloud.dc.dao.HostPodDao;
import com.cloud.dc.dao.VlanDao;
import com.cloud.deploy.DataCenterDeployment;
import com.cloud.deploy.DeployDestination;
import com.cloud.deploy.DeploymentPlanner;
import com.cloud.deploy.DeploymentPlanner.ExcludeList;
import com.cloud.deploy.DeploymentPlanningManager;
import com.cloud.deploy.PlannerHostReservationVO;
import com.cloud.deploy.dao.PlannerHostReservationDao;
import com.cloud.deployasis.UserVmDeployAsIsDetailVO;
import com.cloud.deployasis.dao.TemplateDeployAsIsDetailsDao;
import com.cloud.deployasis.dao.UserVmDeployAsIsDetailsDao;
import com.cloud.domain.Domain;
import com.cloud.domain.DomainVO;
import com.cloud.domain.dao.DomainDao;
import com.cloud.event.ActionEvent;
import com.cloud.event.ActionEventUtils;
import com.cloud.event.EventTypes;
import com.cloud.event.UsageEventUtils;
import com.cloud.event.UsageEventVO;
import com.cloud.event.dao.UsageEventDao;
import com.cloud.exception.AffinityConflictException;
import com.cloud.exception.AgentUnavailableException;
import com.cloud.exception.CloudException;
import com.cloud.exception.ConcurrentOperationException;
import com.cloud.exception.InsufficientAddressCapacityException;
import com.cloud.exception.InsufficientCapacityException;
import com.cloud.exception.InsufficientServerCapacityException;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.exception.ManagementServerException;
import com.cloud.exception.OperationTimedoutException;
import com.cloud.exception.PermissionDeniedException;
import com.cloud.exception.ResourceAllocationException;
import com.cloud.exception.ResourceUnavailableException;
import com.cloud.exception.StorageUnavailableException;
import com.cloud.exception.UnsupportedServiceException;
import com.cloud.exception.VirtualMachineMigrationException;
import com.cloud.gpu.GPU;
import com.cloud.ha.HighAvailabilityManager;
import com.cloud.host.Host;
import com.cloud.host.HostVO;
import com.cloud.host.Status;
import com.cloud.host.dao.HostDao;
import com.cloud.hypervisor.Hypervisor;
import com.cloud.hypervisor.Hypervisor.HypervisorType;
import com.cloud.hypervisor.dao.HypervisorCapabilitiesDao;
import com.cloud.hypervisor.kvm.dpdk.DpdkHelper;
import com.cloud.network.IpAddressManager;
import com.cloud.network.Network;
import com.cloud.network.Network.IpAddresses;
import com.cloud.network.Network.Provider;
import com.cloud.network.Network.Service;
import com.cloud.network.NetworkModel;
import com.cloud.network.Networks.TrafficType;
import com.cloud.network.PhysicalNetwork;
import com.cloud.network.dao.FirewallRulesDao;
import com.cloud.network.dao.IPAddressDao;
import com.cloud.network.dao.IPAddressVO;
import com.cloud.network.dao.LoadBalancerVMMapDao;
import com.cloud.network.dao.LoadBalancerVMMapVO;
import com.cloud.network.dao.NetworkDao;
import com.cloud.network.dao.NetworkServiceMapDao;
import com.cloud.network.dao.NetworkVO;
import com.cloud.network.dao.PhysicalNetworkDao;
import com.cloud.network.element.UserDataServiceProvider;
import com.cloud.network.guru.NetworkGuru;
import com.cloud.network.lb.LoadBalancingRulesManager;
import com.cloud.network.router.VpcVirtualNetworkApplianceManager;
import com.cloud.network.rules.FirewallManager;
import com.cloud.network.rules.FirewallRuleVO;
import com.cloud.network.rules.PortForwardingRuleVO;
import com.cloud.network.rules.RulesManager;
import com.cloud.network.rules.dao.PortForwardingRulesDao;
import com.cloud.network.security.SecurityGroup;
import com.cloud.network.security.SecurityGroupManager;
import com.cloud.network.security.dao.SecurityGroupDao;
import com.cloud.network.vpc.VpcManager;
import com.cloud.offering.DiskOffering;
import com.cloud.offering.NetworkOffering;
import com.cloud.offering.NetworkOffering.Availability;
import com.cloud.offering.ServiceOffering;
import com.cloud.offerings.NetworkOfferingVO;
import com.cloud.offerings.dao.NetworkOfferingDao;
import com.cloud.org.Cluster;
import com.cloud.org.Grouping;
import com.cloud.resource.ResourceManager;
import com.cloud.resource.ResourceState;
import com.cloud.server.ManagementService;
import com.cloud.server.ResourceTag;
import com.cloud.service.ServiceOfferingVO;
import com.cloud.service.dao.ServiceOfferingDao;
import com.cloud.service.dao.ServiceOfferingDetailsDao;
import com.cloud.storage.DataStoreRole;
import com.cloud.storage.DiskOfferingVO;
import com.cloud.storage.GuestOSCategoryVO;
import com.cloud.storage.GuestOSVO;
import com.cloud.storage.ScopeType;
import com.cloud.storage.Snapshot;
import com.cloud.storage.SnapshotVO;
import com.cloud.storage.Storage;
import com.cloud.storage.Storage.ImageFormat;
import com.cloud.storage.Storage.StoragePoolType;
import com.cloud.storage.Storage.TemplateType;
import com.cloud.storage.StorageManager;
import com.cloud.storage.StoragePool;
import com.cloud.storage.StoragePoolStatus;
import com.cloud.storage.VMTemplateStorageResourceAssoc;
import com.cloud.storage.VMTemplateVO;
import com.cloud.storage.VMTemplateZoneVO;
import com.cloud.storage.Volume;
import com.cloud.storage.VolumeApiService;
import com.cloud.storage.VolumeVO;
import com.cloud.storage.dao.DiskOfferingDao;
import com.cloud.storage.dao.GuestOSCategoryDao;
import com.cloud.storage.dao.GuestOSDao;
import com.cloud.storage.dao.SnapshotDao;
import com.cloud.storage.dao.VMTemplateDao;
import com.cloud.storage.dao.VMTemplateZoneDao;
import com.cloud.storage.dao.VolumeDao;
import com.cloud.tags.ResourceTagVO;
import com.cloud.tags.dao.ResourceTagDao;
import com.cloud.template.TemplateApiService;
import com.cloud.template.TemplateManager;
import com.cloud.template.VirtualMachineTemplate;
import com.cloud.user.Account;
import com.cloud.user.AccountManager;
import com.cloud.user.AccountService;
import com.cloud.user.ResourceLimitService;
import com.cloud.user.SSHKeyPair;
import com.cloud.user.SSHKeyPairVO;
import com.cloud.user.User;
import com.cloud.user.UserStatisticsVO;
import com.cloud.user.UserVO;
import com.cloud.user.VmDiskStatisticsVO;
import com.cloud.user.dao.AccountDao;
import com.cloud.user.dao.SSHKeyPairDao;
import com.cloud.user.dao.UserDao;
import com.cloud.user.dao.UserStatisticsDao;
import com.cloud.user.dao.VmDiskStatisticsDao;
import com.cloud.uservm.UserVm;
import com.cloud.utils.DateUtil;
import com.cloud.utils.Journal;
import com.cloud.utils.NumbersUtil;
import com.cloud.utils.Pair;
import com.cloud.utils.component.ManagerBase;
import com.cloud.utils.concurrency.NamedThreadFactory;
import com.cloud.utils.crypt.DBEncryptionUtil;
import com.cloud.utils.crypt.RSAHelper;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.EntityManager;
import com.cloud.utils.db.GlobalLock;
import com.cloud.utils.db.SearchCriteria;
import com.cloud.utils.db.Transaction;
import com.cloud.utils.db.TransactionCallbackNoReturn;
import com.cloud.utils.db.TransactionCallbackWithException;
import com.cloud.utils.db.TransactionCallbackWithExceptionNoReturn;
import com.cloud.utils.db.TransactionStatus;
import com.cloud.utils.db.UUIDManager;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.exception.ExecutionException;
import com.cloud.utils.fsm.NoTransitionException;
import com.cloud.utils.net.NetUtils;
import com.cloud.vm.VirtualMachine.State;
import com.cloud.vm.dao.DomainRouterDao;
import com.cloud.vm.dao.InstanceGroupDao;
import com.cloud.vm.dao.InstanceGroupVMMapDao;
import com.cloud.vm.dao.NicDao;
import com.cloud.vm.dao.NicExtraDhcpOptionDao;
import com.cloud.vm.dao.UserVmDao;
import com.cloud.vm.dao.UserVmDetailsDao;
import com.cloud.vm.dao.VMInstanceDao;
import com.cloud.vm.snapshot.VMSnapshotManager;
import com.cloud.vm.snapshot.VMSnapshotVO;
import com.cloud.vm.snapshot.dao.VMSnapshotDao;
import java.util.HashSet;
import org.apache.cloudstack.utils.bytescale.ByteScaleUtils;
import static com.cloud.configuration.ConfigurationManagerImpl.VM_USERDATA_MAX_LENGTH;
public class UserVmManagerImpl extends ManagerBase implements UserVmManager, VirtualMachineGuru, UserVmService, Configurable {
private static final Logger s_logger = Logger.getLogger(UserVmManagerImpl.class);
/**
* The number of seconds to wait before timing out when trying to acquire a global lock.
*/
private static final int ACQUIRE_GLOBAL_LOCK_TIMEOUT_FOR_COOPERATION = 3;
private static final long GiB_TO_BYTES = 1024 * 1024 * 1024;
@Inject
private EntityManager _entityMgr;
@Inject
private HostDao _hostDao;
@Inject
private ServiceOfferingDao _offeringDao;
@Inject
private DiskOfferingDao _diskOfferingDao;
@Inject
private VMTemplateDao _templateDao;
@Inject
private VMTemplateZoneDao _templateZoneDao;
@Inject
private TemplateDataStoreDao _templateStoreDao;
@Inject
private DomainDao _domainDao;
@Inject
private UserVmDao _vmDao;
@Inject
private VolumeDao _volsDao;
@Inject
private DataCenterDao _dcDao;
@Inject
private FirewallRulesDao _rulesDao;
@Inject
private LoadBalancerVMMapDao _loadBalancerVMMapDao;
@Inject
private PortForwardingRulesDao _portForwardingDao;
@Inject
private IPAddressDao _ipAddressDao;
@Inject
private HostPodDao _podDao;
@Inject
private NetworkModel _networkModel;
@Inject
private NetworkOrchestrationService _networkMgr;
@Inject
private AgentManager _agentMgr;
@Inject
private ConfigurationManager _configMgr;
@Inject
private AccountDao _accountDao;
@Inject
private UserDao _userDao;
@Inject
private SnapshotDao _snapshotDao;
@Inject
private GuestOSDao _guestOSDao;
@Inject
private HighAvailabilityManager _haMgr;
@Inject
private AlertManager _alertMgr;
@Inject
private AccountManager _accountMgr;
@Inject
private AccountService _accountService;
@Inject
private ClusterDao _clusterDao;
@Inject
private PrimaryDataStoreDao _storagePoolDao;
@Inject
private SecurityGroupManager _securityGroupMgr;
@Inject
private ServiceOfferingDao _serviceOfferingDao;
@Inject
private NetworkOfferingDao _networkOfferingDao;
@Inject
private InstanceGroupDao _vmGroupDao;
@Inject
private InstanceGroupVMMapDao _groupVMMapDao;
@Inject
private VirtualMachineManager _itMgr;
@Inject
private NetworkDao _networkDao;
@Inject
private NicDao _nicDao;
@Inject
private RulesManager _rulesMgr;
@Inject
private LoadBalancingRulesManager _lbMgr;
@Inject
private SSHKeyPairDao _sshKeyPairDao;
@Inject
private UserVmDetailsDao userVmDetailsDao;
@Inject
private HypervisorCapabilitiesDao _hypervisorCapabilitiesDao;
@Inject
private SecurityGroupDao _securityGroupDao;
@Inject
private CapacityManager _capacityMgr;
@Inject
private VMInstanceDao _vmInstanceDao;
@Inject
private ResourceLimitService _resourceLimitMgr;
@Inject
private FirewallManager _firewallMgr;
@Inject
private ResourceManager _resourceMgr;
@Inject
private NetworkServiceMapDao _ntwkSrvcDao;
@Inject
private PhysicalNetworkDao _physicalNetworkDao;
@Inject
private VpcManager _vpcMgr;
@Inject
private TemplateManager _templateMgr;
@Inject
private GuestOSCategoryDao _guestOSCategoryDao;
@Inject
private UsageEventDao _usageEventDao;
@Inject
private VmDiskStatisticsDao _vmDiskStatsDao;
@Inject
private VMSnapshotDao _vmSnapshotDao;
@Inject
private VMSnapshotManager _vmSnapshotMgr;
@Inject
private AffinityGroupVMMapDao _affinityGroupVMMapDao;
@Inject
private AffinityGroupDao _affinityGroupDao;
@Inject
private DedicatedResourceDao _dedicatedDao;
@Inject
private AffinityGroupService _affinityGroupService;
@Inject
private PlannerHostReservationDao _plannerHostReservationDao;
@Inject
private ServiceOfferingDetailsDao serviceOfferingDetailsDao;
@Inject
private UserStatisticsDao _userStatsDao;
@Inject
private VlanDao _vlanDao;
@Inject
private VolumeService _volService;
@Inject
private VolumeDataFactory volFactory;
@Inject
private UUIDManager _uuidMgr;
@Inject
private DeploymentPlanningManager _planningMgr;
@Inject
private VolumeApiService _volumeService;
@Inject
private DataStoreManager _dataStoreMgr;
@Inject
private VpcVirtualNetworkApplianceManager _virtualNetAppliance;
@Inject
private DomainRouterDao _routerDao;
@Inject
private VMNetworkMapDao _vmNetworkMapDao;
@Inject
private IpAddressManager _ipAddrMgr;
@Inject
private NicExtraDhcpOptionDao _nicExtraDhcpOptionDao;
@Inject
private TemplateApiService _tmplService;
@Inject
private ConfigurationDao _configDao;
@Inject
private DpdkHelper dpdkHelper;
@Inject
private ResourceTagDao resourceTagDao;
@Inject
private TemplateDeployAsIsDetailsDao templateDeployAsIsDetailsDao;
@Inject
private UserVmDeployAsIsDetailsDao userVmDeployAsIsDetailsDao;
@Inject
private DataStoreProviderManager _dataStoreProviderMgr;
private StorageManager storageManager;
@Inject
private ServiceOfferingJoinDao serviceOfferingJoinDao;
@Inject
private BackupDao backupDao;
@Inject
private BackupManager backupManager;
@Inject
private AnnotationDao annotationDao;
@Inject
protected CommandSetupHelper commandSetupHelper;
@Autowired
@Qualifier("networkHelper")
protected NetworkHelper nwHelper;
private ScheduledExecutorService _executor = null;
private ScheduledExecutorService _vmIpFetchExecutor = null;
private int _expungeInterval;
private int _expungeDelay;
private boolean _dailyOrHourly = false;
private int capacityReleaseInterval;
private ExecutorService _vmIpFetchThreadExecutor;
private String _instance;
private boolean _instanceNameFlag;
private int _scaleRetry;
private Map<Long, VmAndCountDetails> vmIdCountMap = new ConcurrentHashMap<>();
private static final int MAX_HTTP_GET_LENGTH = 2 * MAX_USER_DATA_LENGTH_BYTES;
private static final int NUM_OF_2K_BLOCKS = 512;
private static final int MAX_HTTP_POST_LENGTH = NUM_OF_2K_BLOCKS * MAX_USER_DATA_LENGTH_BYTES;
@Inject
private OrchestrationService _orchSrvc;
@Inject
private VolumeOrchestrationService volumeMgr;
@Inject
private ManagementService _mgr;
private static final ConfigKey<Integer> VmIpFetchWaitInterval = new ConfigKey<Integer>("Advanced", Integer.class, "externaldhcp.vmip.retrieval.interval", "180",
"Wait Interval (in seconds) for shared network vm dhcp ip addr fetch for next iteration ", true);
private static final ConfigKey<Integer> VmIpFetchTrialMax = new ConfigKey<Integer>("Advanced", Integer.class, "externaldhcp.vmip.max.retry", "10",
"The max number of retrieval times for shared entwork vm dhcp ip fetch, in case of failures", true);
private static final ConfigKey<Integer> VmIpFetchThreadPoolMax = new ConfigKey<Integer>("Advanced", Integer.class, "externaldhcp.vmipFetch.threadPool.max", "10",
"number of threads for fetching vms ip address", true);
private static final ConfigKey<Integer> VmIpFetchTaskWorkers = new ConfigKey<Integer>("Advanced", Integer.class, "externaldhcp.vmipfetchtask.workers", "10",
"number of worker threads for vm ip fetch task ", true);
private static final ConfigKey<Boolean> AllowDeployVmIfGivenHostFails = new ConfigKey<Boolean>("Advanced", Boolean.class, "allow.deploy.vm.if.deploy.on.given.host.fails", "false",
"allow vm to deploy on different host if vm fails to deploy on the given host ", true);
private static final ConfigKey<Boolean> EnableAdditionalVmConfig = new ConfigKey<>("Advanced", Boolean.class,
"enable.additional.vm.configuration", "false", "allow additional arbitrary configuration to vm", true, ConfigKey.Scope.Account);
private static final ConfigKey<String> KvmAdditionalConfigAllowList = new ConfigKey<>("Advanced", String.class,
"allow.additional.vm.configuration.list.kvm", "", "Comma separated list of allowed additional configuration options.", true);
private static final ConfigKey<String> XenServerAdditionalConfigAllowList = new ConfigKey<>("Advanced", String.class,
"allow.additional.vm.configuration.list.xenserver", "", "Comma separated list of allowed additional configuration options", true);
private static final ConfigKey<String> VmwareAdditionalConfigAllowList = new ConfigKey<>("Advanced", String.class,
"allow.additional.vm.configuration.list.vmware", "", "Comma separated list of allowed additional configuration options.", true);
private static final ConfigKey<Boolean> VmDestroyForcestop = new ConfigKey<Boolean>("Advanced", Boolean.class, "vm.destroy.forcestop", "false",
"On destroy, force-stop takes this value ", true);
public static final List<HypervisorType> VM_STORAGE_MIGRATION_SUPPORTING_HYPERVISORS = new ArrayList<>(Arrays.asList(
HypervisorType.KVM,
HypervisorType.VMware,
HypervisorType.XenServer,
HypervisorType.Simulator
));
@Override
public UserVmVO getVirtualMachine(long vmId) {
return _vmDao.findById(vmId);
}
@Override
public List<? extends UserVm> getVirtualMachines(long hostId) {
return _vmDao.listByHostId(hostId);
}
private void resourceLimitCheck(Account owner, Boolean displayVm, Long cpu, Long memory) throws ResourceAllocationException {
_resourceLimitMgr.checkResourceLimit(owner, ResourceType.user_vm, displayVm);
_resourceLimitMgr.checkResourceLimit(owner, ResourceType.cpu, displayVm, cpu);
_resourceLimitMgr.checkResourceLimit(owner, ResourceType.memory, displayVm, memory);
}
protected void resourceCountIncrement(long accountId, Boolean displayVm, Long cpu, Long memory) {
if (! VirtualMachineManager.ResourceCountRunningVMsonly.value()) {
_resourceLimitMgr.incrementResourceCount(accountId, ResourceType.user_vm, displayVm);
_resourceLimitMgr.incrementResourceCount(accountId, ResourceType.cpu, displayVm, cpu);
_resourceLimitMgr.incrementResourceCount(accountId, ResourceType.memory, displayVm, memory);
}
}
protected void resourceCountDecrement(long accountId, Boolean displayVm, Long cpu, Long memory) {
if (! VirtualMachineManager.ResourceCountRunningVMsonly.value()) {
_resourceLimitMgr.decrementResourceCount(accountId, ResourceType.user_vm, displayVm);
_resourceLimitMgr.decrementResourceCount(accountId, ResourceType.cpu, displayVm, cpu);
_resourceLimitMgr.decrementResourceCount(accountId, ResourceType.memory, displayVm, memory);
}
}
public class VmAndCountDetails {
long vmId;
int retrievalCount = VmIpFetchTrialMax.value();
public VmAndCountDetails() {
}
public VmAndCountDetails (long vmId, int retrievalCount) {
this.vmId = vmId;
this.retrievalCount = retrievalCount;
}
public VmAndCountDetails (long vmId) {
this.vmId = vmId;
}
public int getRetrievalCount() {
return retrievalCount;
}
public void setRetrievalCount(int retrievalCount) {
this.retrievalCount = retrievalCount;
}
public long getVmId() {
return vmId;
}
public void setVmId(long vmId) {
this.vmId = vmId;
}
public void decrementCount() {
this.retrievalCount--;
}
}
private class VmIpAddrFetchThread extends ManagedContextRunnable {
long nicId;
long vmId;
String vmName;
boolean isWindows;
Long hostId;
String networkCidr;
public VmIpAddrFetchThread(long vmId, long nicId, String instanceName, boolean windows, Long hostId, String networkCidr) {
this.vmId = vmId;
this.nicId = nicId;
this.vmName = instanceName;
this.isWindows = windows;
this.hostId = hostId;
this.networkCidr = networkCidr;
}
@Override
protected void runInContext() {
GetVmIpAddressCommand cmd = new GetVmIpAddressCommand(vmName, networkCidr, isWindows);
boolean decrementCount = true;
try {
s_logger.debug("Trying for vm "+ vmId +" nic Id "+nicId +" ip retrieval ...");
Answer answer = _agentMgr.send(hostId, cmd);
NicVO nic = _nicDao.findById(nicId);
if (answer.getResult()) {
String vmIp = answer.getDetails();
if (NetUtils.isValidIp4(vmIp)) {
// set this vm ip addr in vm nic.
if (nic != null) {
nic.setIPv4Address(vmIp);
_nicDao.update(nicId, nic);
s_logger.debug("Vm "+ vmId +" IP "+vmIp +" got retrieved successfully");
vmIdCountMap.remove(nicId);
decrementCount = false;
ActionEventUtils.onActionEvent(User.UID_SYSTEM, Account.ACCOUNT_ID_SYSTEM,
Domain.ROOT_DOMAIN, EventTypes.EVENT_NETWORK_EXTERNAL_DHCP_VM_IPFETCH,
"VM " + vmId + " nic id " + nicId + " ip address " + vmIp + " got fetched successfully");
}
}
} else {
//previously vm has ip and nic table has ip address. After vm restart or stop/start
//if vm doesnot get the ip then set the ip in nic table to null
if (nic.getIPv4Address() != null) {
nic.setIPv4Address(null);
_nicDao.update(nicId, nic);
}
if (answer.getDetails() != null) {
s_logger.debug("Failed to get vm ip for Vm "+ vmId + answer.getDetails());
}
}
} catch (OperationTimedoutException e) {
s_logger.warn("Timed Out", e);
} catch (AgentUnavailableException e) {
s_logger.warn("Agent Unavailable ", e);
} finally {
if (decrementCount) {
VmAndCountDetails vmAndCount = vmIdCountMap.get(nicId);
vmAndCount.decrementCount();
s_logger.debug("Ip is not retrieved for VM " + vmId +" nic "+nicId + " ... decremented count to "+vmAndCount.getRetrievalCount());
vmIdCountMap.put(nicId, vmAndCount);
}
}
}
}
private void addVmUefiBootOptionsToParams(Map<VirtualMachineProfile.Param, Object> params, String bootType, String bootMode) {
if (s_logger.isTraceEnabled()) {
s_logger.trace(String.format("Adding boot options (%s, %s, %s) into the param map for VM start as UEFI detail(%s=%s) found for the VM",
VirtualMachineProfile.Param.UefiFlag.getName(),
VirtualMachineProfile.Param.BootType.getName(),
VirtualMachineProfile.Param.BootMode.getName(),
bootType,
bootMode));
}
params.put(VirtualMachineProfile.Param.UefiFlag, "Yes");
params.put(VirtualMachineProfile.Param.BootType, bootType);
params.put(VirtualMachineProfile.Param.BootMode, bootMode);
}
@Override
@ActionEvent(eventType = EventTypes.EVENT_VM_RESETPASSWORD, eventDescription = "resetting Vm password", async = true)
public UserVm resetVMPassword(ResetVMPasswordCmd cmd, String password) throws ResourceUnavailableException, InsufficientCapacityException {
Account caller = CallContext.current().getCallingAccount();
Long vmId = cmd.getId();
UserVmVO userVm = _vmDao.findById(cmd.getId());
// Do parameters input validation
if (userVm == null) {
throw new InvalidParameterValueException("unable to find a virtual machine with id " + cmd.getId());
}
_vmDao.loadDetails(userVm);
VMTemplateVO template = _templateDao.findByIdIncludingRemoved(userVm.getTemplateId());
if (template == null || !template.isEnablePassword()) {
throw new InvalidParameterValueException("Fail to reset password for the virtual machine, the template is not password enabled");
}
if (userVm.getState() == State.Error || userVm.getState() == State.Expunging) {
s_logger.error("vm is not in the right state: " + vmId);
throw new InvalidParameterValueException("Vm with id " + vmId + " is not in the right state");
}
if (userVm.getState() != State.Stopped) {
s_logger.error("vm is not in the right state: " + vmId);
throw new InvalidParameterValueException("Vm " + userVm + " should be stopped to do password reset");
}
_accountMgr.checkAccess(caller, null, true, userVm);
boolean result = resetVMPasswordInternal(vmId, password);
if (result) {
userVm.setPassword(password);
} else {
throw new CloudRuntimeException("Failed to reset password for the virtual machine ");
}
return userVm;
}
private boolean resetVMPasswordInternal(Long vmId, String password) throws ResourceUnavailableException, InsufficientCapacityException {
Long userId = CallContext.current().getCallingUserId();
VMInstanceVO vmInstance = _vmDao.findById(vmId);
if (password == null || password.equals("")) {
return false;
}
VMTemplateVO template = _templateDao.findByIdIncludingRemoved(vmInstance.getTemplateId());
if (template.isEnablePassword()) {
Nic defaultNic = _networkModel.getDefaultNic(vmId);
if (defaultNic == null) {
s_logger.error("Unable to reset password for vm " + vmInstance + " as the instance doesn't have default nic");
return false;
}
Network defaultNetwork = _networkDao.findById(defaultNic.getNetworkId());
NicProfile defaultNicProfile = new NicProfile(defaultNic, defaultNetwork, null, null, null, _networkModel.isSecurityGroupSupportedInNetwork(defaultNetwork),
_networkModel.getNetworkTag(template.getHypervisorType(), defaultNetwork));
VirtualMachineProfile vmProfile = new VirtualMachineProfileImpl(vmInstance);
vmProfile.setParameter(VirtualMachineProfile.Param.VmPassword, password);
UserDataServiceProvider element = _networkMgr.getPasswordResetProvider(defaultNetwork);
if (element == null) {
throw new CloudRuntimeException("Can't find network element for " + Service.UserData.getName() + " provider needed for password reset");
}
boolean result = element.savePassword(defaultNetwork, defaultNicProfile, vmProfile);
// Need to reboot the virtual machine so that the password gets
// redownloaded from the DomR, and reset on the VM
if (!result) {
s_logger.debug("Failed to reset password for the virtual machine; no need to reboot the vm");
return false;
} else {
final UserVmVO userVm = _vmDao.findById(vmId);
_vmDao.loadDetails(userVm);
// update the password in vm_details table too
// Check if an SSH key pair was selected for the instance and if so
// use it to encrypt & save the vm password
encryptAndStorePassword(userVm, password);
if (vmInstance.getState() == State.Stopped) {
s_logger.debug("Vm " + vmInstance + " is stopped, not rebooting it as a part of password reset");
return true;
}
if (rebootVirtualMachine(userId, vmId, false, false) == null) {
s_logger.warn("Failed to reboot the vm " + vmInstance);
return false;
} else {
s_logger.debug("Vm " + vmInstance + " is rebooted successfully as a part of password reset");
return true;
}
}
} else {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Reset password called for a vm that is not using a password enabled template");
}
return false;
}
}
@Override
@ActionEvent(eventType = EventTypes.EVENT_VM_RESETSSHKEY, eventDescription = "resetting Vm SSHKey", async = true)
public UserVm resetVMSSHKey(ResetVMSSHKeyCmd cmd) throws ResourceUnavailableException, InsufficientCapacityException {
Account caller = CallContext.current().getCallingAccount();
Account owner = _accountMgr.finalizeOwner(caller, cmd.getAccountName(), cmd.getDomainId(), cmd.getProjectId());
Long vmId = cmd.getId();
UserVmVO userVm = _vmDao.findById(cmd.getId());
if (userVm == null) {
throw new InvalidParameterValueException("unable to find a virtual machine by id" + cmd.getId());
}
VMTemplateVO template = _templateDao.findByIdIncludingRemoved(userVm.getTemplateId());
// Do parameters input validation
if (userVm.getState() == State.Error || userVm.getState() == State.Expunging) {
s_logger.error("vm is not in the right state: " + vmId);
throw new InvalidParameterValueException("Vm with specified id is not in the right state");
}
if (userVm.getState() != State.Stopped) {
s_logger.error("vm is not in the right state: " + vmId);
throw new InvalidParameterValueException("Vm " + userVm + " should be stopped to do SSH Key reset");
}
SSHKeyPairVO s = _sshKeyPairDao.findByName(owner.getAccountId(), owner.getDomainId(), cmd.getName());
if (s == null) {
throw new InvalidParameterValueException("A key pair with name '" + cmd.getName() + "' does not exist for account " + owner.getAccountName()
+ " in specified domain id");
}
_accountMgr.checkAccess(caller, null, true, userVm);
String sshPublicKey = s.getPublicKey();
boolean result = resetVMSSHKeyInternal(vmId, sshPublicKey);
if (!result) {
throw new CloudRuntimeException("Failed to reset SSH Key for the virtual machine ");
}
removeEncryptedPasswordFromUserVmVoDetails(vmId);
_vmDao.loadDetails(userVm);
return userVm;
}
protected void removeEncryptedPasswordFromUserVmVoDetails(long vmId) {
userVmDetailsDao.removeDetail(vmId, VmDetailConstants.ENCRYPTED_PASSWORD);
}
private boolean resetVMSSHKeyInternal(Long vmId, String sshPublicKey) throws ResourceUnavailableException, InsufficientCapacityException {
Long userId = CallContext.current().getCallingUserId();
VMInstanceVO vmInstance = _vmDao.findById(vmId);
VMTemplateVO template = _templateDao.findByIdIncludingRemoved(vmInstance.getTemplateId());
Nic defaultNic = _networkModel.getDefaultNic(vmId);
if (defaultNic == null) {
s_logger.error("Unable to reset SSH Key for vm " + vmInstance + " as the instance doesn't have default nic");
return false;
}
Network defaultNetwork = _networkDao.findById(defaultNic.getNetworkId());
NicProfile defaultNicProfile = new NicProfile(defaultNic, defaultNetwork, null, null, null, _networkModel.isSecurityGroupSupportedInNetwork(defaultNetwork),
_networkModel.getNetworkTag(template.getHypervisorType(), defaultNetwork));
VirtualMachineProfile vmProfile = new VirtualMachineProfileImpl(vmInstance);
UserDataServiceProvider element = _networkMgr.getSSHKeyResetProvider(defaultNetwork);
if (element == null) {
throw new CloudRuntimeException("Can't find network element for " + Service.UserData.getName() + " provider needed for SSH Key reset");
}
boolean result = element.saveSSHKey(defaultNetwork, defaultNicProfile, vmProfile, sshPublicKey);
// Need to reboot the virtual machine so that the password gets redownloaded from the DomR, and reset on the VM
if (!result) {
s_logger.debug("Failed to reset SSH Key for the virtual machine; no need to reboot the vm");
return false;
} else {
final UserVmVO userVm = _vmDao.findById(vmId);
_vmDao.loadDetails(userVm);
userVm.setDetail(VmDetailConstants.SSH_PUBLIC_KEY, sshPublicKey);
_vmDao.saveDetails(userVm);
if (vmInstance.getState() == State.Stopped) {
s_logger.debug("Vm " + vmInstance + " is stopped, not rebooting it as a part of SSH Key reset");
return true;
}
if (rebootVirtualMachine(userId, vmId, false, false) == null) {
s_logger.warn("Failed to reboot the vm " + vmInstance);
return false;
} else {
s_logger.debug("Vm " + vmInstance + " is rebooted successfully as a part of SSH Key reset");
return true;
}
}
}
@Override
public boolean stopVirtualMachine(long userId, long vmId) {
boolean status = false;
if (s_logger.isDebugEnabled()) {
s_logger.debug("Stopping vm=" + vmId);
}
UserVmVO vm = _vmDao.findById(vmId);
if (vm == null || vm.getRemoved() != null) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("VM is either removed or deleted.");
}
return true;
}
_userDao.findById(userId);
try {
VirtualMachineEntity vmEntity = _orchSrvc.getVirtualMachine(vm.getUuid());
status = vmEntity.stop(Long.toString(userId));
} catch (ResourceUnavailableException e) {
s_logger.debug("Unable to stop due to ", e);
status = false;
} catch (CloudException e) {
throw new CloudRuntimeException("Unable to contact the agent to stop the virtual machine " + vm, e);