package com.bocloud.ims.service.transportor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bocloud.cmp.driver.hmc.HmcPartitionDriver;
import com.bocloud.cmp.entity.enums.BocloudStatus;
import com.bocloud.cmp.entity.enums.CloudProvider;
import com.bocloud.cmp.entity.enums.HmcPartitionType;
import com.bocloud.cmp.entity.enums.ResourceCategory;
import com.bocloud.cmp.entity.enums.ServerAssetCategory;
import com.bocloud.cmp.model.VmNetworkBean;
import com.bocloud.cmp.model.hmc.SyncModel;
import com.bocloud.cmp.model.hmc.sdk.module.AssociatedIPLConfiguration;
import com.bocloud.cmp.model.hmc.sdk.module.AssociatedSystemCapabilities;
import com.bocloud.cmp.model.hmc.sdk.module.AssociatedSystemIOConfiguration;
import com.bocloud.cmp.model.hmc.sdk.module.AssociatedSystemMemoryConfiguration;
import com.bocloud.cmp.model.hmc.sdk.module.AssociatedSystemProcessorConfiguration;
import com.bocloud.cmp.model.hmc.sdk.module.CurrentDedicatedProcessorConfiguration;
import com.bocloud.cmp.model.hmc.sdk.module.CurrentSharedProcessorConfiguration;
import com.bocloud.cmp.model.hmc.sdk.module.HostEthernetAdapter;
import com.bocloud.cmp.model.hmc.sdk.module.HostEthernetAdapterEntry;
import com.bocloud.cmp.model.hmc.sdk.module.IOAdapter;
import com.bocloud.cmp.model.hmc.sdk.module.IOBus;
import com.bocloud.cmp.model.hmc.sdk.module.IOBuses;
import com.bocloud.cmp.model.hmc.sdk.module.IOSlot;
import com.bocloud.cmp.model.hmc.sdk.module.IOSlots;
import com.bocloud.cmp.model.hmc.sdk.module.LogicalPartition;
import com.bocloud.cmp.model.hmc.sdk.module.LogicalPartitionEntry;
import com.bocloud.cmp.model.hmc.sdk.module.LogicalPartitionProfileEntry;
import com.bocloud.cmp.model.hmc.sdk.module.ManagedSystem;
import com.bocloud.cmp.model.hmc.sdk.module.ManagedSystemContent;
import com.bocloud.cmp.model.hmc.sdk.module.ManagedSystemEntry;
import com.bocloud.cmp.model.hmc.sdk.module.NetworkBridge;
import com.bocloud.cmp.model.hmc.sdk.module.PartitionProcessorConfiguration;
import com.bocloud.cmp.model.hmc.sdk.module.PendingPowerOnLogicalPartitionStartPolicy;
import com.bocloud.cmp.model.hmc.sdk.module.PowerVMLogicalPartitionSimplifiedRemoteRestartCapable;
import com.bocloud.cmp.model.hmc.sdk.module.RelatedIOAdapter;
import com.bocloud.cmp.model.hmc.sdk.module.SharedProcessorPool;
import com.bocloud.cmp.model.hmc.sdk.module.SharedProcessorPoolEntry;
import com.bocloud.cmp.model.hmc.sdk.module.TrunkAdapter;
import com.bocloud.cmp.model.hmc.sdk.module.VirtualIOServer;
import com.bocloud.cmp.model.hmc.sdk.module.VirtualIOServerEntry;
import com.bocloud.cmp.model.hmc.sdk.module.VirtualNetworkBridgeEntry;
import com.bocloud.cmp.model.hmc.sdk.module.VirtualSwitch;
import com.bocloud.cmp.model.hmc.sdk.module.VirtualSwitchEntry;
import com.bocloud.cmp.model.hmc.sdk.module.VolumeGroupEntry;
import com.bocloud.common.enums.ResourceCatalog;
import com.bocloud.common.model.BocloudResult;
import com.bocloud.ims.common.enums.HmcStatus;
import com.bocloud.ims.entity.common.MathUtils;
import com.bocloud.ims.entity.resource.CloudServer;
import com.bocloud.ims.entity.resource.CloudVendor;
import com.bocloud.ims.entity.resource.Resource;
import com.bocloud.ims.entity.resource.Server;
import com.bocloud.ims.entity.resource.ServerConfig;
import com.bocloud.ims.entity.resource.hmc.HmcHostEthernetAdapter;
import com.bocloud.ims.entity.resource.hmc.HmcIoAdapter;
import com.bocloud.ims.entity.resource.hmc.HmcIoBus;
import com.bocloud.ims.entity.resource.hmc.HmcIplConfig;
import com.bocloud.ims.entity.resource.hmc.HmcPartition;
import com.bocloud.ims.entity.resource.hmc.HmcServer;
import com.bocloud.ims.entity.resource.hmc.HmcSystemCapability;
import com.bocloud.ims.entity.resource.hmc.HmcSystemMemoryConfig;
import com.bocloud.ims.entity.resource.hmc.HmcSystemProcessorConfig;
import com.bocloud.ims.entity.resource.hmc.HmcSystemSharedProcessorPool;
import com.bocloud.ims.entity.resource.hmc.HmcVirtualNetworkBridge;
import com.bocloud.ims.entity.resource.hmc.HmcVirtualSwitch;
import com.bocloud.ims.interfaces.resource.hmc.HmcPartitionService;
import com.bocloud.ims.repository.resource.CloudServerRepository;
import com.bocloud.ims.repository.resource.CloudVendorRepository;
import com.bocloud.ims.repository.resource.ResourceRepository;
import com.bocloud.ims.repository.resource.ServerConfigRepository;
import com.bocloud.ims.repository.resource.ServerRepository;
import com.bocloud.ims.repository.resource.hmc.HmcHeaLogicalPortRepository;
import com.bocloud.ims.repository.resource.hmc.HmcHeaPhysicalPortRepository;
import com.bocloud.ims.repository.resource.hmc.HmcHostEthernetAdapterRepository;
import com.bocloud.ims.repository.resource.hmc.HmcIoAdapterRepository;
import com.bocloud.ims.repository.resource.hmc.HmcIoBusRepository;
import com.bocloud.ims.repository.resource.hmc.HmcIplConfigRepository;
import com.bocloud.ims.repository.resource.hmc.HmcPartitionRepository;
import com.bocloud.ims.repository.resource.hmc.HmcServerRepository;
import com.bocloud.ims.repository.resource.hmc.HmcSystemCapabilityRepository;
import com.bocloud.ims.repository.resource.hmc.HmcSystemMemoryConfigRepository;
import com.bocloud.ims.repository.resource.hmc.HmcSystemProcessorConfigRepository;
import com.bocloud.ims.repository.resource.hmc.HmcSystemSharedProcessorPoolRepository;
import com.bocloud.ims.repository.resource.hmc.HmcVirtualNetworkBridgeRepository;
import com.bocloud.ims.repository.resource.hmc.HmcVirtualSwitchRepository;
import com.bocloud.ims.service.resource.hmc.HmcDatabaseHelper;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 同步HMC工具类
 *
 * @author ShaolongTan
 * @author sxp
 */
@Deprecated
@Service("hmcTransportor")
public class HmcTransportor {
	private static Logger logger = LoggerFactory.getLogger(HmcTransportor.class);
	@Autowired
	private HmcPartitionDriver hmcPartitionDriver;
	@Autowired
	private HmcServerRepository hmcServerRepository;
	@Autowired
	private ServerRepository serverRepository;
	@Autowired
	private ServerConfigRepository serverConfigRepository;
	@Autowired
	private HmcPartitionRepository hmcPartitionRepository;
	@Autowired
	private HmcIplConfigRepository iplConfigRepository;
	@Autowired
	private HmcSystemCapabilityRepository systemCapabilityRepository;
	@Autowired
	private HmcSystemMemoryConfigRepository systemMemoryConfigRepository;
	@Autowired
	private HmcSystemProcessorConfigRepository systemProcessorConfigRepository;
	@Autowired
	private HmcIoBusRepository ioBusRepository;
	@Autowired
	private HmcIoAdapterRepository ioAdapterRepository;
	@Autowired
	private HmcVirtualSwitchRepository hmcVirtualSwitchRepository;
	@Autowired
	private HmcHostEthernetAdapterRepository hmcHostEthernetAdapterRepository;
	@Autowired
	private HmcHeaLogicalPortRepository hmcHeaLogicalPortRepository;
	@Autowired
	private HmcHeaPhysicalPortRepository hmcHeaPhysicalPortRepository;
	@Autowired
	private HmcDatabaseHelper hmcDatabaseHelper;
	@Autowired
	private HmcPartitionService hmcPartitionService;
	@Autowired
	private ResourceRepository resourceRepository;
	@Autowired
	private HmcSystemProcessorConfigRepository processorConfigRepository;
	@Autowired
	private HmcSystemMemoryConfigRepository memoryConfigRepository;
	@Autowired
	private CloudServerRepository cloudServerRepository;
	@Autowired
	private CloudVendorRepository cloudVendorRepository;
	@Autowired
	private HmcVirtualNetworkBridgeRepository hmcVirtualNetworkBridgeRepository;
	@Autowired
	private HmcSystemSharedProcessorPoolRepository sharedProcessorPoolRepository;

	public HmcTransportor() {
		super();
	}

	/**
	 * 同步平台实体
	 *
	 * @param vendor
	 * @param data
	 * @param userId
	 */
	@SuppressWarnings("unchecked")
	public BocloudResult sync(CloudVendor vendor, Object data, Long userId) {
		try {
			if (null != data) {
				Long vendorId = vendor.getId();
				// 获取服务器列表数据
				List<HmcServer> hmcServers = hmcServerRepository.listByVendorId(vendorId);
				Map<String, HmcServer> oldServerMap = Maps.newHashMap();
				for (HmcServer hmcServer : hmcServers) {
					oldServerMap.put(hmcServer.getUuid(), hmcServer);
				}

				// 获取server表数据
				List<Server> servers = serverRepository.listByVendor(vendorId);
				Map<String, Server> oldCmpServerMap = Maps.newHashMap();
				for (Server server : servers) {
					oldCmpServerMap.put(server.getUuid(), server);
				}

				// 数据同步
				List<SyncModel> syncModels = (List<SyncModel>) data;

				HmcServer hmcServer;
				Long serverId;
				logger.info("开始同步平台[" + vendorId + "]的server信息");

				for (SyncModel syncModel : syncModels) {
					if (oldServerMap.containsKey(syncModel.getUuid())) {
						hmcServer = oldServerMap.get(syncModel.getUuid());
						convertToHmcServer(hmcServer, syncModel, vendorId);
						hmcServer.setMenderId(userId);
						hmcServerRepository.update(hmcServer);

						serverId = hmcServer.getId();
						oldServerMap.remove(syncModel.getUuid());
					} else {
						hmcServer = new HmcServer();
						convertToHmcServer(hmcServer, syncModel, vendorId);
						hmcServer.preSave(userId, userId, vendorId);
						hmcServerRepository.save(hmcServer);
						serverId = hmcServer.getId();
					}
					// 更新cmp server表内的信息,
					if (oldCmpServerMap.containsKey(syncModel.getUuid())) {
						Server server = oldCmpServerMap.get(syncModel.getUuid());
						Long cmpServerId = server.getId();
						BeanUtils.copyProperties(hmcServer, server);
						server.setId(cmpServerId);
						server.setManageIp(hmcServer.getPrimaryIpAddress());
						server.setMenderId(userId);
						server.setStatus(convertHmcServerStatusToServerStatus(hmcServer.getStatus()));
						server.setPowerState(convertHmcServerStatusToServerStatus(hmcServer.getStatus()));
						if (syncModel.getViosEntries() != null && syncModel.getViosEntries().size() > 0) {
							server.setOsCategory("VIOS");
						} else {
							server.setOsCategory("AIX");
						}
						serverRepository.update(server);
						oldCmpServerMap.remove(syncModel.getUuid());
					} else {
						Server server = new Server();
						BeanUtils.copyProperties(hmcServer, server);
						server.setId(null);
						server.setResourceId(hmcServer.getUuid());
						server.setCategory("IBM");
						server.setManageIp(hmcServer.getPrimaryIpAddress());
						server.setProps(serverId.toString());
						server.preSave(userId, userId, vendorId, null, null);
						server.setStatus(convertHmcServerStatusToServerStatus(hmcServer.getStatus()));
						server.setPowerState(convertHmcServerStatusToServerStatus(hmcServer.getStatus()));
						server.setAssetCategory(ServerAssetCategory.POWER_SERVER.name());
						if (syncModel.getViosEntries() != null && syncModel.getViosEntries().size() > 0) {
							server.setOsCategory("VIOS");
						} else {
							server.setOsCategory("AIX");
						}
						serverRepository.save(server);
					}
					// 同步虚拟交换机信息
					syncVirtualSwitch(serverId, syncModel.getVswitchEntries(), userId);

					// 同步虚拟网桥信息
					syncNetworkBridge(serverId, syncModel.getNetworkBridgeEntries(), userId);

					// 同步主机以太网物理信息
					syncHostEthernetAdapter(serverId, syncModel.getHostEthernetAdapterEntries());

					// 同步主机共享存储池信息
					syncSharedProcessorPool(serverId, syncModel.getSharedProcessorPoolEntries(), userId);

					// 同步服务器关联数据
					syncServerAssociatedData(hmcServer, syncModel.getSystemEntry());

					// 同步分区信息
					syncPartiton(serverId, syncModel, userId, vendorId);

					// 同步资源信息
					syncHmcResource(vendorId, hmcServer, userId);
				}

				// 删除不存在的服务器数据
				Iterator<HmcServer> iteratorServer = oldServerMap.values().iterator();
				while (iteratorServer.hasNext()) {
					hmcServer = iteratorServer.next();
					Long id = hmcServer.getId();

					// 删除分区数据
					List<HmcPartition> pars = this.hmcPartitionRepository.listByServerId(id);
					for (HmcPartition partition : pars) {
						this.hmcPartitionRepository.remove(partition.getId(), userId);
					}
					// 删除服务器关联数据
					hmcDatabaseHelper.removeServerAttributer(hmcServer.getId());

					// 删除服务器的虚拟交换机
					this.hmcVirtualSwitchRepository.removeByServerId(hmcServer.getId(), userId);

					// 删除主机以太网数据
					hmcDatabaseHelper.deleteHostEthernetAdapter(hmcServer.getId());

					// 删除服务器
					this.hmcServerRepository.remove(id, userId);

					// 删除resouece
					this.resourceRepository.remove(id, ResourceCategory.Computer.name(),
							ResourceCatalog.PHYSICAL.name(), userId);
				}

				// 删除不存在的CMP服务器数据
				Iterator<Server> iteratorCmpServer = oldCmpServerMap.values().iterator();
				while (iteratorCmpServer.hasNext()) {
					Server oldCmpServer = iteratorCmpServer.next();
					serverRepository.remove(oldCmpServer.getId(), userId);
				}
			}
			return new BocloudResult(true, "云平台[ " + vendor.getName() + "] 同步任务结果:同步HMC平台数据成功");
		} catch (Exception e) {
			logger.error("HMC Sync error:", e);
			return new BocloudResult(false, "云平台[ " + vendor.getName() + "] 同步任务结果:同步HMC平台数据失败");
		}
	}

	// 更新和同步一个服务器的所有信息
	public BocloudResult syncServer(HmcServer hmcServer, SyncModel syncModel, Long userId) {
		try {
			// 同步服务器信息
			convertToHmcServer(hmcServer, syncModel, hmcServer.getVendorId());
			hmcServer.setMenderId(userId);
			hmcServerRepository.update(hmcServer);
			// 同步资源信息
			// syncHmcResource(vendorId, vendor.getEnv(), hmcServer, userId);

			// 同步虚拟交换机信息
			syncVirtualSwitch(hmcServer.getId(), syncModel.getVswitchEntries(), userId);

			// 同步主机以太网物理信息
			syncHostEthernetAdapter(hmcServer.getId(), syncModel.getHostEthernetAdapterEntries());

			// 同步服务器关联数据
			syncServerAssociatedData(hmcServer, syncModel.getSystemEntry());

			// 同步分区信息
			syncPartiton(hmcServer.getId(), syncModel, userId, hmcServer.getVendorId());
			return new BocloudResult(true, "服务器[ " + hmcServer.getPrimaryIpAddress() + "] 同步数据成功");
		} catch (Exception e) {
			logger.error("HMC Sync error:", e);
			return new BocloudResult(false, "服务器[ " + hmcServer.getPrimaryIpAddress() + "] 同步数据失败");
		}
	}

	/**
	 * 同步数据至resource
	 *
	 * @param vendorId
	 * @param hmcServer
	 * @param userId
	 * @return
	 * @throws Exception
	 */
	private Resource syncHmcResource(Long vendorId, HmcServer hmcServer, Long userId) throws Exception {
		logger.info("start to sync resource data for hmc server {}", hmcServer.getId());
		List<String> ips = Lists.newArrayList();
		ips.add(hmcServer.getPrimaryIpAddress());
		Resource resource = resourceRepository.query(ResourceCategory.Computer.name(), "MIDRANGE", hmcServer.getId(),
				vendorId);
		if (null != resource) {
			resource.setStatus(convertStatus(hmcServer.getStatus()));
			resource.setPrivateIps(JSONObject.toJSONString(ips));
			resource.setMenderId(userId);
			resource.setTenantId(0L);
			// 底层代码又又又动了，鬼知道这里面放什么
			// resource.setProjectId(0L);
			logger.debug("update old resource:{}", resource);
			resourceRepository.update(resource);
		} else {
			resource = new Resource(ResourceCategory.Computer.name(), "MIDRANGE", hmcServer.getId(),
					JSONObject.toJSONString(ips), "AIX", vendorId);
			resource.preSave(hmcServer.getName(), convertStatus(hmcServer.getStatus()), userId, 0L);
			Server server = HmcServerToServer(hmcServer.getId());
			resource.setInventory(JSONObject.toJSONString(server));
			logger.info("add new resource:{}", resource);
			resourceRepository.save(resource);
		}
		return resource;
	}

	private Server HmcServerToServer(Long hmcServerId) {
		Server server = new Server();
		ServerConfig config = new ServerConfig();
		server.setConfig(config);

		try {
			// 内存
			HmcSystemMemoryConfig memoryConfig = memoryConfigRepository.getByServerId(hmcServerId);
			if (null != memoryConfig) {
				Long memory = memoryConfig.getConfigurableSystemMemory();
				if (null != memory) {
					config.setMemoryCapacity(new BigDecimal(Double.valueOf(memory))
							.divide(new BigDecimal(1024), 2, RoundingMode.HALF_UP).doubleValue());
				}
			}
			// 厂商
			config.setVendor("IBM");
			// CPU
			HmcSystemProcessorConfig cpuConfig = processorConfigRepository.getByServerId(hmcServerId);
			if (null != cpuConfig) {
				config.setCpuCore(cpuConfig.getConfigurableSystemProcessorUnits().intValue());
			}
			// disk
			config.setDiskCapacity(0.0);
		} catch (Exception e) {
			return null;
		}

		return server;
	}

	private String convertStatus(String status) {
		if ("operating".equalsIgnoreCase(status)) {
			return BocloudStatus.Server.RUNNING.name();
		} else if ("power off".equalsIgnoreCase(status)) {
			return BocloudStatus.Server.STOPPED.name();
		}
		return BocloudStatus.Server.ERROR.name();
	}

	/**
	 * 将HmcServer表中的状态值转换为Server表中的状态值 <br/>
	 * HmcServer表中的状态值见下面代码中的switch <br/>
	 * Server表中的状态值包含 <br/>
	 * RUNNING: '运行中', <br/>
	 * STOPPED: '关机', <br/>
	 * STOPPING: '关机中', <br/>
	 * STARTING: '开机中', <br/>
	 * SUSPENDED: '挂起', <br/>
	 * SUSPENDING: '挂起中', <br/>
	 * ACTIVING: '激活中', <br/>
	 * PAUSED: '停止', <br/>
	 * PAUSING: '停止中', <br/>
	 * RECOVERING: '恢复中', <br/>
	 * BUILDING: '创建中', <br/>
	 * RESTARTING: '重启中', <br/>
	 * EXCEPTION: '异常', <br/>
	 * SYNSEXCEPTION: '同步异常', <br/>
	 * UNKNOWN: '已断开', <br/>
	 * UNKNOWNON: '已断开', <br/>
	 * UNKNOWNOFF: '已断开', <br/>
	 * UNKNOWNSUSPEND: '已断开' <br/>
	 *
	 * 2019-02-28 by 卢艳超
	 * 
	 * @param status
	 * @return
	 */
	private String convertHmcServerStatusToServerStatus(String status) {
		switch (status) {
		case "operating":
			return "RUNNING"; // 运行
		case "power off":
			return "STOPPED"; // 断电
		case "initializing":
			return "BUILDING"; // 正在初始化
		case "standby":
			return "UNKNOWNSUSPEND"; // 待机
		case "service processor failover":
			return "EXCEPTION"; // 服务处理器故障
		case "power off in progress":
			return "STOPPING"; // 正在断电
		case "error":
			return "EXCEPTION"; // 错误
		case "error - dump in progress":
			return "EXCEPTION"; // 错误-正在转储'
		case "error - terminated":
			return "EXCEPTION"; // 错误-终止
		case "version mismatch":
			return "EXCEPTION"; // 版本不匹配
		case "incomplete":
			return "EXCEPTION"; // 残缺
		case "recovery":
			return "RECOVERING"; // 恢复
		case "no connection":
			return "UNKNOWNOFF"; // 未连接
		case "failed authentication":
			return "UNKNOWNOFF"; // 身份验证失败
		case "pending authentication - password updates required":
			return "UNKNOWNOFF"; // 等待验证-需要更新密码
		case "CREATE_RUNNING":
			return "BUILDING"; // 创建中
		case "POWERON_RUNNING":
			return "STARTING"; // 开机中
		case "POWEROFF_RUNNING":
			return "STOPPING"; // 断电中
		case "REMOVE_CONNECTION_RUNNING":
			return "UNKNOWNOFF"; // 关闭连接中
		case "RESET_CONNECTION_RUNNING":
			return "UNKNOWNOFF"; // 重置连接中
		default:
			return "UNKNOWN";
		}
	}

	/**
	 * 将HmcPartition表中的状态值转换为CloudServer表中的状态值 <br/>
	 *
	 * CloudServer表中的状态值包含 <br/>
	 * RUNNING: '运行中', <br/>
	 * STOPPED: '关机', <br/>
	 * STOPPING: '关机中', <br/>
	 * STARTING: '开机中', <br/>
	 * SUSPENDED: '挂起', <br/>
	 * SUSPENDING: '挂起中', <br/>
	 * ACTIVING: '激活中', <br/>
	 * PAUSED: '停止', <br/>
	 * PAUSING: '停止中', <br/>
	 * RECOVERING: '恢复中', <br/>
	 * BUILDING: '创建中', <br/>
	 * RESTARTING: '重启中', <br/>
	 * EXCEPTION: '异常', <br/>
	 * SYNSEXCEPTION: '同步异常', <br/>
	 * UNKNOWN: '已断开', <br/>
	 * UNKNOWNON: '已断开', <br/>
	 * UNKNOWNOFF: '已断开', <br/>
	 * UNKNOWNSUSPEND: '已断开' <br/>
	 *
	 * 2019-02-28 by 卢艳超
	 * 
	 * @param status
	 * @return
	 */
	private String convertHmcPartitionStatusToCloudServerStatus(String status) {
		// TODO: 2019/2/28 暂时未处理对应关系 直接返回
		return status;
	}

	private void syncVirtualSwitch(Long serverId, List<VirtualSwitchEntry> vswitchEntries, Long userId)
			throws Exception {
		// 获取服务器的虚拟交换机列表
		List<HmcVirtualSwitch> vswitches = hmcVirtualSwitchRepository.listByServerId(serverId);
		Map<String, HmcVirtualSwitch> oldParMap = Maps.newHashMap();
		for (HmcVirtualSwitch vswitch : vswitches) {
			oldParMap.put(vswitch.getUuid(), vswitch);
		}

		// 同步虚拟交换机列表数据
		logger.info("开始同步server[" + serverId + "]的虚拟交换机信息");
		if (null != vswitchEntries) {
			for (VirtualSwitchEntry vswitchEntry : vswitchEntries) {
				HmcVirtualSwitch hmcVirtualSwitch = new HmcVirtualSwitch();
				VirtualSwitch virtualSwitch = vswitchEntry.getContent().getVirtualSwitch();
				if (oldParMap.containsKey(vswitchEntry.getId())) {
					// 更新虚拟交换机列表数据
					hmcVirtualSwitch = oldParMap.get(vswitchEntry.getId());
					hmcVirtualSwitch.setName(virtualSwitch.getSwitchName());
					hmcVirtualSwitch.setMenderId(userId);
					hmcVirtualSwitch.setUuid(vswitchEntry.getId());
					hmcVirtualSwitchRepository.update(hmcVirtualSwitch);
					oldParMap.remove(vswitchEntry.getId());
				} else {
					// 插入虚拟交换机列表数据
					hmcVirtualSwitch.setName(virtualSwitch.getSwitchName());
					hmcVirtualSwitch.setSwitchId(MathUtils.castToIntNoException(virtualSwitch.getSwitchId()));
					hmcVirtualSwitch.preSave(userId, userId, serverId);
					hmcVirtualSwitch.setUuid(vswitchEntry.getId());
					hmcVirtualSwitchRepository.save(hmcVirtualSwitch);
				}
			}
		}

		// 删除已经不存在的虚拟交换机数据
		Iterator<HmcVirtualSwitch> iteratorVswitch = oldParMap.values().iterator();
		while (iteratorVswitch.hasNext()) {
			Long id = iteratorVswitch.next().getId();
			hmcVirtualSwitchRepository.remove(id, userId);
		}
	}

	private void syncNetworkBridge(Long serverId, List<VirtualNetworkBridgeEntry> networkBridgeEntries, Long userId)
			throws Exception {
		// 获取服务器的虚拟网桥列表
		List<HmcVirtualNetworkBridge> bridges = hmcVirtualNetworkBridgeRepository.listByServerId(serverId);
		Map<String, HmcVirtualNetworkBridge> oldParMap = Maps.newHashMap();
		for (HmcVirtualNetworkBridge bridge : bridges) {
			oldParMap.put(bridge.getUuid(), bridge);
		}

		// 同步虚拟网桥列表数据
		logger.info("开始同步server[" + serverId + "]的虚拟网桥信息");
		if (null != networkBridgeEntries) {
			for (VirtualNetworkBridgeEntry virtualNetworkBridgeEntry : networkBridgeEntries) {
				HmcVirtualNetworkBridge hmcVirtualNetworkBridge = new HmcVirtualNetworkBridge();
				NetworkBridge networkBridge = virtualNetworkBridgeEntry.getContent().getNetworkBridge();
				if (oldParMap.containsKey(virtualNetworkBridgeEntry.getId())) {
					// 更新虚拟网桥列表数据
					hmcVirtualNetworkBridge = oldParMap.get(virtualNetworkBridgeEntry.getId());
					hmcVirtualNetworkBridge.setMenderId(userId);
					hmcVirtualNetworkBridge.setUuid(virtualNetworkBridgeEntry.getId());
					List<TrunkAdapter> trunkAdapters = networkBridge.getLoadGroups().getLoadGroup().getTrunkAdapters()
							.getTrunkAdapters();
					HmcVirtualSwitch hmcVirtualSwitch = hmcVirtualSwitchRepository.getBySwitchId(
							MathUtils.castToIntNoException(trunkAdapters.get(0).getVirtualSwitchID()), serverId);
					hmcVirtualNetworkBridge.setSwitchId(hmcVirtualSwitch.getId());
					hmcVirtualNetworkBridgeRepository.update(hmcVirtualNetworkBridge);
					oldParMap.remove(virtualNetworkBridgeEntry.getId());
				} else {
					// 插入虚拟网桥列表数据
					List<TrunkAdapter> trunkAdapters = networkBridge.getLoadGroups().getLoadGroup().getTrunkAdapters()
							.getTrunkAdapters();
					HmcVirtualSwitch hmcVirtualSwitch = hmcVirtualSwitchRepository.getBySwitchId(
							MathUtils.castToIntNoException(trunkAdapters.get(0).getVirtualSwitchID()), serverId);
					hmcVirtualNetworkBridge.setSwitchId(hmcVirtualSwitch.getId());
					hmcVirtualNetworkBridge
							.setPortVlanId(MathUtils.castToIntNoException(trunkAdapters.get(0).getPortVLANID()));
					for (TrunkAdapter trunkAdapter : trunkAdapters) {
						if (trunkAdapter.getTaggedVlanIds() != null) {
							hmcVirtualNetworkBridge
									.setTaggedVlanIds(MathUtils.castToIntNoException(trunkAdapter.getTaggedVlanIds()));
						}
					}
					hmcVirtualNetworkBridge.preSave(userId, userId, serverId);
					hmcVirtualNetworkBridge.setUuid(virtualNetworkBridgeEntry.getId());
					hmcVirtualNetworkBridgeRepository.save(hmcVirtualNetworkBridge);
				}
			}
		}
		// 删除已经不存在的虚拟交换机数据
		Iterator<HmcVirtualNetworkBridge> iteratorBrideg = oldParMap.values().iterator();
		while (iteratorBrideg.hasNext()) {
			Long id = iteratorBrideg.next().getId();
			hmcVirtualNetworkBridgeRepository.remove(id, userId);
		}

	}

	private void syncHostEthernetAdapter(Long serverId, List<HostEthernetAdapterEntry> entries) throws Exception {
		if (null == entries) {
			logger.warn("Failed to get host ethernet adapter information");
			return;
		}
		if (entries.isEmpty()) {
			hmcDatabaseHelper.deleteHostEthernetAdapter(serverId);
			return;
		}
		List<HmcHostEthernetAdapter> hmcHostEthernetAdapters = hmcHostEthernetAdapterRepository
				.listByServerId(serverId);
		Map<Long, HmcHostEthernetAdapter> oldMap = Maps.newHashMap();
		for (HmcHostEthernetAdapter adapter : hmcHostEthernetAdapters) {
			oldMap.put(adapter.getAdapterId(), adapter);
		}

		for (HostEthernetAdapterEntry entry : entries) {
			HostEthernetAdapter hostEthernetAdapter = entry.getContent().getHostEthernetAdapter();
			if (null != hostEthernetAdapter) {
				Boolean result = hmcDatabaseHelper.updateHostEthernetAdapter(serverId, hostEthernetAdapter,
						entry.getId());
				if (result) {
					oldMap.remove(MathUtils.castToLong(hostEthernetAdapter.getAdapterID()));
				}
			}
		}

		// 删除已经不存在的主机以太网数据
		Iterator<HmcHostEthernetAdapter> iteratorHea = oldMap.values().iterator();
		while (iteratorHea.hasNext()) {
			HmcHostEthernetAdapter adapter = iteratorHea.next();
			hmcHeaLogicalPortRepository.deleteByHeaId(adapter.getId());
			hmcHeaPhysicalPortRepository.deleteByHeaId(adapter.getId());
			hmcHostEthernetAdapterRepository.delete(adapter);
		}
	}

	private void syncSharedProcessorPool(Long serverId, List<SharedProcessorPoolEntry> entries, Long userId)
			throws Exception {
		// 获取主机的共享存储池信息
		List<HmcSystemSharedProcessorPool> sharedProcessorPools = sharedProcessorPoolRepository
				.listByServerId(serverId);
		Map<String, HmcSystemSharedProcessorPool> oldParMap = Maps.newHashMap();
		for (HmcSystemSharedProcessorPool sharedProcessorPool : sharedProcessorPools) {
			oldParMap.put(sharedProcessorPool.getUuid(), sharedProcessorPool);
		}

		// 同步共享存储池列表数据
		logger.info("开始同步server[" + serverId + "]的共享存储池信息");
		if (null != entries) {
			for (SharedProcessorPoolEntry sharedProcessorPoolEntry : entries) {
				HmcSystemSharedProcessorPool sharedProcessorPool = new HmcSystemSharedProcessorPool();
				SharedProcessorPool processorPool = sharedProcessorPoolEntry.getContent().getSharedProcessorPool();
				if (oldParMap.containsKey(sharedProcessorPoolEntry.getId())) {
					// 更新共享存储池列表数据
					sharedProcessorPool = oldParMap.get(sharedProcessorPoolEntry.getId());
					sharedProcessorPool.setMenderId(userId);
					sharedProcessorPool.setUuid(sharedProcessorPoolEntry.getId());
					sharedProcessorPool.setName(processorPool.getPoolName());
					sharedProcessorPool.setHmcPoolId(Integer.valueOf(processorPool.getPoolID()));
					sharedProcessorPool.setAssignedPartitions(processorPool.getAssignedPartitions() != null
							? processorPool.getAssignedPartitions().getLink().size()
							: 0);
					sharedProcessorPool
							.setCurrentReservedProcessingUnits(processorPool.getCurrentReservedProcessingUnits() != null
									? MathUtils.castToDoubleClass(processorPool.getCurrentReservedProcessingUnits())
									: null);
					sharedProcessorPool.setMaximumProcessingUnits(processorPool.getMaximumProcessingUnits() != null
							? MathUtils.castToDoubleClass(processorPool.getMaximumProcessingUnits())
							: null);
					sharedProcessorPool
							.setPendingReservedProcessingUnits(processorPool.getPendingReservedProcessingUnits() != null
									? MathUtils.castToDoubleClass(processorPool.getPendingReservedProcessingUnits())
									: null);
					sharedProcessorPool.setAvailableProcUnits(processorPool.getAvailableProcUnits() != null
							? MathUtils.castToDoubleClass(processorPool.getAvailableProcUnits())
							: null);
					sharedProcessorPoolRepository.update(sharedProcessorPool);
					oldParMap.remove(sharedProcessorPoolEntry.getId());
				} else {
					// 插入共享处理池列表数据
					sharedProcessorPool.setUuid(sharedProcessorPoolEntry.getId());
					sharedProcessorPool.setName(processorPool.getPoolName());
					sharedProcessorPool.setHmcPoolId(Integer.valueOf(processorPool.getPoolID()));
					sharedProcessorPool.setAssignedPartitions(processorPool.getAssignedPartitions() != null
							? processorPool.getAssignedPartitions().getLink().size()
							: 0);
					sharedProcessorPool
							.setCurrentReservedProcessingUnits(processorPool.getCurrentReservedProcessingUnits() != null
									? MathUtils.castToDoubleClass(processorPool.getCurrentReservedProcessingUnits())
									: null);
					sharedProcessorPool.setMaximumProcessingUnits(processorPool.getMaximumProcessingUnits() != null
							? MathUtils.castToDoubleClass(processorPool.getMaximumProcessingUnits())
							: null);
					sharedProcessorPool
							.setPendingReservedProcessingUnits(processorPool.getPendingReservedProcessingUnits() != null
									? MathUtils.castToDoubleClass(processorPool.getPendingReservedProcessingUnits())
									: null);
					sharedProcessorPool.setAvailableProcUnits(processorPool.getAvailableProcUnits() != null
							? MathUtils.castToDoubleClass(processorPool.getAvailableProcUnits())
							: null);
					sharedProcessorPool.preSave(userId, userId, serverId);
					sharedProcessorPoolRepository.save(sharedProcessorPool);
				}
			}
		}
		// 删除已经不存在的共享存储池数据
		Iterator<HmcSystemSharedProcessorPool> iteratorPool = oldParMap.values().iterator();
		while (iteratorPool.hasNext()) {
			Long id = iteratorPool.next().getId();
			sharedProcessorPoolRepository.remove(id, userId);
		}

	}

	public BocloudStatus.Server convertCloudServerStatus(String hmcServerStatus) {
		BocloudStatus.Server cloudServerStatus = null;
		try {
			cloudServerStatus = BocloudStatus.Server.valueOf(hmcServerStatus.toUpperCase());
		} catch (IllegalArgumentException e) {
		}
		if (cloudServerStatus != null) {
			return cloudServerStatus;
		}
		if ("NOT ACTIVATED".equals(hmcServerStatus.toUpperCase())) {
			return BocloudStatus.Server.STOPPED;
		}
		if ("OPEN FIRMWARE".equals(hmcServerStatus.toUpperCase())) {
			return BocloudStatus.Server.RUNNING;
		}
		return BocloudStatus.Server.UNKNOWN;
	}

	public void convertToCloudServer(HmcPartition lpar, CloudServer cloudServer, CloudVendor cloudVendor)
			throws Exception {
		boolean isVios = HmcPartitionType.VIOS.getType().equalsIgnoreCase(lpar.getPartitionType());
		BocloudResult bocloudResult = hmcPartitionDriver.getPartitionAttribute(cloudVendor.getUuid(), lpar.getUuid(),
				isVios);
		if (bocloudResult.isFailed()) {
			throw new RuntimeException(bocloudResult.getMessage());
		}
		if (isVios) {
			VirtualIOServerEntry viosEntry = (VirtualIOServerEntry) bocloudResult.getData();
			convertToCloudServer(viosEntry.getContent().getVirtualIOServer(), cloudServer);
		} else {
			LogicalPartitionEntry lparEntry = (LogicalPartitionEntry) bocloudResult.getData();
			convertToCloudServer(lparEntry.getContent().getLogicalPartition(), cloudServer);
		}
	}

	public void convertToCloudServer(LogicalPartition lpar, CloudServer cloudServer) throws Exception {
		VmNetworkBean networkBean = new VmNetworkBean();
		networkBean.setConnected(true);
		networkBean.setAddress(lpar.getResourceMonitoringIPAddress());
		List<VmNetworkBean> networkBeans = new ArrayList<>();
		networkBeans.add(networkBean);

		cloudServer.setUuid(lpar.getPartitionUUID());
		cloudServer.setInstanceId(lpar.getPartitionUUID());
		cloudServer.setName(lpar.getPartitionName());
		cloudServer.setPrivateIps(JSON.toJSONString(networkBeans));
		cloudServer.setManagerIp(lpar.getResourceMonitoringIPAddress());
		cloudServer.setStatus(convertCloudServerStatus(lpar.getPartitionState()).name());

		String sharingMode = lpar.getPartitionProcessorConfiguration().getCurrentSharingMode();
		if ("capped".equals(sharingMode) || "uncapped".equals(sharingMode)) {
			Optional.of(lpar).map(LogicalPartition::getPartitionProcessorConfiguration)
					.map(PartitionProcessorConfiguration::getCurrentSharedProcessorConfiguration)
					.map(CurrentSharedProcessorConfiguration::getAllocatedVirtualProcessors).map(Integer::parseInt)
					.ifPresent(cloudServer::setCpu);
		} else {
			Optional.of(lpar).map(LogicalPartition::getPartitionProcessorConfiguration)
					.map(PartitionProcessorConfiguration::getCurrentDedicatedProcessorConfiguration)
					.map(CurrentDedicatedProcessorConfiguration::getCurrentProcessors).map(Integer::parseInt)
					.ifPresent(cloudServer::setCpu);
		}

		cloudServer.setMemory(new BigDecimal(
				MathUtils.castToDoubleNoException(lpar.getPartitionMemoryConfiguration().getCurrentMemory()))
						.divide(new BigDecimal(1024)).setScale(2, BigDecimal.ROUND_HALF_UP));
		cloudServer.setDisk(0); // hmcPartition 中没有硬盘容量，所以不处理
		cloudServer.setIsTemplate(false);
		cloudServer.setRecycle(false);
		cloudServer.setVendorType(CloudProvider.HMC.name());
	}

	public void convertToCloudServer(VirtualIOServer vios, CloudServer cloudServer) throws Exception {
		VmNetworkBean networkBean = new VmNetworkBean();
		networkBean.setConnected(true);
		networkBean.setAddress(vios.getResourceMonitoringIPAddress());
		List<VmNetworkBean> networkBeans = new ArrayList<>();
		networkBeans.add(networkBean);

		cloudServer.setUuid(vios.getPartitionUUID());
		cloudServer.setInstanceId(vios.getPartitionUUID());
		cloudServer.setName(vios.getPartitionName());
		cloudServer.setPrivateIps(JSON.toJSONString(networkBeans));
		cloudServer.setManagerIp(vios.getResourceMonitoringIPAddress());
		cloudServer.setStatus(convertCloudServerStatus(vios.getPartitionState()).name());

		String sharingMode = vios.getPartitionProcessorConfiguration().getCurrentSharingMode();
		if ("capped".equals(sharingMode) || "uncapped".equals(sharingMode)) {
			cloudServer.setCpu(Integer.parseInt(vios.getPartitionProcessorConfiguration()
					.getCurrentSharedProcessorConfiguration().getAllocatedVirtualProcessors()));
		} else {
			cloudServer.setCpu(Integer.parseInt(vios.getPartitionProcessorConfiguration()
					.getCurrentDedicatedProcessorConfiguration().getCurrentProcessors()));
		}

		cloudServer.setMemory(new BigDecimal(
				MathUtils.castToDoubleNoException(vios.getPartitionMemoryConfiguration().getCurrentMemory()))
						.divide(new BigDecimal(1024)).setScale(2, BigDecimal.ROUND_HALF_UP));
		cloudServer.setDisk(0); // hmcPartition 中没有硬盘容量，所以不处理
		cloudServer.setIsTemplate(false);
		cloudServer.setRecycle(false);
		cloudServer.setVendorType(CloudProvider.HMC.name());
	}

	private void syncPartiton(Long serverId, SyncModel syncModel, Long userId, Long vendorId) throws Exception {
		// 获取分区列表数据
		List<HmcPartition> hmcPartitions = hmcPartitionRepository.listByServerId(serverId);
		Map<String, HmcPartition> oldParMap = Maps.newHashMap();
		for (HmcPartition hmcPartition : hmcPartitions) {
			// 删除不存在uuid的分区
			if (null == hmcPartition.getUuid() || hmcPartition.getUuid().isEmpty()) {
				hmcDatabaseHelper.removePartition(hmcPartition.getId(), userId);
			} else if (oldParMap.containsKey(hmcPartition.getUuid())) {
				// 如果一个服务器下面有相同的UUID分区，这说明这里面有冗余数据，必须删除这个
				hmcDatabaseHelper.removePartition(hmcPartition.getId(), userId);
			} else {
				oldParMap.put(hmcPartition.getUuid(), hmcPartition);
			}
		}

		// 获取虚拟机数据列表
		HmcServer hmcServer = hmcServerRepository.getServerById(serverId);
		Server server = serverRepository.getByUuid(hmcServer.getUuid());
		List<CloudServer> cloudServers = cloudServerRepository.listByHid(server.getId());
		Map<String, CloudServer> oldCloudServerMap = Maps.newHashMap();
		for (CloudServer cloudServer : cloudServers) {
			// 删除不存在uuid的虚拟机
			if (null == cloudServer.getUuid() || cloudServer.getUuid().isEmpty()) {
				resourceRepository.remove(cloudServer.getId(), ResourceCategory.Computer.name(),
						ResourceCatalog.LOGICAL.name(), userId);
				cloudServerRepository.remove(cloudServer.getId(), userId);
			} else if (oldCloudServerMap.containsKey(cloudServer.getUuid())) {
				// 如果一个服务器下面有相同的UUID，这说明这里面有冗余数据，必须删除这个
				resourceRepository.remove(cloudServer.getId(), ResourceCategory.Computer.name(),
						ResourceCatalog.LOGICAL.name(), userId);
				cloudServerRepository.remove(cloudServer.getId(), userId);
			} else {
				oldCloudServerMap.put(cloudServer.getUuid(), cloudServer);
			}
		}

		Map<String, List<LogicalPartitionProfileEntry>> profileEntrys = syncModel.getProfileEntries();
		Map<String, List<VolumeGroupEntry>> volumeGroupEntries = syncModel.getVolumeGroupEntries();

		/**
		 * 先同步lpar的数据，把lpar信息入库，然后再同步vios。
		 *
		 * 这样同步vios的时候，虚拟磁盘才能拿到LPAR的平台id
		 */
		// 先同步Lpar数据
		logger.info("开始同步server[" + serverId + "]的逻辑分区");
		List<LogicalPartitionEntry> lparEntrys = syncModel.getLparEntries();
		if (null != lparEntrys) {
			for (LogicalPartitionEntry lparEntry : lparEntrys) {
				HmcPartition par = new HmcPartition();
				LogicalPartition lpar = lparEntry.getContent().getLogicalPartition();
				if (oldParMap.containsKey(lpar.getPartitionUUID())) {
					// 更新lpar数据
					par = oldParMap.get(lpar.getPartitionUUID());
					convertToHmcPartition(par, lpar);
					par.setServerId(serverId);
					par.setMenderId(userId);
					hmcPartitionRepository.update(par);
					oldParMap.remove(lpar.getPartitionUUID());
				} else {
					// 插入lpar数据
					convertToHmcPartition(par, lpar);
					par.setServerId(serverId);
					par.preSave(userId, userId, serverId);
					hmcPartitionRepository.save(par);
				}

				// 更新RMC链接状态
				logger.info("开始同步RMC链接状态[" + par.getName() + "]");
				if (syncModel.getRmcStatus().containsKey(par.getUuid())) {
					par.setRmcState(syncModel.getRmcStatus().get(par.getUuid()));
					hmcPartitionRepository.update(par);
				}

				if (oldCloudServerMap.containsKey(lpar.getPartitionUUID())) {
					// 更新cloudserver数据
					CloudServer cloudServer = cloudServerRepository.getByUuid(par.getUuid());
					convertToCloudServer(lpar, cloudServer);
					cloudServer.setHostId(server.getId());
					cloudServer.setVendorId(server.getVendorId());
					cloudServer.setMenderId(userId);
					cloudServer.setGmtModify(new Date());
					cloudServerRepository.update(cloudServer);
					oldCloudServerMap.remove(lpar.getPartitionUUID());
				} else {
					// 插入cloudserver数据
					CloudServer cloudServer = new CloudServer();
					convertToCloudServer(lpar, cloudServer);
					cloudServer.setHostId(server.getId());
					cloudServer.setVendorId(server.getVendorId());
					cloudServer.setCreatorId(userId);
					cloudServer.setMenderId(userId);
					cloudServer.setGmtCreate(new Date());
					cloudServerRepository.save(cloudServer);
				}

				if (null != profileEntrys && profileEntrys.containsKey(par.getUuid())) {
					// 获得分区激活的概要文件uuid
					String profileUuid = null;
					if (null != lpar.getAssociatedPartitionProfile()) {
						String[] values = lpar.getAssociatedPartitionProfile().getHref().split("/");
						profileUuid = values[values.length - 1];
					}
					hmcDatabaseHelper.syncLparProfiles(par, profileEntrys.get(par.getUuid()), profileUuid, userId);
				}
				// 同步处理器
				logger.info("开始同步处理器[" + par.getName() + "]");
				hmcDatabaseHelper.setPartitionProcessor(par, lpar.getPartitionProcessorConfiguration(), userId);

				// 同步内存
				logger.info("开始同步内存[" + par.getName() + "]");
				hmcDatabaseHelper.setPartitionMemory(par, lpar.getPartitionMemoryConfiguration(), false, userId);

				// 同步IO
				logger.info("开始同步IO[" + par.getName() + "]");
				hmcDatabaseHelper.setPartitionIo(par, lpar.getPartitionIOConfiguration(), userId);

				// 同步虚拟scsi适配器
				logger.info("开始同步虚拟scsi[" + par.getName() + "]");
				hmcPartitionService.updateVirtualScsiAdapterForLpar(par, vendorId);

				// 同步虚拟光纤通道mapping
				logger.info("开始同步虚拟vfc[" + par.getName() + "]");
				hmcPartitionService.updateVirtualFibreChannelMappingForLpar(par, vendorId);

				// 同步虚拟网络适配器
				logger.info("开始同步虚拟以太网适配器[" + par.getName() + "]");
				hmcPartitionService.updateNetworkAdapterForLpar(par, vendorId);

				// 同步磁盘容量到CloudServer表
				logger.info("开始同步磁盘容量到CloudServer[" + par.getName() + "]");
				hmcPartitionService.updateCloudServerDiskOfLpar(par.getId());
			}
		}

		// 再同步vios数据
		logger.info("开始同步server[" + serverId + "]的vios");
		List<VirtualIOServerEntry> viosEntrys = syncModel.getViosEntries();
		if (null != viosEntrys) {
			for (VirtualIOServerEntry viosEntry : viosEntrys) {
				HmcPartition par = new HmcPartition();
				VirtualIOServer vioServer = viosEntry.getContent().getVirtualIOServer();
				if (oldParMap.containsKey(vioServer.getPartitionUUID())) {
					// 更新vios数据
					par = oldParMap.get(vioServer.getPartitionUUID());
					convertToHmcPartition(par, vioServer);
					par.setServerId(serverId);
					par.setMenderId(userId);
					hmcPartitionRepository.update(par);
					oldParMap.remove(vioServer.getPartitionUUID());
				} else {
					// 插入vios数据
					convertToHmcPartition(par, vioServer);
					par.setServerId(serverId);
					par.preSave(userId, userId, serverId);
					hmcPartitionRepository.save(par);
				}

				// 更新RMC链接状态
				logger.info("开始同步RMC链接状态[" + par.getName() + "]");
				if (syncModel.getRmcStatus().containsKey(par.getUuid())) {
					par.setRmcState(syncModel.getRmcStatus().get(par.getUuid()));
					hmcPartitionRepository.update(par);
				}

				if (oldCloudServerMap.containsKey(vioServer.getPartitionUUID())) {
					// 更新cloudserver数据
					CloudServer cloudServer = cloudServerRepository.getByUuid(par.getUuid());
					convertToCloudServer(vioServer, cloudServer);
					cloudServer.setHostId(server.getId());
					cloudServer.setVendorId(server.getVendorId());
					cloudServer.setMenderId(userId);
					cloudServer.setGmtModify(new Date());
					cloudServerRepository.update(cloudServer);
					oldCloudServerMap.remove(vioServer.getPartitionUUID());
				} else {
					// 插入cloudserver数据
					CloudServer cloudServer = new CloudServer();
					convertToCloudServer(vioServer, cloudServer);
					cloudServer.setHostId(server.getId());
					cloudServer.setVendorId(server.getVendorId());
					cloudServer.setCreatorId(userId);
					cloudServer.setMenderId(userId);
					cloudServer.setGmtCreate(new Date());
					cloudServerRepository.save(cloudServer);
				}

				if (null != profileEntrys && profileEntrys.containsKey(par.getUuid())) {
					// 获得分区激活的概要文件uuid
					String profileUuid = null;
					if (null != vioServer.getAssociatedPartitionProfile()) {
						String[] values = vioServer.getAssociatedPartitionProfile().getHref().split("/");
						profileUuid = values[values.length - 1];
					}
					hmcDatabaseHelper.syncLparProfiles(par, profileEntrys.get(par.getUuid()), profileUuid, userId);
				}
				if (null != volumeGroupEntries && volumeGroupEntries.containsKey(par.getUuid())) {
					// 获得虚拟磁盘信息
					hmcDatabaseHelper.syncVirutalStorage(par, volumeGroupEntries.get(par.getUuid()),
							vioServer.getVirtualSCSIMappings() == null ? null
									: vioServer.getVirtualSCSIMappings().getVirtualScsiMapping());
				}

				// 同步处理器
				logger.info("开始同步处理器[" + par.getName() + "]");
				hmcDatabaseHelper.setPartitionProcessor(par, vioServer.getPartitionProcessorConfiguration(), userId);

				// 同步内存
				logger.info("开始同步内存[" + par.getName() + "]");
				hmcDatabaseHelper.setPartitionMemory(par, vioServer.getPartitionMemoryConfiguration(), true, userId);

				// 同步IO
				logger.info("开始同步IO[" + par.getName() + "]");
				hmcDatabaseHelper.setPartitionIo(par, vioServer.getPartitionIOConfiguration(), userId);

				// 获得物理磁盘信息
				hmcDatabaseHelper.syncPhysicalDisk(par,
						vioServer.getPhysicalVolumes() == null ? null
								: vioServer.getPhysicalVolumes().getPhysicalVolumeList(),
						vioServer.getVirtualSCSIMappings() == null ? null
								: vioServer.getVirtualSCSIMappings().getVirtualScsiMapping(),
						volumeGroupEntries != null && volumeGroupEntries.containsKey(par.getUuid())
								? volumeGroupEntries.get(par.getUuid())
								: null);

				// 同步物理光纤通道信息
				logger.info("开始同步物理fc[" + par.getName() + "]");
				hmcDatabaseHelper.syncPhysicalFibreChannel(par,
						vioServer.getPartitionIOConfiguration().getProfileIOSlots().getProfileIOSlot());

				// 同步虚拟scsi
				logger.info("开始同步虚拟scsi[" + par.getName() + "]");
				hmcPartitionService.updateVirtualScsiAdapterForVios(par, vioServer.getVirtualSCSIMappings());

				// 同步虚拟光纤通道mapping
				logger.info("开始同步虚拟vfc[" + par.getName() + "]");
				hmcPartitionService.updateVirtualFibreChannelMappingForVios(par,
						vioServer.getVirtualFibreChannelMappings());

				// 同步虚拟光纤通道mapping
				logger.info("开始同步虚拟以太网适配器[" + par.getName() + "]");
				hmcPartitionService.updateNetworkAdapterForVios(par, vioServer.getTrunkAdapters());

				// 同步磁盘容量到CloudServer表
				logger.info("开始同步磁盘容量到CloudServer[" + par.getName() + "]");
				hmcPartitionService.updateCloudServerDiskOfVios(par.getId());

				// 2019-09-03 : 虚拟网络功能尚未开发完成，此段代码先注释掉
				// 同步物理以太网适配器
				// logger.info("开始同步物理以太网适配器[" + par.getName() + "]");
				// hmcPartitionService.updatePhysicalEthernetAdapter(par, vioServer);

				// 2019-09-03 : 虚拟网络功能尚未开发完成，此段代码先注释掉
				// 同步虚拟以太网适配器
				// logger.info("开始同步共享以太网适配器[" + par.getName() + "]");
				// hmcPartitionService.updateShareEthernetAdapter(par, vioServer);
			}
		}

		// 删除已经不存在的分区数据
		Iterator<HmcPartition> iteratorPar = oldParMap.values().iterator();
		while (iteratorPar.hasNext()) {
			Long id = iteratorPar.next().getId();
			hmcDatabaseHelper.removePartition(id, userId);
		}
		// 删除已经不存在的虚拟机数据
		Iterator<CloudServer> iteratorCloudServer = oldCloudServerMap.values().iterator();
		while (iteratorCloudServer.hasNext()) {
			Long id = iteratorCloudServer.next().getId();
			resourceRepository.remove(id, ResourceCategory.Computer.name(), ResourceCatalog.LOGICAL.name(), userId);
			cloudServerRepository.remove(id, userId);
		}
	}

	private void convertToHmcPartition(HmcPartition par, VirtualIOServer vioServer) throws Exception {
		// TODO
		par.setKeyLockPosition(vioServer.getKeylockPosition());
		par.setProcessorCompatibilityMode(vioServer.getCurrentProcessorCompatibilityMode());
		par.setErrorPathReport(Boolean.parseBoolean(vioServer.getIsRedundantErrorPathReportingEnabled()));
		// Need to confirm
		par.setServicePartition(Boolean.parseBoolean(vioServer.getIsServicePartition()));
		par.setName(vioServer.getPartitionName());
		par.setHmcPartitionId(Integer.parseInt(vioServer.getPartitionID()));
		par.setPartitionType(vioServer.getPartitionType());
		if (null != vioServer.getIsConnectionMonitoringEnabled()) {
			par.setCurrentProfileSync(vioServer.getCurrentProfileSync());
		}
		par.setConnMonitorEnabled(Boolean.parseBoolean(vioServer.getIsConnectionMonitoringEnabled()));
		par.setAllowPerformanceCollection(Boolean.parseBoolean(vioServer.getAllowPerformanceDataCollection()));
		par.setUuid(vioServer.getPartitionUUID());
		par.setStatus(vioServer.getPartitionState());
		par.setMemory(
				MathUtils.castToDoubleNoException(vioServer.getPartitionMemoryConfiguration().getCurrentMemory()));
		if (null != vioServer.getPartitionProcessorConfiguration().getCurrentSharedProcessorConfiguration()) {
			// 设置目前共享cpu
			par.setProcessor(MathUtils.castToDoubleNoException(vioServer.getPartitionProcessorConfiguration()
					.getCurrentSharedProcessorConfiguration().getCurrentProcessingUnits()));
		} else {
			// 设置目前专用cpu
			par.setProcessor(MathUtils.castToDoubleNoException(vioServer.getPartitionProcessorConfiguration()
					.getCurrentDedicatedProcessorConfiguration().getCurrentProcessors()));
		}
		par.setCode(vioServer.getReferenceCode());
		par.setOsVersion(vioServer.getOperatingSystemVersion());
		par.setIp(vioServer.getResourceMonitoringIPAddress());
		par.setLedOn(Boolean.parseBoolean(vioServer.getIsVirtualServiceAttentionLEDOn()));
		par.setCurrentMaxVirtualIOSlots(
				MathUtils.castToIntClass(vioServer.getPartitionIOConfiguration().getCurrentMaximumVirtualIOSlots()));
		par.setPendingProcessorCompatibilityMode(vioServer.getPendingProcessorCompatibilityMode());

	}

	private void convertToHmcPartition(HmcPartition par, LogicalPartition lpar) throws Exception {
		par.setKeyLockPosition(lpar.getKeylockPosition());
		par.setProcessorCompatibilityMode(lpar.getCurrentProcessorCompatibilityMode());
		par.setErrorPathReport(Boolean.parseBoolean(lpar.getIsRedundantErrorPathReportingEnabled()));
		// Need to confirm
		par.setServicePartition(Boolean.parseBoolean(lpar.getIsServicePartition()));
		par.setName(lpar.getPartitionName());
		par.setHmcPartitionId(Integer.parseInt(lpar.getPartitionID()));
		par.setPartitionType(lpar.getPartitionType());
		par.setCurrentProfileSync(lpar.getCurrentProfileSync());
		if (null != lpar.getIsConnectionMonitoringEnabled()) {
			par.setConnMonitorEnabled(Boolean.parseBoolean(lpar.getIsConnectionMonitoringEnabled()));
		}
		par.setAllowPerformanceCollection(Boolean.parseBoolean(lpar.getAllowPerformanceDataCollection()));
		par.setUuid(lpar.getPartitionUUID());
		par.setMemory(MathUtils.castToDoubleNoException(lpar.getPartitionMemoryConfiguration().getCurrentMemory()));
		if (null != lpar.getPartitionProcessorConfiguration().getCurrentSharedProcessorConfiguration()) {
			// 设置目前共享cpu
			par.setProcessor(MathUtils.castToDoubleNoException(lpar.getPartitionProcessorConfiguration()
					.getCurrentSharedProcessorConfiguration().getCurrentProcessingUnits()));
		} else if (null != lpar.getPartitionProcessorConfiguration().getCurrentDedicatedProcessorConfiguration()) {
			// 设置目前专用cpu
			par.setProcessor(MathUtils.castToDoubleNoException(lpar.getPartitionProcessorConfiguration()
					.getCurrentDedicatedProcessorConfiguration().getCurrentProcessors()));
		}
		par.setCode(lpar.getReferenceCode());
		par.setOsVersion(lpar.getOperatingSystemVersion());
		par.setLedOn(Boolean.parseBoolean(lpar.getIsVirtualServiceAttentionLEDOn()));
		par.setCurrentMaxVirtualIOSlots(
				MathUtils.castToIntClass(lpar.getPartitionIOConfiguration().getCurrentMaximumVirtualIOSlots()));
		par.setPendingProcessorCompatibilityMode(lpar.getPendingProcessorCompatibilityMode());
		if (HmcStatus.PARTITION.INSTALLING.name().equals(par.getStatus())) {
			logger.warn("分区{}正在装机，暂不更新其状态和IP", par.getName());
		} else {
			par.setStatus(lpar.getPartitionState());
			par.setIp(lpar.getResourceMonitoringIPAddress());
		}
	}

	/**
	 * 转换服务器信息为HmcServer
	 *
	 * @author sxp
	 * @since Jun 5, 2018
	 */
	private void convertToHmcServer(HmcServer server, SyncModel syncModel, Long vendorId) {
		ManagedSystemEntry entry = syncModel.getSystemEntry();
		if (entry == null) {
			return;
		}
		hmcDatabaseHelper.updateHmcServerEntity(server, entry);

		// 更新一些服务器非HMC属性
		Date today = Calendar.getInstance().getTime();
		if (server.getGmtCreate() == null) {
			server.setGmtCreate(today);
		} else {
			server.setGmtModify(today);
		}
		server.setDeleted(false);
		server.setVendorId(vendorId);
	}

	/**
	 * 同步服务器关联数据
	 *
	 * @author sxp
	 * @since Jun 4, 2018
	 */
	private void syncServerAssociatedData(HmcServer server, ManagedSystemEntry entry) throws Exception {
		logger.info("正在同步HMC服务器关联数据...");
		if (entry == null) {
			return;
		}

		ManagedSystemContent content = entry.getContent();
		if (content == null) {
			return;
		}

		ManagedSystem system = content.getManagedSystem();
		if (system == null) {
			return;
		}

		// 更新或者保存服务器供电
		HmcIplConfig oldIplConfig = iplConfigRepository.getByServerId(server.getId());
		HmcIplConfig iplConfig = getManagedSystemIplConfig(server, system);
		if (null != oldIplConfig && null != iplConfig) {
			iplConfig.setId(oldIplConfig.getId());
			iplConfig.setServerId(oldIplConfig.getServerId());
			iplConfigRepository.updateEntity(iplConfig);
		} else if (null == oldIplConfig && null != iplConfig) {
			iplConfig.setServerId(server.getId());
			iplConfigRepository.save(iplConfig);
		} else if (null != oldIplConfig) {
			iplConfigRepository.delete(oldIplConfig);
		}

		// 更新或者保存服务器功能
		HmcSystemCapability oldCapability = systemCapabilityRepository.getByServerId(server.getId());
		HmcSystemCapability capability = getManagedSystemCapability(server, system);
		if (null != oldCapability && null != capability) {
			capability.setId(oldCapability.getId());
			capability.setServerId(oldCapability.getServerId());
			systemCapabilityRepository.updateEntity(capability);
		} else if (null == oldCapability && null != capability) {
			capability.setServerId(server.getId());
			systemCapabilityRepository.save(capability);
		} else if (null != oldCapability) {
			systemCapabilityRepository.delete(oldCapability);
		}

		// 更新或者保存服务器内存信息
		HmcSystemMemoryConfig oldMemoryConfig = systemMemoryConfigRepository.getByServerId(server.getId());
		HmcSystemMemoryConfig memoryConfig = getManagedSystemMemoryConfig(server, system);
		if (null != oldMemoryConfig && null != memoryConfig) {
			memoryConfig.setId(oldMemoryConfig.getId());
			memoryConfig.setServerId(oldMemoryConfig.getServerId());
			systemMemoryConfigRepository.updateEntity(memoryConfig);
		} else if (null == oldMemoryConfig && null != memoryConfig) {
			memoryConfig.setServerId(server.getId());
			systemMemoryConfigRepository.save(memoryConfig);
		} else if (null != oldMemoryConfig) {
			systemMemoryConfigRepository.delete(oldMemoryConfig);
		}

		// 更新或者保存服务器处理器信息
		HmcSystemProcessorConfig oldProcessorConfig = systemProcessorConfigRepository.getByServerId(server.getId());
		HmcSystemProcessorConfig processorConfig = getManagedSystemProcessorConfig(server, system);
		if (null != oldProcessorConfig && null != processorConfig) {
			processorConfig.setId(oldProcessorConfig.getId());
			processorConfig.setServerId(oldProcessorConfig.getServerId());
			systemProcessorConfigRepository.updateEntity(processorConfig);
		} else if (null == oldProcessorConfig && null != processorConfig) {
			processorConfig.setServerId(server.getId());
			systemProcessorConfigRepository.save(processorConfig);
		} else if (null != oldProcessorConfig) {
			systemProcessorConfigRepository.delete(oldProcessorConfig);
		}

		// hmc_io_bus, hmc_io_adapter
		Long serverId = server.getId();
		ioBusRepository.deleteByHmcServerId(serverId);
		ioAdapterRepository.deleteByHmcServerId(serverId);
		saveIoBusAndAdapter(server, system);

		// 更新或者保存到ServerConfig表
		Server cmpServer = serverRepository.getByUuid(server.getUuid());
		if (cmpServer != null) {
			ServerConfig serverConfig = serverConfigRepository.getBySid(cmpServer.getId());
			if (serverConfig == null) {
				serverConfig = new ServerConfig();
			}
			serverConfig.setServerId(cmpServer.getId());
			serverConfig.setHmcCpu(processorConfig == null ? null : processorConfig.getInstalledSystemProcessorUnits());
			serverConfig
					.setMemoryCapacity(memoryConfig == null ? null : memoryConfig.getInstalledSystemMemory() / 1024D);
			if (serverConfig.getId() != null) {
				serverConfigRepository.update(serverConfig);
			} else {
				serverConfigRepository.save(serverConfig);
			}
		}

		logger.info("HMC服务器关联数据同步完毕");
	}

	/**
	 * 转换服务器的供电和灯光配置
	 *
	 * @author sxp
	 * @since May 25, 2018
	 */
	private HmcIplConfig getManagedSystemIplConfig(HmcServer server, ManagedSystem system) {
		AssociatedIPLConfiguration config = system.getAssociatedIPLConfiguration();
		if (config == null) {
			return null;
		}

		HmcIplConfig hmcConfig = new HmcIplConfig();
		hmcConfig.setPoweronLparStartPolicy(config.getPowerOnLogicalPartitionStartPolicy());
		Optional.of(config).map(AssociatedIPLConfiguration::getPendingPowerOnLogicalPartitionStartPolicy)
			.map(PendingPowerOnLogicalPartitionStartPolicy::getValue)
			.ifPresent(hmcConfig::setPendingPoweronLparStartPolicy);
		hmcConfig.setCurrentPowerOnSide(config.getCurrentPowerOnSide());
		hmcConfig.setPendingPowerOnSide(config.getPendingPowerOnSide());
		hmcConfig.setPowerOnSpeed(config.getPowerOnSpeed());
		hmcConfig.setPowerOnSpeedOverride(config.getPowerOnSpeedOverride());
		hmcConfig.setCurrentSystemKeylock(config.getCurrentSystemKeylock());
		hmcConfig.setPendingSystemKeylock(config.getPendingSystemKeylock());
		hmcConfig.setPoweronSource(config.getPowerOnSource() == null ? null : config.getPowerOnSource().getValue());
		hmcConfig.setCurrentBootMode(config.getCurrentManufacturingDefaultConfigurationBootMode());
		hmcConfig.setPendingBootMode(config.getPendingManufacturingDefaultConfigurationBootMode());
		hmcConfig.setPoweroffAllLparShutdown(
				Boolean.parseBoolean(config.getPowerOffWhenLastLogicalPartitionIsShutdown()));

		return hmcConfig;
	}

	/**
	 * 转换服务器的功能特性
	 *
	 * @author sxp
	 * @since May 25, 2018
	 */
	private HmcSystemCapability getManagedSystemCapability(HmcServer server, ManagedSystem system) {
		AssociatedSystemCapabilities cap = system.getAssociatedSystemCapabilities();
		if (cap == null) {
			return null;
		}

		HmcSystemCapability hmc = new HmcSystemCapability();
		hmc.setActiveMemorySharingCapable(cap.getActiveMemorySharingCapable());
		hmc.setIbmiCapable(cap.getIBMiCapable());
		hmc.setTelnet5250ApplicationCapable(cap.getTelnet5250ApplicationCapable());
		hmc.setCapacityOnDemandProcessorCapable(cap.getCapacityOnDemandProcessorCapable());
		hmc.setCapacityOnDemandMemoryCapable(cap.getCapacityOnDemandMemoryCapable());
		hmc.setMicroLogicalPartitionCapable(cap.getMicroLogicalPartitionCapable());
		hmc.setVirtualIOServerCapable(cap.getVirtualIOServerCapable());
		hmc.setHostChannelAdapterCapable(cap.getHostChannelAdapterCapable());
		hmc.setLogicalHostEthernetAdapterCapable(cap.getLogicalHostEthernetAdapterCapable());
		hmc.setHugePageMemoryCapable(cap.getHugePageMemoryCapable());
		hmc.setBarrierSynchronizationRegisterCapable(cap.getBarrierSynchronizationRegisterCapable());
		hmc.setServiceProcessorFailoverCapable(cap.getServiceProcessorFailoverCapable());
		hmc.setSharedEthernetFailoverCapable(cap.getSharedEthernetFailoverCapable());
		hmc.setRedundantErrorPathReportingCapable(cap.getRedundantErrorPathReportingCapable());
		hmc.setHardwareDiscoveryCapable(cap.getHardwareDiscoveryCapable());
		hmc.setActiveLogicalPartitionMobilityCapable(cap.getActiveLogicalPartitionMobilityCapable());
		hmc.setInactiveLogicalPartitionMobilityCapable(cap.getInactiveLogicalPartitionMobilityCapable());
		hmc.setIbmiLogicalPartitionMobilityCapable(cap.getIBMiLogicalPartitionMobilityCapable());
		hmc.setLogicalPartitionProcessorCompatibilityModeCapable(
				cap.getLogicalPartitionProcessorCompatibilityModeCapable());
		hmc.setLogicalPartitionAvailabilityPriorityCapable(cap.getLogicalPartitionAvailabilityPriorityCapable());
		hmc.setElectronicErrorReportingCapable(cap.getElectronicErrorReportingCapable());
		hmc.setActiveLogicalPartitionSharedIdeProcessorsCapable(
				cap.getActiveLogicalPartitionSharedIdeProcessorsCapable());
		hmc.setFirmwarePowerSaverCapable(cap.getFirmwarePowerSaverCapable());
		hmc.setHardwarePowerSaverCapable(cap.getHardwarePowerSaverCapable());
		hmc.setVirtualSwitchCapable(cap.getVirtualSwitchCapable());
		hmc.setVirtualFiberChannelCapable(cap.getVirtualFiberChannelCapable());
		hmc.setIbmiLogicalPartitionSuspendCapable(cap.getIBMiLogicalPartitionSuspendCapable());
		hmc.setLogicalPartitionRemoteRestartCapable(cap.getLogicalPartitionRemoteRestartCapable());
		hmc.setVirtualTrustedPlatformModuleCapable(cap.getVirtualTrustedPlatformModuleCapable());
		hmc.setActiveSystemOptimizerCapable(cap.getActiveSystemOptimizerCapable());
		hmc.setVirtualServerNetworkingPhase2Capable(cap.getVirtualServerNetworkingPhase2Capable());
		Optional.ofNullable(cap.getPowerVMLogicalPartitionSimplifiedRemoteRestartCapable())
				.map(PowerVMLogicalPartitionSimplifiedRemoteRestartCapable::getValue)
				.ifPresent(hmc::setPowerVMLogicalPartitionSimplifiedRemoteRestartCapable);
		hmc.setSharedProcessorPoolCapable(cap.getSharedProcessorPoolCapable());
		hmc.setVirtualEthernetCustomMACAddressCapable(cap.getVirtualEthernetCustomMACAddressCapable());

		return hmc;
	}

	/**
	 * 转换服务器的内存配置信息
	 *
	 * @author sxp
	 * @since May 25, 2018
	 */
	private HmcSystemMemoryConfig getManagedSystemMemoryConfig(HmcServer server, ManagedSystem system) {
		AssociatedSystemMemoryConfiguration config = system.getAssociatedSystemMemoryConfiguration();
		if (config == null) {
			return null;
		}

		HmcSystemMemoryConfig hmc = new HmcSystemMemoryConfig();
		hmc.setCurrentAvailableSystemMemory(MathUtils.castToLongNoException(config.getCurrentAvailableSystemMemory()));
		hmc.setMemoryUsedByHypervisor(MathUtils.castToLongNoException(config.getMemoryUsedByHypervisor()));
		hmc.setConfigurableSystemMemory(MathUtils.castToLongNoException(config.getConfigurableSystemMemory()));
		hmc.setInstalledSystemMemory(MathUtils.castToLongNoException(config.getInstalledSystemMemory()));
		hmc.setMemoryRegionSize(MathUtils.castToLongNoException(config.getMemoryRegionSize()));
		hmc.setCurrentAvailableHugePages(MathUtils.castToLongNoException(config.getCurrentAvailableHugePages()));
		hmc.setConfigurableHugePages(MathUtils.castToLongNoException(config.getConfigurableHugePages()));
		hmc.setHugePageSize(MathUtils.castToLongNoException(config.getHugePageSize()));
		hmc.setMaximumHugePages(MathUtils.castToLongNoException(config.getMaximumHugePages()));
		hmc.setRequestedHugePages(MathUtils.castToLongNoException(config.getRequestedHugePages()));
		hmc.setTotalBarrierSynchronizationRegisterArrays(
				MathUtils.castToLongNoException(config.getTotalBarrierSynchronizationRegisterArrays()));
		hmc.setBarrierSynchronizationRegisterArraySize(
				MathUtils.castToLongNoException(config.getBarrierSynchronizationRegisterArraySize()));
		hmc.setAvailableBarrierSynchronizationRegisterArrays(
				MathUtils.castToLongNoException(config.getAvailableBarrierSynchronizationRegisterArrays()));

		return hmc;
	}

	/**
	 * 转换服务器的CPU配置信息
	 *
	 * @author sxp
	 * @since May 25, 2018
	 */
	private HmcSystemProcessorConfig getManagedSystemProcessorConfig(HmcServer server, ManagedSystem system) {
		AssociatedSystemProcessorConfiguration config = system.getAssociatedSystemProcessorConfiguration();
		if (config == null) {
			return null;
		}

		HmcSystemProcessorConfig hmc = new HmcSystemProcessorConfig();
		hmc.setCurrentAvailableSystemProcessorUnits(
				MathUtils.castToDoubleNoException(config.getCurrentAvailableSystemProcessorUnits()));
		hmc.setConfigurableSystemProcessorUnits(
				MathUtils.castToDoubleNoException(config.getConfigurableSystemProcessorUnits()));
		hmc.setInstalledSystemProcessorUnits(
				MathUtils.castToDoubleNoException(config.getInstalledSystemProcessorUnits()));
		hmc.setSupportedPartitionProcessorCompatibilityModes(
				JSON.toJSONString(config.getSupportedPartitionProcessorCompatibilityModes()));

		return hmc;
	}

	/**
	 * 保存服务器的输入输出总线和相应的适配器信息
	 *
	 * @author sxp
	 * @since May 30, 2018
	 */
	private void saveIoBusAndAdapter(HmcServer server, ManagedSystem system) throws Exception {
		AssociatedSystemIOConfiguration associatedSystemIOConfiguration = system.getAssociatedSystemIOConfiguration();
		if (associatedSystemIOConfiguration == null) {
			return;
		}

		IOBuses ioBuses = associatedSystemIOConfiguration.getIoBuses();
		if (ioBuses == null) {
			return;
		}

		List<IOBus> ioBusList = ioBuses.getIoBusList();
		if (ioBusList == null || ioBusList.size() == 0) {
			return;
		}

		HmcIoBus hmcIoBus;
		IOSlots ioSlots;
		List<IOSlot> isSlotList;
		RelatedIOAdapter relatedIOAdapter;
		IOAdapter ioAdapter;
		HmcIoAdapter hmcIoAdapter;

		for (IOBus ioBus : ioBusList) {
			hmcIoBus = new HmcIoBus();
			hmcIoBus.setIoBusId(ioBus.getIoBusID());
			hmcIoBus.setHmcServerId(server.getId());
			ioBusRepository.save(hmcIoBus);

			ioSlots = ioBus.getIoSlots();
			if (ioSlots == null) {
				continue;
			}
			isSlotList = ioSlots.getIsSlotList();
			if (isSlotList == null || isSlotList.size() == 0) {
				continue;
			}

			for (IOSlot isSlot : isSlotList) {
				relatedIOAdapter = isSlot.getRelatedIOAdapter();
				if (relatedIOAdapter == null) {
					continue;
				}
				ioAdapter = relatedIOAdapter.getIoAdapter();
				if (ioAdapter == null) {
					continue;
				}
				hmcIoAdapter = new HmcIoAdapter();
				hmcIoAdapter.setDeviceName(ioAdapter.getDeviceName());
				hmcIoAdapter.setDescription(ioAdapter.getDescription());
				hmcIoAdapter.setAdapterId(ioAdapter.getAdapterID());
				hmcIoAdapter.setHmcIoBusId(hmcIoBus.getId());
				hmcIoAdapter.setHmcServerId(server.getId());
				ioAdapterRepository.save(hmcIoAdapter);
			}
		}
	}
}
