Ejemplo n.º 1
0
        protected Dictionary <Guid, DatabaseInfo> FilterDatabasesNeedingAction(Dictionary <Guid, DatabaseInfo> dbMap)
        {
            Dictionary <Guid, DatabaseInfo> dictionary = new Dictionary <Guid, DatabaseInfo>();

            foreach (DatabaseInfo databaseInfo in dbMap.Values)
            {
                databaseInfo.Analyze();
                if (base.IsActionRequired(databaseInfo))
                {
                    if (this.m_isDebugOptionEnabled && this.m_amConfig.IsIgnoreServerDebugOptionEnabled(databaseInfo.ActiveServer))
                    {
                        AmTrace.Warning("Periodic action for database {0} is not performed since debug option {1} is set for server {2} which is the current active for the database", new object[]
                        {
                            databaseInfo.Database.Name,
                            databaseInfo.ActiveServer.NetbiosName,
                            AmDebugOptions.IgnoreServerFromAutomaticActions.ToString()
                        });
                    }
                    else
                    {
                        dictionary.Add(databaseInfo.Database.Guid, databaseInfo);
                    }
                }
            }
            return(dictionary);
        }
        // Token: 0x06000061 RID: 97 RVA: 0x00003424 File Offset: 0x00001624
        protected bool AllCopiesAreDisfavored(IADDatabase db)
        {
            IMonitoringADConfig config = Dependencies.MonitoringADConfigProvider.GetConfig(true);
            bool flag = true;

            IADDatabaseCopy[] databaseCopies = db.DatabaseCopies;
            foreach (IADDatabaseCopy iaddatabaseCopy in databaseCopies)
            {
                AmServerName serverName = new AmServerName(iaddatabaseCopy.HostServerName);
                IADServer    iadserver  = config.LookupMiniServerByName(serverName);
                if (!iadserver.DatabaseCopyActivationDisabledAndMoveNow)
                {
                    flag = false;
                    break;
                }
            }
            if (flag)
            {
                AmTrace.Warning("db ({0}) is ActivationDisfavored but no favored server exists. Move is skipped", new object[]
                {
                    db.Name
                });
                ReplayCrimsonEvents.AllServersMarkedDisfavored.LogPeriodic <Guid, string>(db.Name, DiagCore.DefaultEventSuppressionInterval, db.Guid, db.Name);
            }
            return(flag);
        }
        // Token: 0x060003BF RID: 959 RVA: 0x00014544 File Offset: 0x00012744
        private static Dictionary <AmServerName, AmMdbStatusServerInfo> GetMultiNodeServerInfo(AmConfig cfg, List <AmServerName> serversList)
        {
            Dictionary <AmServerName, AmMdbStatusServerInfo> dictionary = new Dictionary <AmServerName, AmMdbStatusServerInfo>();

            foreach (AmServerName amServerName in serversList)
            {
                if (!cfg.IsUnknown)
                {
                    if (cfg.IsDebugOptionsEnabled() && cfg.IsIgnoreServerDebugOptionEnabled(amServerName))
                    {
                        AmTrace.Warning("Server {0} is ignored from batch mounter operation since debug option {1} is enabled", new object[]
                        {
                            amServerName.NetbiosName,
                            AmDebugOptions.IgnoreServerFromAutomaticActions.ToString()
                        });
                    }
                    else if (cfg.IsStandalone || cfg.DagConfig.IsNodePubliclyUp(amServerName))
                    {
                        dictionary[amServerName] = new AmMdbStatusServerInfo(amServerName, true, TimeSpan.FromSeconds((double)RegistryParameters.MdbStatusFetcherServerUpTimeoutInSec));
                    }
                    else if (RegistryParameters.TransientFailoverSuppressionDelayInSec > 0)
                    {
                        dictionary[amServerName] = new AmMdbStatusServerInfo(amServerName, false, TimeSpan.FromSeconds((double)RegistryParameters.MdbStatusFetcherServerDownTimeoutInSec));
                    }
                }
            }
            return(dictionary);
        }
 // Token: 0x0600005F RID: 95 RVA: 0x000031C0 File Offset: 0x000013C0
 protected void MergeDatabaseInfoWithMdbStatus(Dictionary <Guid, DatabaseInfo> dbMap, Dictionary <AmServerName, MdbStatus[]> mdbFullStatusMap, Dictionary <AmServerName, AmMdbStatusServerInfo> serverInfoMap)
 {
     if (mdbFullStatusMap == null)
     {
         AmTrace.Warning("MergeDatabaseInfoWithMdbStatus: mdbFullStatusMap was null.", new object[0]);
         return;
     }
     foreach (AmServerName amServerName in mdbFullStatusMap.Keys)
     {
         MdbStatus[]           array = mdbFullStatusMap[amServerName];
         AmMdbStatusServerInfo amMdbStatusServerInfo = serverInfoMap[amServerName];
         if (array == null)
         {
             AmListMdbStatusMonitor.Instance.RecordFailure(amServerName);
         }
         else
         {
             AmListMdbStatusMonitor.Instance.RecordSuccess(amServerName);
         }
         if (this.ShouldConsiderMdbStatus(amMdbStatusServerInfo, array))
         {
             if (!amMdbStatusServerInfo.IsNodeUp && array.Length > 0)
             {
                 base.AddDelayedFailoverEntryAsync(amServerName, this.m_reasonCode);
             }
             foreach (MdbStatus mdbStatus in array)
             {
                 DatabaseInfo databaseInfo = null;
                 dbMap.TryGetValue(mdbStatus.MdbGuid, out databaseInfo);
                 if (databaseInfo != null)
                 {
                     databaseInfo.StoreStatus[amServerName] = new MdbStatusFlags?(mdbStatus.Status);
                     string text = string.Format("{0}{1}{2}", mdbStatus.MdbGuid, amServerName.NetbiosName, mdbStatus.Status);
                     ReplayCrimsonEvents.ObservedMdbStatus.LogPeriodic <string, Guid, string, string>(text, TimeSpan.FromMinutes(480.0), databaseInfo.Database.Name, mdbStatus.MdbGuid, amServerName.NetbiosName, string.Format("{0} (0x{0:X})", mdbStatus.Status));
                 }
                 else
                 {
                     AmTrace.Warning("{0} is reported from MdbStatus but not present in the dbmap - so ignoring", new object[]
                     {
                         mdbStatus.MdbGuid
                     });
                 }
             }
             foreach (DatabaseInfo databaseInfo2 in dbMap.Values)
             {
                 MdbStatusFlags?mdbStatusFlags;
                 if (databaseInfo2.StoreStatus.TryGetValue(amServerName, out mdbStatusFlags) && mdbStatusFlags == null)
                 {
                     databaseInfo2.StoreStatus[amServerName] = new MdbStatusFlags?(MdbStatusFlags.Offline);
                 }
             }
         }
     }
 }
Ejemplo n.º 5
0
 // Token: 0x060001B0 RID: 432 RVA: 0x0000AB10 File Offset: 0x00008D10
 internal void AttemptCopyLastLogsDirect(Guid mdbGuid, AmAcllArgs acllArgs, ref AmAcllReturnStatus acllStatus)
 {
     acllStatus = new AmAcllReturnStatus();
     ThirdPartyManager.PreventOperationWhenTPREnabled("AttemptCopyLastLogsDirect");
     if (!AmHelper.IsDatabaseRcrEnabled(mdbGuid))
     {
         throw new AmDbMoveOperationNotSupportedException(mdbGuid.ToString());
     }
     AmTrace.Debug("AttemptCopyLastLogsDirect: Calling AmAcllCallback ({0})", new object[]
     {
         mdbGuid
     });
     acllStatus = this.m_replicaInstanceManager.AmAttemptCopyLastLogsCallback(mdbGuid, acllArgs);
     if (acllArgs.ActionCode.IsAutomaticShutdownSwitchover)
     {
         if (!acllStatus.NoLoss)
         {
             ReplayCrimsonEvents.AcllFailedOnSwitchover.Log <Guid>(mdbGuid);
             throw new AcllFailedException(acllStatus.LastError);
         }
         ReplayCrimsonEvents.AcllLosslessOnSwitchover.Log <Guid>(mdbGuid);
         return;
     }
     else
     {
         if (!acllStatus.NoLoss && acllStatus.MountAllowed)
         {
             ReplayCrimsonEvents.LossyMountEnabled.Log <Guid>(mdbGuid);
             AmTrace.Warning("AttemptCopyLastLogsDirect: ACLL detected a lossy mount will be allowed for DB {0}.", new object[]
             {
                 mdbGuid
             });
             return;
         }
         if (acllStatus.MountAllowed)
         {
             AmTrace.Debug("AttemptCopyLastLogsDirect: ACLL completed with no loss for DB {0}.", new object[]
             {
                 mdbGuid
             });
             ReplayCrimsonEvents.AcllLosslessOnMoveOrFailover.Log <Guid>(mdbGuid);
             return;
         }
         if (string.IsNullOrEmpty(acllStatus.LastError))
         {
             ReplayCrimsonEvents.MountRejected.Log <Guid>(mdbGuid);
             throw new AmDbMountNotAllowedDueToLossException();
         }
         ReplayCrimsonEvents.MountRejectedAcllError.Log <Guid, string>(mdbGuid, acllStatus.LastError);
         throw new AmDbMountNotAllowedDueToAcllErrorException(acllStatus.LastError, acllStatus.NumberOfLogsLost);
     }
 }
Ejemplo n.º 6
0
 protected void DeferDatabaseActionsIfRequired(Dictionary <Guid, DatabaseInfo> filteredMap)
 {
     if (filteredMap.Count > 0)
     {
         AmEvtPeriodicDbStateRestore amEvtPeriodicDbStateRestore = new AmEvtPeriodicDbStateRestore(filteredMap);
         if (AmSystemManager.Instance.PeriodicEventManager.EnqueueDeferredSystemEvent(amEvtPeriodicDbStateRestore, RegistryParameters.AmDeferredDatabaseStateRestorerIntervalInMSec))
         {
             AmTrace.Debug("Enqueuing deferred system event for restoring database states if the state is confirmed (evt={0})", new object[]
             {
                 amEvtPeriodicDbStateRestore
             });
             return;
         }
         AmTrace.Warning("There is already a timer pending for periodic action verification. Until it is completed a new one won't be posted.", new object[0]);
     }
 }
Ejemplo n.º 7
0
        // Token: 0x06000829 RID: 2089 RVA: 0x00027A30 File Offset: 0x00025C30
        internal static EventRecord FindEvent(string logName, int eventId, long occuredBeforeMs)
        {
            string query = string.Concat(new string[]
            {
                "*[System[(EventID = ",
                eventId.ToString(),
                ") and (TimeCreated[timediff(@SystemTime) <= ",
                occuredBeforeMs.ToString(),
                "])]]"
            });
            EventLogQuery eventQuery  = new EventLogQuery(logName, PathType.LogName, query);
            EventRecord   eventRecord = null;

            try
            {
                using (EventLogReader eventLogReader = new EventLogReader(eventQuery))
                {
                    eventRecord = eventLogReader.ReadEvent();
                    if (eventRecord == null)
                    {
                        AmTrace.Warning("Failed to find an event. (logname={0}, eventId={1}, occuredBefore={2})", new object[]
                        {
                            logName,
                            eventId,
                            occuredBeforeMs
                        });
                    }
                    else
                    {
                        AmTrace.Debug("Found event (logname={0}, eventId={1}, occuredBefore={2})", new object[]
                        {
                            logName,
                            eventId,
                            occuredBeforeMs
                        });
                    }
                }
            }
            catch (EventLogException ex)
            {
                AmTrace.Error("FindEvent caught {0}", new object[]
                {
                    ex
                });
            }
            return(eventRecord);
        }
Ejemplo n.º 8
0
        // Token: 0x0600019E RID: 414 RVA: 0x00009ED4 File Offset: 0x000080D4
        internal static long GetLastLogGenerationNumber(Guid dbGuid)
        {
            AmConfig config = AmSystemManager.Instance.Config;

            if (config.IsUnknown)
            {
                AmTrace.Error("GetLastLogGenerationNumber: AmConfig is invalid!", new object[0]);
                throw new AmInvalidConfiguration(config.LastError);
            }
            long result;

            if (config.DbState.GetLastLogGenerationNumber(dbGuid, out result))
            {
                return(result);
            }
            AmTrace.Warning("GetLastLogGenerationNumber: returning 0 for DB '{0}' since the corresponding LastLog key was not found.", new object[]
            {
                dbGuid
            });
            return(0L);
        }
Ejemplo n.º 9
0
        internal static void DismountIfMismounted(IADDatabase db, AmDbActionCode actionCode, List <AmServerName> mismountedNodes)
        {
            AmConfig config = AmSystemManager.Instance.Config;

            if (config.Role == AmRole.Unknown)
            {
                throw new AmInvalidConfiguration(config.LastError);
            }
            AmDbStateInfo amDbStateInfo = config.DbState.Read(db.Guid);

            if (amDbStateInfo.IsEntryExist)
            {
                using (List <AmServerName> .Enumerator enumerator = mismountedNodes.GetEnumerator())
                {
                    while (enumerator.MoveNext())
                    {
                        AmServerName amServerName = enumerator.Current;
                        if (!AmServerName.IsEqual(amServerName, amDbStateInfo.ActiveServer))
                        {
                            ReplayCrimsonEvents.DismountingMismountedDatabase.Log <string, Guid, AmServerName>(db.Name, db.Guid, amServerName);
                            AmStoreHelper.RemoteDismount(amServerName, db.Guid, UnmountFlags.SkipCacheFlush, false);
                        }
                        else
                        {
                            AmTrace.Warning("Ignoring force dismount for {0} since it is the current active {1}", new object[]
                            {
                                db.Name,
                                amServerName
                            });
                        }
                    }
                    return;
                }
            }
            AmTrace.Warning("DismountIfMismounted skipped since the database {0} was never mounted", new object[]
            {
                db.Name
            });
        }
Ejemplo n.º 10
0
        // Token: 0x0600019C RID: 412 RVA: 0x00009E04 File Offset: 0x00008004
        internal static MountStatus GetDatabaseMountStatus(Guid dbGuid, out string activeServer)
        {
            AmConfig config = AmSystemManager.Instance.Config;

            activeServer = string.Empty;
            if (config.IsUnknown)
            {
                AmTrace.Warning("GetDatabaseMountStatus: returning Unknown since AM role is Unknown", new object[0]);
                return(MountStatus.Unknown);
            }
            AmDbStateInfo amDbStateInfo = config.DbState.Read(dbGuid);

            if (amDbStateInfo.IsEntryExist)
            {
                activeServer = amDbStateInfo.ActiveServer.NetbiosName;
                return(amDbStateInfo.MountStatus);
            }
            AmTrace.Debug("GetDatabaseMountStatus: returning Dismounted since we failed to find the AmDbStateInfo for {0}, it could be a brand new db", new object[]
            {
                dbGuid.ToString()
            });
            return(MountStatus.Dismounted);
        }
Ejemplo n.º 11
0
        // Token: 0x060001A0 RID: 416 RVA: 0x00009FA4 File Offset: 0x000081A4
        internal static ExDateTime GetLastLogGenerationTimeStamp(Guid dbGuid, out bool doesValueExist)
        {
            AmConfig config = AmSystemManager.Instance.Config;

            if (config.IsUnknown)
            {
                AmTrace.Error("GetLastLogGenerationTimeStamp: AmConfig is invalid!", new object[0]);
                throw new AmInvalidConfiguration(config.LastError);
            }
            ExDateTime minValue;

            doesValueExist = config.DbState.GetLastLogGenerationTimeStamp(dbGuid, out minValue);
            if (doesValueExist)
            {
                return(minValue);
            }
            minValue = ExDateTime.MinValue;
            AmTrace.Warning("GetLastLogGenerationTimeStamp: returning {0} for DB '{1}' since the corresponding LastLog key was not found.", new object[]
            {
                minValue,
                dbGuid
            });
            return(minValue);
        }
Ejemplo n.º 12
0
        private IADDatabase[] GetDatabasesToMonitor()
        {
            List <IADDatabase> list = new List <IADDatabase>();

            try
            {
                IADServer localServer = this.adConfig.GetLocalServer();
                if (localServer != null)
                {
                    IEnumerable <IADDatabase> databasesOnServer = this.adConfig.GetDatabasesOnServer(localServer);
                    if (databasesOnServer == null)
                    {
                        goto IL_CF;
                    }
                    using (IEnumerator <IADDatabase> enumerator = databasesOnServer.GetEnumerator())
                    {
                        while (enumerator.MoveNext())
                        {
                            IADDatabase iaddatabase = enumerator.Current;
                            try
                            {
                                string name;
                                ActiveManagerCore.GetDatabaseMountStatus(iaddatabase.Guid, out name);
                                if (string.IsNullOrEmpty(name))
                                {
                                    name = iaddatabase.Server.Name;
                                }
                                if (Cluster.StringIEquals(name, localServer.Name))
                                {
                                    list.Add(iaddatabase);
                                }
                            }
                            catch (AmGetFqdnFailedNotFoundException ex)
                            {
                                AmTrace.Error("RegistryMonitor.GetDatabasesToMonitor ignoring db {0} due to {1}", new object[]
                                {
                                    iaddatabase.Guid,
                                    ex
                                });
                            }
                        }
                        goto IL_CF;
                    }
                }
                AmTrace.Warning("FindLocalServer() failed.", new object[0]);
                IL_CF :;
            }
            catch (AmCommonTransientException ex2)
            {
                AmTrace.Warning("GetDatabasesToMonitor() failed with {0}", new object[]
                {
                    ex2
                });
            }
            catch (ADTransientException ex3)
            {
                AmTrace.Warning("GetDatabasesToMonitor() failed with {0}", new object[]
                {
                    ex3
                });
            }
            catch (ADExternalException ex4)
            {
                AmTrace.Warning("GetDatabasesToMonitor() failed with {0}", new object[]
                {
                    ex4
                });
            }
            catch (ADOperationException ex5)
            {
                AmTrace.Warning("GetDatabasesToMonitor() failed with {0}", new object[]
                {
                    ex5
                });
            }
            catch (ClusterException ex6)
            {
                AmTrace.Warning("GetDatabasesToMonitor() failed with {0}", new object[]
                {
                    ex6
                });
            }
            return(list.ToArray());
        }
Ejemplo n.º 13
0
 internal void Warning(string format, params object[] args)
 {
     AmTrace.Warning(this.PrefixDatabase(format), args);
 }
Ejemplo n.º 14
0
        private void BackgroundCopy(object data)
        {
            int millisecondsTimeout = 5000;
            RegistryReplicator registryReplicator = null;
            bool flag = false;

            while (!this.stopEvent.WaitOne(millisecondsTimeout, false))
            {
                millisecondsTimeout = 5000;
                AmConfig config = AmSystemManager.Instance.Config;
                if (config.IsPamOrSam)
                {
                    AmClusterHandle handle = null;
                    if (flag)
                    {
                        handle = config.DagConfig.Cluster.Handle;
                        flag   = false;
                    }
                    while (this.workQueue.Count > 0 && !this.stopEvent.WaitOne(0, false))
                    {
                        lock (this.workQueue)
                        {
                            registryReplicator = this.workQueue.Dequeue();
                        }
                        Exception ex = null;
                        try
                        {
                            registryReplicator.Copy(handle);
                        }
                        catch (AmRegistryException ex2)
                        {
                            ex = ex2;
                            lock (this.workQueue)
                            {
                                this.workQueue.Enqueue(registryReplicator);
                            }
                        }
                        catch (ClusterException ex3)
                        {
                            ex = ex3;
                            AmTrace.Warning("Caught AmClusterApiException during registry replication: {0}", new object[]
                            {
                                ex3
                            });
                            lock (this.workQueue)
                            {
                                this.workQueue.Enqueue(registryReplicator);
                                millisecondsTimeout = 30000;
                                flag = true;
                                break;
                            }
                        }
                        finally
                        {
                            if (ex != null)
                            {
                                ReplayEventLogConstants.Tuple_RegistryReplicatorException.LogEvent(null, new object[]
                                {
                                    ex
                                });
                            }
                        }
                    }
                }
            }
        }
        // Token: 0x060007CC RID: 1996 RVA: 0x00026040 File Offset: 0x00024240
        private void CopyWorker(RegistryManipulator source, RegistryManipulator destination)
        {
            string text  = null;
            string text2 = null;
            bool   flag  = true;
            bool   flag2 = true;

            this.m_isCopying = true;
            try
            {
                Queue <string> queue  = new Queue <string>();
                Queue <string> queue2 = new Queue <string>();
                List <string>  list   = new List <string>();
                List <string>  list2  = new List <string>();
                queue.Enqueue(string.Empty);
                queue2.Enqueue(string.Empty);
                while (this.m_isValid)
                {
                    if (flag)
                    {
                        list.Clear();
                        if (queue.Count > 0)
                        {
                            text = queue.Dequeue();
                            flag = false;
                            foreach (string text3 in source.GetSubKeyNames(text))
                            {
                                string item = text3;
                                if (text.CompareTo(string.Empty) != 0)
                                {
                                    item = text + "\\" + text3;
                                }
                                queue.Enqueue(item);
                            }
                        }
                        else
                        {
                            text = null;
                        }
                    }
                    if (flag2)
                    {
                        list2.Clear();
                        if (queue2.Count > 0)
                        {
                            text2 = queue2.Dequeue();
                            foreach (string text4 in destination.GetSubKeyNames(text2))
                            {
                                string item2 = text4;
                                if (text2.CompareTo(string.Empty) != 0)
                                {
                                    item2 = text2 + "\\" + text4;
                                }
                                queue2.Enqueue(item2);
                            }
                        }
                        else
                        {
                            text2 = null;
                        }
                    }
                    int num;
                    if (text == null)
                    {
                        num = 1;
                    }
                    else if (text2 == null)
                    {
                        num = -1;
                    }
                    else
                    {
                        num = string.Compare(text, text2, StringComparison.OrdinalIgnoreCase);
                    }
                    if (num == 0)
                    {
                        foreach (string item3 in source.GetValueNames(text))
                        {
                            list.Add(item3);
                        }
                        list.Sort();
                        foreach (string item4 in destination.GetValueNames(text2))
                        {
                            list2.Add(item4);
                        }
                        list2.Sort();
                        int num2 = 0;
                        int num3 = 0;
                        while (num3 < list.Count || num2 < list2.Count)
                        {
                            int num4;
                            if (num3 >= list.Count)
                            {
                                num4 = 1;
                            }
                            else if (num2 >= list2.Count)
                            {
                                num4 = -1;
                            }
                            else
                            {
                                num4 = string.Compare(list[num3], list2[num2]);
                            }
                            if (num4 == 0)
                            {
                                RegistryValue value  = source.GetValue(text, list[num3]);
                                RegistryValue value2 = destination.GetValue(text2, list2[num2]);
                                if (value != null && !value.Equals(value2))
                                {
                                    destination.SetValue(text, value);
                                }
                                else if (value == null)
                                {
                                    destination.DeleteValue(text2, list2[num2]);
                                }
                                num3++;
                                num2++;
                            }
                            else if (num4 < 0)
                            {
                                RegistryValue value3 = source.GetValue(text, list[num3]);
                                if (value3 != null)
                                {
                                    destination.SetValue(text, value3);
                                }
                                num3++;
                            }
                            else
                            {
                                destination.DeleteValue(text2, list2[num2]);
                                num2++;
                            }
                        }
                        flag  = true;
                        flag2 = true;
                    }
                    else if (num < 0 && text != null)
                    {
                        destination.CreateKey(text);
                        flag2 = false;
                        text2 = text;
                    }
                    else
                    {
                        if (text2 == null)
                        {
                            return;
                        }
                        destination.DeleteKey(text2);
                        flag2 = true;
                    }
                }
                AmTrace.Warning("Skipping a copy notification since the database has changed master. Source root: {0}", new object[]
                {
                    source.Root
                });
            }
            finally
            {
                this.m_isCopying = false;
            }
        }
Ejemplo n.º 16
0
        private void MonitorRegistry()
        {
            int      num      = 0;
            int      num2     = RegistryParameters.RegistryMonitorPollingIntervalInSec / 5;
            AmConfig amConfig = null;

            Dictionary <Guid, RegistryReplicator> .KeyCollection.Enumerator enumerator = this.replicators.Keys.GetEnumerator();
            try
            {
                bool flag = false;
                RegistryReplicator registryReplicator = null;
                RealRegistry       realRegistry       = null;
                ClusterRegistry    clusterRegistry    = null;
                List <Guid>        list  = new List <Guid>();
                List <WaitHandle>  list2 = new List <WaitHandle>();
                while (!this.stopEvent.WaitOne(5000, false))
                {
                    amConfig = AmSystemManager.Instance.Config;
                    while (!this.stopEvent.WaitOne(0, false) && amConfig.IsPamOrSam)
                    {
                        AmClusterHandle handle = amConfig.DagConfig.Cluster.Handle;
                        if (flag)
                        {
                            enumerator.Dispose();
                            enumerator = this.replicators.Keys.GetEnumerator();
                        }
                        int num3 = 0;
                        list2.Clear();
                        list.Clear();
                        while (num3 < 64 && enumerator.MoveNext())
                        {
                            if (this.replicators[enumerator.Current].IsValid)
                            {
                                list2.Add(this.replicators[enumerator.Current].KeyChanged);
                                list.Add(enumerator.Current);
                                num3++;
                            }
                        }
                        flag = (num3 < 64);
                        if (list2.Count <= 0)
                        {
                            goto IL_205;
                        }
                        int num4 = WaitHandle.WaitAny(list2.ToArray(), 5000, false);
                        if (num4 >= 0 && num4 < list2.Count)
                        {
                            Guid key = list[num4];
                            if (this.replicators[key].IsCopyEnabled)
                            {
                                lock (this.workQueue)
                                {
                                    this.workQueue.Enqueue(this.replicators[key]);
                                    this.replicators[key].KeyChanged.Reset();
                                }
                                try
                                {
                                    DiagnosticsNativeMethods.ErrorCode errorCode = DiagnosticsNativeMethods.RegNotifyChangeKeyValue((SafeRegistryHandle)this.replicators[key].Handle, true, DiagnosticsNativeMethods.RegistryNotifications.ChangeName | DiagnosticsNativeMethods.RegistryNotifications.ChangeAttributes | DiagnosticsNativeMethods.RegistryNotifications.LastSet, this.replicators[key].KeyChanged.SafeWaitHandle, true);
                                    if (errorCode != DiagnosticsNativeMethods.ErrorCode.Success)
                                    {
                                        throw new AmRegistryException("RegNotifyChangeKeyValue", new Win32Exception((int)errorCode));
                                    }
                                    goto IL_21B;
                                }
                                catch (AmRegistryException ex)
                                {
                                    AmTrace.Warning("Registering for registry key change notifications failed. Inner Exception: {0}", new object[]
                                    {
                                        ex
                                    });
                                    goto IL_21B;
                                }
                                goto IL_205;
                            }
                        }
IL_21B:
                        if (num == 0 || this.dbMountedEvent.WaitOne(0, false))
                        {
                            num2 = RegistryParameters.RegistryMonitorPollingIntervalInSec / 5;
                            foreach (KeyValuePair <Guid, RegistryReplicator> keyValuePair in this.replicators)
                            {
                                keyValuePair.Value.SetMarkedForRemoval();
                            }
                            IADDatabase[] databasesToMonitor = this.GetDatabasesToMonitor();
                            if (databasesToMonitor != null)
                            {
                                foreach (IADDatabase iaddatabase in databasesToMonitor)
                                {
                                    if (this.replicators.ContainsKey(iaddatabase.Guid))
                                    {
                                        this.replicators[iaddatabase.Guid].ResetMarkedForRemoval();
                                    }
                                    else
                                    {
                                        Exception ex2 = null;
                                        try
                                        {
                                            if (!flag)
                                            {
                                                enumerator.Dispose();
                                                flag = true;
                                            }
                                            string             text             = iaddatabase.IsPublicFolderDatabase ? RegistryMonitor.publicString : RegistryMonitor.privateString;
                                            string             text2            = string.Format(RegistryMonitor.localRegistryPathFormat, Environment.MachineName, iaddatabase.Guid, text);
                                            string             root             = string.Format(RegistryMonitor.clusterRegistryPathFormat, iaddatabase.Guid, text);
                                            ManualResetEvent   manualResetEvent = new ManualResetEvent(false);
                                            SafeRegistryHandle safeRegistryHandle;
                                            DiagnosticsNativeMethods.ErrorCode errorCode = DiagnosticsNativeMethods.RegOpenKeyEx(SafeRegistryHandle.LocalMachine, text2, 0, 131097, out safeRegistryHandle);
                                            if (DiagnosticsNativeMethods.ErrorCode.FileNotFound == errorCode)
                                            {
                                                RegistryKey registryKey = Registry.LocalMachine.CreateSubKey(text2);
                                                if (registryKey != null)
                                                {
                                                    registryKey.Close();
                                                    errorCode = DiagnosticsNativeMethods.RegOpenKeyEx(SafeRegistryHandle.LocalMachine, text2, 0, 131097, out safeRegistryHandle);
                                                }
                                            }
                                            if (errorCode != DiagnosticsNativeMethods.ErrorCode.Success)
                                            {
                                                throw new AmRegistryException("RegOpenKeyEx", new Win32Exception((int)errorCode));
                                            }
                                            realRegistry       = new RealRegistry(text2, safeRegistryHandle);
                                            clusterRegistry    = new ClusterRegistry(root, amConfig.DagConfig.Cluster.Handle);
                                            registryReplicator = new RegistryReplicator(realRegistry, clusterRegistry, manualResetEvent);
                                            realRegistry       = null;
                                            clusterRegistry    = null;
                                            if (registryReplicator.IsInitialReplication)
                                            {
                                                registryReplicator.Copy(handle);
                                                registryReplicator.SetInitialReplication();
                                            }
                                            else
                                            {
                                                registryReplicator.InverseCopy();
                                            }
                                            errorCode = DiagnosticsNativeMethods.RegNotifyChangeKeyValue(safeRegistryHandle, true, DiagnosticsNativeMethods.RegistryNotifications.ChangeName | DiagnosticsNativeMethods.RegistryNotifications.ChangeAttributes | DiagnosticsNativeMethods.RegistryNotifications.LastSet, manualResetEvent.SafeWaitHandle, true);
                                            if (errorCode != DiagnosticsNativeMethods.ErrorCode.Success)
                                            {
                                                throw new AmRegistryException("RegNotifyChangeKeyValue", new Win32Exception((int)errorCode));
                                            }
                                            this.replicators.Add(iaddatabase.Guid, registryReplicator);
                                            registryReplicator = null;
                                        }
                                        catch (AmRegistryException ex3)
                                        {
                                            ex2 = ex3;
                                            AmTrace.Warning("Failed to add database to monitor: {0}. Exception: {1}", new object[]
                                            {
                                                iaddatabase.Name,
                                                ex3
                                            });
                                        }
                                        catch (ClusterException ex4)
                                        {
                                            ex2 = ex4;
                                            AmTrace.Warning("Failed to add database to monitor: {0}. Exception: {1}", new object[]
                                            {
                                                iaddatabase.Name,
                                                ex4
                                            });
                                        }
                                        finally
                                        {
                                            if (ex2 != null)
                                            {
                                                ReplayEventLogConstants.Tuple_RegistryReplicatorException.LogEvent(null, new object[]
                                                {
                                                    ex2
                                                });
                                            }
                                            if (registryReplicator != null)
                                            {
                                                registryReplicator.Dispose();
                                                registryReplicator = null;
                                            }
                                            if (realRegistry != null)
                                            {
                                                realRegistry.Dispose();
                                                realRegistry = null;
                                            }
                                            if (clusterRegistry != null)
                                            {
                                                clusterRegistry.Dispose();
                                                clusterRegistry = null;
                                            }
                                        }
                                    }
                                }
                            }
                            list.Clear();
                            foreach (KeyValuePair <Guid, RegistryReplicator> keyValuePair2 in this.replicators)
                            {
                                if (keyValuePair2.Value.IsMarkedForRemoval)
                                {
                                    list.Add(keyValuePair2.Key);
                                }
                            }
                            lock (this.workQueue)
                            {
                                foreach (Guid key2 in list)
                                {
                                    registryReplicator = this.replicators[key2];
                                    registryReplicator.SetInvalid();
                                    if (!registryReplicator.IsCopying)
                                    {
                                        if (!flag)
                                        {
                                            flag = true;
                                        }
                                        this.replicators.Remove(key2);
                                        registryReplicator.Dispose();
                                    }
                                }
                            }
                            registryReplicator = null;
                        }
                        num      = (num + 1) % num2;
                        amConfig = AmSystemManager.Instance.Config;
                        continue;
IL_205:
                        if (!this.stopEvent.WaitOne(5000, false))
                        {
                            goto IL_21B;
                        }
                        break;
                    }
                }
                foreach (KeyValuePair <Guid, RegistryReplicator> keyValuePair3 in this.replicators)
                {
                    if (!keyValuePair3.Value.IsCopying)
                    {
                        keyValuePair3.Value.SetInvalid();
                    }
                }
            }
            finally
            {
                enumerator.Dispose();
            }
        }
 // Token: 0x06000062 RID: 98 RVA: 0x000034CC File Offset: 0x000016CC
 protected virtual void PopulateWithDatabaseOperations(Dictionary <Guid, DatabaseInfo> dbMap)
 {
     foreach (DatabaseInfo databaseInfo in dbMap.Values)
     {
         databaseInfo.Analyze();
         if (this.m_isDebugOptionEnabled && this.m_amConfig.IsIgnoreServerDebugOptionEnabled(databaseInfo.ActiveServer))
         {
             AmTrace.Warning("Batchmounter operation for database {0} is not performed since debug option {1} is set for server {2} which is the current active for the database", new object[]
             {
                 databaseInfo.Database.Name,
                 databaseInfo.ActiveServer.NetbiosName,
                 AmDebugOptions.IgnoreServerFromAutomaticActions.ToString()
             });
         }
         else
         {
             List <AmDbOperation> list     = new List <AmDbOperation>();
             IADDatabase          database = databaseInfo.Database;
             if (databaseInfo.IsMountedButAdminRequestedDismount)
             {
                 AmDbActionCode actionCode = new AmDbActionCode(AmDbActionInitiator.Admin, this.m_reasonCode, AmDbActionCategory.Dismount);
                 AmDbDismountAdminDismountedOperation item = new AmDbDismountAdminDismountedOperation(database, actionCode);
                 list.Add(item);
                 this.m_dismountRequests++;
             }
             else
             {
                 if (databaseInfo.IsMismounted)
                 {
                     AmDbActionCode actionCode2            = new AmDbActionCode(AmDbActionInitiator.Automatic, this.m_reasonCode, AmDbActionCategory.ForceDismount);
                     AmDbDismountMismountedOperation item2 = new AmDbDismountMismountedOperation(database, actionCode2, databaseInfo.MisMountedServerList);
                     list.Add(item2);
                     this.m_dismountRequests++;
                 }
                 if (databaseInfo.IsActiveOnDisabledServer && !this.AllCopiesAreDisfavored(database))
                 {
                     list.Add(this.BuildMoveForActivationDisabled(database));
                     this.m_moveRequests++;
                 }
                 if (!databaseInfo.IsMountedOnActive)
                 {
                     AmDbActionCode     actionCode3 = new AmDbActionCode(AmDbActionInitiator.Automatic, this.m_reasonCode, AmDbActionCategory.Mount);
                     AmDbMountOperation item3       = new AmDbMountOperation(database, actionCode3);
                     list.Add(item3);
                     this.m_mountRequests++;
                 }
                 if (databaseInfo.IsClusterDatabaseOutOfSync)
                 {
                     AmDbActionCode actionCode4             = new AmDbActionCode(AmDbActionInitiator.Automatic, this.m_reasonCode, AmDbActionCategory.SyncState);
                     AmDbClusterDatabaseSyncOperation item4 = new AmDbClusterDatabaseSyncOperation(database, actionCode4);
                     list.Add(item4);
                     this.m_clusDbSyncRequests++;
                 }
                 if (databaseInfo.IsAdPropertiesOutOfSync)
                 {
                     AmDbActionCode actionCode5        = new AmDbActionCode(AmDbActionInitiator.Automatic, this.m_reasonCode, AmDbActionCategory.SyncAd);
                     AmDbAdPropertySyncOperation item5 = new AmDbAdPropertySyncOperation(database, actionCode5);
                     list.Add(item5);
                     this.m_adSyncRequests++;
                 }
             }
             databaseInfo.OperationsQueued = list;
         }
     }
 }