/// <summary>
        /// Prepares data directory and obtains exclusive lock for the directory.
        /// </summary>
        /// <exception cref="LockFailedException"></exception>
        public SharedDataDirectory()
        {
            var dataDirPath =
                Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.LocalApplicationData),
                    "AldursLab",
                    "WurmAssistantData");

            dataDir = new DirectoryInfo(dataDirPath);
            if (!dataDir.Exists) dataDir.Create();

            var lockFile = new FileInfo(Path.Combine(dataDir.FullName, "app.lock"));
            if (!lockFile.Exists)
            {
                try
                {
                    lockFile.Create().Dispose();
                }
                catch (IOException)
                {
                    // wait a moment to ensure file system is updated
                    Thread.Sleep(100);
                    lockFile.Refresh();
                    if (lockFile.Exists)
                    {
                        // ignore, something else created the lock file
                    }
                    else
                    {
                        throw;
                    }
                }
            }

            appLock = FileLock.Enter(lockFile.FullName);
        }
 public TemporaryFileServiceImpl(IClientConfiguration configuration, IFileSystemProxy fileSystemProxy)
 {
     this.configuration = configuration;
      this.fileSystemProxy = fileSystemProxy;
      this.temporaryDirectoryRoot = Path.Combine(configuration.UserDataDirectoryPath, "temp"); ;
      this.temporaryFilesLockPath = Path.Combine(temporaryDirectoryRoot, "LOCK");
      this.temporaryFilesLock = new FileLock(temporaryFilesLockPath);
 }
        public void WaitOneWithTimeoutTimesOut()
        {
            var lockIo    = Substitute.For <ILockIo>();
            var name      = Guid.NewGuid().ToString();
            var semaphore = new LockFileBasedSemaphore(name, TimeSpan.FromSeconds(30), lockIo, Substitute.For <IProcessFinder>(), new InMemoryLog());
            var fileLock  = new FileLock(System.Diagnostics.Process.GetCurrentProcess().Id, Guid.NewGuid().ToString(), Thread.CurrentThread.ManagedThreadId, DateTime.Now.Ticks);

            lockIo.ReadLock(Arg.Any <string>()).Returns(fileLock);
            lockIo.LockExists(Arg.Any <string>()).Returns(true);
            //failed to write the lock file (ie, someone else got in first)
            lockIo.WriteLock(Arg.Any <string>(), Arg.Any <FileLock>()).Returns(false);

            var stopwatch = new Stopwatch();

            stopwatch.Start();

            var result = semaphore.WaitOne(300);

            Assert.That(result, Is.False);
            Assert.That(stopwatch.ElapsedMilliseconds, Is.GreaterThan(300));
        }
            private BufferInfo ModifyBuffer(FileLock markLock, string bufferName, Func <BufferInfo, BufferInfo> mutator)
            {
                try
                {
                    markLock.Lock();

                    var buffers        = ReadMark(markLock).Buffers;
                    var buffer         = GetBufferIndex(bufferName, buffers, out var index);
                    var modifiedBuffer = mutator(buffer);

                    buffers[index] = modifiedBuffer;

                    WriteMark(markLock, buffers);

                    return(modifiedBuffer);
                }
                finally
                {
                    markLock.Unlock();
                }
            }
            private bool IsReadBufferEmpty(FileLock markLock)
            {
                try
                {
                    markLock.Lock();

                    var mark = ReadMark(markLock);

                    return(mark.Read >= mark.Written);
                }
                catch (IOException e)
                {
                    _logger.LogError(e, "IsReadBufferEmpty");

                    return(true);
                }
                finally
                {
                    markLock.Unlock();
                }
            }
Beispiel #6
0
        private int GenerateAndDeployUnreliableTransportSettings()
        {
            string filePath = System.IO.Path.Combine(this.nodeSettings.DeploymentFoldersInfo.WorkFolder, UnreliableTransportSettings.SettingsFileName);

            DeployerTrace.WriteNoise("Writing Unreliable Transport Settings file at {0}", filePath);

            UnreliableTransportSettings unreliableTransportSettings = new UnreliableTransportSettings(this.clusterSettings);

            // acquiring lock to read and write to unreliable transport settings file.
            FileLock fileLock = new FileLock(filePath, false /* writing lock */);

            if (!fileLock.Acquire(new TimeSpan(0, 0, 5)))
            {
                DeployerTrace.WriteWarning("Failed to acquire lock to load Unreliable Transport Settings File. Aborting loading at file: {0}", filePath);
                return(Constants.ErrorCode_Failure);
            }

            // checks if it necessary to merge
            if (!File.Exists(filePath))
            {
                // writes the result to Unreliable Transport Settings File
                unreliableTransportSettings.WriteUnreliableTransportSettingsFile(filePath);
            }
            else
            {
                // creates a new UnreliableTransportSettings from existing UnreliableTransportSettings file
                UnreliableTransportSettings unreliableTransportSettingsExisting = new UnreliableTransportSettings(filePath);
                // merge files giving precedence to settings coming from cluster manifest
                unreliableTransportSettingsExisting.Merge(unreliableTransportSettings);
                // writes the result to Unreliable Transport Settings File
                unreliableTransportSettingsExisting.WriteUnreliableTransportSettingsFile(filePath);
            }
#if DotNetCoreClrLinux
            Helpers.UpdateFilePermission(filePath);
#endif
            // releasing lock.
            fileLock.Release();

            return(Constants.ErrorCode_Success);
        }
Beispiel #7
0
        public void DeletesLockIfOwnedBySomeoneElseAndLockHasTimedOut()
        {
            var lockIo        = Substitute.For <ILockIo>();
            var name          = Guid.NewGuid().ToString();
            var processFinder = Substitute.For <IProcessFinder>();

            processFinder.ProcessIsRunning(Arg.Any <int>(), Arg.Any <string>()).Returns(true);
            var semaphore = new LockFileBasedSemaphore(name, TimeSpan.FromSeconds(30), lockIo, processFinder);
            //not setting processid/threadid, therefore its someone elses
            var fileLock = new FileLock {
                Timestamp = (DateTime.Now.Subtract(TimeSpan.FromMinutes(5))).Ticks
            };

            lockIo.ReadLock(Arg.Any <string>()).Returns(fileLock);
            lockIo.LockExists(Arg.Any <string>()).Returns(true);
            lockIo.WriteLock(Arg.Any <string>(), Arg.Any <FileLock>()).Returns(true);
            var result = semaphore.TryAcquireLock();

            Assert.That(result, Is.True);
            lockIo.Received().DeleteLock(Arg.Any <string>());
            lockIo.Received().WriteLock(Arg.Any <string>(), Arg.Any <FileLock>());
        }
Beispiel #8
0
        /// <summary>
        /// Try to establish the lock.
        /// </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 temporary output file could not be created. The caller
        /// does not hold the lock.
        /// </exception>
        public bool Lock()
        {
            _lockFile.Directory.Mkdirs();
            if (_lockFile.Exists)
            {
                return(false);
            }

            try
            {
                _haveLock = true;
                _os       = _lockFile.Create();

                _fLck = FileLock.TryLock(_os, _lockFile);
                if (_fLck == null)
                {
                    // We cannot use unlock() here as this file is not
                    // held by us, but we thought we created it. We must
                    // not delete it, as it belongs to some other process.
                    _haveLock = false;
                    try
                    {
                        _os.Close();
                    }
                    catch (Exception)
                    {
                        // Fail by returning haveLck = false.
                    }
                    _os = null;
                }
            }
            catch (Exception)
            {
                Unlock();
                throw;
            }

            return(_haveLock);
        }
Beispiel #9
0
        public void AttemptsToAquireLockIfOtherProcessIsNoLongerRunning()
        {
            var log           = new InMemoryLog();
            var lockIo        = Substitute.For <ILockIo>();
            var name          = Guid.NewGuid().ToString();
            var processFinder = Substitute.For <IProcessFinder>();

            processFinder.ProcessIsRunning(Arg.Any <int>(), Arg.Any <string>()).Returns(false);
            var semaphore = new LockFileBasedSemaphore(name, TimeSpan.FromSeconds(30), lockIo, processFinder, log);
            var fileLock  = new FileLock
            {
                ProcessId   = -1,
                ThreadId    = -2,
                ProcessName = Guid.NewGuid().ToString()
            };

            lockIo.LockExists(Arg.Any <string>()).Returns(true);
            var result = semaphore.ShouldAquireLock(fileLock);

            Assert.That(result, Is.EqualTo(LockFileBasedSemaphore.AquireLockAction.AquireLock));
            log.Messages.Should().Contain(m => m.Level == InMemoryLog.Level.Warn && m.FormattedMessage == "Process -1, thread -2 had lock, but appears to have crashed. Taking lock.");
        }
Beispiel #10
0
        public static async Task TestMultipleFileLockOnSameThread()
        {
            IDataStore fileInfo = New <IDataStore>(_fileExtPath);

            Assert.That(New <FileLocker>().IsLocked(fileInfo), Is.False, "There should be no lock for this file to start with.");
            using (FileLock lock1 = New <FileLocker>().Acquire(fileInfo, TimeSpan.Zero))
            {
                Assert.That(await Task.Run(() => New <FileLocker>().IsLocked(fileInfo)), Is.True, "There should be a lock for this from a different thread (1).");
                Assert.That(New <FileLocker>().IsLocked(fileInfo), Is.True, "There should still be a lock for this from the same thread (1).");
                Assert.Throws <InternalErrorException>(() =>
                {
                    bool wasHere = false;
                    using (FileLock lock2 = New <FileLocker>().Acquire(fileInfo, TimeSpan.Zero))
                    {
                        wasHere = true;
                    }
                    Assert.That(wasHere, Is.False, "This point should never be reached! The Acquire() should throw an exception since this is a deadlock situation.");
                });
            }
            Assert.That(await Task.Run(() => New <FileLocker>().IsLocked(fileInfo)), Is.False, "There should be no lock for this file now.");
            Assert.That(New <FileLocker>().IsLocked(fileInfo), Is.False, "There should be no lock for this file now.");
        }
        protected void DeleteEntity(long entId)
        {
            try {
                FileLock.WaitOne();
                List <T> allObjects = new List <T> (GetAllEntities(false));
                int      index      = DataProvider.FindObjectIndexByField(allObjects, XmlEntityFields.Id, entId);

                if (index < 0)
                {
                    return;
                }

                allObjects.RemoveAt(index);

                DoCommitChanges(allObjects.ToArray());
#if !DEBUG
            } catch (InvalidOperationException) {
#endif
            } finally {
                FileLock.ReleaseMutex();
            }
        }
        public static void TestSimple()
        {
            using (MemoryStream stream = FakeRuntimeFileInfo.ExpandableMemoryStream(Encoding.UTF8.GetBytes("A short dummy stream")))
            {
                IRuntimeFileInfo fileInfo = OS.Current.FileInfo(_davidCopperfieldTxtPath);
                using (LockingStream lockingStream = new LockingStream(fileInfo, stream))
                {
                    Assert.That(FileLock.IsLocked(fileInfo), "The file should be locked now.");
                    Assert.That(lockingStream.CanRead, "The stream should be readable.");
                    Assert.That(lockingStream.CanSeek, "The stream should be seekable.");
                    Assert.That(lockingStream.CanWrite, "The stream should be writeable.");
                    Assert.That(lockingStream.Length, Is.EqualTo("A short dummy stream".Length), "The length should be the same as the string.");

                    byte[] b    = new byte[1];
                    int    read = lockingStream.Read(b, 0, 1);
                    Assert.That(read, Is.EqualTo(1), "There should be one byte read.");
                    Assert.That(b[0], Is.EqualTo(Encoding.UTF8.GetBytes("A")[0]), "The byte read should be an 'A'.");
                    Assert.That(lockingStream.Position, Is.EqualTo(1), "After reading the first byte, the position should be at one.");

                    lockingStream.Write(b, 0, 1);
                    lockingStream.Position = 1;
                    read = lockingStream.Read(b, 0, 1);
                    Assert.That(read, Is.EqualTo(1), "There should be one byte read.");
                    Assert.That(b[0], Is.EqualTo(Encoding.UTF8.GetBytes("A")[0]), "The byte read should be an 'A'.");

                    lockingStream.Seek(-1, SeekOrigin.End);
                    Assert.That(lockingStream.Position, Is.EqualTo(lockingStream.Length - 1), "The position should be set by the Seek().");

                    lockingStream.SetLength(5);
                    lockingStream.Seek(0, SeekOrigin.End);
                    Assert.That(lockingStream.Position, Is.EqualTo(5), "After setting the length to 5, seeking to the end should set the position at 5.");

                    Assert.DoesNotThrow(() => { lockingStream.Flush(); }, "It's hard to test Flush() behavior here, not worth the trouble, but it should not throw!");
                }
                Assert.That(!FileLock.IsLocked(fileInfo), "The file should be unlocked now.");
                Assert.Throws <ObjectDisposedException>(() => { stream.Position = 0; }, "The underlying stream should be disposed.");
            }
        }
Beispiel #13
0
        /// <summary>
        /// Obtains lock on store file so that we can ensure the store is not shared between database instances
        /// <para>
        /// Creates store dir if necessary, creates store lock file if necessary
        /// </para>
        /// <para>
        /// Please note that this lock is only valid for as long the <seealso cref="storeLockFileChannel"/> lives, so make sure the
        /// lock cannot be garbage collected as long as the lock should be valid.
        ///
        /// </para>
        /// </summary>
        /// <exception cref="StoreLockException"> if lock could not be acquired </exception>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public void checkLock() throws org.neo4j.kernel.StoreLockException
        public virtual void CheckLock()
        {
            if (HaveLockAlready())
            {
                return;
            }

            try
            {
                if (!FileSystemAbstraction.fileExists(StoreLockFile))
                {
                    FileSystemAbstraction.mkdirs(StoreLockFile.ParentFile);
                }
            }
            catch (IOException e)
            {
                string message = "Unable to create path for store dir: " + StoreLockFile.Parent;
                throw StoreLockException(message, e);
            }

            try
            {
                if (_storeLockFileChannel == null)
                {
                    _storeLockFileChannel = FileSystemAbstraction.open(StoreLockFile, OpenMode.READ_WRITE);
                }
                StoreLockFileLock = _storeLockFileChannel.tryLock();
                if (StoreLockFileLock == null)
                {
                    string message = "Store and its lock file has been locked by another process: " + StoreLockFile;
                    throw StoreLockException(message, null);
                }
            }
            catch (Exception e) when(e is OverlappingFileLockException || e is IOException)
            {
                throw UnableToObtainLockException();
            }
        }
Beispiel #14
0
        public bool Lock()
        {
            lockFile.Directory.Create();
            if (lockFile.Exists)
                return false;

            try
            {
                haveLock = true;
                os = lockFile.Create();

                fLck = FileLock.TryLock(os, lockFile);
                if (fLck == null)
                {
                    // We cannot use unlock() here as this file is not
                    // held by us, but we thought we created it. We must
                    // not delete it, as it belongs to some other process.
                    //
                    haveLock = false;
                    try
                    {
                        os.Close();
                    }
                    catch (Exception)
                    {
                        // Fail by returning haveLck = false.
                    }
                    os = null;
                }
            }
            catch (Exception)
            {
                Unlock();
                throw;
            }

            return haveLock;
        }
        private bool RemoveSessionFragment(FileInfo victimFile)
        {
            bool fileRemoved = false;

            //make sure the file no longer exists on disk
            try
            {
                //see if we can get a lock on the file; if not we won't be able to delete it.
                using (FileLock fileLock = FileHelper.GetFileLock(victimFile.FullName, FileMode.Open, FileAccess.Read, FileShare.Delete))
                {
                    if (fileLock != null)
                    {
                        victimFile.Delete();
                        fileRemoved = true;
                    }
                    else
                    {
                        if (victimFile.Exists)
                        {
                            if (m_LoggingEnabled)
                            {
                                Log.Write(LogMessageSeverity.Warning, LogCategory, "Unable to Delete Session Fragment", "Unable to delete the session fragment at '{0}' because it could not be locked.", victimFile.FullName);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                GC.KeepAlive(ex);
                if (m_LoggingEnabled)
                {
                    Log.Write(LogMessageSeverity.Warning, LogWriteMode.Queued, ex, LogCategory, "Unable to Delete Session Fragment", "Unable to delete the session fragment at '{0}' because of an exception: {1}", victimFile.FullName, ex);
                }
            }

            return(fileRemoved);
        }
            private void HandleSuccessSend(FileLock markLock, string bufferName, ref LineReader streamReader, FileLock readerLock, List <string> memoryBuffer)
            {
                try
                {
                    var buffer = MarkRead(markLock, bufferName, memoryBuffer.Count);

                    if (buffer.WriteActive == false && buffer.Read >= buffer.Written)
                    {
                        streamReader.Close();
                        streamReader = null;

                        DeleteBuffer(readerLock.Path);
                    }
                }
                catch (IOException e)
                {
                    _logger.LogError(e, "Mark read failed.");
                }
                finally
                {
                    memoryBuffer.Clear();
                }
            }
Beispiel #17
0
        /// <summary>
        /// Loads the specified schema if it exists, saving it otherwise, and sets it as Current
        /// </summary>
        /// <param name="schemaName"></param>
        /// <returns></returns>
        public SchemaDefinition SetSchema(string schemaName, bool useExisting = true)
        {
            string filePath = SchemaNameToFilePath(schemaName);

            lock (FileLock.Named(filePath))
            {
                if (!useExisting && File.Exists(filePath))
                {
                    if (BackupExisting)
                    {
                        string backUpPath = SchemaNameToFilePath("{0}_{1}_{2}"._Format(schemaName, DateTime.UtcNow.ToJulianDate(), 4.RandomLetters()));
                        File.Move(filePath, backUpPath);
                    }
                    else
                    {
                        File.Delete(filePath);
                    }
                }
                SchemaDefinition schema = LoadSchema(schemaName);
                CurrentSchema = schema;
                return(schema);
            }
        }
Beispiel #18
0
        private async Task ProcessChange(File file, EofMessage eofMessage)
        {
            var tempPath = await BuildFile(file, eofMessage);

            if (tempPath is null)
            {
                return;
            }

            var filePath = file.GetFullPath();

            if (System.IO.File.Exists(filePath) && !FileLock.IsLocked(filePath, checkWriteAccess: true))
            {
                WorkerLog.Instance.Information($"Applying delta to {filePath}");
                file.ApplyDelta(System.IO.File.ReadAllBytes(tempPath));
                await MarkFileAsCompleted(file);
            }
            else
            {
                WorkerLog.Instance.Warning($"File '{filePath}' does not exist or is locked for writing. unable to apply delta");
            }
            DeleteTempPath(tempPath);
        }
Beispiel #19
0
        public async Task TestEncryptToFileWithBackup()
        {
            string destinationFilePath = _rootPath.PathCombine("Written", "File.txt");

            byte[] encryptedData;
            using (Stream encrypted = New <IDataStore>(_helloWorldAxxPath).OpenRead())
            {
                encryptedData = new byte[encrypted.Length];
                encrypted.Read(encryptedData, 0, encryptedData.Length);
            }

            using (FileLock destinationFileLock = New <FileLocker>().Acquire(New <IDataStore>(destinationFilePath)))
            {
                await New <AxCryptFile>().EncryptToFileWithBackupAsync(destinationFileLock, async(Stream stream) => { await Task.Delay(0); stream.Write(encryptedData, 0, encryptedData.Length); }, new ProgressContext());

                using (Stream read = destinationFileLock.DataStore.OpenRead())
                {
                    byte[] writtenData = new byte[encryptedData.Length];
                    read.Read(writtenData, 0, (int)read.Length);
                    Assert.That(writtenData.IsEquivalentTo(encryptedData), "We're expecting the same data to be read back.");
                }
            }
        }
Beispiel #20
0
        private static LauncherErrorCode TryRun()
        {
            try
            {
                // Ensure to create parent of lock directory.
                Directory.CreateDirectory(EditorPath.DefaultTempPath);
                using (Mutex = FileLock.TryLock(Path.Combine(EditorPath.DefaultTempPath, "launcher.lock")))
                {
                    if (Mutex != null)
                    {
                        return(RunSingleInstance(false));
                    }

                    MessageBox.Show("An instance of Stride Launcher is already running.", "Stride", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                    return(LauncherErrorCode.ServerAlreadyRunning);
                }
            }
            catch (Exception e)
            {
                DisplayError($"Cannot start the instance of the Stride Launcher due to the following exception:\n{e.Message}");
                return(LauncherErrorCode.UnknownError);
            }
        }
Beispiel #21
0
        public void WritesLockFile()
        {
            var lockIo        = Substitute.For <ILockIo>();
            var name          = Guid.NewGuid().ToString();
            var processFinder = Substitute.For <IProcessFinder>();

            processFinder.ProcessIsRunning(Arg.Any <int>(), Arg.Any <string>()).Returns(true);
            var semaphore = new LockFileBasedSemaphore(name, TimeSpan.FromSeconds(30), lockIo, processFinder);
            var fileLock  = new FileLock
            {
                ProcessId = System.Diagnostics.Process.GetCurrentProcess().Id,
                ThreadId  = Thread.CurrentThread.ManagedThreadId
            };

            lockIo.ReadLock(Arg.Any <string>()).Returns(fileLock);
            lockIo.LockExists(Arg.Any <string>()).Returns(true);
            lockIo.WriteLock(Arg.Any <string>(), Arg.Any <FileLock>()).Returns(true);
            var result = semaphore.TryAcquireLock();

            Assert.That(result, Is.True);
            lockIo.DidNotReceive().DeleteLock(Arg.Any <string>());
            lockIo.Received().WriteLock(Arg.Any <string>(), Arg.Any <FileLock>());
        }
Beispiel #22
0
        public void Exception(Exception ex)
        {
            MoveCurrentLogFileContentToPreviousLogFileIfSizeIncreaseMoreThanMaxSize();
            using (FileLock fileLock = New <FileLocker>().Acquire(New <IDataStore>(_currentFilePath)))
            {
                StringBuilder sb = new StringBuilder();
                if (!fileLock.DataStore.IsAvailable)
                {
                    sb.AppendLine(Texts.ReportSnapshotIntro).AppendLine();
                }

                AxCryptException ace            = ex as AxCryptException;
                string           displayContext = ace?.DisplayContext ?? string.Empty;
                sb.AppendFormat("----------- Exception at {0} -----------", New <INow>().Utc.ToString("u")).AppendLine();
                sb.AppendLine(displayContext);
                sb.AppendLine(ex?.ToString() ?? "(null)");

                using (StreamWriter writer = new StreamWriter(fileLock.DataStore.OpenUpdate(), Encoding.UTF8))
                {
                    writer.Write(sb.ToString());
                }
            }
        }
Beispiel #23
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldFailToUnbindLiveDatabase() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldFailToUnbindLiveDatabase()
        {
            // given
            CreateClusterStateDir(_fs);
            UnbindFromClusterCommand command = new UnbindFromClusterCommand(_homeDir, _confDir, _outsideWorld);

            FileLock fileLock = CreateLockedFakeDbDir(_homeDir);

            try
            {
                // when
                command.Execute(DatabaseNameParameter(GraphDatabaseSettings.DEFAULT_DATABASE_NAME));
                fail();
            }
            catch (CommandFailed e)
            {
                // then
                assertThat(e.Message, containsString("Database is currently locked. Please shutdown Neo4j."));
            }
            finally
            {
                fileLock.release();
            }
        }
Beispiel #24
0
        public async Task <EofMessage> ProcessFile()
        {
            var path = _file.GetFullPath();

            EofMessage eofMessage = null;

            if (!string.IsNullOrWhiteSpace(path) && System.IO.File.Exists(path) && !FileLock.IsLocked(path))
            {
                try
                {
                    if (_file.IsNew())
                    {
                        eofMessage = await ProcessNewFile();
                    }
                    else
                    {
                        eofMessage = await ProcessChangedFile();
                    }
                }
                catch (Exception ex)
                {
                    WorkerLog.Instance.Error(ex, $"Unexpected error occured while disassembling file '{_file.Path}'");
                }
            }
            else
            {
                WorkerLog.Instance.Warning($"File '{path}' does not exist or is locked. File will not be processed");
            }

            if (eofMessage is null)
            {
                await _fileRepository.UpdateFileAsFailed(_file.Id);
            }

            return(eofMessage);
        }
Beispiel #25
0
        public async Task TestCheckActiveFilesIsLocked()
        {
            DateTime utcNow       = New <INow>().Utc;
            DateTime utcYesterday = utcNow.AddDays(-1);

            FakeDataStore.AddFile(_anAxxPath, utcNow, utcNow, utcNow, new MemoryStream(Resources.helloworld_key_a_txt));
            FakeDataStore.AddFile(_decryptedFile1, utcYesterday, utcYesterday, utcYesterday, Stream.Null);

            ActiveFile activeFile = new ActiveFile(New <IDataStore>(_anAxxPath), New <IDataStore>(_decryptedFile1), new LogOnIdentity("passphrase"), ActiveFileStatus.NotDecrypted, new V1Aes128CryptoFactory().CryptoId);

            ((FakeNow)New <INow>()).TimeFunction = (() => { return(utcNow.AddMinutes(10)); });
            bool changedWasRaised = false;

            Resolve.FileSystemState.Add(activeFile);
            Resolve.SessionNotify.AddCommand((SessionNotification notification) =>
            {
                changedWasRaised = notification.NotificationType == SessionNotificationType.ActiveFileChange;
                return(Constant.CompletedTask);
            });
            using (FileLock fileLock = New <FileLocker>().Acquire(activeFile.EncryptedFileInfo))
            {
                await Task.Run((Action)(async() =>
                {
                    await New <ActiveFileAction>().CheckActiveFiles(new ProgressContext());
                }));
            }
            Assert.That(changedWasRaised, Is.False, "The file should be not be detected as decrypted being created because the encrypted file is locked.");
            using (FileLock fileLock = New <FileLocker>().Acquire(activeFile.DecryptedFileInfo))
            {
                await Task.Run((Action)(async() =>
                {
                    await New <ActiveFileAction>().CheckActiveFiles(new ProgressContext());
                }));
            }
            Assert.That(changedWasRaised, Is.False, "The file should be not be detected as decrypted being created because the decrypted file is locked.");
        }
Beispiel #26
0
        /// <summary>
        /// Asserts that the storage lock file in the given directory has been
        /// released.
        /// </summary>
        /// <remarks>
        /// Asserts that the storage lock file in the given directory has been
        /// released.  This method works by trying to acquire the lock file itself.  If
        /// locking fails here, then the main code must have failed to release it.
        /// </remarks>
        /// <param name="dir">the storage directory to check</param>
        /// <exception cref="System.IO.IOException">if there is an unexpected I/O error</exception>
        public static void AssertFileLockReleased(string dir)
        {
            StorageLocation sl       = StorageLocation.Parse(dir);
            FilePath        lockFile = new FilePath(sl.GetFile(), Storage.StorageFileLock);

            try
            {
                using (RandomAccessFile raf = new RandomAccessFile(lockFile, "rws"))
                {
                    using (FileChannel channel = raf.GetChannel())
                    {
                        FileLock Lock = channel.TryLock();
                        NUnit.Framework.Assert.IsNotNull(string.Format("Lock file at %s appears to be held by a different process."
                                                                       , lockFile.GetAbsolutePath()), Lock);
                        if (Lock != null)
                        {
                            try
                            {
                                Lock.Release();
                            }
                            catch (IOException e)
                            {
                                FsDatasetImpl.Log.Warn(string.Format("I/O error releasing file lock %s.", lockFile
                                                                     .GetAbsolutePath()), e);
                                throw;
                            }
                        }
                    }
                }
            }
            catch (OverlappingFileLockException)
            {
                NUnit.Framework.Assert.Fail(string.Format("Must release lock file at %s.", lockFile
                                                          .GetAbsolutePath()));
            }
        }
Beispiel #27
0
        public void WaitOneReturnsAfterAquiringLock()
        {
            var lockIo    = Substitute.For <ILockIo>();
            var name      = Guid.NewGuid().ToString();
            var semaphore = new LockFileBasedSemaphore(name, TimeSpan.FromSeconds(30), lockIo, Substitute.For <IProcessFinder>());
            var fileLock  = new FileLock
            {
                ProcessId = System.Diagnostics.Process.GetCurrentProcess().Id,
                ThreadId  = Thread.CurrentThread.ManagedThreadId
            };

            lockIo.ReadLock(Arg.Any <string>()).Returns(fileLock);
            lockIo.LockExists(Arg.Any <string>()).Returns(true);
            lockIo.WriteLock(Arg.Any <string>(), Arg.Any <FileLock>()).Returns(false, false, true);

            var stopwatch = new Stopwatch();

            stopwatch.Start();

            var result = semaphore.WaitOne();

            Assert.That(result, Is.True);
            Assert.That(stopwatch.ElapsedMilliseconds, Is.GreaterThan(200));
        }
Beispiel #28
0
            public OpenFilesFaked()
            {
                FileLock01 = new FileLock()
                {
                    AccessedBy = "Tester01",
                    Hostname   = "Server01",
                    Id         = "1",
                    Locks      = 1,
                    OpenMode   = "Write",
                    Path       = "C:/TEST/FILE.PDF",
                    Type       = "Unknown"
                };

                FileLock02 = new FileLock()
                {
                    AccessedBy = "Tester01",
                    Hostname   = "Server01",
                    Id         = "1",
                    Locks      = 1,
                    OpenMode   = "Write",
                    Path       = "C:/test2/file.xls",
                    Type       = "Unknown"
                };
            }
Beispiel #29
0
        private static async Task <ActiveFile> CheckIfTimeToUpdate(ActiveFile activeFile, FileLock encryptedFileLock, FileLock decryptedFileLock, IProgressContext progress)
        {
            if (!activeFile.Status.HasMask(ActiveFileStatus.AssumedOpenAndDecrypted) || activeFile.Status.HasMask(ActiveFileStatus.NotShareable))
            {
                return(activeFile);
            }
            if (New <KnownIdentities>().DefaultEncryptionIdentity == LogOnIdentity.Empty && activeFile.Identity == LogOnIdentity.Empty)
            {
                return(activeFile);
            }

            return(await activeFile.CheckUpdateDecrypted(encryptedFileLock, decryptedFileLock, progress).Free());
        }
Beispiel #30
0
        private static async Task <ActiveFile> CheckActiveFileActions(ActiveFile activeFile, FileLock encryptedFileLock, FileLock decryptedFileLock, IProgressContext progress)
        {
            activeFile = CheckIfKeyIsKnown(activeFile);
            activeFile = CheckIfCreated(activeFile);
            activeFile = CheckIfProcessExited(activeFile);
            activeFile = await CheckIfTimeToUpdate(activeFile, encryptedFileLock, decryptedFileLock, progress).Free();

            activeFile = await CheckIfTimeToDelete(activeFile, decryptedFileLock, progress).Free();

            return(activeFile);
        }
Beispiel #31
0
        public void Unlock()
        {
            if (_os != null)
            {
                if (_fLck != null)
                {
                    try
                    {
                        _fLck.Release();
                    }
                    catch (IOException)
                    {
                        // Huh?
                    }
                    _fLck = null;
                }
                try
                {
                    _os.Close();
                }
                catch (IOException)
                {
                    // Ignore this
                }
                _os = null;
            }

            if (_haveLock)
            {
                _haveLock = false;
                File.Delete(_lockFilePath);
            }
        }
Beispiel #32
0
        ///	<summary> * Try to establish the lock.
        ///	</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 temporary output file could not be created. The caller
        ///	does not hold the lock.
        /// </exception>
        public bool Lock()
        {
            _lockFile.Directory.Mkdirs();
            if (_lockFile.Exists)
            {
                return false;
            }

            try
            {
                _haveLock = true;
                _os = _lockFile.Create();

                _fLck = FileLock.TryLock(_os, _lockFile);
                if (_fLck == null)
                {
                    // We cannot use unlock() here as this file is not
                    // held by us, but we thought we created it. We must
                    // not delete it, as it belongs to some other process.
                    _haveLock = false;
                    try
                    {
                        _os.Close();
                    }
                    catch (Exception)
                    {
                        // Fail by returning haveLck = false.
                    }
                    _os = null;
                }
            }
            catch (Exception)
            {
                Unlock();
                throw;
            }

            return _haveLock;
        }
        public void Update(ProjectConfiguration projConfig, Project proj, MonoDevelopWorkspace.ProjectDataMap projectMap,
                           ImmutableArray <ProjectFile> files,
                           ImmutableArray <FilePath> analyzers,
                           ImmutableArray <MonoDevelopMetadataReference> metadataReferences,
                           ImmutableArray <Microsoft.CodeAnalysis.ProjectReference> projectReferences)
        {
            if (!loaded)
            {
                return;
            }

            var paths   = new string [files.Length];
            var actions = new string [files.Length];

            for (int i = 0; i < files.Length; ++i)
            {
                paths [i]   = files [i].FilePath;
                actions [i] = files [i].BuildAction;
            }

            var projectRefs = new ReferenceItem [projectReferences.Length];

            for (int i = 0; i < projectReferences.Length; ++i)
            {
                var pr        = projectReferences [i];
                var mdProject = projectMap.GetMonoProject(pr.ProjectId);
                projectRefs [i] = new ReferenceItem {
                    FilePath = mdProject.FileName,
                    Aliases  = pr.Aliases.ToArray(),
                };
            }

            var item = new ProjectCache {
                Format             = format,
                Analyzers          = analyzers.Select(x => (string)x).ToArray(),
                Files              = paths,
                BuildActions       = actions,
                MetadataReferences = metadataReferences.Select(x => {
                    var ri = new ReferenceItem {
                        FilePath = x.FilePath,
                        Aliases  = x.Properties.Aliases.ToArray(),
                    };
                    return(ri);
                }).ToArray(),
                ProjectReferences = projectRefs,
            };

            var cacheFile = GetProjectCacheFile(proj, projConfig.Id);

            FileLock fileLock = AcquireWriteLock(cacheFile);

            try {
                lock (fileLock) {
                    var serializer = new JsonSerializer();
                    using (var fs = File.Open(cacheFile, FileMode.Create))
                        using (var sw = new StreamWriter(fs)) {
                            serializer.Serialize(sw, item);
                        }
                }
            } finally {
                ReleaseWriteLock(cacheFile, fileLock);
            }
        }
Beispiel #34
0
        public void Unlock()
        {
            if (os != null)
            {
                if (fLck != null)
                {
                    try
                    {
                        fLck.Release();
                    }
                    catch (IOException)
                    {
                        // Huh?
                    }
                    fLck = null;
                }
                try
                {
                    os.Close();
                }
                catch (IOException)
                {
                    // Ignore this
                }
                os = null;
            }

            if (haveLock)
            {
                haveLock = false;
                lockFile.Delete();
            }
        }
		public static void GeneratorCreate(SqlString code, SqlInt64 seed, SqlInt32 offset) {
			CheckSystemLock();
			if (code.IsNull) {
				throw new ArgumentException("code");
			}
			if (seed.IsNull) {
				throw new ArgumentException("seed");
			}
			if (offset.IsNull) {
				throw new ArgumentException("offset");
			}

			var filename = Path.Combine(GeneratorsDirectory, code.Value + ".xml");
			if (File.Exists(filename)) {
				throw new IOException("generator with given code already existed");
			}
			using (var f = new FileLock(filename)) {
				f.WriteFile(DefineGeneratorXml(seed.Value, offset.Value).ToString());
			}
			SqlContext.Pipe.Send("generator created sucessfully");
		}
Beispiel #36
0
        private static async Task <ActiveFile> CheckIfTimeToDelete(ActiveFile activeFile, FileLock decryptedFileLock, IProgressContext progress)
        {
            switch (OS.Current.Platform)
            {
            case Platform.WindowsDesktop:
            case Platform.Linux:
            case Platform.MacOsx:
                break;

            default:
                return(activeFile);
            }

            if (!activeFile.Status.HasMask(ActiveFileStatus.AssumedOpenAndDecrypted))
            {
                return(activeFile);
            }
            if (activeFile.Status.HasMask(ActiveFileStatus.NotShareable))
            {
                return(activeFile);
            }
            if (activeFile.Status.HasMask(ActiveFileStatus.NoProcessKnown))
            {
                return(activeFile);
            }
            if (Resolve.ProcessState.HasActiveProcess(activeFile))
            {
                return(activeFile);
            }

            activeFile = await TryDelete(activeFile, decryptedFileLock, progress).Free();

            return(activeFile);
        }
Beispiel #37
0
        private static int Main(string[] args)
        {
            if (args.Length < 2)
            {
                Usage();
                return(-1);
            }

            string configurationName = args[0];
            string mode = args[1].ToLowerInvariant();

            using (FileLock locker = FileLock.TryGet(String.Format("Arriba.TfsWorkItemCrawler.{0}.lock", configurationName)))
            {
                try
                {
                    // Ensure we got the file lock (no duplicate crawlers
                    if (locker == null)
                    {
                        Console.WriteLine("Another instance running. Stopping.");
                        return(-2);
                    }

                    // Load the Configuration [up two or three folders, for Databases\<configurationName>\config.json
                    string thisExePath    = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
                    string configJsonPath = Path.Combine(thisExePath, @"..\..\Databases", configurationName, "config.json");
                    if (!File.Exists(configJsonPath))
                    {
                        configJsonPath = Path.Combine(thisExePath, @"..\..\..\Databases", configurationName, "config.json");
                    }
                    string configJson = File.ReadAllText(configJsonPath);

                    CrawlerConfiguration config = JsonConvert.DeserializeObject <CrawlerConfiguration>(configJson);
                    config.ConfigurationName = configurationName;

                    // Password storage mode
                    if (mode.Equals("-password", StringComparison.OrdinalIgnoreCase))
                    {
                        return(TfsItemProvider.EncryptPassword(config));
                    }

                    // Build the item consumer
                    IItemConsumer consumer = ItemConsumerUtilities.Build(config);

                    // Build the item provider
                    IItemProvider provider = ItemProviderUtilities.Build(config);

                    // Determine the list of columns to crawl
                    IEnumerable <ColumnDetails> columns = provider.GetColumns();
                    if (config.ColumnsToInclude.Count > 0)
                    {
                        columns = columns.Where(cd => config.ColumnsToInclude.Contains(cd.Name));
                    }
                    if (config.ColumnsToExclude.Count > 0)
                    {
                        columns = columns.Where(cd => !config.ColumnsToExclude.Contains(cd.Name));
                    }
                    List <ColumnDetails> columnsToAdd = new List <ColumnDetails>(columns);

                    // Create the target table (if it doesn't already exist)
                    consumer.CreateTable(columnsToAdd, config.LoadPermissions());

                    // Build a crawler and crawl the items in restartable order
                    DefaultCrawler crawler = new DefaultCrawler(config, columnsToAdd.Select((cd) => cd.Name), configurationName, !mode.Equals("-i"));
                    crawler.Crawl(provider, consumer);

                    return(0);
                }
                catch (AggregateException ex)
                {
                    foreach (Exception inner in ex.InnerExceptions)
                    {
                        Trace.TraceError(String.Format("ERROR: {0}\r\n{1}", Environment.CommandLine, inner));
                    }

                    return(-2);
                }
                catch (Exception ex)
                {
                    Trace.TraceError(String.Format("ERROR: {0}\r\n{1}", Environment.CommandLine, ex));
                    return(-2);
                }
            }
        }
		public static SqlInt64 GeneratorNext(SqlString code) {
			if (code.IsNull) {
				throw new ArgumentException("code");
			}
			CheckSystemLock();

			var filename = Path.Combine(GeneratorsDirectory, code.Value + ".xml");

			if (!File.Exists(filename)) {
				throw new IOException("generator not existed");
			}
			long result = 0;
			using (var f = new FileLock(filename)) {
				var x = XElement.Parse(f.ReadFile());
				var value = Convert.ToInt64(x.Attr("value"));
				var offset = Convert.ToInt32(x.Attr("offset"));
				result = value + offset;
				x.SetAttributeValue("value", result);
				f.WriteFile(x.ToString());
			}
			return result;
		}