forked from apache/cloudstack
-
Notifications
You must be signed in to change notification settings - Fork 3
/
CitrixResourceBase.java
5607 lines (4931 loc) · 240 KB
/
CitrixResourceBase.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.hypervisor.xenserver.resource;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;
import java.util.Queue;
import java.util.Random;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeoutException;
import javax.naming.ConfigurationException;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.cloudstack.storage.to.TemplateObjectTO;
import org.apache.cloudstack.storage.to.VolumeObjectTO;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.log4j.Logger;
import org.apache.xmlrpc.XmlRpcException;
import org.joda.time.Duration;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import com.cloud.agent.IAgentControl;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.Command;
import com.cloud.agent.api.GetHostStatsCommand;
import com.cloud.agent.api.GetVmStatsCommand;
import com.cloud.agent.api.HostStatsEntry;
import com.cloud.agent.api.HostVmStateReportEntry;
import com.cloud.agent.api.PingCommand;
import com.cloud.agent.api.PingRoutingCommand;
import com.cloud.agent.api.PingRoutingWithNwGroupsCommand;
import com.cloud.agent.api.PingRoutingWithOvsCommand;
import com.cloud.agent.api.RebootAnswer;
import com.cloud.agent.api.RebootCommand;
import com.cloud.agent.api.SetupGuestNetworkCommand;
import com.cloud.agent.api.StartAnswer;
import com.cloud.agent.api.StartCommand;
import com.cloud.agent.api.StartupCommand;
import com.cloud.agent.api.StartupRoutingCommand;
import com.cloud.agent.api.StartupStorageCommand;
import com.cloud.agent.api.StopAnswer;
import com.cloud.agent.api.StopCommand;
import com.cloud.agent.api.StoragePoolInfo;
import com.cloud.agent.api.VgpuTypesInfo;
import com.cloud.agent.api.VmStatsEntry;
import com.cloud.agent.api.routing.IpAssocCommand;
import com.cloud.agent.api.routing.IpAssocVpcCommand;
import com.cloud.agent.api.routing.NetworkElementCommand;
import com.cloud.agent.api.routing.SetNetworkACLCommand;
import com.cloud.agent.api.routing.SetSourceNatCommand;
import com.cloud.agent.api.to.DataStoreTO;
import com.cloud.agent.api.to.DataTO;
import com.cloud.agent.api.to.DiskTO;
import com.cloud.agent.api.to.GPUDeviceTO;
import com.cloud.agent.api.to.IpAddressTO;
import com.cloud.agent.api.to.NfsTO;
import com.cloud.agent.api.to.NicTO;
import com.cloud.agent.api.to.VirtualMachineTO;
import com.cloud.agent.resource.virtualnetwork.VRScripts;
import com.cloud.agent.resource.virtualnetwork.VirtualRouterDeployer;
import com.cloud.agent.resource.virtualnetwork.VirtualRoutingResource;
import com.cloud.exception.InternalErrorException;
import com.cloud.host.Host.Type;
import com.cloud.hypervisor.Hypervisor.HypervisorType;
import com.cloud.hypervisor.xenserver.resource.wrapper.xenbase.CitrixRequestWrapper;
import com.cloud.hypervisor.xenserver.resource.wrapper.xenbase.XenServerUtilitiesHelper;
import com.cloud.network.Networks;
import com.cloud.network.Networks.BroadcastDomainType;
import com.cloud.network.Networks.TrafficType;
import com.cloud.resource.ServerResource;
import com.cloud.resource.hypervisor.HypervisorResource;
import com.cloud.storage.Storage;
import com.cloud.storage.Storage.StoragePoolType;
import com.cloud.storage.Volume;
import com.cloud.storage.VolumeVO;
import com.cloud.storage.resource.StorageSubsystemCommandHandler;
import com.cloud.storage.resource.StorageSubsystemCommandHandlerBase;
import com.cloud.template.VirtualMachineTemplate.BootloaderType;
import com.cloud.utils.ExecutionResult;
import com.cloud.utils.NumbersUtil;
import com.cloud.utils.Pair;
import com.cloud.utils.PropertiesUtil;
import com.cloud.utils.StringUtils;
import com.cloud.utils.Ternary;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.net.NetUtils;
import com.cloud.utils.script.Script;
import com.cloud.utils.ssh.SSHCmdHelper;
import com.cloud.utils.ssh.SshHelper;
import com.cloud.vm.VirtualMachine;
import com.cloud.vm.VirtualMachine.PowerState;
import com.cloud.vm.VmDetailConstants;
import com.trilead.ssh2.SCPClient;
import com.xensource.xenapi.Bond;
import com.xensource.xenapi.Connection;
import com.xensource.xenapi.Console;
import com.xensource.xenapi.Host;
import com.xensource.xenapi.HostCpu;
import com.xensource.xenapi.HostMetrics;
import com.xensource.xenapi.Network;
import com.xensource.xenapi.PBD;
import com.xensource.xenapi.PIF;
import com.xensource.xenapi.Pool;
import com.xensource.xenapi.SR;
import com.xensource.xenapi.Session;
import com.xensource.xenapi.Task;
import com.xensource.xenapi.Types;
import com.xensource.xenapi.Types.BadServerResponse;
import com.xensource.xenapi.Types.VmPowerState;
import com.xensource.xenapi.Types.XenAPIException;
import com.xensource.xenapi.VBD;
import com.xensource.xenapi.VDI;
import com.xensource.xenapi.VIF;
import com.xensource.xenapi.VLAN;
import com.xensource.xenapi.VM;
import com.xensource.xenapi.XenAPIObject;
/**
* CitrixResourceBase encapsulates the calls to the XenServer Xapi process to
* perform the required functionalities for CloudStack.
*
* ==============> READ THIS <============== Because the XenServer objects can
* expire when the session expires, we cannot keep any of the actual XenServer
* objects in this class. The only thing that is constant is the UUID of the
* XenServer objects but not the objects themselves! This is very important
* before you do any changes in this code here.
*
*/
public abstract class CitrixResourceBase implements ServerResource, HypervisorResource, VirtualRouterDeployer {
/**
* used to describe what type of resource a storage device is of
*/
public enum SRType {
EXT, ISO, LVM, LVMOHBA, LVMOISCSI,
/**
* used for resigning metadata (like SR UUID and VDI UUID when a
* particular storage manager is installed on a XenServer host (for back-end snapshots to work))
*/
RELVMOISCSI, NFS;
String _str;
private SRType() {
_str = super.toString().toLowerCase();
}
public boolean equals(final String type) {
return _str.equalsIgnoreCase(type);
}
@Override
public String toString() {
return _str;
}
}
private final static int BASE_TO_CONVERT_BYTES_INTO_KILOBYTES = 1024;
private static final XenServerConnectionPool ConnPool = XenServerConnectionPool.getInstance();
// static min values for guests on xenserver
private static final long mem_128m = 134217728L;
static final Random Rand = new Random(System.currentTimeMillis());
private static final Logger s_logger = Logger.getLogger(CitrixResourceBase.class);
protected static final HashMap<VmPowerState, PowerState> s_powerStatesTable;
private String xenServer70plusGuestToolsName = "guest-tools.iso";
private String xenServerBefore70GuestToolsName = "xs-tools.iso";
static {
s_powerStatesTable = new HashMap<VmPowerState, PowerState>();
s_powerStatesTable.put(VmPowerState.HALTED, PowerState.PowerOff);
s_powerStatesTable.put(VmPowerState.PAUSED, PowerState.PowerOff);
s_powerStatesTable.put(VmPowerState.RUNNING, PowerState.PowerOn);
s_powerStatesTable.put(VmPowerState.SUSPENDED, PowerState.PowerOff);
s_powerStatesTable.put(VmPowerState.UNRECOGNIZED, PowerState.PowerUnknown);
}
private static PowerState convertToPowerState(final VmPowerState ps) {
final PowerState powerState = s_powerStatesTable.get(ps);
return powerState == null ? PowerState.PowerUnknown : powerState;
}
private static boolean isAlienVm(final VM vm, final Connection conn) throws XenAPIException, XmlRpcException {
// TODO : we need a better way to tell whether or not the VM belongs to
// CloudStack
final String vmName = vm.getNameLabel(conn);
if (vmName.matches("^[ivs]-\\d+-.+")) {
return false;
}
return true;
}
protected IAgentControl _agentControl;
protected boolean _canBridgeFirewall = false;
protected String _cluster;
// Guest and Host Performance Statistics
protected String _consolidationFunction = "AVERAGE";
protected long _dcId;
protected String _guestNetworkName;
protected int _heartbeatInterval = 60;
protected int _heartbeatTimeout = 120;
protected XsHost _host = new XsHost();
protected String _instance; // instance name (default is usually "VM")
protected boolean _isOvs = false;
protected String _linkLocalPrivateNetworkName;
protected int _maxNics = 7;
final int _maxWeight = 256;
protected int _migratewait;
protected String _name;
protected Queue<String> _password = new LinkedList<String>();
protected String _pod;
protected int _pollingIntervalInSeconds = 60;
protected String _privateNetworkName;
protected String _publicNetworkName;
protected final int _retry = 100;
protected boolean _securityGroupEnabled;
protected final int _sleep = 10000;
protected String _storageNetworkName1;
protected String _storageNetworkName2;
protected List<VIF> _tmpDom0Vif = new ArrayList<VIF>();
protected String _username;
protected VirtualRoutingResource _vrResource;
protected String _configDriveIsopath = "/opt/xensource/packages/configdrive_iso/";
protected String _configDriveSRName = "ConfigDriveISOs";
public String _attachIsoDeviceNum = "3";
protected XenServerUtilitiesHelper xenServerUtilitiesHelper = new XenServerUtilitiesHelper();
protected int _wait;
// Hypervisor specific params with generic value, may need to be overridden
// for specific versions
long _xsMemoryUsed = 128 * 1024 * 1024L; // xenserver hypervisor used 128 M
double _xsVirtualizationFactor = 63.0 / 64.0; // 1 - virtualization overhead
protected StorageSubsystemCommandHandler storageHandler;
private static final String XENSTORE_DATA_IP = "vm-data/ip";
private static final String XENSTORE_DATA_GATEWAY = "vm-data/gateway";
private static final String XENSTORE_DATA_NETMASK = "vm-data/netmask";
private static final String XENSTORE_DATA_CS_INIT = "vm-data/cloudstack/init";
public CitrixResourceBase() {
}
/**
* Replaces the old password with the new password used to connect to the host.
*
* @param password - the new host password.
* @return the old password.
*/
public String replaceOldPasswdInQueue(final String password) {
final String oldPasswd = _password.poll();
_password.add(password);
return oldPasswd;
}
public String getPwdFromQueue() {
return _password.peek();
}
public XenServerUtilitiesHelper getXenServerUtilitiesHelper() {
return xenServerUtilitiesHelper;
}
protected StorageSubsystemCommandHandler buildStorageHandler() {
final XenServerStorageProcessor processor = new XenServerStorageProcessor(this);
return new StorageSubsystemCommandHandlerBase(processor);
}
public String callHostPlugin(final Connection conn, final String plugin, final String cmd, final String... params) {
final Map<String, String> args = new HashMap<String, String>();
String msg;
try {
for (int i = 0; i < params.length; i += 2) {
args.put(params[i], params[i + 1]);
}
if (s_logger.isTraceEnabled()) {
s_logger.trace("callHostPlugin executing for command " + cmd + " with " + getArgsString(args));
}
final Host host = Host.getByUuid(conn, _host.getUuid());
final String result = host.callPlugin(conn, plugin, cmd, args);
if (s_logger.isTraceEnabled()) {
s_logger.trace("callHostPlugin Result: " + result);
}
return result.replace("\n", "");
} catch (final XenAPIException e) {
msg = "callHostPlugin failed for cmd: " + cmd + " with args " + getArgsString(args) + " due to " + e.toString();
s_logger.warn(msg);
} catch (final XmlRpcException e) {
msg = "callHostPlugin failed for cmd: " + cmd + " with args " + getArgsString(args) + " due to " + e.getMessage();
s_logger.debug(msg);
}
throw new CloudRuntimeException(msg);
}
protected String callHostPluginAsync(final Connection conn, final String plugin, final String cmd, final int wait, final Map<String, String> params) {
final int timeout = wait * 1000;
final Map<String, String> args = new HashMap<String, String>();
Task task = null;
try {
for (final Map.Entry<String, String> entry : params.entrySet()) {
args.put(entry.getKey(), entry.getValue());
}
if (s_logger.isTraceEnabled()) {
s_logger.trace("callHostPlugin executing for command " + cmd + " with " + getArgsString(args));
}
final Host host = Host.getByUuid(conn, _host.getUuid());
task = host.callPluginAsync(conn, plugin, cmd, args);
// poll every 1 seconds
waitForTask(conn, task, 1000, timeout);
checkForSuccess(conn, task);
final String result = task.getResult(conn);
if (s_logger.isTraceEnabled()) {
s_logger.trace("callHostPlugin Result: " + result);
}
return result.replace("<value>", "").replace("</value>", "").replace("\n", "");
} catch (final Types.HandleInvalid e) {
s_logger.warn("callHostPlugin failed for cmd: " + cmd + " with args " + getArgsString(args) + " due to HandleInvalid clazz:" + e.clazz + ", handle:" + e.handle);
} catch (final Exception e) {
s_logger.warn("callHostPlugin failed for cmd: " + cmd + " with args " + getArgsString(args) + " due to " + e.toString(), e);
} finally {
if (task != null) {
try {
task.destroy(conn);
} catch (final Exception e1) {
s_logger.debug("unable to destroy task(" + task.toString() + ") on host(" + _host.getUuid() + ") due to " + e1.toString());
}
}
}
return null;
}
protected String callHostPluginAsync(final Connection conn, final String plugin, final String cmd, final int wait, final String... params) {
final int timeout = wait * 1000;
final Map<String, String> args = new HashMap<String, String>();
Task task = null;
try {
for (int i = 0; i < params.length; i += 2) {
args.put(params[i], params[i + 1]);
}
if (s_logger.isTraceEnabled()) {
s_logger.trace("callHostPlugin executing for command " + cmd + " with " + getArgsString(args));
}
final Host host = Host.getByUuid(conn, _host.getUuid());
task = host.callPluginAsync(conn, plugin, cmd, args);
// poll every 1 seconds
waitForTask(conn, task, 1000, timeout);
checkForSuccess(conn, task);
final String result = task.getResult(conn);
if (s_logger.isTraceEnabled()) {
s_logger.trace("callHostPlugin Result: " + result);
}
return result.replace("<value>", "").replace("</value>", "").replace("\n", "");
} catch (final Types.HandleInvalid e) {
s_logger.warn("callHostPlugin failed for cmd: " + cmd + " with args " + getArgsString(args) + " due to HandleInvalid clazz:" + e.clazz + ", handle:" + e.handle);
} catch (final XenAPIException e) {
s_logger.warn("callHostPlugin failed for cmd: " + cmd + " with args " + getArgsString(args) + " due to " + e.toString(), e);
} catch (final Exception e) {
s_logger.warn("callHostPlugin failed for cmd: " + cmd + " with args " + getArgsString(args) + " due to " + e.getMessage(), e);
} finally {
if (task != null) {
try {
task.destroy(conn);
} catch (final Exception e1) {
s_logger.debug("unable to destroy task(" + task.toString() + ") on host(" + _host.getUuid() + ") due to " + e1.toString());
}
}
}
return null;
}
public String callHostPluginPremium(final Connection conn, final String cmd, final String... params) {
return callHostPlugin(conn, "vmopspremium", cmd, params);
}
protected String callHostPluginThroughMaster(final Connection conn, final String plugin, final String cmd, final String... params) {
final Map<String, String> args = new HashMap<String, String>();
try {
final Map<Pool, Pool.Record> poolRecs = Pool.getAllRecords(conn);
if (poolRecs.size() != 1) {
throw new CloudRuntimeException("There are " + poolRecs.size() + " pool for host :" + _host.getUuid());
}
final Host master = poolRecs.values().iterator().next().master;
for (int i = 0; i < params.length; i += 2) {
args.put(params[i], params[i + 1]);
}
if (s_logger.isTraceEnabled()) {
s_logger.trace("callHostPlugin executing for command " + cmd + " with " + getArgsString(args));
}
final String result = master.callPlugin(conn, plugin, cmd, args);
if (s_logger.isTraceEnabled()) {
s_logger.trace("callHostPlugin Result: " + result);
}
return result.replace("\n", "");
} catch (final Types.HandleInvalid e) {
s_logger.warn("callHostPlugin failed for cmd: " + cmd + " with args " + getArgsString(args) + " due to HandleInvalid clazz:" + e.clazz + ", handle:" + e.handle);
} catch (final XenAPIException e) {
s_logger.warn("callHostPlugin failed for cmd: " + cmd + " with args " + getArgsString(args) + " due to " + e.toString(), e);
} catch (final XmlRpcException e) {
s_logger.warn("callHostPlugin failed for cmd: " + cmd + " with args " + getArgsString(args) + " due to " + e.getMessage(), e);
}
return null;
}
public boolean canBridgeFirewall() {
return _canBridgeFirewall;
}
public boolean canBridgeFirewall(final Connection conn) {
return Boolean.valueOf(callHostPlugin(conn, "vmops", "can_bridge_firewall", "host_uuid", _host.getUuid(), "instance", _instance));
}
public void checkForSuccess(final Connection c, final Task task) throws XenAPIException, XmlRpcException {
if (task.getStatus(c) == Types.TaskStatusType.SUCCESS) {
if (s_logger.isTraceEnabled()) {
s_logger.trace("Task " + task.getNameLabel(c) + " (" + task.getUuid(c) + ") completed");
}
return;
} else {
final String msg = "Task failed! Task record: " + task.getRecord(c);
s_logger.warn(msg);
task.cancel(c);
task.destroy(c);
throw new Types.BadAsyncResult(msg);
}
}
protected boolean checkSR(final Connection conn, final SR sr) {
try {
final SR.Record srr = sr.getRecord(conn);
final Set<PBD> pbds = sr.getPBDs(conn);
if (pbds.size() == 0) {
final String msg = "There is no PBDs for this SR: " + srr.nameLabel + " on host:" + _host.getUuid();
s_logger.warn(msg);
return false;
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("Checking " + srr.nameLabel + " or SR " + srr.uuid + " on " + _host);
}
if (srr.shared) {
if (SRType.NFS.equals(srr.type)) {
final Map<String, String> smConfig = srr.smConfig;
if (!smConfig.containsKey("nosubdir")) {
smConfig.put("nosubdir", "true");
sr.setSmConfig(conn, smConfig);
}
}
final Host host = Host.getByUuid(conn, _host.getUuid());
boolean found = false;
for (final PBD pbd : pbds) {
final PBD.Record pbdr = pbd.getRecord(conn);
if (host.equals(pbdr.host)) {
if (!pbdr.currentlyAttached) {
pbdPlug(conn, pbd, pbdr.uuid);
}
found = true;
break;
}
}
if (!found) {
final PBD.Record pbdr = srr.PBDs.iterator().next().getRecord(conn);
pbdr.host = host;
pbdr.uuid = "";
final PBD pbd = PBD.create(conn, pbdr);
pbdPlug(conn, pbd, pbd.getUuid(conn));
}
} else {
for (final PBD pbd : pbds) {
final PBD.Record pbdr = pbd.getRecord(conn);
if (!pbdr.currentlyAttached) {
pbdPlug(conn, pbd, pbdr.uuid);
}
}
}
} catch (final Exception e) {
final String msg = "checkSR failed host:" + _host + " due to " + e.toString();
s_logger.warn(msg, e);
return false;
}
return true;
}
private void CheckXenHostInfo() throws ConfigurationException {
final Connection conn = ConnPool.getConnect(_host.getIp(), _username, _password);
if (conn == null) {
throw new ConfigurationException("Can not create connection to " + _host.getIp());
}
try {
Host.Record hostRec = null;
try {
final Host host = Host.getByUuid(conn, _host.getUuid());
hostRec = host.getRecord(conn);
final Pool.Record poolRec = Pool.getAllRecords(conn).values().iterator().next();
_host.setPool(poolRec.uuid);
} catch (final Exception e) {
throw new ConfigurationException("Can not get host information from " + _host.getIp());
}
if (!hostRec.address.equals(_host.getIp())) {
final String msg = "Host " + _host.getIp() + " seems be reinstalled, please remove this host and readd";
s_logger.error(msg);
throw new ConfigurationException(msg);
}
} finally {
try {
Session.logout(conn);
} catch (final Exception e) {
}
}
}
@Override
public ExecutionResult cleanupCommand(final NetworkElementCommand cmd) {
if (cmd instanceof IpAssocCommand && !(cmd instanceof IpAssocVpcCommand)) {
return cleanupNetworkElementCommand((IpAssocCommand)cmd);
}
return new ExecutionResult(true, null);
}
public boolean cleanupHaltedVms(final Connection conn) throws XenAPIException, XmlRpcException {
final Host host = Host.getByUuid(conn, _host.getUuid());
final Map<VM, VM.Record> vms = VM.getAllRecords(conn);
boolean success = true;
if (vms != null && !vms.isEmpty()) {
for (final Map.Entry<VM, VM.Record> entry : vms.entrySet()) {
final VM vm = entry.getKey();
final VM.Record vmRec = entry.getValue();
if (vmRec.isATemplate || vmRec.isControlDomain) {
continue;
}
if (VmPowerState.HALTED.equals(vmRec.powerState) && vmRec.affinity.equals(host) && !isAlienVm(vm, conn)) {
try {
vm.destroy(conn);
} catch (final Exception e) {
s_logger.warn("Catch Exception " + e.getClass().getName() + ": unable to destroy VM " + vmRec.nameLabel + " due to ", e);
success = false;
}
}
}
}
return success;
}
protected ExecutionResult cleanupNetworkElementCommand(final IpAssocCommand cmd) {
final Connection conn = getConnection();
final String routerName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME);
final String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
final String lastIp = cmd.getAccessDetail(NetworkElementCommand.NETWORK_PUB_LAST_IP);
try {
final IpAddressTO[] ips = cmd.getIpAddresses();
for (final IpAddressTO ip : ips) {
final VM router = getVM(conn, routerName);
final NicTO nic = new NicTO();
nic.setMac(ip.getVifMacAddress());
nic.setType(ip.getTrafficType());
if (ip.getBroadcastUri() == null) {
nic.setBroadcastType(BroadcastDomainType.Native);
} else {
final URI uri = BroadcastDomainType.fromString(ip.getBroadcastUri());
nic.setBroadcastType(BroadcastDomainType.getSchemeValue(uri));
nic.setBroadcastUri(uri);
}
nic.setDeviceId(0);
nic.setNetworkRateMbps(ip.getNetworkRate());
nic.setName(ip.getNetworkName());
Network network = getNetwork(conn, nic);
// If we are disassociating the last IP address in the VLAN, we
// need
// to remove a VIF
boolean removeVif = false;
// there is only one ip in this public vlan and removing it, so
// remove the nic
if (org.apache.commons.lang.StringUtils.equalsIgnoreCase(lastIp, "true") && !ip.isAdd()) {
final VIF correctVif = getCorrectVif(conn, router, network);
// in isolated network eth2 is the default public interface. We don't want to delete it.
if (correctVif != null && !correctVif.getDevice(conn).equals("2")) {
removeVif = true;
}
}
if (removeVif) {
// Determine the correct VIF on DomR to
// associate/disassociate the
// IP address with
final VIF correctVif = getCorrectVif(conn, router, network);
if (correctVif != null) {
network = correctVif.getNetwork(conn);
// Mark this vif to be removed from network usage
networkUsage(conn, routerIp, "deleteVif", "eth" + correctVif.getDevice(conn));
// Remove the VIF from DomR
correctVif.unplug(conn);
correctVif.destroy(conn);
// Disable the VLAN network if necessary
disableVlanNetwork(conn, network);
}
}
}
} catch (final Exception e) {
s_logger.debug("Ip Assoc failure on applying one ip due to exception: ", e);
return new ExecutionResult(false, e.getMessage());
}
return new ExecutionResult(true, null);
}
public void cleanupTemplateSR(final Connection conn) {
Set<PBD> pbds = null;
try {
final Host host = Host.getByUuid(conn, _host.getUuid());
pbds = host.getPBDs(conn);
} catch (final XenAPIException e) {
s_logger.warn("Unable to get the SRs " + e.toString(), e);
throw new CloudRuntimeException("Unable to get SRs " + e.toString(), e);
} catch (final Exception e) {
throw new CloudRuntimeException("Unable to get SRs " + e.getMessage(), e);
}
for (final PBD pbd : pbds) {
SR sr = null;
SR.Record srRec = null;
try {
sr = pbd.getSR(conn);
srRec = sr.getRecord(conn);
} catch (final Exception e) {
s_logger.warn("pbd.getSR get Exception due to ", e);
continue;
}
final String type = srRec.type;
if (srRec.shared) {
continue;
}
if (SRType.NFS.equals(type) || SRType.ISO.equals(type) && srRec.nameDescription.contains("template")) {
try {
pbd.unplug(conn);
pbd.destroy(conn);
sr.forget(conn);
} catch (final Exception e) {
s_logger.warn("forget SR catch Exception due to ", e);
}
}
}
}
public void cleanUpTmpDomVif(final Connection conn, final Network nw) throws XenAPIException, XmlRpcException {
final Pair<VM, VM.Record> vm = getControlDomain(conn);
final VM dom0 = vm.first();
final Set<VIF> dom0Vifs = dom0.getVIFs(conn);
for (final VIF v : dom0Vifs) {
String vifName = "unknown";
try {
final VIF.Record vifr = v.getRecord(conn);
if (v.getNetwork(conn).getUuid(conn).equals(nw.getUuid(conn))) {
if (vifr != null) {
final Map<String, String> config = vifr.otherConfig;
vifName = config.get("nameLabel");
}
s_logger.debug("A VIF in dom0 for the network is found - so destroy the vif");
v.destroy(conn);
s_logger.debug("Destroy temp dom0 vif" + vifName + " success");
}
} catch (final Exception e) {
s_logger.warn("Destroy temp dom0 vif " + vifName + "failed", e);
}
}
}
protected VDI cloudVDIcopy(final Connection conn, final VDI vdi, final SR sr, int wait) throws Exception {
Task task = null;
if (wait == 0) {
wait = 2 * 60 * 60;
}
try {
task = vdi.copyAsync(conn, sr);
// poll every 1 seconds , timeout after 2 hours
waitForTask(conn, task, 1000, (long)wait * 1000);
checkForSuccess(conn, task);
final VDI dvdi = Types.toVDI(task, conn);
return dvdi;
} finally {
if (task != null) {
try {
task.destroy(conn);
} catch (final Exception e) {
s_logger.debug("unable to destroy task(" + task.toString() + ") on host(" + _host.getUuid() + ") due to " + e.toString());
}
}
}
}
public HashMap<String, String> clusterVMMetaDataSync(final Connection conn) {
final HashMap<String, String> vmMetaDatum = new HashMap<String, String>();
try {
final Map<VM, VM.Record> vm_map = VM.getAllRecords(conn); // USE
if (vm_map != null) {
for (final VM.Record record : vm_map.values()) {
if (record.isControlDomain || record.isASnapshot || record.isATemplate) {
continue; // Skip DOM0
}
final String platform = StringUtils.mapToString(record.platform);
if (platform.isEmpty()) {
continue; //Skip if platform is null
}
vmMetaDatum.put(record.nameLabel, StringUtils.mapToString(record.platform));
}
}
} catch (final Throwable e) {
final String msg = "Unable to get vms through host " + _host.getUuid() + " due to to " + e.toString();
s_logger.warn(msg, e);
throw new CloudRuntimeException(msg);
}
return vmMetaDatum;
}
@Override
public boolean configure(final String name, final Map<String, Object> params) throws ConfigurationException {
_name = name;
try {
_dcId = Long.parseLong((String)params.get("zone"));
} catch (final NumberFormatException e) {
throw new ConfigurationException("Unable to get the zone " + params.get("zone"));
}
_host.setUuid((String)params.get("guid"));
_name = _host.getUuid();
_host.setIp((String)params.get("ipaddress"));
_username = (String)params.get("username");
_password.add((String)params.get("password"));
_pod = (String)params.get("pod");
_cluster = (String)params.get("cluster");
_privateNetworkName = (String)params.get("private.network.device");
_publicNetworkName = (String)params.get("public.network.device");
_guestNetworkName = (String)params.get("guest.network.device");
_instance = (String)params.get("instance.name");
_securityGroupEnabled = Boolean.parseBoolean((String)params.get("securitygroupenabled"));
_linkLocalPrivateNetworkName = (String)params.get("private.linkLocal.device");
if (_linkLocalPrivateNetworkName == null) {
_linkLocalPrivateNetworkName = "cloud_link_local_network";
}
_storageNetworkName1 = (String)params.get("storage.network.device1");
_storageNetworkName2 = (String)params.get("storage.network.device2");
_heartbeatTimeout = NumbersUtil.parseInt((String)params.get("xenserver.heartbeat.timeout"), 120);
_heartbeatInterval = NumbersUtil.parseInt((String)params.get("xenserver.heartbeat.interval"), 60);
String value = (String)params.get("wait");
_wait = NumbersUtil.parseInt(value, 600);
value = (String)params.get("migratewait");
_migratewait = NumbersUtil.parseInt(value, 3600);
_maxNics = NumbersUtil.parseInt((String)params.get("xenserver.nics.max"), 7);
if (_pod == null) {
throw new ConfigurationException("Unable to get the pod");
}
if (_host.getIp() == null) {
throw new ConfigurationException("Unable to get the host address");
}
if (_username == null) {
throw new ConfigurationException("Unable to get the username");
}
if (_password.peek() == null) {
throw new ConfigurationException("Unable to get the password");
}
if (_host.getUuid() == null) {
throw new ConfigurationException("Unable to get the uuid");
}
CheckXenHostInfo();
storageHandler = buildStorageHandler();
_vrResource = new VirtualRoutingResource(this);
if (!_vrResource.configure(name, params)) {
throw new ConfigurationException("Unable to configure VirtualRoutingResource");
}
return true;
}
/**
* This method creates a XenServer network and configures it for being used
* as a L2-in-L3 tunneled network
*/
public synchronized Network configureTunnelNetwork(final Connection conn, final Long networkId, final long hostId, final String bridgeName) {
try {
final Network nw = findOrCreateTunnelNetwork(conn, bridgeName);
// Invoke plugin to setup the bridge which will be used by this
// network
final String bridge = nw.getBridge(conn);
final Map<String, String> nwOtherConfig = nw.getOtherConfig(conn);
final String configuredHosts = nwOtherConfig.get("ovs-host-setup");
boolean configured = false;
if (configuredHosts != null) {
final String hostIdsStr[] = configuredHosts.split(",");
for (final String hostIdStr : hostIdsStr) {
if (hostIdStr.equals(((Long)hostId).toString())) {
configured = true;
break;
}
}
}
if (!configured) {
String result;
if (bridgeName.startsWith("OVS-DR-VPC-Bridge")) {
result = callHostPlugin(conn, "ovstunnel", "setup_ovs_bridge_for_distributed_routing", "bridge", bridge, "key", bridgeName, "xs_nw_uuid", nw.getUuid(conn), "cs_host_id",
((Long)hostId).toString());
} else {
result = callHostPlugin(conn, "ovstunnel", "setup_ovs_bridge", "bridge", bridge, "key", bridgeName, "xs_nw_uuid", nw.getUuid(conn), "cs_host_id", ((Long)hostId).toString());
}
// Note down the fact that the ovs bridge has been setup
final String[] res = result.split(":");
if (res.length != 2 || !res[0].equalsIgnoreCase("SUCCESS")) {
throw new CloudRuntimeException("Unable to pre-configure OVS bridge " + bridge);
}
}
return nw;
} catch (final Exception e) {
s_logger.warn("createandConfigureTunnelNetwork failed", e);
return null;
}
}
public String connect(final Connection conn, final String vmname, final String ipAddress) {
return connect(conn, vmname, ipAddress, 3922);
}
public String connect(final Connection conn, final String vmName, final String ipAddress, final int port) {
for (int i = 0; i <= _retry; i++) {
try {
final Set<VM> vms = VM.getByNameLabel(conn, vmName);
if (vms.size() < 1) {
final String msg = "VM " + vmName + " is not running";
s_logger.warn(msg);
return msg;
}
} catch (final Exception e) {
final String msg = "VM.getByNameLabel " + vmName + " failed due to " + e.toString();
s_logger.warn(msg, e);
return msg;
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("Trying to connect to " + ipAddress + " attempt " + i + " of " + _retry);
}
if (pingdomr(conn, ipAddress, Integer.toString(port))) {
return null;
}
try {
Thread.sleep(_sleep);
} catch (final InterruptedException e) {
}
}
final String msg = "Timeout, Unable to logon to " + ipAddress;
s_logger.debug(msg);
return msg;
}
public String copyVhdFromSecondaryStorage(final Connection conn, final String mountpoint, final String sruuid, final int wait) {
final String nameLabel = "cloud-" + UUID.randomUUID().toString();
final String results = callHostPluginAsync(conn, "vmopspremium", "copy_vhd_from_secondarystorage", wait, "mountpoint", mountpoint, "sruuid", sruuid, "namelabel", nameLabel);
String errMsg = null;
if (results == null || results.isEmpty()) {
errMsg = "copy_vhd_from_secondarystorage return null";
} else {
final String[] tmp = results.split("#");
final String status = tmp[0];
if (status.equals("0")) {
return tmp[1];
} else {
errMsg = tmp[1];
}
}
final String source = mountpoint.substring(mountpoint.lastIndexOf('/') + 1);
if (killCopyProcess(conn, source)) {
destroyVDIbyNameLabel(conn, nameLabel);
}
s_logger.warn(errMsg);
throw new CloudRuntimeException(errMsg);
}
@Override
public ExecutionResult createFileInVR(final String routerIp, final String path, final String filename, final String content) {
final Connection conn = getConnection();
final String hostPath = "/tmp/";
s_logger.debug("Copying VR with ip " + routerIp + " config file into host " + _host.getIp());
try {
SshHelper.scpTo(_host.getIp(), 22, _username, null, _password.peek(), hostPath, content.getBytes(Charset.defaultCharset()), filename, null);
} catch (final Exception e) {
s_logger.warn("scp VR config file into host " + _host.getIp() + " failed with exception " + e.getMessage().toString());
}
final String rc = callHostPlugin(conn, "vmops", "createFileInDomr", "domrip", routerIp, "srcfilepath", hostPath + filename, "dstfilepath", path);
s_logger.debug("VR Config file " + filename + " got created in VR, ip " + routerIp + " with content \n" + content);
return new ExecutionResult(rc.startsWith("succ#"), rc.substring(5));
}
protected SR createIsoSRbyURI(final Connection conn, final URI uri, final String vmName, final boolean shared) {
try {
final Map<String, String> deviceConfig = new HashMap<String, String>();
String path = uri.getPath();
path = path.replace("//", "/");
deviceConfig.put("location", uri.getHost() + ":" + path);
final Host host = Host.getByUuid(conn, _host.getUuid());
final SR sr = SR.create(conn, host, deviceConfig, new Long(0), uri.getHost() + path, "iso", "iso", "iso", shared, new HashMap<String, String>());
sr.setNameLabel(conn, vmName + "-ISO");
sr.setNameDescription(conn, deviceConfig.get("location"));
sr.scan(conn);
return sr;
} catch (final XenAPIException e) {
final String msg = "createIsoSRbyURI failed! mountpoint: " + uri.getHost() + uri.getPath() + " due to " + e.toString();
s_logger.warn(msg, e);
throw new CloudRuntimeException(msg, e);
} catch (final Exception e) {