public PerformanceCounterTracker(Logging.IBasicLogger logger, PerformanceCounterSpec pcs)
            {
                this.pcs = pcs;
                pcc      = pcs.GetPerformanceCounterCategory();

                useRawPerfCtrValue = pcs.UseRawValue;

                gpInfo = new MDRF.Writer.GroupPointInfo()
                {
                    Name     = pcs.PointName,
                    ValueCST = ContainerStorageType.None,
                };

                try
                {
                    var categorySample = pcc.ReadCategory();
                    Service(logger, categorySample, true);
                }
                catch (System.Exception ex)
                {
                    Logging.IMesgEmitter emitter = (logger == null ? Logging.NullEmitter : logger.Info);

                    emitter.Emit("{0} for '{1}' generated unexpected exception: {2}", CurrentMethodName, gpInfo.Name, ex.ToString(ExceptionFormat.TypeAndMessage));

                    isUsable = false;
                }
            }
        /// <summary>
        /// This method generates log messages for each of the groups in the current table and then for the [Global] group.
        /// </summary>
        public void DumpTableToLog(string reason, Logging.IMesgEmitter dumpTableEmitter = null)
        {
            dumpTableEmitter = dumpTableEmitter ?? DefaultDumpEmitter;

            lock (mutex)
            {
                dumpTableEmitter.Emit("{0}: {1} [table size: {2}]", Fcns.CurrentMethodName, reason, groupTrackingInfoDictionary.Count);

                foreach (var tracker in groupTrackingInfoDictionary.Values)
                {
                    dumpTableEmitter.Emit("{0}", tracker);
                }

                dumpTableEmitter.Emit("{0}", globalTrackingInfo);
            }
        }
Exemple #3
0
        /// <summary>
        /// Attempts to delete files/directories given in the list of DirectoryEntryInfo items to prune.
        /// <para/>returns the number of items that were successfully deleted.
        /// </summary>
        /// <param name="pruneItemList">Gives the list of DirectoryEntryInfo items that are to be removed from the file system.</param>
        /// <param name="deleteEmitter">Gives the IMesgEmitter that will recieve messages about the successfull deletions</param>
        /// <param name="issueEmitter">Gives the IMesgEmitter that will receive any messages about failures while attempting to delete each item.</param>
        /// <param name="reason">Gives the string description for the reason that these items are to be deleted.  Null or Empty will be replaced with [NoReasonGiven]</param>
        /// <returns>The number of items that were successfully deleted.</returns>
        public int DeletePrunedItems(List <DirectoryEntryInfo> pruneItemList, Logging.IMesgEmitter deleteEmitter, Logging.IMesgEmitter issueEmitter, string reason = null)
        {
            int deletedItemCount = 0;           // actually the count of the number of items that we have attempted to delete

            reason = reason.MapNullOrEmptyTo("[NoReasonGiven]");

            for (int idx = 0; idx < pruneItemList.Count; idx++)
            {
                DirectoryEntryInfo entryToDelete = pruneItemList[idx];

                double ageInDays = entryToDelete.CreationAge.TotalDays;

                if (entryToDelete.IsFile)
                {
                    try
                    {
                        System.IO.File.Delete(entryToDelete.Path);
                        deletedItemCount++;
                        deleteEmitter.Emit("Pruned file:'{0}', size:{1}, age:{2:f6} days, reason:{3}", entryToDelete.Path, entryToDelete.Length, ageInDays, reason);
                    }
                    catch (System.Exception ex)
                    {
                        issueEmitter.Emit("Prune failed to delete file:'{0}', error:'{1}'", entryToDelete.Path, ex.Message);
                    }
                }
                else if (entryToDelete.IsDirectory)
                {
                    try
                    {
                        System.IO.Directory.Delete(entryToDelete.Path);
                        deletedItemCount++;
                        deleteEmitter.Emit("Pruned directory:'{0}', size:{1}, age:{2:f6} days, reason:{3}", entryToDelete.Path, entryToDelete.Length, ageInDays, reason);
                    }
                    catch (System.Exception ex)
                    {
                        issueEmitter.Emit("Prune failed to delete directory:'{0}', error:'{1}'", entryToDelete.Path, ex.Message);
                    }
                }
                else
                {
                    issueEmitter.Emit("Prune cannot delete unknown tree node at path:'{0}', reason:{1}", entryToDelete.Path, reason);
                }
            }

            return(deletedItemCount);
        }
Exemple #4
0
        /// <summary>Requests the node to build its sub-tree and allows the caller to indicate if it should be updated after being built.</summary>
        public void BuildTree(bool updateAtEnd = true, Logging.IMesgEmitter issueEmitter = null, bool forceBuildTree = false)
        {
            try
            {
                // If the tree has already need built and does not have its IsTreeBuildNeeded flag set then do not (re)build this node
                if (!IsTreeBuildNeeded && !forceBuildTree)		// this flag should only be set for directories
                    return;

                issueEmitter = issueEmitter ?? Logging.NullEmitter;

                if (!IsDirectory)
                {
                    issueEmitter.Emit("BuildTree failed: Tree Path '{0}' is neither a normal file nor a normal directory.", Path);
                }

                ClearSubTreeInformation();

                sortedDirContentsNodeArray = null;
                System.IO.Directory.GetFileSystemEntries(Path).Select(path => new DirectoryTreeEntryNode(path, this)).DoForEach(node => sortedDirContentsNodeSet.Add(node));

                SetTreeUpdateNeeded(true);

                foreach (var entry in UpdateAndGetSortedDirContentsNodeArray())
                {
                    if (entry.IsExistingDirectory)
                        entry.BuildTree(issueEmitter: issueEmitter);
                    else if (!entry.IsExistingFile)
                        issueEmitter.Emit("BuildTree issue: Sub Tree Path '{0}' is neither a normal file nor a normal directory.", entry.Path);
                }

                // we have completed the tree build for this level and the levels below it
                IsTreeBuildNeeded = false;

                // update the tree to update our summary fields - only scan the top level as the 
                if (updateAtEnd)
                    UpdateTree(issueEmitter: issueEmitter);
            }
            catch (System.Exception ex)
            {
                issueEmitter.Emit("BuiltTree failed at path:'{0}' error:{1}", path, ex);
            }
        }
Exemple #5
0
        /// <summary>
        /// Used to inform manager about the addition of another file or diretory which should be monitored by the manager (and which should eventually be pruned).
        /// This method may also be used to inform the manager that the file contents might have changed.
        /// </summary>
        public void NotePathAdded(string pathToAdd, Logging.IMesgEmitter issueEmitter)
        {
            try
            {
                string fullPathToAdd   = System.IO.Path.GetFullPath(pathToAdd);
                string workingRootPath = treeRootEntry.Path;

                string   relativePathPart     = String.Empty;
                string[] relativePathSegments = null;

                if (fullPathToAdd.StartsWith(workingRootPath))
                {
                    // convert the full path into a relative path
                    relativePathPart = @".{0}".CheckedFormat(fullPathToAdd.Substring(workingRootPath.Length));

                    relativePathSegments = relativePathPart.Split(new char[] { System.IO.Path.DirectorySeparatorChar, System.IO.Path.AltDirectorySeparatorChar }).Skip(1).ToArray();
                }

                string regeneratedFullPath = System.IO.Path.GetFullPath(System.IO.Path.Combine(workingRootPath, relativePathPart));

                if (!String.IsNullOrEmpty(relativePathPart) && (regeneratedFullPath == fullPathToAdd))
                {
                    treeRootEntry.AddRelativePath(relativePathSegments, issueEmitter);
                }
                else
                {
                    issueEmitter.Emit("NotePathAdded '{0}' failed: given path is a proper subpath under under the monitored path '{1}'", pathToAdd, workingRootPath);
                }

                treeRootEntry.UpdateTree(issueEmitter);
            }
            catch (System.Exception ex)
            {
                issueEmitter.Emit("NotePathAdded '{0}' failed: error:'{1}'", pathToAdd, ex);
            }
        }
Exemple #6
0
        public Message SetState(QpcTimeStamp qpcTimeStamp, MessageState state, string reason, bool autoReleaseByState = false)
        {
            MessageState entryState = State;

            reason = reason ?? "NoReasonGiven";

            State     = state;
            TimeStamp = qpcTimeStamp;
            Reason    = reason;

            Logging.IMesgEmitter emitterToUse = StateEmitter;

            switch (state)
            {
            case MessageState.Initial:
            case MessageState.Released:
                ReturnBuffersToPool(qpcTimeStamp);
                break;

            case MessageState.Delivered:
                if (autoReleaseByState)
                {
                    ReturnBuffersToPool(qpcTimeStamp);
                }
                break;

            case MessageState.Failed:
                emitterToUse = IssueEmitter;
                break;

            case MessageState.SendPosted:
                SendPostedTimeStamp = qpcTimeStamp;
                break;

            default:
                break;
            }

            if (emitterToUse.IsEnabled)
            {
                emitterToUse.Emit("Message_{0:x4} State changed to {1} [from: {2}, reason: {3}]", instanceNum & 0x0ffff, state, entryState, reason);
            }

            return(this);
        }
            public void Service(Logging.IBasicLogger logger, InstanceDataCollectionCollection categorySample, bool rethrow = false)
            {
                if (!isUsable)
                {
                    return;
                }

                try
                {
                    InstanceDataCollection instanceDataCollection = categorySample[pcs.CounterName];
                    InstanceData           instanceData           = instanceDataCollection[pcs.InstanceName.MapNullToEmpty()]; // use empty string for counters that only have one value

                    CounterSample counterSample = instanceData.Sample;

                    if (!useRawPerfCtrValue)
                    {
                        gpInfo.VC = new ValueContainer(CounterSample.Calculate(lastCounterSample, counterSample));
                    }
                    else
                    {
                        gpInfo.VC = new ValueContainer(counterSample.RawValue);
                    }

                    lastCounterSample = counterSample;

                    logExceptionElevationHoldoffTimer.StopIfNeeded();
                }
                catch (System.Exception ex)
                {
                    bool useHighLevelMesg = (logExceptionElevationHoldoffTimer.IsTriggered || !logExceptionElevationHoldoffTimer.Started);
                    logExceptionElevationHoldoffTimer.StartIfNeeded();

                    Logging.IMesgEmitter emitter = (logger == null ? Logging.NullEmitter : (useHighLevelMesg ? logger.Info : logger.Trace));

                    emitter.Emit("{0} for '{1}' generated exception: {2}", CurrentMethodName, gpInfo.Name, ex.ToString(ExceptionFormat.TypeAndMessage));
                }
            }
Exemple #8
0
        /// <summary>
        /// Appends a list of the DirectoryEntryInfo items for the tree item's that have been removed from the memory copy of the tree.  
        /// Caller is expected to attempt to delete the actual files/directories.
        /// Performs UpdateTree prior to returning.
        /// </summary>
        public void AppendAndRemoveOldestTreeDirectory(List<DirectoryEntryInfo> pruneItemList, int maxEntriesToDeletePerIteration, Logging.IMesgEmitter issueEmitter = null)
        {
            issueEmitter = issueEmitter ?? Logging.NullEmitter;

            Stack<DirectoryTreeEntryNode> nodeStack = new Stack<DirectoryTreeEntryNode>();

			DirectoryTreeEntryNode currentEntry = this;

			// create a stack of the entries from the root down to the oldest leaf (file or directory).  
			//	Each level in the stack retains the current entry at that level, the parent entry and the index in the parent entries content vector at which you will find the current entry
			while (currentEntry != null)
			{
                DirectoryTreeEntryNode nextEntryDown = currentEntry.OldestDirContentsNodeEntry;

                if (nextEntryDown != null)
				{
					nodeStack.Push(nextEntryDown);

					currentEntry = nextEntryDown;
				}
				else if (!currentEntry.IsRootNode)
				{
					break;	// reached the bottom of the search path
				}
				else
				{
                    // 
					// we can never remove the root item - there is nothing further to prune.
					return;
				}
			}

			// start at the bottom of the stack and determine if that entry can be removed (or not).  If so then:
			//	A) added it to the list of entries to remove
			//	B) remove it from its parrent's entry content vector
			//	and then repeate for the each level up in the stack until an entry is encountered that cannot be deleted (is not an empty directory after the sub item has been removed.)

            while (nodeStack.Count != 0)
            {
                DirectoryTreeEntryNode topStackNode = nodeStack.Pop();
                DirectoryTreeEntryNode topStackNodeParentItem = topStackNode.ParentDirEntry;

                bool isFile = topStackNode.IsFile;
                bool isNormalFile = topStackNode.IsExistingFile;
                bool isNormalDirectory = topStackNode.IsExistingDirectory;
                bool isEmptyDirectory = topStackNode.IsEmptyDirectory;

                string skipReason = null;
                if (!isNormalFile && !isNormalDirectory)
                    skipReason = Fcns.CheckedFormat("Skipping non-normal node at path:'{0}'", Path);

                bool skipIt = (skipReason != null);

                if (skipIt)
                    issueEmitter.Emit(skipReason);

                bool removeIt = (isNormalFile || isEmptyDirectory) && !skipIt;
                bool removeItFromTree = removeIt;

                if (!removeIt && !skipIt)
                    break;						// once we have reached a level where nothing more can be removed (ie it is not an empty directory), we stop iterating up the stack.

                if (removeItFromTree)
                {
                    if (removeIt)
                        pruneItemList.Add(topStackNode);		// append a copy of the topStackNode as a DirectoryEntryInfo object onto the pruneItemList

                    topStackNodeParentItem.sortedDirContentsNodeArray = null;

                    topStackNodeParentItem.sortedDirContentsNodeSet.Remove(topStackNode);
                    RootDirectoryTreeEntryNodeDictionary.Remove(topStackNode.Path);

                    if (removeIt && isFile && maxEntriesToDeletePerIteration > 1)
                    {
                        // identify the other n oldest items in this directory and add them to the delete list
                        while (pruneItemList.Count < maxEntriesToDeletePerIteration)
                        {
                            DirectoryTreeEntryNode nextOldestEntryInCurrentDir = topStackNodeParentItem.OldestDirContentsNodeEntry;

                            if (nextOldestEntryInCurrentDir == null)
                                break;

                            // stop adding to the current list of items to delete once we reach any non-normal file - special cases will be covered on the next go around.
                            if (!nextOldestEntryInCurrentDir.IsExistingFile)
                                break;

                            // append a copy of the nextEntryInCurrentDir as a DirectoryEntryInfo object
                            pruneItemList.Add(nextOldestEntryInCurrentDir);

                            // remove the pointer to the entry that just got added to the delete list and then delete the entry
                            topStackNodeParentItem.sortedDirContentsNodeSet.Remove(nextOldestEntryInCurrentDir);
                            RootDirectoryTreeEntryNodeDictionary.Remove(nextOldestEntryInCurrentDir.Path);

                            if (topStackNodeParentItem.IsEmptyDirectory)
                                break;
                        }
                    }

                    topStackNodeParentItem.SetTreeUpdateNeeded(true);
                }
            }

			UpdateTree(issueEmitter);
        }
Exemple #9
0
        /// <summary>
        /// Addes a new node in the tree at the relative location under the given node produced by iteratavely concactinating the given list of relative path elements
        /// onto the full path to this node and treversing downward until the relative path elements have been used up.  
        /// Performs UpdateTree prior to returning.
        /// </summary>
        public void AddRelativePath(IList<String> relativePathElementList, Logging.IMesgEmitter issueEmitter = null)
        {
            issueEmitter = issueEmitter ?? Logging.NullEmitter;

            int relativePathElementListSize = relativePathElementList.Count;
            if (relativePathElementListSize <= 0)
            {
                issueEmitter.Emit("AddRelativePath failed at node:'{0}': given relative path list is empty", Path);
                return;
            }

			DirectoryTreeEntryNode treeScanEntry = this;

			for (int rPathElemIdx = 0; ((treeScanEntry != null) && (rPathElemIdx < relativePathElementListSize)); rPathElemIdx++)
			{
				bool onLastRPathElement = (rPathElemIdx == (relativePathElementListSize - 1));

				string leafName = relativePathElementList[rPathElemIdx];
                string newEntryPath = System.IO.Path.Combine(treeScanEntry.Path, leafName);

                DirectoryTreeEntryNode subLeafNode = RootDirectoryTreeEntryNodeDictionary.SafeTryGetValue(newEntryPath);

                if (subLeafNode != null && subLeafNode.Name != leafName)
                    subLeafNode = treeScanEntry.UpdateAndGetSortedDirContentsNodeArray().FirstOrDefault(item => item.Name == leafName);

				if (subLeafNode == null)
				{
                    DirectoryTreeEntryNode newEntry = new DirectoryTreeEntryNode(newEntryPath, treeScanEntry);
                    subLeafNode = newEntry;

					if (newEntry == null)
					{
						issueEmitter.Emit("Allocation Failure while attempting to added entry path:{0}", newEntryPath);
					}
					else
					{
                        treeScanEntry.sortedDirContentsNodeArray = null;
                        treeScanEntry.sortedDirContentsNodeSet.Add(newEntry);

                        if (newEntry.IsExistingDirectory)
                        {
                            newEntry.BuildTree(issueEmitter: issueEmitter);
                        }
                        else if (newEntry.IsExistingFile)
                        {
                            // nothing more to do here
                        }
                        else
                        {
                            issueEmitter.Emit("Added entry path:{0} is neither a known file or directory object", newEntry.Path);
                        }
					}
				}
				else
				{
                    if (subLeafNode.IsFile)
                        subLeafNode.Refresh();

                    if (!subLeafNode.IsExistingDirectory && !onLastRPathElement)
					{
                        issueEmitter.Emit("Add relative path traverse error: partial path is not a directory at {0}", subLeafNode.Path);

						break;		 // cannot continue to go lower from this point down
					}
				}

                treeScanEntry.SetTreeUpdateNeeded(true);

                treeScanEntry = subLeafNode;
			}

            UpdateTree(issueEmitter: issueEmitter);
        }