/// <summary>
        /// This method should be called prior to using this class
        /// </summary>
        static internal CompletionCode Init()
        {
            CompletionCode completionCode = CompletionCode.CommDevFailedToInit;

            // populdate Blade_En State Cache.
            foreach (byte Id in physicalServerIdTable)
            {
                CachedBladePowerStatus.Add(Id, new BladeEnState());
            }

            // Clear this flag in case that CM retries to initialize
            isTerminating = false;

            // Enforce that the update to the flag variable is visible to other threads orderly
            Thread.MemoryBarrier();

            portManagers = new PortManager[numPorts];

            for (int i = 0; i < numPorts; i++)
            {
                portManagers[i] = new SerialPortManager(i, numPriorityLevels);
                completionCode  = portManagers[i].Init();
                if (CompletionCodeChecker.Failed(completionCode) == true)
                {
                    Tracer.WriteError("Failed to initialize portManager: {0} Logical Id: {1}", i,
                                      PortManager.GetPhysicalPortNameFromLogicalId(i));
                    Release();
                    return(completionCode);
                }
            }

            return(completionCode);
        }
 /// <summary>
 /// Checks the Chassis Manager Service is not already runing
 /// </summary>
 private static bool ServiceNotRunning()
 {
     if (ChassisManagerExist())
     {
         try
         {
             ServiceController sc = new ServiceController(ServiceName);
             if (sc.Status == ServiceControllerStatus.Stopped)
             {
                 return(true);
             }
             else
             {
                 return(false);
             }
         }
         catch (Exception ex)
         {
             Tracer.WriteError("Chassis Manager InstallHelper ServiceNotRunning failed to get service state: {0}",
                               ex.ToString());
             return(false);
         }
     }
     else
     {
         return(true);
     }
 }
Пример #3
0
        /// <summary>
        /// Write to Chassis Fru - (Important) note that this function enables write to any offset
        /// Offset checks ensures that we are within permissible limits, but cannot enforce semantics within those limits
        /// Length checks validity of packet, however empty fields in packet are responsibility of writing function
        /// User level priority since this is not an internal call
        /// </summary>
        /// <param name="offset"></param>
        /// <param name="length"></param>
        /// <param name="packet"></param>
        /// <returns></returns>
        public byte writeChassisFru(ushort offset, ushort length, byte[] packet)
        {
            byte deviceId = 1;

            ChassisFruWriteResponse response = new ChassisFruWriteResponse();

            try
            {
                response = (ChassisFruWriteResponse)this.SendReceive(DeviceType.ChassisFruEeprom, deviceId, new ChassisFruWriteRequest(offset, length, packet),
                                                                     typeof(ChassisFruWriteResponse), (byte)PriorityLevel.User);
            }
            catch (Exception ex)
            {
                Tracer.WriteWarning("ChassisFru write had an exception", ex);
            }

            if (response.CompletionCode != (byte)CompletionCode.Success)
            {
                Tracer.WriteError("Fru Write failed with completion code {0:X}", response.CompletionCode);
            }
            else
            {
                Tracer.WriteInfo("Fru Write succeeded");
            }

            return((byte)response.CompletionCode);
        }
Пример #4
0
        /// <summary>
        /// Checks the validity of the current blade id passed
        /// </summary>
        /// <param name="bladeId"></param>
        /// <returns></returns>
        public static bool checkBladeTypeValidity(byte bladeId)
        {
            try
            {
                // Open the request message using an xml reader
                XmlReader xr = OperationContext.Current.IncomingMessageHeaders.GetReaderAtHeader(0);

                // Split the URL at the API name--Parameters junction indicated by the '?' character - taking the first string will ignore all parameters
                string[] urlSplit = xr.ReadElementContentAsString().Split('/');
                // Extract just the API name and rest of the URL, which will be the last item in the split using '/'
                string[] apiSplit = urlSplit[3].Split('?');

                BladeType val = BladeType.Unknown;
                invalidBladeFunction.TryGetValue(apiSplit[0], out val);

                // If the blade type does not support this function, return false, so we can send back useful info to user
                if ((byte)val == ChassisState.GetBladeType(bladeId))
                {
                    Tracer.WriteWarning("Command {0} not valid for Blade id {1}, Blade Type {2}",
                                        apiSplit[0], bladeId, ChassisState.GetBladeTypeName((byte)val));

                    return(false);
                }
            }
            catch (Exception ex)
            {
                Tracer.WriteError("Checking Blade Type validity encountered an exception" + ex);
                // We decide to go ahead and issue the command to the blade if the blade type check fails with exception,
                // This is done in order to not penalize a user command based on some failure in checking
                // The command might fail eventually, but with an unhelpful error message
            }
            return(true);
        }
        /// <summary>
        /// Retrives NTP Servers
        /// </summary>
        internal static CompletionCode GetNtpServer(RegisteryKey registryKey, out string response)
        {
            lock (locker)
            {
                try
                {
                    RegistryKey regkey = Registry.LocalMachine.OpenSubKey(ControlStrings.W32TimeKey, RegistryKeyPermissionCheck.ReadSubTree,
                                                                          System.Security.AccessControl.RegistryRights.ReadKey);
                    response = (string)regkey.GetValue(RegistryKeyName(registryKey));

                    // dispose of unmanaged object
                    if (regkey != null)
                    {
                        regkey.Dispose();
                    }
                }
                catch (Exception ex)
                {
                    Tracer.WriteError("Chassis Manager GetNtpServer failed with Exception: {0}", ex);
                    response = string.Empty;
                    return(CompletionCode.UnspecifiedError);
                }
            }

            if (!string.IsNullOrEmpty(response))
            {
                // replace flag for clean output.
                response = response.Replace(",0x9", "");
            }

            return(CompletionCode.Success);
        }
        /// <summary>
        /// Attempts to clear the Psu error status. This method
        /// calls down to the Chassis Manager with SendReceive
        /// </summary>
        private CompletionCode SetPsuClearFaults(byte psuId)
        {
            CompletionCode returnPacket = new CompletionCode();

            returnPacket = CompletionCode.UnspecifiedError;

            try
            {
                PsuChassisResponse myResponse = new PsuChassisResponse();
                myResponse = (PsuChassisResponse)this.SendReceive(this.PsuDeviceType, this.PsuId, new PsuRequest((byte)PmBusCommand.CLEAR_FAULTS, (byte)PmBusResponseLength.CLEAR_FAULTS), typeof(PsuChassisResponse));

                // check for completion code
                if (myResponse.CompletionCode != 0)
                {
                    returnPacket = (CompletionCode)myResponse.CompletionCode;
                }
                else
                {
                    returnPacket = CompletionCode.Success;
                }
            }
            catch (System.Exception ex)
            {
                returnPacket = CompletionCode.UnspecifiedError;
                Tracer.WriteError(this.PsuId, DeviceType.Psu, ex);
            }

            return(returnPacket);
        }
Пример #7
0
        private SerialStatusPacket openSerialPortConsole(byte id, int communicationDeviceTimeoutIn1ms, BaudRate baudrate)
        {
            // Initialize return packet
            SerialStatusPacket returnPacket = new SerialStatusPacket();

            returnPacket.completionCode = CompletionCode.UnspecifiedError;
            Tracer.WriteInfo("Invoked SerialPortConsole.openSerialPortConsole({0})", id);

            try
            {
                // Call device layer below
                SerialConsolePortOpenResponse serialResponse = (SerialConsolePortOpenResponse)this.SendReceive(this.SerialPortConsoleDeviceType,
                                                                                                               translateSerialPortId(this.PortId), new SerialConsolePortOpenRequest(communicationDeviceTimeoutIn1ms, baudrate),
                                                                                                               typeof(SerialConsolePortOpenResponse), (byte)PriorityLevel.User);

                // check for completion code
                if (serialResponse.CompletionCode != 0)
                {
                    Tracer.WriteError("SerialPortConsole.openSerialPortConsole({0}) error in commdev.sendreceive", id);
                    returnPacket.completionCode = (CompletionCode)serialResponse.CompletionCode;
                }
                else
                {
                    returnPacket.completionCode = CompletionCode.Success;
                }
            }
            catch (System.Exception ex)
            {
                returnPacket.completionCode = CompletionCode.UnspecifiedError;
                Tracer.WriteError(this.PortId, DeviceType.SerialPortConsole, ex);
            }

            return(returnPacket);
        }
Пример #8
0
        /// <summary>
        /// Set PSU On/OFF
        /// </summary>
        /// <param name="psuId">Psu Id</param>
        /// <param name="cmd">command ON or OFF</param>
        /// <returns>Completion code success/failure</returns>
        private CompletionCode SetPsuOnOff(PmBusCommandPayload payload)
        {
            CompletionCode returnPacket = new CompletionCode();

            returnPacket = CompletionCode.UnspecifiedError;

            try
            {
                PsuOnOffResponse response = new PsuOnOffResponse();

                response = (PsuOnOffResponse)this.SendReceive(this.PsuDeviceType, this.PsuId,
                                                              new PsuPayloadRequest((byte)PmBusCommand.SET_POWER, (byte)payload, (byte)PmBusResponseLength.SET_POWER), typeof(PsuOnOffResponse));

                // check for completion code
                if (response.CompletionCode != 0)
                {
                    returnPacket = (CompletionCode)response.CompletionCode;
                }
                else
                {
                    returnPacket = CompletionCode.Success;
                }
            }
            catch (System.Exception ex)
            {
                Tracer.WriteError("SetPsuOnOff failed with the exception: " + ex);
            }

            return(returnPacket);
        }
Пример #9
0
        /// <summary>
        /// Reads raw CM information - can be called individually if needed
        /// User level priority since this is not an internal call
        /// </summary>
        public ChassisFruReadResponse readRawChassisFru(ushort offset, ushort length)
        {
            byte deviceId = 1;
            ChassisFruReadResponse response = new ChassisFruReadResponse();

            try
            {
                response = (ChassisFruReadResponse)this.SendReceive(DeviceType.ChassisFruEeprom, deviceId, new ChassisFruReadRequest(offset, length),
                                                                    typeof(ChassisFruReadResponse), (byte)PriorityLevel.User);
            }
            catch (Exception ex)
            {
                Tracer.WriteWarning("Chassis Fru read had an exception", ex);
            }

            if (response.CompletionCode != (byte)CompletionCode.Success)
            {
                Tracer.WriteError("Fru read failed with completion code {0:X}", response.CompletionCode);
            }
            else
            {
                Tracer.WriteInfo("Chassis Fru info read: {0:X}", response.DataReturned.ToString());
            }
            return(response);
        }
        private BladePowerStatePacket GetBladePowerState(byte deviceId)
        {
            // Initialize return packet
            BladePowerStatePacket returnPacket = new BladePowerStatePacket();

            returnPacket.CompletionCode  = CompletionCode.UnspecifiedError;
            returnPacket.BladePowerState = 3;

            try
            {
                BladePowerStateResponse stateResponse = (BladePowerStateResponse)this.SendReceive(this.DeviceType, deviceId, new BladePowerStateRequest(), typeof(BladePowerStateResponse));
                if (stateResponse.CompletionCode != 0)
                {
                    returnPacket.CompletionCode = (CompletionCode)stateResponse.CompletionCode;
                }
                else
                {
                    returnPacket.CompletionCode    = CompletionCode.Success;
                    returnPacket.BladePowerState   = stateResponse.BladePowerState;
                    returnPacket.DecompressionTime = stateResponse.DecompressionTime;
                }
            }
            catch (System.Exception ex)
            {
                returnPacket.CompletionCode  = CompletionCode.UnspecifiedError;
                returnPacket.BladePowerState = 2;
                Tracer.WriteError(this.DeviceId, this.DeviceType, ex);
            }
            return(returnPacket);
        }
Пример #11
0
        /// <summary>
        /// Check if the request is valid with respect to device type, id, and request length
        /// </summary>
        /// <param name="deviceType"></param>
        /// <param name="deviceId"></param>
        /// <param name="request"></param>
        /// <returns></returns>
        static private bool IsValidRequest(byte deviceType, byte deviceId, ref byte[] request)
        {
            if (DeviceTypeChecker.IsValidDeviceType(deviceType) == false)
            {
                Tracer.WriteError("Invalid device type: {0}", deviceType);
                return(false);
            }
            if (DeviceIdChecker.IsValidLogicalDeviceId(deviceType, deviceId) == false)
            {
                Tracer.WriteError("Invalid device ID: {0}", deviceId);
                return(false);
            }
            if (request == null)
            {
                Tracer.WriteError("Null request packet");
                return(false);
            }

            // For server commands, simply pass through.
            // Thus, no need to check the request packet length as long as it is not null
            if (deviceType != (byte)DeviceType.Server)
            {
                if (RequestPacketUtil.IsValidRequestLength(ref request) == false)
                {
                    return(false);
                }
            }
            return(true);
        }
Пример #12
0
        internal static Contracts.ChassisResponse SendBladeSerialData(int bladeId, string sessionToken, byte[] data)
        {
            Contracts.ChassisResponse response = new Contracts.ChassisResponse();
            response.completionCode = Contracts.CompletionCode.Failure;
            Tracer.WriteInfo("BladeSerialSessionMetadata.SendBladeSerialData({0})", bladeId);

            // If there is NOT an already existing Blade serial session (indicated by a invalid bladeId and a invalid sessionToken), return failure with appropriate completion code
            if (CompareAndSwapMetadata(ConfigLoaded.InactiveBladePortId, ConfigLoaded.InactiveBladeSerialSessionToken, ConfigLoaded.InactiveBladePortId, ConfigLoaded.InactiveBladeSerialSessionToken) == CompletionCode.Success)
            {
                Tracer.WriteError("SendBladeSerialData({0}): Send failed because of no active session.", bladeId);
                response.completionCode = Contracts.CompletionCode.NoActiveSerialSession;
                return(response);
            }

            // If this bladeid currently holds the serial session, update the timestamp else return failure
            if (BladeSerialSessionMetadata.CompareAndSwapMetadata(bladeId, sessionToken, bladeId, sessionToken, DateTime.Now) != CompletionCode.Success)
            {
                response.completionCode = Contracts.CompletionCode.SerialSessionActive;
                return(response);
            }

            BladeSerialSession currSession  = new BladeSerialSession((byte)bladeId);
            SerialStatusPacket serialStatus = new SerialStatusPacket();

            serialStatus = currSession.sendSerialData(data);
            if (serialStatus.completionCode != CompletionCode.Success)
            {
                Tracer.WriteError("BladeSerialSessionMetadata.SendBladeSerialData({0}): Error in BladeSerialSession.sendSerialData()", bladeId);
                return(response);
            }
            response.completionCode = Contracts.CompletionCode.Success;
            return(response);
        }
        public static bool IsEMSEnabled()
        {
            bool isEMSEnabled = false;

            try
            {
                // {9dea862c-5cdd-4e70-acc1-f32b344d4795} is the GUID of the System BcdStore
                ManagementObject scopeObj = new ManagementObject(new ManagementScope(@"root\WMI"), new ManagementPath("root\\WMI:BcdObject.Id=\"{9dea862c-5cdd-4e70-acc1-f32b344d4795}\",StoreFilePath=\"\""), null);

                ManagementBaseObject elementObj = null;
                elementObj = scopeObj.GetMethodParameters("GetElement");

                // Get the list of IDs from 0x24000001, which is a BCD constant: BcdBootMgrObjectList_DisplayOrder
                elementObj["Type"] = ((UInt32)0x24000001);
                ManagementBaseObject BCDObj = scopeObj.InvokeMethod("GetElement", elementObj, null);
                ManagementBaseObject value  = ((ManagementBaseObject)(BCDObj.Properties["Element"].Value));

                // Get list of Ids
                string[] idList = (string[])value.GetPropertyValue("Ids");

                // Define the Management object used to access the WMI info from BCD store
                scopeObj = new ManagementObject(new ManagementScope(@"root\WMI"), new ManagementPath("root\\WMI:BcdObject.Id=\"" + idList[0] + "\",StoreFilePath=\"\""), null);

                elementObj = scopeObj.GetMethodParameters("GetElement");

                // BcdOSLoaderBoolean_EmsEnabled (0x260000b0)
                // The EMS enabled setting. The element data format is BcdBooleanElement.

                elementObj["Type"] = ((UInt32)0x260000b0);
                BCDObj             = scopeObj.InvokeMethod("GetElement", elementObj, null);
                value = ((ManagementBaseObject)(BCDObj.Properties["Element"].Value));

                // try get EMS enabled setting
                Boolean.TryParse(value.GetPropertyValue("boolean").ToString(), out isEMSEnabled);

                // Dispose unmanaged objects
                if (scopeObj != null)
                {
                    scopeObj.Dispose();
                }
                if (elementObj != null)
                {
                    elementObj.Dispose();
                }
                if (BCDObj != null)
                {
                    BCDObj.Dispose();
                }
                if (value != null)
                {
                    value.Dispose();
                }
            }
            catch (Exception e)
            {
                Tracer.WriteError(String.Format("Exception {0} Trace {1}", e.Message, e.StackTrace));
            }

            return(isEMSEnabled);
        }
        /// <summary>
        /// Get wcscli exe path from wcscli service properties
        /// </summary>
        /// <returns>Wcscli path</returns>
        public static string GetWcscliPath()
        {
            string path = null;

            try
            {
                ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_Service where Name= 'WcscliCOM5'");
                ManagementObjectSearcher   objSearch     = new ManagementObjectSearcher(Scope, query);
                ManagementObjectCollection objCollection = objSearch.Get();

                foreach (ManagementObject service in objCollection)
                {
                    path = service["PathName"].ToString();
                }

                if (objSearch != null)
                {
                    objSearch.Dispose();
                }

                if (objCollection != null)
                {
                    objCollection.Dispose();
                }
            }
            catch (Exception e)
            {
                Tracer.WriteError(string.Format("GetWcscliPath: Exception: {0} Trace {1}", e.Message, e.StackTrace));
            }

            return(path);
        }
        /// <summary>
        /// Get all members in a group
        /// </summary>
        /// <param name="domain">domain</param>
        /// <param name="grpName">group name</param>
        /// <returns>list of members</returns>
        public static List <string> GetAllMembersInGroup(string domain, string grpName)
        {
            List <string> members = new List <string>();

            try
            {
                ObjectQuery query = new ObjectQuery("select * from Win32_GroupUser where GroupComponent=\"Win32_Group.Domain='" + domain + "',Name='" + grpName + "'\"");

                using (ManagementObjectSearcher objSearch = new ManagementObjectSearcher(Scope, query))
                {
                    ManagementObjectCollection objCollection = objSearch.Get();

                    foreach (ManagementObject obj in objCollection)
                    {
                        ManagementPath path = new ManagementPath(obj["PartComponent"].ToString());

                        // get the user object
                        ManagementObject objnew = new ManagementObject();
                        objnew.Path = path;
                        objnew.Get();

                        // Add member to list
                        members.Add(objnew["Caption"].ToString());
                    }
                }
            }
            catch (Exception e)
            {
                Tracer.WriteError(String.Format("Exception {0} Trace {1}", e.Message, e.StackTrace));
            }

            return(members);
        }
        /// <summary>
        /// Check if Chassis Manager SSL certificate is installed.
        /// </summary>
        /// <returns>True/False</returns>
        public static bool IsChassisManagerSSLCertInstalled()
        {
            bool isCertInstalled = false;

            X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);

            try
            {
                store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);

                // look for Chassis Manager certificate
                X509Certificate2Collection foundCerts = store.Certificates.Find(X509FindType.FindBySubjectName, ConfigLoaded.SslCertificateName, false);

                if (foundCerts.Count != 0)
                {
                    // Matching certificate found
                    isCertInstalled = true;
                }
            }
            catch (Exception e)
            {
                Tracer.WriteError(String.Format("Exception {0} Trace {1}", e.Message, e.StackTrace));
            }
            finally
            {
                store.Close();
            }

            return(isCertInstalled);
        }
        /// <summary>
        /// Scan device and list all groups.
        /// </summary>
        /// <returns>List of groups</returns>
        public static List <Contracts.UserGroup> ListAllGroupsAndMembers()
        {
            List <Contracts.UserGroup> userGroups = new List <Contracts.UserGroup>();

            try
            {
                ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_Group WHERE LocalAccount = TRUE");

                using (ManagementObjectSearcher objSearch = new ManagementObjectSearcher(Scope, query))
                {
                    ManagementObjectCollection objCollection = objSearch.Get();

                    foreach (ManagementObject group in objCollection)
                    {
                        Contracts.UserGroup grp = new Contracts.UserGroup();
                        grp.Group          = group["Caption"].ToString();
                        grp.Members        = GetAllMembersInGroup(group["Domain"].ToString(), group["Name"].ToString());
                        grp.completionCode = Contracts.CompletionCode.Success;
                        userGroups.Add(grp);
                    }
                }
            }
            catch (Exception e)
            {
                Tracer.WriteError(String.Format("Exception {0} Trace {1}", e.Message, e.StackTrace));
            }

            return(userGroups);
        }
        /// <summary>
        /// Scan device and list all users.
        /// </summary>
        /// <returns>List of users</returns>
        public static List <String> ListAllUsers()
        {
            List <string> users = new List <string>();

            string caption  = string.Empty;
            string enabled  = string.Empty;
            string password = string.Empty;

            try
            {
                ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_UserAccount");

                using (ManagementObjectSearcher objSearch = new ManagementObjectSearcher(Scope, query))
                {
                    ManagementObjectCollection objCollection = objSearch.Get();

                    foreach (ManagementObject user in objCollection)
                    {
                        caption  = user["Caption"].ToString();
                        enabled  = user["Disabled"].ToString();
                        password = user["PasswordExpires"].ToString();

                        users.Add(string.Format("User: {0} \t Account Disabled: {1}   Password Expires: {2}", caption, enabled, password));
                    }
                }
            }
            catch (Exception e)
            {
                Tracer.WriteError(String.Format("Exception {0} Trace {1}", e.Message, e.StackTrace));
            }

            return(users);
        }
        /// <summary>
        /// Get the Chassis Manager or PDB FRU areas information.
        /// </summary>
        private static Ipmi.FruDevice GetFruDevice(DeviceType deviceType)
        {
            Ipmi.FruDevice fru = new Ipmi.FruDevice((byte)CompletionCode.UnspecifiedError);

            lock (locker)
            {
                try
                {
                    if (initialized)
                    {
                        fru = ChassisState.CmFruData.ReadFru((DeviceType)deviceType);
                    }
                    else
                    {
                        Tracer.WriteError(
                            " GetFruDevice failed: InstallHelper Uninitialized");
                    }
                }
                catch (Exception ex)
                {
                    Tracer.WriteError(
                        " GetFruDevice failed with the exception: " + ex.Message);
                }
            }

            return(fru);
        }
Пример #20
0
        /// <summary>
        /// Send I2C/Smbus Payloads to BMC via MasterWriteRead for setting Pass-Through Mode
        /// </summary>
        /// <param name="bladeId"></param>
        /// <param name="passThroughMode"></param>
        /// <param name="apiName"></param>
        /// <returns>CompletionCode</returns>
        internal static CompletionCode SetMezzPassThroughMode(int bladeId, bool passThroughMode, string apiName)
        {
            // Initialize return fields
            CompletionCode setMezzPassThroughCompletionCode = CompletionCode.UnknownState;

            // Initialize I2C/Smbus payloads
            byte count = 0x01;           // bytes to read (0x00 means write)

            byte[] writeData = { 0x02 }; // { starting address }

            try
            {
                // Send I2C/Smbus Payload to BMC for reading pass-through byte before re-writing
                Ipmi.SmbusWriteRead sendSmbusPayloadResponse = SendSmbusPayload((byte)bladeId, channel, slaveId, count, writeData, apiName);
                if (sendSmbusPayloadResponse.CompletionCode == (byte)CompletionCode.Success &&
                    sendSmbusPayloadResponse.RawData.Length == (int)count)
                {
                    // Configure writeData based on passThroughMode
                    if (passThroughMode)
                    {
                        // Configure writeData to activate Pass-Through Mode (smbusPayloadByte bit 0 = 1)
                        writeData = new byte[2] {
                            writeData[0], (byte)(sendSmbusPayloadResponse.RawData[0] | 0x01)
                        };                                                                                            // { starting address, write byte }
                    }
                    else
                    {
                        // Configure writeData to turn off Pass-Through Mode (smbusPayloadByte bit 0 = 0)
                        writeData = new byte[2] {
                            writeData[0], (byte)(sendSmbusPayloadResponse.RawData[0] & 0xFE)
                        };                                                                                            // { starting address, write byte }
                    }

                    // Send I2C/Smbus Payload to BMC for setting pass-through mode on FPGA Mezz
                    sendSmbusPayloadResponse = SendSmbusPayload((byte)bladeId, channel, slaveId, 0x00, writeData, apiName);
                    if (sendSmbusPayloadResponse.CompletionCode != (byte)CompletionCode.Success)
                    {
                        setMezzPassThroughCompletionCode = CompletionCode.I2cErrors;
                    }
                    else
                    {
                        setMezzPassThroughCompletionCode = CompletionCode.Success;
                    }
                }
                else
                {
                    Tracer.WriteError(string.Format(
                                          "{0}(): MasterWriteRead returned unexpected payload data or did not return Success Completion Code for bladeId {1} (Data: {2})",
                                          apiName, bladeId, sendSmbusPayloadResponse.MessageData));
                    setMezzPassThroughCompletionCode = CompletionCode.I2cErrors;
                }
            }
            catch (Exception ex)
            {
                Tracer.WriteError(string.Format("Exception occured in {0}() for blade {1}: {2}", apiName, bladeId, ex));
                setMezzPassThroughCompletionCode = CompletionCode.UnspecifiedError;
            }

            return(setMezzPassThroughCompletionCode);
        }
        /// <summary>
        /// Get list of all services with the properties.
        /// </summary>
        /// <returns></returns>
        public static List <Contracts.ScanServices> ListAllServices()
        {
            List <Contracts.ScanServices> services = new List <Contracts.ScanServices>();

            try
            {
                ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_Service");

                using (ManagementObjectSearcher objSearch = new ManagementObjectSearcher(Scope, query))
                {
                    ManagementObjectCollection objCollection = objSearch.Get();

                    foreach (ManagementObject service in objCollection)
                    {
                        Contracts.ScanServices sc = new Contracts.ScanServices();

                        sc.ServiceName  = service["DisplayName"].ToString();
                        sc.CurrentState = service["State"].ToString();
                        sc.StartUpType  = service["StartMode"].ToString();
                        if (service["Description"] != null)
                        {
                            sc.Detail = service["Description"].ToString();
                        }
                        sc.completionCode = Contracts.CompletionCode.Success;
                        services.Add(sc);
                    }
                }
            }
            catch (Exception e)
            {
                Tracer.WriteError(String.Format("Exception {0} Trace {1}", e.Message, e.StackTrace));
            }

            return(services);
        }
Пример #22
0
        /// <summary>
        /// This method should be called prior to using this class
        /// </summary>
        static internal CompletionCode Init()
        {
            CompletionCode completionCode = CompletionCode.CommDevFailedToInit;

            // Clear this flag in case that CM retries to initialize
            isTerminating = false;

            // Safe mode is disabled by default when initialized
            isSafeModeEnabled = false;

            // Enforce that the update to the flag variable is visible to other threads orderly
            Thread.MemoryBarrier();

            portManagers = new PortManager[numPorts];

            for (int i = 0; i < numPorts; i++)
            {
                portManagers[i] = new SerialPortManager(i, numPriorityLevels);
                completionCode  = portManagers[i].Init();
                if (CompletionCodeChecker.Failed(completionCode) == true)
                {
                    Tracer.WriteError("Failed to initialize portManager: {0} Logical Id: {1}", i,
                                      PortManager.GetPhysicalPortNameFromLogicalId(i));
                    Release();
                    return(completionCode);
                }
            }

            return(completionCode);
        }
        /// <summary>
        /// Write to Chassis Fru - (Important) note that this function enables write to any offset
        /// Offset checks ensures that we are within permissible limits, but cannot enforce semantics within those limits
        /// Length checks validity of packet, however empty fields in packet are responsibility of writing function
        /// User level priority since this is not an internal call
        /// </summary>
        /// <param name="offset"></param>
        /// <param name="length"></param>
        /// <param name="packet"></param>
        /// <returns></returns>
        public CompletionCode WriteChassisFru(ushort offset, ushort length,
                                              byte[] packet, DeviceType deviceType)
        {
            ChassisFruWriteResponse response = new ChassisFruWriteResponse();

            response.CompletionCode = (byte)CompletionCode.UnspecifiedError;

            try
            {
                response = (ChassisFruWriteResponse)this.SendReceive(deviceType,
                                                                     this.DeviceId, new ChassisFruWriteRequest(offset, length, packet),
                                                                     typeof(ChassisFruWriteResponse), (byte)PriorityLevel.User);
            }
            catch (Exception ex)
            {
                Tracer.WriteError(string.Format("ChassisFru.WriteChassisFru() Write had an exception with paramaters: Offset: {0} Length: {1} Packet: {2} DeviceType: {3} Exception: {4}",
                                                offset, length, (packet == null ? "Null packet" : Ipmi.IpmiSharedFunc.ByteArrayToHexString(packet)), deviceType.ToString(), ex));
            }

            if (response.CompletionCode != (byte)CompletionCode.Success)
            {
                Tracer.WriteError("ChassisFru.WriteChassisFru() write failed with completion code {0:X}", response.CompletionCode);
            }

            return((CompletionCode)response.CompletionCode);
        }
Пример #24
0
        // Function to be called by the getbladerequirement monitoring thread if chassisManagerSafeState is true
        internal static void BladeSerialSessionInactivityCheck()
        {
            // Timespan time parameters are in the order -- hours, minutes, and seconds.
            TimeSpan span              = new TimeSpan(0, 0, ConfigLoaded.TimeoutBladeSerialSessionInSecs);
            DateTime currTime          = DateTime.Now;
            DateTime lastActivityBound = currTime.Subtract(span);

            int currBladeId = bladeId;

            if (CompareAndSwapMetadata(ConfigLoaded.InactiveBladePortId, ConfigLoaded.InactiveBladeSerialSessionToken,
                                       ConfigLoaded.InactiveBladePortId, ConfigLoaded.InactiveBladeSerialSessionToken) ==
                CompletionCode.Success)
            {
                return;
            }

            // If there is an active session, if it has been inactive in the last 'x' minutes (2), then kill the session
            if (SetSecretMetadataIfInactive(lastActivityBound))
            {
                Contracts.ChassisResponse sessionResponse = new Contracts.ChassisResponse();
                sessionResponse = StopBladeSerialSession(ConfigLoaded.SecretBladePortId,
                                                         ConfigLoaded.SecretBladeSerialSessionToken, true);
                if (sessionResponse.completionCode != Contracts.CompletionCode.Success)
                {
                    Tracer.WriteError(
                        "BladeSerialSessionMetadata.BladeSerialSessionInactiveCheck: Error StopBladeSerialSession failure");
                }
            }
        }
Пример #25
0
        private SerialStatusPacket sendSerialData(byte id, byte[] data)
        {
            // Initialize return packet
            SerialStatusPacket returnPacket = new SerialStatusPacket();

            returnPacket.completionCode = CompletionCode.UnspecifiedError;

            try
            {
                // Call device layer below
                SerialConsolePortSendResponse serialResponse =
                    (SerialConsolePortSendResponse)this.SendReceive(this.SerialPortConsoleDeviceType, translateSerialPortId(this.PortId),
                                                                    new SerialConsolePortSendRequest(data), typeof(SerialConsolePortSendResponse), (byte)PriorityLevel.User);

                // check for completion code
                if (serialResponse.CompletionCode != 0)
                {
                    returnPacket.completionCode = (CompletionCode)serialResponse.CompletionCode;
                }
                else
                {
                    returnPacket.completionCode = CompletionCode.Success;
                }
            }
            catch (System.Exception ex)
            {
                returnPacket.completionCode = CompletionCode.UnspecifiedError;
                Tracer.WriteError(this.PortId, DeviceType.SerialPortConsole, ex);
            }

            return(returnPacket);
        }
        private BladePowerStatePacket SetBladePowerState(byte deviceId, byte state)
        {
            // Initialize return packet
            BladePowerStatePacket returnPacket = new BladePowerStatePacket();

            returnPacket.CompletionCode  = CompletionCode.UnspecifiedError;
            returnPacket.BladePowerState = 3;

            Tracer.WriteInfo("SetSledPowerState Switch id: " + deviceId);

            if (state == (byte)Contracts.PowerState.ON)
            {
                try
                {
                    BladePowerStateOnResponse response = (BladePowerStateOnResponse)this.SendReceive(this.DeviceType, deviceId, new BladePowerStateOnRequest(state), typeof(BladePowerStateOnResponse));
                    if (response.CompletionCode != 0)
                    {
                        returnPacket.CompletionCode = (CompletionCode)response.CompletionCode;
                    }
                    else
                    {
                        returnPacket.CompletionCode    = CompletionCode.Success;
                        returnPacket.BladePowerState   = 1; //NOTE: response is not actually returned.
                        returnPacket.DecompressionTime = response.DecompressionTime;
                    }
                }
                catch (System.Exception ex)
                {
                    returnPacket.CompletionCode  = CompletionCode.UnspecifiedError;
                    returnPacket.BladePowerState = 3;
                    Tracer.WriteError(this.DeviceId, DeviceType.Power, ex);
                }
            }
            else
            {
                try
                {
                    BladePowerStateOffResponse response = (BladePowerStateOffResponse)this.SendReceive(this.DeviceType, deviceId, new BladePowerStateOffRequest(state), typeof(BladePowerStateOffResponse));
                    if (response.CompletionCode != 0)
                    {
                        returnPacket.CompletionCode = (CompletionCode)response.CompletionCode;
                    }
                    else
                    {
                        returnPacket.CompletionCode    = CompletionCode.Success;
                        returnPacket.BladePowerState   = 0; // blade is off
                        returnPacket.DecompressionTime = 0; // blade is off.
                    }
                }
                catch (System.Exception ex)
                {
                    returnPacket.CompletionCode  = CompletionCode.UnspecifiedError;
                    returnPacket.BladePowerState = 3;
                    Tracer.WriteError(this.DeviceId, DeviceType.Power, ex);
                }
            }

            return(returnPacket);
        }
Пример #27
0
        /// <summary>
        /// Read function
        /// </summary>
        /// <param name="offset"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public byte readChassisFru()
        {
            // Constants - TODO - move to config file
            ushort offset          = (ushort)ConfigLoaded.ChassisStartingOffset;
            ushort length          = (ushort)ConfigLoaded.ChassisFruLength;
            ushort internalUseSize = (ushort)ConfigLoaded.InternalUseSize; // bytes
            ushort chassisInfoSize = (ushort)ConfigLoaded.ChassisInfoSize; // bytes
            ushort boardInfoSize   = (ushort)ConfigLoaded.BoardInfoSize;   // bytes
            ushort productInfoSize = (ushort)ConfigLoaded.ProductInfoSize; // bytes

            try
            {
                ChassisFruReadResponse fruResponse = readRawChassisFru(offset, length);

                if (fruResponse.CompletionCode != 0 || fruResponse.DataReturned == null)
                {
                    Tracer.WriteInfo("Error in CM Fru Read {0}", fruResponse.CompletionCode);
                    this._completionCode = (byte)CompletionCode.UnspecifiedError;
                    return(this._completionCode);
                }

                Ipmi.FruCommonHeader commonHeader = new Ipmi.FruCommonHeader(fruResponse.DataReturned);
                ushort areaOffset;

                byte[] chassisInfoBytes = new byte[chassisInfoSize];
                byte[] boardInfoBytes   = new byte[boardInfoSize];
                byte[] productInfoBytes = new byte[productInfoSize];

                areaOffset = commonHeader.ChassisInfoStartingOffset;
                if (areaOffset != 0)
                {
                    Array.Copy(fruResponse.DataReturned, areaOffset, chassisInfoBytes, 0, chassisInfoSize);
                }

                areaOffset = commonHeader.BoardAreaStartingOffset;
                if (areaOffset != 0)
                {
                    Array.Copy(fruResponse.DataReturned, areaOffset, boardInfoBytes, 0, boardInfoSize);
                }

                areaOffset = commonHeader.ProductAreaStartingOffset;
                if (areaOffset != 0)
                {
                    Array.Copy(fruResponse.DataReturned, areaOffset, productInfoBytes, 0, productInfoSize);
                }

                this.PopulateChassisFru(commonHeader,
                                        chassisInfoBytes,
                                        boardInfoBytes,
                                        productInfoBytes, fruResponse.CompletionCode);
            }
            catch (Exception e)
            {
                Tracer.WriteError("CM Fru Read had exception {0}", e);
                this._completionCode = (byte)CompletionCode.UnspecifiedError;
            }
            return(this._completionCode);
        }
Пример #28
0
        /// <summary>
        /// Send Smbus payload to Fpga Mezz via MasterWriteRead
        /// </summary>
        /// <param name="bladeId"></param>
        /// <param name="channel"></param>
        /// <param name="slaveId"></param>
        /// <param name="count"></param>
        /// <param name="writeData"></param>
        /// <param name="cmd"></param>
        /// <returns>SmbusWriteRead</returns>
        private static Ipmi.SmbusWriteRead SendSmbusPayload(int bladeId, byte channel, byte slaveId, byte count, byte[] writeData, string cmd)
        {
            Ipmi.SmbusWriteRead sendSmbusPayloadResponse = WcsBladeFacade.MasterWriteRead((byte)bladeId, channel, slaveId, count, writeData);
            if (sendSmbusPayloadResponse.CompletionCode != (byte)CompletionCode.Success)
            {
                Tracer.WriteError(string.Format("{0}(): MasterWriteRead failed for bladeId {1} with completion code {2}",
                                                cmd, bladeId, sendSmbusPayloadResponse.CompletionCode));
            }

            return(sendSmbusPayloadResponse);
        }
        // Returns the most privileged role this user belongs to
        static internal authorizationRole GetCurrentUserMostPrivilegedRole()
        {
            try
            {
                ServiceSecurityContext context         = OperationContext.Current.ServiceSecurityContext;
                WindowsIdentity        windowsIdentity = context.WindowsIdentity;
                var principal = new WindowsPrincipal(windowsIdentity);

                // Extract domain + role names to check for access privilege
                // The first item before '\' is the domain name - extract it
                string[] usernameSplit = windowsIdentity.Name.Split('\\');
                // Apend role names after the domain name
                string wcscmadminRole    = usernameSplit[0] + "\\" + "WcsCmAdmin";
                string wcscmoperatorRole = usernameSplit[0] + "\\" + "WcsCmOperator";
                string wcscmuserRole     = usernameSplit[0] + "\\" + "WcsCmUser";

                if (principal.IsInRole("Administrators"))
                {
                    Tracer.WriteUserLog("User({0}) belongs to Administrators group and hence belongs to WcsCmAdmin privilege role", windowsIdentity.Name);
                    return(authorizationRole.WcsCmAdmin);
                }

                // Is user in local WcsCmAdmin group or domain's WcsCmAdmin group?
                if (principal.IsInRole("WcsCmAdmin") || principal.IsInRole(wcscmadminRole))
                {
                    Tracer.WriteUserLog("User({0}) belongs to WcsCmAdmin privilege role", windowsIdentity.Name);
                    return(authorizationRole.WcsCmAdmin);
                }

                // Is user in local WcsCmOperator group or domain's WcsCmOperator group?
                if (principal.IsInRole("WcsCmOperator") || principal.IsInRole(wcscmoperatorRole))
                {
                    Tracer.WriteUserLog("User({0}) belongs to WcsCmOperator privilege role", windowsIdentity.Name);
                    return(authorizationRole.WcsCmOperator);
                }

                // Is user in local WcsCmUser group or domain's WcsCmUser group?
                if (principal.IsInRole("WcsCmUser") || principal.IsInRole(wcscmuserRole))
                {
                    Tracer.WriteUserLog("User({0}) belongs to WcsCmUser privilege role", windowsIdentity.Name);
                    return(authorizationRole.WcsCmUser);
                }
                // User not mapped to any standard roles
                Tracer.WriteWarning("GetCurrentUserMostPrivilegedRole: Current user({0}) not mapped to the standard WCS roles", windowsIdentity.Name);
                Tracer.WriteUserLog("GetCurrentUserMostPrivilegedRole: Current user({0}) not mapped to the standard WCS roles", windowsIdentity.Name);
            }
            catch (Exception ex)
            {
                Tracer.WriteError("User Authorization check exception  was thrown: " + ex);
            }

            // Return as unauthorized if the user do not belong to any of the category or if there is an exception
            return(authorizationRole.WcsCmUnAuthorized);
        }
Пример #30
0
 /// <summary>
 /// Clear blade classification
 /// </summary>
 internal static void ClearBladeClassification(byte deviceId)
 {
     if (clients.ContainsKey(deviceId))
     {
         clients[deviceId].ClearBladeClassification();
     }
     else
     {
         Tracer.WriteError("ClearBladeClassification(): Invalid device ID: {0}", deviceId);
     }
 }