Vijava (更改虚拟机配置信息(内存、CPU和添加新磁盘)终极版本)
无情
阅读:604
2021-03-31 22:29:17
评论:0
package com.vmware.server;
import java.util.List;
import java.util.Map;
import org.apache.log4j.FileAppender;
import org.apache.log4j.Logger;
import org.apache.log4j.SimpleLayout;
import com.vmware.pojo.VirtualMachineConfig;
import com.vmware.util.DataBase;
import com.vmware.util.Session;
import com.vmware.util.StringRandom;
import com.vmware.util.VmwareUtil;
import com.vmware.vim25.VirtualDevice;
import com.vmware.vim25.VirtualDeviceConfigSpec;
import com.vmware.vim25.VirtualDeviceConfigSpecFileOperation;
import com.vmware.vim25.VirtualDeviceConfigSpecOperation;
import com.vmware.vim25.VirtualDisk;
import com.vmware.vim25.VirtualDiskFlatVer2BackingInfo;
import com.vmware.vim25.VirtualMachineConfigSpec;
import com.vmware.vim25.VirtualMachinePowerState;
import com.vmware.vim25.mo.Folder;
import com.vmware.vim25.mo.InventoryNavigator;
import com.vmware.vim25.mo.ServiceInstance;
import com.vmware.vim25.mo.Task;
import com.vmware.vim25.mo.VirtualMachine;
/**
* VirtualMachineConfigServer:虚拟机配置更改服务
**/
public class VirtualMachineConfigServer {
public static Logger logger = Logger
.getLogger(VirtualMachineConfigServer.class);
//
public void vmConfig(List<VirtualMachineConfig> list) {
// 自定义工具栏
VmwareUtil util = new VmwareUtil();
// 日志处理
SimpleLayout layout = new SimpleLayout();
FileAppender appender = null;
try {
appender = new FileAppender(layout, "log.txt", false);
} catch (Exception e) {
}
logger.addAppender(appender);
// 逻辑处理
try {
Map map = util.getURL();
String ip = String.valueOf(map.get("ip"));
String username = String.valueOf(map.get("username"));
String password = String.valueOf(map.get("password"));
if (list.size() > 0 && list != null) {
for (VirtualMachineConfig config : list) {
ServiceInstance instance = Session.getInstance(ip,
username, password);
if (instance != null) {
logger.debug("vmware 连接成功");
} else {
logger.debug("vmware 连接失败,请检查vmware连接相关配置信息");
}
Folder rootFolder = instance.getRootFolder();
InventoryNavigator inventoryNavigator = new InventoryNavigator(
rootFolder);
try {
com.vmware.vim25.mo.VirtualMachine VM = (com.vmware.vim25.mo.VirtualMachine) inventoryNavigator
.searchManagedEntity("VirtualMachine",
config.getXnjName());
if (VM != null) {
logger.debug("虚拟机 查询成功");
} else {
logger.debug("虚拟机 查询失败,请仔细检查配置模板是否存在");
}
if(!VM.getRuntime().getPowerState().name().equalsIgnoreCase(VirtualMachinePowerState.poweredOff.name())){
Task tasks = VM.powerOffVM_Task();
tasks.waitForTask();
}
// 修改虚拟机相关配置属性
VirtualMachineConfigSpec configSpec = new VirtualMachineConfigSpec();
// 设置CPU核数
configSpec
.setNumCPUs(Integer.parseInt(config.getCpu()));
// 设置内存大小
configSpec.setMemoryMB((long) Integer.parseInt(config
.getRam()));
int diskSize = Integer.parseInt(config.getRl())*1024*1024;
// mode: persistent|independent_persistent,independent_nonpersistent
String diskMode = "persistent";
VirtualDeviceConfigSpec vdiskSpec = createDiskSpec(config.getDsName(),diskSize, diskMode,VM);
VirtualDeviceConfigSpec[] vdiskSpecArray = {vdiskSpec};
configSpec.setDeviceChange(vdiskSpecArray);
Task task = VM.reconfigVM_Task(configSpec);
String result = task.waitForTask();
if (result.equals(Task.SUCCESS)) {
logger.debug("模板生成虚拟机成功");
logger.debug("模板生成虚拟机成功");
System.out.println("flwId:"+config.getFlwId());
String sql = "update tb_flw_content set `status`='3' where `flw_id`='"
+ config.getFlwId() + "'";
DataBase.update(sql);
String deleteAll = "update tb_flw_content set `status`='6' where `flw_id`='"
+ config.getFlwId() + "'";
DataBase.update(deleteAll);
} else {
logger.debug("模板生成虚拟机失败,请查询Vcenter 上相关日志信息");
}
instance.getServerConnection().logout();
} catch (Exception e) {
logger.debug("template 查询失败,请仔细检查配置模板是否存在");
instance.getServerConnection().logout();
break;
}
}
}
} catch (Exception e) {
}
}
public static VirtualDeviceConfigSpec createDiskSpec(String dsName, long diskSizeKB, String diskMode, VirtualMachine vm)
{
VirtualDeviceConfigSpec diskSpec = new VirtualDeviceConfigSpec();
diskSpec.setOperation(VirtualDeviceConfigSpecOperation.add);
diskSpec.setFileOperation(VirtualDeviceConfigSpecFileOperation.create);
VirtualDisk vd = new VirtualDisk();
vd.setCapacityInKB(diskSizeKB);
diskSpec.setDevice(vd);
vd.setKey(getkey(vm));
vd.setUnitNumber(getUnitNumber(vm));
vd.setControllerKey(getcontrollerkey(vm));
VirtualDiskFlatVer2BackingInfo diskfileBacking = new VirtualDiskFlatVer2BackingInfo();
String diskName=StringRandom.getStringRandom(12);
String fileName = "["+ dsName +"] "+ vm.getName() + "/" + diskName + ".vmdk";
diskfileBacking.setFileName(fileName);
diskfileBacking.setDiskMode(diskMode);
diskfileBacking.setThinProvisioned(true);
vd.setBacking(diskfileBacking);
return diskSpec;
}
// 获取虚拟机磁盘管理的controlerkey
public static int getcontrollerkey(VirtualMachine vm) {
int controllerkey = 0;
if (vm != null) {
VirtualDevice[] devices = vm.getConfig().getHardware().getDevice();
if (devices != null && devices.length > 0) {
for (int i = 0; i < devices.length; i++) {
VirtualDevice device = devices[i];
if (device instanceof VirtualDisk) {
controllerkey = device.getControllerKey();
}
}
}
}
return controllerkey;
}
// 获取虚拟机已生成key
public static int getkey(VirtualMachine vm) {
int key = 0;
if (vm != null) {
VirtualDevice[] devices = vm.getConfig().getHardware().getDevice();
if (devices != null && devices.length > 0) {
for (int i = 0; i < devices.length; i++) {
VirtualDevice device = devices[i];
if (device instanceof VirtualDisk) {
key = device.getKey();
}
}
}
}
key = key + 1;
return key;
}
// 获取虚拟机已生成UnitNumber
public static int getUnitNumber(VirtualMachine vm) {
int UnitNumber = 0;
if (vm != null) {
VirtualDevice[] devices = vm.getConfig().getHardware().getDevice();
if (devices != null && devices.length > 0) {
for (int i = 0; i < devices.length; i++) {
VirtualDevice device = devices[i];
if (device instanceof VirtualDisk) {
UnitNumber = device.getUnitNumber();
}
}
}
}
UnitNumber = UnitNumber + 1;
return UnitNumber;
}
}
以上代码是 核心代码。
声明
1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。