private LockFile AcquireSessionLock(MonitoringSession session, string methodName = "") { string sessionFilePath = (session.EndDate != DateTime.MinValue.ToUniversalTime()) ? GetCpuMonitoringPath(MonitoringSessionDirectories.Completed) : GetCpuMonitoringPath(MonitoringSessionDirectories.Active); string lockFilePath = sessionFilePath + ".lock"; LockFile _lockFile = new LockFile(lockFilePath); int loopCount = 0; int lognum = 1; int maximumWaitTimeInSeconds = 15 * 60; while (!_lockFile.Lock($"AcquireSessionLock by {methodName} on {Environment.MachineName}") && loopCount <= maximumWaitTimeInSeconds) { ++loopCount; if (loopCount > lognum * 120) { ++lognum; Logger.LogCpuMonitoringVerboseEvent($"Waiting to acquire the lock on session file , loop {lognum}", session.SessionId); } Thread.Sleep(1000); } if (loopCount == maximumWaitTimeInSeconds) { Logger.LogCpuMonitoringVerboseEvent($"Deleting the lock file as it seems to be in an orphaned stage", session.SessionId); _lockFile.Release(); return(null); } return(_lockFile); }
private void updateFETCH_HEAD(FetchResult result) { LockFile @lock = new LockFile(new FileInfo(Path.Combine(_transport.Local.Directory.FullName, "FETCH_HEAD"))); try { if (@lock.Lock()) { StreamWriter w = new StreamWriter(@lock.GetOutputStream()); try { foreach (FetchHeadRecord h in _fetchHeadUpdates) { h.Write(w); result.Add(h); } } finally { w.Close(); } @lock.Commit(); } } finally { @lock.Unlock(); } }
private bool TryGetLockIfSingleton(out bool acquired) { acquired = false; bool isSingleton = JobSettings.IsSingleton; if (_isSingleton == null || _isSingleton.Value != isSingleton) { if (_isSingleton == null) { LogInformation("WebJob singleton setting is {0}", isSingleton); } else { LogInformation("WebJob singleton setting changed from {0} to {1}", _isSingleton.Value, isSingleton); } _isSingleton = isSingleton; } if (!isSingleton) { return(true); } if (_singletonLock.Lock("Acquiring continuous WebJob singleton lock")) { acquired = true; LogInformation("WebJob singleton lock is acquired"); return(true); } UpdateStatusIfChanged(ContinuousJobStatus.InactiveInstance); return(false); }
public void AsyncLock_BasicTest() { for (int i = 0; i < 2; i++) { // Acquire Assert.Equal(false, _lockFile.IsHeld); Assert.Equal(true, _lockFile.Lock()); // Test Assert.Equal(true, _lockFile.IsHeld); Assert.Equal(false, _lockFile.Lock()); // Release _lockFile.Release(); Assert.Equal(false, _lockFile.IsHeld); } }
public void StartJobRun(TriggeredJob triggeredJob, JobSettings jobSettings, string trigger, Action <string, string> reportAction) { JobSettings = jobSettings; if (Settings.IsWebJobsStopped()) { throw new WebJobsStoppedException(); } if (!_lockFile.Lock()) { throw new ConflictException(); } TriggeredJobRunLogger logger = TriggeredJobRunLogger.LogNewRun(triggeredJob, trigger, Environment, TraceFactory, Settings); Debug.Assert(logger != null); try { if (_currentRunningJobWaitHandle != null) { _currentRunningJobWaitHandle.Dispose(); _currentRunningJobWaitHandle = null; } _currentRunningJobWaitHandle = new ManualResetEvent(false); var tracer = TraceFactory.GetTracer(); var step = tracer.Step("Run {0} {1}", triggeredJob.JobType, triggeredJob.Name); ThreadPool.QueueUserWorkItem(_ => { try { InitializeJobInstance(triggeredJob, logger); RunJobInstance(triggeredJob, logger, logger.Id, trigger, tracer); } catch (Exception ex) { logger.LogError("WebJob run failed due to: " + ex); } finally { step.Dispose(); logger.ReportEndRun(); _lockFile.Release(); reportAction(triggeredJob.Name, logger.Id); _currentRunningJobWaitHandle.Set(); } }); } catch (Exception ex) { logger.LogError("Failed to start job due to: " + ex); _lockFile.Release(); throw; } }
public void tryRenameWhenLocked(string toLock, string fromName, string toName, string headPointsTo) { // setup writeSymref(Constants.HEAD, headPointsTo); ObjectId oldfromId = db.Resolve(fromName); ObjectId oldHeadId = db.Resolve(Constants.HEAD); writeReflog(db, oldfromId, oldfromId, "Just a message", fromName); IList <ReflogReader.Entry> oldFromLog = db .ReflogReader(fromName).getReverseEntries(); IList <ReflogReader.Entry> oldHeadLog = oldHeadId != null?db .ReflogReader(Constants.HEAD).getReverseEntries() : null; Assert.IsTrue(new FileInfo(Path.Combine(db.Directory.FullName, "logs/" + fromName)).Exists, "internal check, we have a log"); // "someone" has branch X locked var lockFile = new LockFile(new FileInfo(Path.Combine(db.Directory.FullName, toLock))); try { Assert.IsTrue(lockFile.Lock()); // Now this is our test RefRename renameRef = db.RenameRef(fromName, toName); RefUpdate.RefUpdateResult result = renameRef.rename(); Assert.AreEqual(RefUpdate.RefUpdateResult.LOCK_FAILURE, result); // Check that the involved refs are the same despite the failure assertExists(false, toName); if (!toLock.Equals(toName)) { assertExists(false, toName + ".lock"); } assertExists(true, toLock + ".lock"); if (!toLock.Equals(fromName)) { assertExists(false, "logs/" + fromName + ".lock"); } assertExists(false, "logs/" + toName + ".lock"); Assert.AreEqual(oldHeadId, db.Resolve(Constants.HEAD)); Assert.AreEqual(oldfromId, db.Resolve(fromName)); Assert.IsNull(db.Resolve(toName)); Assert.AreEqual(oldFromLog.ToString(), db.ReflogReader(fromName) .getReverseEntries().ToString()); if (oldHeadId != null) { Assert.AreEqual(oldHeadLog.ToString(), db.ReflogReader(Constants.HEAD) .getReverseEntries().ToString()); } } finally { lockFile.Unlock(); } }
// Locking private bool LaunchNormally() { LockResult result = lockFile.Lock(); if (result is LockResult.HasProcess info) { if (!RestoreProcess(info.Process, WindowRestoreMessage) && FormMessage.Error("TweetDuck is Already Running", "Another instance of TweetDuck is already running.\nDo you want to close it?", FormMessage.Yes, FormMessage.No)) { if (!CloseProcess(info.Process)) { FormMessage.Error("TweetDuck Has Failed :(", "Could not close the other process.", FormMessage.OK); return(false); } info.Dispose(); result = lockFile.Lock(); } else { return(false); } } if (result is LockResult.Fail fail) { ShowGenericException(fail); return(false); } else if (result != LockResult.Success) { FormMessage.Error("TweetDuck Has Failed :(", "An unknown error occurred accessing the data folder. Please, make sure TweetDuck is not already running. If the problem persists, try restarting your system.", FormMessage.OK); return(false); } return(true); }
/// <summary>Try to establish an update lock on the cache file.</summary> /// <remarks>Try to establish an update lock on the cache file.</remarks> /// <returns> /// true if the lock is now held by the caller; false if it is held /// by someone else. /// </returns> /// <exception cref="System.IO.IOException"> /// the output file could not be created. The caller does not /// hold the lock. /// </exception> public virtual bool Lock() { if (liveFile == null) { throw new IOException(JGitText.Get().dirCacheDoesNotHaveABackingFile); } LockFile tmp = new LockFile(liveFile, fs); if (tmp.Lock()) { tmp.SetNeedStatInformation(true); myLock = tmp; return(true); } return(false); }
/// <summary> /// Try to establish an update lock on the cache file. /// </summary> /// <returns> /// True if the lock is now held by the caller; false if it is held /// by someone else. /// </returns> /// <exception cref="IOException"> /// The output file could not be created. The caller does not /// hold the lock. /// </exception> public bool Lock() { if (_liveFile == null) { throw new IOException("DirCache does not have a backing file"); } _myLock = new LockFile(_liveFile); if (_myLock.Lock()) { _myLock.NeedStatInformation = true; return(true); } return(false); }
private bool TryGetLockIfSingleton() { bool isSingleton = _jobSettings.GetSetting("is_singleton", defaultValue: false); if (!isSingleton) { return(true); } if (_singletonLock.Lock()) { return(true); } _continuousJobLogger.ReportStatus(ContinuousJobStatus.InactiveInstance); return(false); }
private bool TryGetLockIfSingleton() { bool isSingleton = JobSettings.IsSingleton; if (!isSingleton) { return(true); } if (_singletonLock.Lock()) { return(true); } UpdateStatusIfChanged(ContinuousJobStatus.InactiveInstance); return(false); }
private void updateFETCH_HEAD(FetchResult result) { using (LockFile @lock = new LockFile(PathUtil.CombineFilePath(_transport.Local.Directory, "FETCH_HEAD"))) { if (@lock.Lock()) { using (StreamWriter w = new StreamWriter(@lock.GetOutputStream())) { foreach (FetchHeadRecord h in _fetchHeadUpdates) { h.Write(w); result.Add(h); } } @lock.Commit(); } } }
protected override void writeFile(string file, byte[] content) { FileInfo p = PathUtil.CombineFilePath(_db.Directory, file); LockFile lck = new LockFile(p); if (!lck.Lock()) { throw new ObjectWritingException("Can't write " + p); } try { lck.Write(content); } catch (IOException) { throw new ObjectWritingException("Can't write " + p); } if (!lck.Commit()) { throw new ObjectWritingException("Can't write " + p); } }
protected internal override void WriteFile(string file, byte[] content) { FilePath p = new FilePath(_db.Directory, file); LockFile lck = new LockFile(p, FS.DETECTED); if (!lck.Lock()) { throw new ObjectWritingException("Can't write " + p); } try { lck.Write(content); } catch (IOException) { throw new ObjectWritingException("Can't write " + p); } if (!lck.Commit()) { throw new ObjectWritingException("Can't write " + p); } }
public void StartJobRun(TriggeredJob triggeredJob) { if (Settings.IsWebJobsStopped()) { throw new WebJobsStoppedException(); } if (!_lockFile.Lock()) { throw new ConflictException(); } TriggeredJobRunLogger logger = TriggeredJobRunLogger.LogNewRun(triggeredJob, Environment, TraceFactory, Settings); Debug.Assert(logger != null); try { InitializeJobInstance(triggeredJob, logger); ThreadPool.QueueUserWorkItem(_ => { try { RunJobInstance(triggeredJob, logger, logger.Id); } finally { logger.ReportEndRun(); _lockFile.Release(); } }); } catch (Exception ex) { logger.LogError("Failed to start job due to: " + ex); _lockFile.Release(); throw; } }
public void testUpdateRefLockFailureLocked() { ObjectId opid = db.Resolve("refs/heads/master"); ObjectId pid = db.Resolve("refs/heads/master^"); RefUpdate updateRef = db.UpdateRef("refs/heads/master"); updateRef.NewObjectId = pid; var lockFile1 = new LockFile(new FileInfo(Path.Combine(db.Directory.FullName, "refs/heads/master"))); try { Assert.IsTrue(lockFile1.Lock()); // precondition to test RefUpdate.RefUpdateResult update = updateRef.update(); Assert.AreEqual(RefUpdate.RefUpdateResult.LOCK_FAILURE, update); Assert.AreEqual(opid, db.Resolve("refs/heads/master")); var lockFile2 = new LockFile(new FileInfo(Path.Combine(db.Directory.FullName, "refs/heads/master"))); Assert.IsFalse(lockFile2.Lock()); // was locked, still is } finally { lockFile1.Unlock(); } }
/// <exception cref="System.IO.IOException"></exception> private void UpdateFETCH_HEAD(FetchResult result) { FilePath meta = transport.local.Directory; if (meta == null) { return; } LockFile Lock = new LockFile(new FilePath(meta, "FETCH_HEAD"), transport.local.FileSystem ); try { if (Lock.Lock()) { TextWriter w = new OutputStreamWriter(Lock.GetOutputStream()); try { foreach (FetchHeadRecord h in fetchHeadUpdates) { h.Write(w); result.Add(h); } } finally { w.Close(); } Lock.Commit(); } } finally { Lock.Unlock(); } }
/** * Try to establish an update lock on the cache file. * * @return true if the lock is now held by the caller; false if it is held * by someone else. * @ * the output file could not be created. The caller does not * hold the lock. */ public bool Lock() { if (liveFile == null) throw new IOException("DirCache does not have a backing file"); LockFile tmp = new LockFile(liveFile); if (tmp.Lock()) { tmp.NeedStatInformation=true; myLock = tmp; return true; } return false; }
/// <summary> /// Try to establish an update lock on the cache file. /// </summary> /// <returns> /// True if the lock is now held by the caller; false if it is held /// by someone else. /// </returns> /// <exception cref="IOException"> /// The output file could not be created. The caller does not /// hold the lock. /// </exception> public bool Lock() { if (_liveFile == null) { throw new IOException("DirCache does not have a backing file"); } _myLock = new LockFile(_liveFile); if (_myLock.Lock()) { _myLock.NeedStatInformation = true; return true; } return false; }
public void tryRenameWhenLocked(string toLock, string fromName, string toName, string headPointsTo) { // setup writeSymref(Constants.HEAD, headPointsTo); ObjectId oldfromId = db.Resolve(fromName); ObjectId oldHeadId = db.Resolve(Constants.HEAD); writeReflog(db, oldfromId, oldfromId, "Just a message", fromName); IList<ReflogReader.Entry> oldFromLog = db .ReflogReader(fromName).getReverseEntries(); IList<ReflogReader.Entry> oldHeadLog = oldHeadId != null ? db .ReflogReader(Constants.HEAD).getReverseEntries() : null; Assert.IsTrue(new FileInfo(Path.Combine(db.Directory.FullName, "logs/" + fromName)).Exists, "internal check, we have a log"); // "someone" has branch X locked var lockFile = new LockFile(new FileInfo(Path.Combine(db.Directory.FullName, toLock))); try { Assert.IsTrue(lockFile.Lock()); // Now this is our test RefRename renameRef = db.RenameRef(fromName, toName); RefUpdate.RefUpdateResult result = renameRef.rename(); Assert.AreEqual(RefUpdate.RefUpdateResult.LOCK_FAILURE, result); // Check that the involved refs are the same despite the failure assertExists(false, toName); if (!toLock.Equals(toName)) assertExists(false, toName + ".lock"); assertExists(true, toLock + ".lock"); if (!toLock.Equals(fromName)) assertExists(false, "logs/" + fromName + ".lock"); assertExists(false, "logs/" + toName + ".lock"); Assert.AreEqual(oldHeadId, db.Resolve(Constants.HEAD)); Assert.AreEqual(oldfromId, db.Resolve(fromName)); Assert.IsNull(db.Resolve(toName)); Assert.AreEqual(oldFromLog.ToString(), db.ReflogReader(fromName) .getReverseEntries().ToString()); if (oldHeadId != null) Assert.AreEqual(oldHeadLog.ToString(), db.ReflogReader(Constants.HEAD) .getReverseEntries().ToString()); } finally { lockFile.Unlock(); } }