public void ReleaseLock_Unlocked_LockFileDoesNotExist()
        {
            SimpleFileLock fileLock = SimpleFileLock.Create("SimpleFileLockTests");

            fileLock.ReleaseLock();
            Assert.That(File.Exists(LockPath), Is.False);
        }
Beispiel #2
0
        static void Main(string[] args)
        {
            var process  = Process.GetCurrentProcess();
            var fileLock = SimpleFileLock.Create(LockName, LockTimeout);

            for (var i = 0; i < 20; i++)
            {
                Console.WriteLine("{0}: PID {1} attempting to acquire FileLock {2} (attempt {3}", DateTime.Now, process.Id, fileLock.LockName, i);
                var acquired = fileLock.TryAcquireLock();
                if (acquired)
                {
                    Console.WriteLine("{0}: PID {1} ACQUIRED FileLock {2} - releasing", DateTime.Now, process.Id,
                                      fileLock.LockName);
                    fileLock.ReleaseLock();
                    Console.WriteLine("{0}: PID {1} RELEASED FileLock {2} - releasing", DateTime.Now, process.Id,
                                      fileLock.LockName);
                    Console.WriteLine("{0}: PID {1} EXITING", DateTime.Now, process.Id);
                    return;
                }
                else
                {
                    Console.WriteLine("{0}: PID {1} UNABLE TO ACQUIRE FileLock {2} - sleeping", DateTime.Now, process.Id,
                                      fileLock.LockName);
                    Thread.Sleep(TimeSpan.FromSeconds(1));
                }
            }
        }
Beispiel #3
0
        private void EventWatcher_Load(object sender, EventArgs e)
        {
            notifyIcon1.Icon = Constants.DEFAULT_ICON;

            // onLoad
            if (runMode == RUN_MODE.MONITOR)
            {
                // Set up pidfile to enforce a single instance of the monitor
                var fileLock = SimpleFileLock.Create(Constants.PIDLOCK_PATH);
                if (!fileLock.TryAcquireLock())
                {
                    Close();
                    // Another instance of this program is already running on the machine (silent exit)
                    return;
                }

                SystemEvents.PowerModeChanged += OnPowerChange;
                this.FormClosed += EventWatcher_FormClosed;

                // Run it now
                DoWork();
            }
            else if (runMode == RUN_MODE.ONCE)
            {
                // Run it now
                DoWork();
                Close();
            }
        }
        public void TryAcquireLock_Unlocked_ReturnsTrue()
        {
            SimpleFileLock fileLock = SimpleFileLock.Create("SimpleFileLockTests");

            Assert.That(fileLock.TryAcquireLock(), Is.True);
            fileLock.ReleaseLock();
        }
        public void ReleaseLock_HasLock_LockFileDoesNotExist()
        {
            SimpleFileLock fileLock = SimpleFileLock.Create("SimpleFileLockTests");

            Assert.That(fileLock.TryAcquireLock(), Is.True);
            fileLock.ReleaseLock();
            Assert.That(File.Exists(LockPath), Is.False);
        }
        public void TryAcquireLock_OldEmptyFileLock_ReturnsTrue()
        {
            File.WriteAllText(LockPath, "");
            SimpleFileLock fileLock = SimpleFileLock.Create("SimpleFileLockTests");

            Assert.That(fileLock.TryAcquireLock(), Is.True);
            fileLock.ReleaseLock();
        }
Beispiel #7
0
 /// <summary>
 /// Releases the token when client is finished with it
 ///
 /// Even though it is a very good idea to release the token when finished with it,
 /// in the event of a crash, the file is released anyway meaning another application can get it.
 /// </summary>
 public static void ReleaseToken()
 {
     if (s_fileLock != null)
     {
         s_fileLock.ReleaseLock();
         s_fileLock = null;
     }
 }
        public void TryAcquireLock_LockFileCurrentlyOpen_ReturnsFalse()
        {
            SimpleFileLock fileLock = SimpleFileLock.Create("SimpleFileLockTests");

            using (File.Open(LockPath, FileMode.Create))
            {
                Assert.That(fileLock.TryAcquireLock(), Is.False);
            }
        }
        public void ReleaseLock_LockFileCurrentlyOpen_LockFileExists()
        {
            SimpleFileLock fileLock = SimpleFileLock.Create("SimpleFileLockTests");

            using (File.Open(LockPath, FileMode.Create))
            {
                fileLock.ReleaseLock();
            }
            Assert.That(File.Exists(LockPath), Is.True);
        }
        public void TryAcquireLock_LockedByActiveProcess_ReturnsFalse()
        {
            LockIO.WriteLock(LockPath, new FileLockContent
            {
                PID         = ActiveProcessId,
                ProcessName = GetSafeActiveProcessName(),
                Timestamp   = DateTime.Now.Ticks
            });
            SimpleFileLock fileLock = SimpleFileLock.Create("SimpleFileLockTests");

            Assert.That(fileLock.TryAcquireLock(), Is.False);
        }
        public void TryAcquireLock_LockedByActiveProcessTimedOut_ReturnsTrue()
        {
            LockIO.WriteLock(LockPath, new FileLockContent
            {
                PID         = ActiveProcessId,
                ProcessName = GetSafeActiveProcessName(),
                Timestamp   = (DateTime.Now - TimeSpan.FromHours(2)).Ticks
            });
            SimpleFileLock fileLock = SimpleFileLock.Create("SimpleFileLockTests", TimeSpan.FromHours(1));

            Assert.That(fileLock.TryAcquireLock(), Is.True);
        }
        public void ReleaseLock_LockedByActiveProcess_LockFileExists()
        {
            LockIO.WriteLock(LockPath, new FileLockContent
            {
                PID         = ActiveProcessId,
                ProcessName = GetSafeActiveProcessName(),
                Timestamp   = DateTime.Now.Ticks
            });
            SimpleFileLock fileLock = SimpleFileLock.Create("SimpleFileLockTests");

            fileLock.ReleaseLock();
            Assert.That(File.Exists(LockPath), Is.True);
        }
Beispiel #13
0
        /// <summary>
        /// Try to acquire the token quietly
        /// </summary>
        /// <param name="uniqueIdentifier"></param>
        /// <returns>True if we successfully acquired the token, false otherwise</returns>
        public static bool AcquireTokenQuietly(string uniqueIdentifier)
        {
            Guard.AgainstNull(uniqueIdentifier, "uniqueIdentifier");

            // Each process may only acquire one token
            if (s_fileLock != null)
            {
                return(false);
            }

            s_fileLock = SimpleFileLock.Create(uniqueIdentifier + FileExtension);
            return(s_fileLock.TryAcquireLock());
        }
        public void TryAcquireLock_LockedByDeadProcess_ReturnsTrue()
        {
            LockIO.WriteLock(LockPath, new FileLockContent
            {
                PID         = 9999,
                ProcessName = Path.GetRandomFileName(),
                Timestamp   = DateTime.Now.Ticks
            });
            SimpleFileLock fileLock = SimpleFileLock.Create("SimpleFileLockTests");

            Assert.That(fileLock.TryAcquireLock(), Is.True);
            fileLock.ReleaseLock();
        }
Beispiel #15
0
        static void Main(string[] args)
        {
            Console.WriteLine("Starting");

            var lockFolder = args[0];

            var path     = System.IO.Path.Combine(lockFolder, "file.lock");
            var fileLock = SimpleFileLock.Create(path, TimeSpan.FromMinutes(1));

            Console.WriteLine("Lock Initialised");

            var cts = new CancellationTokenSource();

            cts.CancelAfter(new TimeSpan(0, 1, 0));

            bool acquired = false;

            var task = Task.Run(async() =>
            {
                while (!acquired)
                {
                    Console.WriteLine("Trying to acquire");
                    acquired = fileLock.TryAcquireLock();
                    if (!acquired)
                    {
                        Console.WriteLine("Waiting before trying again");
                        await Task.Delay(1000, cts.Token);
                    }
                }
            }, cts.Token);

            task.Wait();

            if (!acquired)
            {
                Console.WriteLine("Didn't acquire the lock in time");
            }
            else
            {
                var stillAcquired = fileLock.TryAcquireLock();
                Console.WriteLine($"Still acquired: {stillAcquired}");

                Console.WriteLine("Work, Work");
                Thread.Sleep(10 * 1000); // 10 seconds of work
                fileLock.ReleaseLock();
                Console.WriteLine("Work Complete!");
            }

            Console.WriteLine("Finished");
        }
        /// <summary>
        /// Run an action only if this application is not locked
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="a"></param>
        /// <param name="operation"></param>
        /// <returns></returns>
        protected T RunActionIfApplicationNotLocked <T>(Func <T> a, string operation)
        {
            // Don't let an application be deployed in parallel, could lead to breaks!
            string lockPath = this.LockPathForApplication();
            var    fileLock = SimpleFileLock.Create(lockPath, TimeSpan.FromMinutes(3));

            if (fileLock.TryAcquireLock() || Debugger.IsAttached)
            {
                try
                {
                    return(a());
                }
                finally
                {
                    fileLock.ReleaseLock();
                }
            }
            else
            {
                throw new StopDeploymentException($"Could not run operation {operation} because the application is locked in another process {lockPath}.");
            }
        }
Beispiel #17
0
        static void Main(string[] args)
        {
            var fileLock = SimpleFileLock.Create(LockName, LockTimeout);

            Console.WriteLine("Acquiring lock");
            var lockAcquired = fileLock.TryAcquireLock();

            if (lockAcquired)
            {
                Console.WriteLine("Lock Acquired");
                Console.WriteLine("Spawning other lock-contending process...");
                var p = StartProcess();
                Console.WriteLine("Sleeping until lock times out (and not releasing it)...");
                Thread.Sleep(TimeSpan.FromSeconds(20));
                Console.WriteLine("Waking up...");
                Console.WriteLine("Press any key to exit");
                Console.ReadKey();
            }
            else
            {
                Console.WriteLine("Failed to acquire lock.");
            }
        }
Beispiel #18
0
        public bool ScheduleWork(CancellationToken mainToken, TimeSpan until, int milliSecondsBeforeMoreWork)
        {
            var fileLock = SimpleFileLock.Create(LockPath, until);
            var acquired = fileLock.TryAcquireLock();

            if (!acquired)
            {
                return(false);
            }

            var worker = NextWorker();

            var ending            = DateTime.Now.Add(until);
            var workerTokenSource = new CancellationTokenSource(until.Add(TimeSpan.FromSeconds(2)));

            using (var combinedSource = CancellationTokenSource.CreateLinkedTokenSource(mainToken, workerTokenSource.Token))
            {
                try
                {
                    var task = Task.Run(async() =>
                    {
                        bool cancelled = false;
                        while (DateTime.Now < ending && !cancelled)
                        {
                            Console.WriteLine("Work, Work");
                            try
                            {
                                worker.Do();
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine(ex.ToString());
                                throw new Exception("While running Worker.Do", ex);
                            }

                            try
                            {
                                await Task.Delay(milliSecondsBeforeMoreWork, mainToken);
                            }
                            catch (TaskCanceledException)
                            {
                                Console.WriteLine("Simulated delay caused by work was cancelled");
                                cancelled = true;
                            }
                        }
                        ;

                        Console.WriteLine("Work complete!");
                    }
                                        , combinedSource.Token);

                    task.Wait();
                }
                catch (OperationCanceledException)
                {
                    if (mainToken.IsCancellationRequested)
                    {
                        Console.WriteLine("Main process timed-out");
                    }
                    else if (workerTokenSource.IsCancellationRequested)
                    {
                        Console.WriteLine("Worker process took longer than allotted");
                    }
                }
            }

            fileLock.ReleaseLock(); // not strictly required in this case but does remove the lock file
            return(true);
        }
Beispiel #19
0
        // Public methods
        public static bool IsRunning()
        {
            var fileLock = SimpleFileLock.Create(Constants.PIDLOCK_PATH);

            return(!fileLock.TestLockIsFree());
        }
        protected override void InnerLoad()
        {
            var contentPhysicalPath = _modulesLocalPath;

            if (string.IsNullOrEmpty(_assembliesPath))
            {
                throw new InvalidOperationException("The AssembliesPath cannot contain a null value or be empty");
            }
            if (string.IsNullOrEmpty(_contentVirtualPath))
            {
                throw new InvalidOperationException("The ContentVirtualPath cannot contain a null value or be empty");
            }
            if (string.IsNullOrEmpty(contentPhysicalPath))
            {
                throw new InvalidOperationException("The ContentPhysicalPath cannot contain a null value or be empty");
            }

            //Use lock file in file system to synhronize multiple platform instances initialization (to avoid collisions on initialization process)
            var fileLock           = SimpleFileLock.Create("vc-lock", TimeSpan.FromMinutes(1));
            var needCopyAssemblies = fileLock.TryAcquireLock();

            if (!contentPhysicalPath.EndsWith("\\", StringComparison.OrdinalIgnoreCase))
            {
                contentPhysicalPath += "\\";
            }

            var rootUri = new Uri(contentPhysicalPath);

            if (needCopyAssemblies)
            {
                if (!Directory.Exists(_assembliesPath))
                {
                    Directory.CreateDirectory(_assembliesPath);
                }

                // Clear ~/moules directory from old assemblies
                // Ignore any errors, because shadow copy may not work
                try
                {
                    foreach (var assembly in Directory.GetFiles(_assembliesPath))
                    {
                        File.Delete(assembly);
                    }
                }
                catch (Exception)
                {
                }

                CopyAssemblies(_modulesLocalPath, _assembliesPath);
            }

            foreach (var pair in GetModuleManifests())
            {
                var manifest     = pair.Value;
                var manifestPath = pair.Key;

                var modulePath = Path.GetDirectoryName(manifestPath);
                if (needCopyAssemblies)
                {
                    CopyAssemblies(modulePath, _assembliesPath);
                }

                var moduleVirtualPath = GetModuleVirtualPath(rootUri, modulePath);
                ConvertVirtualPath(manifest.Scripts, moduleVirtualPath);
                ConvertVirtualPath(manifest.Styles, moduleVirtualPath);

                var moduleInfo = new ManifestModuleInfo(manifest)
                {
                    FullPhysicalPath = Path.GetDirectoryName(manifestPath)
                };

                // Modules without assembly file don't need initialization
                if (string.IsNullOrEmpty(manifest.AssemblyFile))
                {
                    moduleInfo.State = ModuleState.Initialized;
                }
                else
                {
                    moduleInfo.Ref = GetFileAbsoluteUri(_assembliesPath, manifest.AssemblyFile);
                }

                moduleInfo.IsInstalled = true;
                AddModule(moduleInfo);
            }

            //Wait until other (first) platform instance finished initialization (copying assemblies)
            if (!needCopyAssemblies)
            {
                while (!fileLock.TryAcquireLock())
                {
                    Thread.Sleep(500);
                }
            }
            //Release file system lock
            fileLock.ReleaseLock();
        }
Beispiel #21
0
        public static void Main(string[] args)
        {
            ExceptionLogging.Initialize("17a42e4a67dd2e42d4aa40d8bf2d23ee", Assembly.GetExecutingAssembly().GetName().Name);
            var options = QueueManagerOptions.ParseCommandLineArgs(args);

            if (options == null)
            {
                return;
            }

            MainClass.Logger.Notice("LfMergeQueueManager starting with args: {0}", string.Join(" ", args));

            // initialize the SLDR
            Sldr.Initialize();

            var settings = MainClass.Container.Resolve <LfMergeSettings>();

            settings.Initialize();
            var fileLock = SimpleFileLock.CreateFromFilePath(settings.LockFile);

            try
            {
                if (!fileLock.TryAcquireLock())
                {
                    MainClass.Logger.Error("Can't acquire file lock - is another instance running?");
                    return;
                }
                MainClass.Logger.Notice("Lock acquired");

                if (!CheckSetup(settings))
                {
                    return;
                }

                // Cleanup any hang projects
                new Janitor(settings, MainClass.Logger).CleanupAndRescheduleJobs();

                for (var queue = Queue.FirstQueueWithWork;
                     queue != null;
                     queue = queue.NextQueueWithWork)
                {
                    var clonedQueue = queue.QueuedProjects.ToList();
                    foreach (var projectCode in clonedQueue)
                    {
                        var projectPath = Path.Combine(settings.LcmDirectorySettings.ProjectsDirectory,
                                                       projectCode, $"{projectCode}{LcmFileHelper.ksFwDataXmlFileExtension}");
                        var modelVersion = FwProject.GetModelVersion(projectPath);
                        queue.DequeueProject(projectCode);
                        int retCode = MainClass.StartLfMerge(projectCode, queue.CurrentActionName,
                                                             modelVersion, true);

                        // TODO: If LfMerge fails, should we re-queue the project, or not?
                        if (retCode != 0)
                        {
                            // queue.EnqueueProject(projectCode);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                MainClass.Logger.Error("Unhandled Exception:\n{0}", e);
                throw;
            }
            finally
            {
                if (fileLock != null)
                {
                    fileLock.ReleaseLock();
                }

                if (Sldr.IsInitialized)
                {
                    Sldr.Cleanup();
                }

                MainClass.Container.Dispose();
            }

            MainClass.Logger.Notice("LfMergeQueueManager finished");
        }