use of com.xensource.xenapi.Host in project OpenAttestation by OpenAttestation.
the class CitrixClient method getAIKCertificate.
/* */
// Commenting the below function since it is not being used and klocwork is throwing a warning
/*private void createRSAKeyFile(String sessionId) {
String command = String.format("%s %s %s",opensslCmd,aikverifyhomeData + File.separator + getCertFileName(sessionId),aikverifyhomeData + File.separator+getRSAPubkeyFileName(sessionId));
log.debug( "RSA Key Command " + command);
CommandUtil.runCommand(command, false, "CreateRsaKey" );
//log.log(Level.INFO, "Result - {0} ", result);
} */
/*private String getRSAPubkeyFileName(String sessionId) {
return "rsapubkey_" + sessionId + ".key";
}*/
/*
public HostInfo getHostInfo() throws NoSuchAlgorithmException, KeyManagementException, MalformedURLException, BadServerResponse, XenAPIException, XmlRpcException {
//log.info("stdalex-error getHostInfo IP:" + hostIpAddress + " port:" + port + " user: " + userName + " pw:" + password);
HostInfo response = new HostInfo();
if( !isConnected()) { connect(); }
log.debug( "CitrixClient: connected to server ["+hostIpAddress+"]");
// Map<String, String> myMap = new HashMap<String, String>();
Set<Host> hostList = Host.getAll(connection);
Iterator iter = hostList.iterator();
// hasNext() will always be valid otherwise we will get an exception from the getAll method. So, we not need
// to throw an exception if the hasNext is false.
Host h = null;
if (iter.hasNext()) {
h = (Host)iter.next();
}
response.setClientIp(hostIpAddress);
Map<String, String> map = h.getSoftwareVersion(connection);
response.setOsName(map.get("product_brand"));
response.setOsVersion(map.get("product_version"));
response.setVmmName("xen");
response.setVmmVersion(map.get("xen"));
map = h.getBiosStrings(connection);
response.setBiosOem(map.get("bios-vendor"));
response.setBiosVersion(map.get("bios-version"));
map = h.getCpuInfo(connection);
int stepping = Integer.parseInt(map.get("stepping"));
int model = Integer.parseInt(map.get("model"));
int family = Integer.parseInt(map.get("family"));
// EAX register contents is used for defining CPU ID and as well as family/model/stepping
// 0-3 bits : Stepping
// 4-7 bits: Model #
// 8-11 bits: Family code
// 12 & 13: Processor type, which will always be zero
// 14 & 15: Reserved
// 16 to 19: Extended model
// Below is the sample of the data got from the Citrix API
// Model: 45, Stepping:7 and Family: 6
// Mapping it to the EAX register we would get
// 0-3 bits: 7
// 4-7 bits: D (Actually 45 would be 2D. So, we would put D in 4-7 bits and 2 in 16-19 bits
// 8-11 bits: 6
//12-15 bits: 0
// 16-19 bits: 2
// 20-31 bits: Extended family and reserved, which will be 0
// So, the final content would be : 000206D7
// On reversing individual bytes, we would get D7 06 02 00
String modelInfo = Integer.toHexString(model);
String processorInfo = modelInfo.charAt(1) + Integer.toHexString(stepping) + " " + "0" + Integer.toHexString(family) + " " + "0" + modelInfo.charAt(0);
processorInfo = processorInfo.trim().toUpperCase();
response.setProcessorInfo(processorInfo);
java.util.Date date= new java.util.Date();
response.setTimeStamp( new Timestamp(date.getTime()).toString());
// log.trace("stdalex-error leaving getHostInfo");
return response;
}
*/
/* */
public String getAIKCertificate() throws NoSuchAlgorithmException, KeyManagementException, BadServerResponse, XenAPIException, XmlRpcException {
String resp = "";
// removed to prevent leaking secrets
log.info("stdalex-error getAIKCert IP:" + hostIpAddress + " port:" + port + " user: " + userName + " pw:" + password);
if (!isConnected()) {
connect();
}
log.debug("CitrixClient: connected to server [" + hostIpAddress + "]");
Map<String, String> myMap = new HashMap<String, String>();
Set<Host> hostList = Host.getAll(connection);
Iterator iter = hostList.iterator();
// hasNext() will always be valid otherwise we will get an exception from the getAll method. So, we not need
// to throw an exception if the hasNext is false.
Host h = null;
if (iter.hasNext()) {
h = (Host) iter.next();
}
String aik = h.callPlugin(connection, "tpm", "tpm_get_attestation_identity", myMap);
int startP = aik.indexOf("<xentxt:TPM_Attestation_KEY_PEM>");
int endP = aik.indexOf("</xentxt:TPM_Attestation_KEY_PEM>");
// 32 is the size of the opening tag <xentxt:TPM_Attestation_KEY_PEM>
String cert = aik.substring(startP + "<xentxt:TPM_Attestation_KEY_PEM>".length(), endP);
keys key = new keys();
// This is the actual value for AIK!!!!!
key.tpmAttKeyPEM = cert;
//resp = new String( Base64.decodeBase64(key.tpmAttKeyPEM));
//new String(key.tpmAttKeyPEM);
resp = key.tpmAttKeyPEM;
// log.trace("stdalex-error getAIKCert: returning back: " + resp);
return resp;
}
use of com.xensource.xenapi.Host in project cloudstack by apache.
the class CitrixReadyCommandWrapper method execute.
@Override
public Answer execute(final ReadyCommand command, final CitrixResourceBase citrixResourceBase) {
final Connection conn = citrixResourceBase.getConnection();
final Long dcId = command.getDataCenterId();
// Ignore the result of the callHostPlugin. Even if unmounting the
// snapshots dir fails, let Ready command
// succeed.
citrixResourceBase.umountSnapshotDir(conn, dcId);
citrixResourceBase.setupLinkLocalNetwork(conn);
// try to destroy CD-ROM device for all system VMs on this host
try {
final Host host = Host.getByUuid(conn, citrixResourceBase.getHost().getUuid());
final Set<VM> vms = host.getResidentVMs(conn);
for (final VM vm : vms) {
citrixResourceBase.destroyPatchVbd(conn, vm.getNameLabel(conn));
}
} catch (final Exception e) {
}
try {
final boolean result = citrixResourceBase.cleanupHaltedVms(conn);
if (!result) {
return new ReadyAnswer(command, "Unable to cleanup halted vms");
}
} catch (final XenAPIException e) {
s_logger.warn("Unable to cleanup halted vms", e);
return new ReadyAnswer(command, "Unable to cleanup halted vms");
} catch (final XmlRpcException e) {
s_logger.warn("Unable to cleanup halted vms", e);
return new ReadyAnswer(command, "Unable to cleanup halted vms");
}
return new ReadyAnswer(command);
}
use of com.xensource.xenapi.Host in project cloudstack by apache.
the class CitrixSetupCommandWrapper method execute.
@Override
public Answer execute(final SetupCommand command, final CitrixResourceBase citrixResourceBase) {
final Connection conn = citrixResourceBase.getConnection();
try {
final Map<Pool, Pool.Record> poolRecs = Pool.getAllRecords(conn);
if (poolRecs.size() != 1) {
throw new CloudRuntimeException("There are " + poolRecs.size() + " pool for host :" + citrixResourceBase.getHost().getUuid());
}
final Host master = poolRecs.values().iterator().next().master;
citrixResourceBase.setupServer(conn, master);
final Host host = Host.getByUuid(conn, citrixResourceBase.getHost().getUuid());
citrixResourceBase.setupServer(conn, host);
if (!citrixResourceBase.setIptables(conn)) {
s_logger.warn("set xenserver Iptable failed");
return null;
}
if (citrixResourceBase.isSecurityGroupEnabled()) {
final boolean canBridgeFirewall = citrixResourceBase.canBridgeFirewall(conn);
citrixResourceBase.setCanBridgeFirewall(canBridgeFirewall);
if (!canBridgeFirewall) {
final String msg = "Failed to configure brige firewall";
s_logger.warn(msg);
s_logger.warn("Check host " + citrixResourceBase.getHost().getIp() + " for CSP is installed or not and check network mode for bridge");
return new SetupAnswer(command, msg);
}
}
final boolean r = citrixResourceBase.launchHeartBeat(conn);
if (!r) {
return null;
}
citrixResourceBase.cleanupTemplateSR(conn);
try {
if (command.useMultipath()) {
// the config value is set to true
host.addToOtherConfig(conn, "multipathing", "true");
host.addToOtherConfig(conn, "multipathhandle", "dmp");
}
} catch (final Types.MapDuplicateKey e) {
s_logger.debug("multipath is already set");
}
if (command.needSetup()) {
final String result = citrixResourceBase.callHostPlugin(conn, "vmops", "setup_iscsi", "uuid", citrixResourceBase.getHost().getUuid());
if (!result.contains("> DONE <")) {
s_logger.warn("Unable to setup iscsi: " + result);
return new SetupAnswer(command, result);
}
Pair<PIF, PIF.Record> mgmtPif = null;
final Set<PIF> hostPifs = host.getPIFs(conn);
for (final PIF pif : hostPifs) {
final PIF.Record rec = pif.getRecord(conn);
if (rec.management) {
if (rec.VLAN != null && rec.VLAN != -1) {
final String msg = new StringBuilder("Unsupported configuration. Management network is on a VLAN. host=").append(citrixResourceBase.getHost().getUuid()).append("; pif=").append(rec.uuid).append("; vlan=").append(rec.VLAN).toString();
s_logger.warn(msg);
return new SetupAnswer(command, msg);
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("Management network is on pif=" + rec.uuid);
}
mgmtPif = new Pair<PIF, PIF.Record>(pif, rec);
break;
}
}
if (mgmtPif == null) {
final String msg = "Unable to find management network for " + citrixResourceBase.getHost().getUuid();
s_logger.warn(msg);
return new SetupAnswer(command, msg);
}
final Map<Network, Network.Record> networks = Network.getAllRecords(conn);
if (networks == null) {
final String msg = "Unable to setup as there are no networks in the host: " + citrixResourceBase.getHost().getUuid();
s_logger.warn(msg);
return new SetupAnswer(command, msg);
}
for (final Network.Record network : networks.values()) {
if (network.nameLabel.equals("cloud-private")) {
for (final PIF pif : network.PIFs) {
final PIF.Record pr = pif.getRecord(conn);
if (citrixResourceBase.getHost().getUuid().equals(pr.host.getUuid(conn))) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Found a network called cloud-private. host=" + citrixResourceBase.getHost().getUuid() + "; Network=" + network.uuid + "; pif=" + pr.uuid);
}
if (pr.VLAN != null && pr.VLAN != -1) {
final String msg = new StringBuilder("Unsupported configuration. Network cloud-private is on a VLAN. Network=").append(network.uuid).append(" ; pif=").append(pr.uuid).toString();
s_logger.warn(msg);
return new SetupAnswer(command, msg);
}
if (!pr.management && pr.bondMasterOf != null && pr.bondMasterOf.size() > 0) {
if (pr.bondMasterOf.size() > 1) {
final String msg = new StringBuilder("Unsupported configuration. Network cloud-private has more than one bond. Network=").append(network.uuid).append("; pif=").append(pr.uuid).toString();
s_logger.warn(msg);
return new SetupAnswer(command, msg);
}
final Bond bond = pr.bondMasterOf.iterator().next();
final Set<PIF> slaves = bond.getSlaves(conn);
for (final PIF slave : slaves) {
final PIF.Record spr = slave.getRecord(conn);
if (spr.management) {
if (!citrixResourceBase.transferManagementNetwork(conn, host, slave, spr, pif)) {
final String msg = new StringBuilder("Unable to transfer management network. slave=" + spr.uuid + "; master=" + pr.uuid + "; host=" + citrixResourceBase.getHost().getUuid()).toString();
s_logger.warn(msg);
return new SetupAnswer(command, msg);
}
break;
}
}
}
}
}
}
}
}
return new SetupAnswer(command, false);
} catch (final XmlRpcException e) {
s_logger.warn("Unable to setup", e);
return new SetupAnswer(command, e.getMessage());
} catch (final XenAPIException e) {
s_logger.warn("Unable to setup", e);
return new SetupAnswer(command, e.getMessage());
} catch (final Exception e) {
s_logger.warn("Unable to setup", e);
return new SetupAnswer(command, e.getMessage());
}
}
use of com.xensource.xenapi.Host in project cloudstack by apache.
the class XcpServerDiscoverer method find.
@Override
public Map<? extends ServerResource, Map<String, String>> find(long dcId, Long podId, Long clusterId, URI url, String username, String password, List<String> hostTags) throws DiscoveryException {
Map<CitrixResourceBase, Map<String, String>> resources = new HashMap<CitrixResourceBase, Map<String, String>>();
Connection conn = null;
if (!url.getScheme().equals("http")) {
String msg = "urlString is not http so we're not taking care of the discovery for this: " + url;
s_logger.debug(msg);
return null;
}
if (clusterId == null) {
String msg = "must specify cluster Id when add host";
s_logger.debug(msg);
throw new RuntimeException(msg);
}
if (podId == null) {
String msg = "must specify pod Id when add host";
s_logger.debug(msg);
throw new RuntimeException(msg);
}
ClusterVO cluster = _clusterDao.findById(clusterId);
if (cluster == null || cluster.getHypervisorType() != HypervisorType.XenServer) {
if (s_logger.isInfoEnabled())
s_logger.info("invalid cluster id or cluster is not for XenServer hypervisors");
return null;
}
try {
String hostname = url.getHost();
InetAddress ia = InetAddress.getByName(hostname);
String hostIp = ia.getHostAddress();
Queue<String> pass = new LinkedList<String>();
pass.add(password);
conn = _connPool.getConnect(hostIp, username, pass);
if (conn == null) {
String msg = "Unable to get a connection to " + url;
s_logger.debug(msg);
throw new DiscoveryException(msg);
}
Set<Pool> pools = Pool.getAll(conn);
Pool pool = pools.iterator().next();
Pool.Record pr = pool.getRecord(conn);
String poolUuid = pr.uuid;
Map<Host, Host.Record> hosts = Host.getAllRecords(conn);
String latestHotFix = "";
if (poolHasHotFix(conn, hostIp, XenserverConfigs.XSHotFix62ESP1004)) {
latestHotFix = XenserverConfigs.XSHotFix62ESP1004;
} else if (poolHasHotFix(conn, hostIp, XenserverConfigs.XSHotFix62ESP1)) {
latestHotFix = XenserverConfigs.XSHotFix62ESP1;
}
/*set cluster hypervisor type to xenserver*/
ClusterVO clu = _clusterDao.findById(clusterId);
if (clu.getGuid() == null) {
setClusterGuid(clu, poolUuid);
} else {
List<HostVO> clusterHosts = _resourceMgr.listAllHostsInCluster(clusterId);
if (clusterHosts != null && clusterHosts.size() > 0) {
if (!clu.getGuid().equals(poolUuid)) {
String msg = "Please join the host " + hostIp + " to XS pool " + clu.getGuid() + " through XC/XS before adding it through CS UI";
s_logger.warn(msg);
throw new DiscoveryException(msg);
}
} else {
setClusterGuid(clu, poolUuid);
}
}
// can not use this conn after this point, because this host may join a pool, this conn is retired
if (conn != null) {
try {
Session.logout(conn);
} catch (Exception e) {
s_logger.debug("Caught exception during logout", e);
}
conn.dispose();
conn = null;
}
poolUuid = clu.getGuid();
_clusterDao.update(clusterId, clu);
if (_checkHvm) {
for (Map.Entry<Host, Host.Record> entry : hosts.entrySet()) {
Host.Record record = entry.getValue();
boolean support_hvm = false;
for (String capability : record.capabilities) {
if (capability.contains("hvm")) {
support_hvm = true;
break;
}
}
if (!support_hvm) {
String msg = "Unable to add host " + record.address + " because it doesn't support hvm";
_alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_HOST, dcId, podId, msg, msg);
s_logger.debug(msg);
throw new RuntimeException(msg);
}
}
}
for (Map.Entry<Host, Host.Record> entry : hosts.entrySet()) {
Host.Record record = entry.getValue();
String hostAddr = record.address;
String prodVersion = CitrixHelper.getProductVersion(record);
String xenVersion = record.softwareVersion.get("xen");
String hostOS = record.softwareVersion.get("product_brand");
if (hostOS == null) {
hostOS = record.softwareVersion.get("platform_name");
}
String hostOSVer = prodVersion;
String hostKernelVer = record.softwareVersion.get("linux");
if (_resourceMgr.findHostByGuid(record.uuid) != null) {
s_logger.debug("Skipping " + record.address + " because " + record.uuid + " is already in the database.");
continue;
}
CitrixResourceBase resource = createServerResource(dcId, podId, record, latestHotFix);
s_logger.info("Found host " + record.hostname + " ip=" + record.address + " product version=" + prodVersion);
Map<String, String> details = new HashMap<String, String>();
Map<String, Object> params = new HashMap<String, Object>();
details.put("url", hostAddr);
details.put("username", username);
params.put("username", username);
details.put("password", password);
params.put("password", password);
params.put("zone", Long.toString(dcId));
params.put("guid", record.uuid);
params.put("pod", podId.toString());
params.put("cluster", clusterId.toString());
params.put("pool", poolUuid);
params.put("ipaddress", record.address);
details.put(HostInfo.HOST_OS, hostOS);
details.put(HostInfo.HOST_OS_VERSION, hostOSVer);
details.put(HostInfo.HOST_OS_KERNEL_VERSION, hostKernelVer);
details.put(HostInfo.HYPERVISOR_VERSION, xenVersion);
String privateNetworkLabel = _networkMgr.getDefaultManagementTrafficLabel(dcId, HypervisorType.XenServer);
String storageNetworkLabel = _networkMgr.getDefaultStorageTrafficLabel(dcId, HypervisorType.XenServer);
if (!params.containsKey("private.network.device") && privateNetworkLabel != null) {
params.put("private.network.device", privateNetworkLabel);
details.put("private.network.device", privateNetworkLabel);
}
if (!params.containsKey("storage.network.device1") && storageNetworkLabel != null) {
params.put("storage.network.device1", storageNetworkLabel);
details.put("storage.network.device1", storageNetworkLabel);
}
DataCenterVO zone = _dcDao.findById(dcId);
boolean securityGroupEnabled = zone.isSecurityGroupEnabled();
params.put("securitygroupenabled", Boolean.toString(securityGroupEnabled));
params.put("router.aggregation.command.each.timeout", _configDao.getValue(Config.RouterAggregationCommandEachTimeout.toString()));
params.put("wait", Integer.toString(_wait));
details.put("wait", Integer.toString(_wait));
params.put("migratewait", _configDao.getValue(Config.MigrateWait.toString()));
params.put(Config.XenServerMaxNics.toString().toLowerCase(), _configDao.getValue(Config.XenServerMaxNics.toString()));
params.put(Config.XenServerHeartBeatTimeout.toString().toLowerCase(), _configDao.getValue(Config.XenServerHeartBeatTimeout.toString()));
params.put(Config.XenServerHeartBeatInterval.toString().toLowerCase(), _configDao.getValue(Config.XenServerHeartBeatInterval.toString()));
params.put(Config.InstanceName.toString().toLowerCase(), _instance);
details.put(Config.InstanceName.toString().toLowerCase(), _instance);
try {
resource.configure("XenServer", params);
} catch (ConfigurationException e) {
_alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_HOST, dcId, podId, "Unable to add " + record.address, "Error is " + e.getMessage());
s_logger.warn("Unable to instantiate " + record.address, e);
continue;
}
resource.start();
resources.put(resource, details);
}
} catch (SessionAuthenticationFailed e) {
throw new DiscoveredWithErrorException("Authentication error");
} catch (XenAPIException e) {
s_logger.warn("XenAPI exception", e);
return null;
} catch (XmlRpcException e) {
s_logger.warn("Xml Rpc Exception", e);
return null;
} catch (UnknownHostException e) {
s_logger.warn("Unable to resolve the host name", e);
return null;
} catch (Exception e) {
s_logger.debug("other exceptions: " + e.toString(), e);
return null;
}
return resources;
}
use of com.xensource.xenapi.Host in project cloudstack by apache.
the class CitrixResourceBase method getManagementNetwork.
protected XsLocalNetwork getManagementNetwork(final Connection conn) throws XmlRpcException, XenAPIException {
PIF mgmtPif = null;
PIF.Record mgmtPifRec = null;
final Host host = Host.getByUuid(conn, _host.getUuid());
final Set<PIF> hostPifs = host.getPIFs(conn);
for (final PIF pif : hostPifs) {
final PIF.Record rec = pif.getRecord(conn);
if (rec.management) {
if (rec.VLAN != null && rec.VLAN != -1) {
final String msg = new StringBuilder("Unsupported configuration. Management network is on a VLAN. host=").append(_host.getUuid()).append("; pif=").append(rec.uuid).append("; vlan=").append(rec.VLAN).toString();
s_logger.warn(msg);
throw new CloudRuntimeException(msg);
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("Management network is on pif=" + rec.uuid);
}
mgmtPif = pif;
mgmtPifRec = rec;
break;
}
}
if (mgmtPif == null) {
final String msg = "Unable to find management network for " + _host.getUuid();
s_logger.warn(msg);
throw new CloudRuntimeException(msg);
}
final Bond bond = mgmtPifRec.bondSlaveOf;
if (!isRefNull(bond)) {
final String msg = "Management interface is on slave(" + mgmtPifRec.uuid + ") of bond(" + bond.getUuid(conn) + ") on host(" + _host.getUuid() + "), please move management interface to bond!";
s_logger.warn(msg);
throw new CloudRuntimeException(msg);
}
final Network nk = mgmtPifRec.network;
final Network.Record nkRec = nk.getRecord(conn);
return new XsLocalNetwork(this, nk, nkRec, mgmtPif, mgmtPifRec);
}
Aggregations