public static void AddOrUpdate(VMwareHostConnectionInfo row)
        {
            try {
                var propNames  = new List <string>();
                var paramNames = new List <string>();
                var parameters = new List <SQLiteParameter>();

                int paramI = 0;
                foreach (PropertyInfo propInfo in row.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public))
                {
                    propNames.Add(propInfo.Name);

                    string paramName = "@param" + (++paramI);
                    paramNames.Add(paramName);
                    parameters.Add(new SQLiteParameter(paramName, propInfo.GetValue(row)));
                }
                if (row.username == ".&DO_NOT_UPDATE_Credentials&.")
                {
                    int fieldI = propNames.IndexOf("username");
                    propNames.RemoveAt(fieldI);
                    paramNames.RemoveAt(fieldI);
                    parameters.RemoveAt(fieldI);

                    fieldI = propNames.IndexOf("password");
                    propNames.RemoveAt(fieldI);
                    paramNames.RemoveAt(fieldI);
                    parameters.RemoveAt(fieldI);
                }

                if (Get(row.ipOrHostname) == null)
                {
                    SQLiteDataAccess.ExecuteSQL("Insert into VMwareHostConnectionInfos(" + string.Join(",", propNames) + ") values(" + string.Join(",", paramNames) + ")", CommandType.Text, null, parameters.ToArray());
                }
                else
                {
                    var set = new List <string>();
                    for (int i = 0; i != propNames.Count; i++)
                    {
                        set.Add(propNames[i] + "=" + paramNames[i]);
                    }


                    string paramName = "@param" + (++paramI);
                    parameters.Add(new SQLiteParameter(paramName, row.ipOrHostname));

                    SQLiteDataAccess.ExecuteSQL("Update VMwareHostConnectionInfos set " + string.Join(",", set) + " where ipOrHostname=" + paramName, CommandType.Text, null, parameters.ToArray());
                }
            }
            catch (Exception ex) {
                //Let IIS handle the errors, but using own logging.
                Loggers.Log(Level.Error, "Failed adding or updating vhost connection info", ex, new object[] { row });
                throw;
            }
        }
        private static VMwareHostConnectionInfo Parse(DataRow row)
        {
            var vmwinfo = new VMwareHostConnectionInfo();

            foreach (PropertyInfo propInfo in vmwinfo.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public))
            {
                var val = row[propInfo.Name];

                if (val is DBNull)
                {
                    if (propInfo.PropertyType == typeof(string))
                    {
                        propInfo.SetValue(vmwinfo, "");
                    }
                }
                else
                {
                    propInfo.SetValue(vmwinfo, Convert.ChangeType(val, propInfo.PropertyType));
                }
            }

            return(vmwinfo);
        }
        public static VMwareHostConnectionInfo[] GetAll()
        {
            try {
                var dt = SQLiteDataAccess.GetDataTable("Select * from VMwareHostConnectionInfos");
                if (dt == null)
                {
                    return(new VMwareHostConnectionInfo[0]);
                }

                var all = new VMwareHostConnectionInfo[dt.Rows.Count];
                for (int i = 0; i != all.Length; i++)
                {
                    all[i] = Parse(dt.Rows[i]);
                }

                return(all);
            }
            catch (Exception ex) {
                //Let IIS handle the errors, but using own logging.
                Loggers.Log(Level.Error, "Failed retrieving all vhost connection info", ex);
                throw;
            }
        }
Пример #4
0
        public static VMwareHostSystemInformation Retrieve(VMwareHostConnectionInfo hostConnectionInfo)
        {
            try {
                var sysinfo = new VMwareHostSystemInformation();

#warning comments
#warning some system so the database don't get hammered too much

                sysinfo.timeStampInSecondsSinceEpochUtc = (long)(DateTime.UtcNow - _epochUtc).TotalSeconds;
                sysinfo.responsive   = 1;
                sysinfo.comments     = "";
                sysinfo.ipOrHostname = hostConnectionInfo.ipOrHostname;
                sysinfo.vmHostnames  = hostConnectionInfo.vmHostnames;

                VimPortType    service        = null;
                ServiceContent serviceContent = null;

                //Connect
                string url = "https://" + hostConnectionInfo.ipOrHostname + "/sdk";
                ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12;

                service = GetVimService(url, hostConnectionInfo.username, hostConnectionInfo.password);

                var svcRef = new ManagedObjectReference();
                svcRef.type    = "ServiceInstance";
                svcRef.Value   = "ServiceInstance";
                serviceContent = service.RetrieveServiceContent(svcRef);


                //Finally connect, we do not need the user session later on.
                UserSession session = service.Login(serviceContent.sessionManager, hostConnectionInfo.username, hostConnectionInfo.password, null);

                //Get the host ref by IP or by host name.
                IPAddress address;
                ManagedObjectReference reference = IPAddress.TryParse(hostConnectionInfo.ipOrHostname, out address) ?
                                                   service.FindByIp(serviceContent.searchIndex, null, hostConnectionInfo.ipOrHostname, false) :
                                                   service.FindByDnsName(serviceContent.searchIndex, null, Dns.GetHostEntry(hostConnectionInfo.ipOrHostname).HostName, false);


                var systemInfo = GetPropertyContent(service, serviceContent, "HostSystem", "hardware.systemInfo", reference)[0].propSet[0].val as HostSystemInfo;
                sysinfo.system = systemInfo.vendor + " " + systemInfo.model;

                sysinfo.os = GetPropertyContent(service, serviceContent, "HostSystem", "summary.config.product.fullName", reference)[0].propSet[0].val.ToString();

                var biosInfo = GetPropertyContent(service, serviceContent, "HostSystem", "hardware.biosInfo", reference)[0].propSet[0].val as HostBIOSInfo;
                sysinfo.bios = biosInfo.vendor + " " + biosInfo.biosVersion;

                var cpuPkgs = GetPropertyContent(service, serviceContent, "HostSystem", "hardware.cpuPkg", reference)[0].propSet[0].val as HostCpuPackage[];
                var cpuDict = new SortedDictionary <string, int>();
                foreach (var cpuPkg in cpuPkgs)
                {
                    string[] candidateArr = cpuPkg.description.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
                    string   candidate    = string.Join(" ", candidateArr);
                    if (cpuDict.ContainsKey(candidate))
                    {
                        ++cpuDict[candidate];
                    }
                    else
                    {
                        cpuDict.Add(candidate, 1);
                    }
                }
                sysinfo.processors = ComponentDictToString(cpuDict);

                var cpuInfo = GetPropertyContent(service, serviceContent, "HostSystem", "hardware.cpuInfo", reference)[0].propSet[0].val as HostCpuInfo;
                sysinfo.numCpuCores   = cpuInfo.numCpuCores;
                sysinfo.numCpuThreads = cpuInfo.numCpuThreads;

                long memorySize = (long)GetPropertyContent(service, serviceContent, "HostSystem", "hardware.memorySize", reference)[0].propSet[0].val;
                sysinfo.memoryInGB = Convert.ToInt32(Math.Round(Convert.ToDouble(memorySize) / (1024 * 1024 * 1024), MidpointRounding.AwayFromZero));

                //----

                //First ask the childentity from the rootfolder (datacenter)
                ObjectContent[] oCont = GetPropertyContent(service, serviceContent, "Folder", "childEntity", serviceContent.rootFolder);

                ManagedObjectReference datacenter = (oCont[0].propSet[0].val as ManagedObjectReference[])[0];

                //Then ask the datastore from the datacenter
                var datastoreRefs = GetPropertyContent(service, serviceContent, "Datacenter", "datastore", datacenter)[0].propSet[0].val as ManagedObjectReference[];

                var hostMultipathInfo = GetPropertyContent(service, serviceContent, "HostSystem", "config.storageDevice.multipathInfo", reference)[0].propSet[0].val as HostMultipathInfo;
                var scsiLuns          = GetPropertyContent(service, serviceContent, "HostSystem", "config.storageDevice.scsiLun", reference)[0].propSet[0].val as ScsiLun[];

                string[] datastoreArr = new string[datastoreRefs.Length];
                for (int i = 0; i != datastoreRefs.Length; i++)
                {
                    var    candidate = datastoreRefs[i];
                    var    dsInfo = GetPropertyContent(service, serviceContent, "Datastore", "info", candidate)[0].propSet[0].val;
                    string dataStoreName = null, diskName = null;

                    if (dsInfo is VmfsDatastoreInfo)
                    {
                        dataStoreName = (dsInfo as VmfsDatastoreInfo).name;
                        diskName      = (dsInfo as VmfsDatastoreInfo).vmfs.extent[0].diskName;
                    }
                    else if (dsInfo is NasDatastoreInfo)
                    {
                        dataStoreName = (dsInfo as NasDatastoreInfo).name;
                    }
                    if (diskName == null)
                    {
                        diskName = "unknown";
                    }
                    else
                    {
                        foreach (ScsiLun lun in scsiLuns)
                        {
                            if (lun.canonicalName == diskName)
                            {
                                diskName = lun.displayName;
                                break;
                            }
                        }
                    }

                    if (dataStoreName == null)
                    {
                        dataStoreName = "Unknown";
                    }

                    datastoreArr[i] = dataStoreName + " disk " + diskName;
                }
                sysinfo.datastores = string.Join("\t", datastoreArr);

                //Then ask the vm folder from the datacenter
                var vmFolder = GetPropertyContent(service, serviceContent, "Datacenter", "vmFolder", datacenter)[0].propSet[0].val as ManagedObjectReference;
                //finally get the list of the managed object from the vms.
                var vmRefs = GetPropertyContent(service, serviceContent, "Folder", "childEntity", vmFolder)[0].propSet[0].val as ManagedObjectReference[];

                var vDiskPathsHs = new HashSet <string>();
                foreach (var vmRef in vmRefs)
                {
                    foreach (var dev in (GetPropertyContent(service, serviceContent, "VirtualMachine", "config.hardware", vmRef)[0].propSet[0].val as VirtualHardware).device)
                    {
                        if (dev is VirtualDisk)
                        {
                            if (dev.backing is VirtualDiskFlatVer2BackingInfo)
                            {
                                vDiskPathsHs.Add((dev.backing as VirtualDiskFlatVer2BackingInfo).fileName);
                            }
                            else if (dev.backing is VirtualDiskFlatVer1BackingInfo)
                            {
                                vDiskPathsHs.Add((dev.backing as VirtualDiskFlatVer1BackingInfo).fileName);
                            }
                        }
                    }
                }

                sysinfo.vDiskPaths = string.Join("\t", vDiskPathsHs);

                //---

                var      physicalNics = GetPropertyContent(service, serviceContent, "HostSystem", "config.network.pnic", reference)[0].propSet[0].val as PhysicalNic[];
                string[] pNicsArr     = new string[physicalNics.Length];
                for (int i = 0; i != physicalNics.Length; i++)
                {
                    var candidate = physicalNics[i];
                    pNicsArr[i] = candidate.device + " " + candidate.driver + " driver (" + (candidate.linkSpeed == null ? "not connected)" : "connected)");
                }
                sysinfo.nics = string.Join("\t", pNicsArr);

                var ipmiPropset = GetPropertyContent(service, serviceContent, "HostSystem", "config.ipmi", reference)[0].propSet;
                sysinfo.bmcIp = ipmiPropset == null ? "Unable to detect" : ipmiPropset[0].val.ToString();

                return(sysinfo);
            }
            catch (Exception ex) {
                //Let IIS handle the errors, but using own logging.
                Loggers.Log(Level.Error, "Failed retrieving vhost system info", ex, new object[] { hostConnectionInfo });
                throw;
            }
        }