Exemplo n.º 1
0
        /// <summary>
        /// Check if content is present in the store.
        /// </summary>
        /// <param name="tag"> Location (relative to RootUri) where to check the presence of the content. </param>
        /// <param name="timeout">Check existence timeout</param>
        /// <returns> True if the content exists, false otherwise. </returns>
        public bool DoesContentExist(string tag, TimeSpan timeout)
        {
            TimeoutHelper helper = timeout == TimeSpan.MaxValue ? null : new TimeoutHelper(timeout);

#if !DotNetCoreClr
            using (WindowsImpersonationContext impersonationContext = this.GetImpersonationContext())
#endif
            {
                string smbTag = this.ConvertTagToSMBPath(tag);
                if (FabricFile.Exists(smbTag))
                {
                    return(!FileLock.DoesWriterLockExist(smbTag));
                }

                if (helper != null)
                {
                    helper.ThrowIfExpired();
                }

                if (FabricDirectory.Exists(smbTag))
                {
                    return(!FileLock.DoesWriterLockExist(smbTag));
                }
            }

            return(false);
        }
Exemplo n.º 2
0
        public static string ComputeHash(string resourcePath, bool imageStoreServiceEnabled)
        {
            byte[] hash = null;

            if (FabricFile.Exists(resourcePath))
            {
                hash = ComputeHashOnFile(resourcePath);
            }
            else if (FabricDirectory.Exists(resourcePath))
            {
                hash = ComputeHashOnDirectory(resourcePath, imageStoreServiceEnabled);
            }
            else
            {
                System.Fabric.Interop.Utility.ReleaseAssert(true, "{0} is not found.");
            }

            StringBuilder hashStringBuilder = new StringBuilder();

            for (int i = 0; i < hash.Length; i++)
            {
                hashStringBuilder.Append(string.Format(CultureInfo.InvariantCulture, "{0:X2}", hash[i]));
            }

            return(hashStringBuilder.ToString());
        }
Exemplo n.º 3
0
        public static void SafeFileReplace(string currentFilePath, string newFilePath, string backupFilePath, string traceType)
        {
            if (FabricFile.Exists(backupFilePath))
            {
                FabricFile.Delete(backupFilePath);
            }
            if (FabricFile.Exists(backupFilePath))
            {
                TestableAssertHelper.FailInvalidData(traceType, "CheckpointFileHelper.SafeFileReplace", "!FabricFile.Exists(backupFilePath) : {0}", backupFilePath);
            }

            // Previous replace could have failed in the middle before the next metadata table file got renamed to current.
            if (!FabricFile.Exists(currentFilePath))
            {
                FabricFile.Move(newFilePath, currentFilePath);
            }
            else
            {
                FabricFile.Replace(newFilePath, currentFilePath, backupFilePath, ignoreMetadataErrors: false);
            }

            if (FabricFile.Exists(backupFilePath))
            {
                FabricFile.Delete(backupFilePath);
            }
            if (FabricFile.Exists(backupFilePath))
            {
                TestableAssertHelper.FailInvalidData(traceType, "CheckpointFileHelper.SafeFileReplace", "!FabricFile.Exists(backupFilePath) : {0}", backupFilePath);
            }
        }
Exemplo n.º 4
0
        /// <summary>
        /// Open an existing <see cref="RecoveryPointMetadataFile"/> from the given file path.
        /// </summary>
        /// <param name="recoveryPointMetadataFilePath">Path of the recovery point meta data file.</param>
        /// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
        /// <returns>The read <see cref="RecoveryPointMetadataFile"/>.</returns>
        public static async Task <RecoveryPointMetadataFile> OpenAsync(
            string recoveryPointMetadataFilePath,
            CancellationToken cancellationToken)
        {
            if (string.IsNullOrEmpty(recoveryPointMetadataFilePath))
            {
                throw new ArgumentException(
                          string.Format(CultureInfo.CurrentCulture,
                                        SR.Error_NullArgument_Formatted,
                                        "recoveryPointMetadataFilePath"));
            }

            if (!FabricFile.Exists(recoveryPointMetadataFilePath))
            {
                throw new ArgumentException(
                          string.Format(
                              CultureInfo.CurrentCulture,
                              SR.Error_FilePath_Null,
                              recoveryPointMetadataFilePath),
                          "recoveryPointMetadataFilePath");
            }

            // Open the file with asynchronous flag and 4096 cache size (C# default).
            using (var filestream = FabricFile.Open(
                       recoveryPointMetadataFilePath,
                       FileMode.Open,
                       FileAccess.Read,
                       FileShare.Read,
                       4096,
                       FileOptions.Asynchronous))
            {
                return(await OpenAsync(filestream, recoveryPointMetadataFilePath, cancellationToken));
            }
        }
Exemplo n.º 5
0
        private Task DeleteLogFileAsync(string fileName)
        {
            var path = FileLogicalLog.GetFullPathToLog(this.LogFileDirectoryPath, fileName);

            if (FabricFile.Exists(path))
            {
                try
                {
                    FabricFile.Delete(path);
                }
                catch (Exception ex)
                {
                    // TODO: Exception/HRESULT work needs to be finished: catch (FabricElementNotFoundException)
                    FabricEvents.Events.LogManagerExceptionInfo(
                        this.Tracer.Type,
                        "DeleteLogFileAsync: Delete logical log: " + fileName,
                        ex.GetType().ToString(),
                        ex.Message,
                        ex.HResult,
                        ex.StackTrace);
                }
            }

            return(Task.FromResult(0));
        }
Exemplo n.º 6
0
        protected override async Task <ILogicalLog> CreateLogFileAsync(
            bool createNew,
            CancellationToken cancellationToken)
        {
            var fullLogfileName = FileLogicalLog.GetFullPathToLog(
                this.LogFileDirectoryPath,
                this.CurrentLogFileAlias);

            if (!FabricFile.Exists(fullLogfileName))
            {
                // If the current log does not exist, try to use the backup file.
                var backupfullLogfileName = FileLogicalLog.GetFullPathToLog(
                    this.LogFileDirectoryPath,
                    this.CurrentLogFileAlias + BackupSuffix);

                if (FabricFile.Exists(backupfullLogfileName))
                {
                    // if the backup file exists, rename it to the current log file name.
                    FabricFile.Move(backupfullLogfileName, fullLogfileName);
                }
            }

            return(await FileLogicalLog.CreateFileLogicalLog(
                       fullLogfileName,
                       this.logWriteFaultInjectionParameters).ConfigureAwait(false));
        }
Exemplo n.º 7
0
        private static T ReadXml <T>(string fileName, XmlReader reader)
        {
            try
            {
                var serializer = new XmlSerializer(typeof(T));
                T   obj        = (T)serializer.Deserialize(reader);
                return(obj);
            }
            catch (InvalidOperationException xmlParseException)
            {
                if (FabricFile.Exists(fileName))
                {
                    ImageBuilder.TraceSource.WriteError(
                        TraceType,
                        "Invalid XML Content. File Size: {0}",
                        FabricFile.GetSize(fileName));
                }
                else
                {
                    ImageBuilder.TraceSource.WriteError(
                        TraceType,
                        "File '{0}' does not exist.",
                        fileName);
                }

                TraceAndThrowValidationErrorWithFileName(
                    xmlParseException,
                    TraceType,
                    fileName,
                    StringResources.ImageBuilderError_ErrorParsingXmlFile,
                    fileName);
            }

            return(default(T));
        }
Exemplo n.º 8
0
        /// <summary>
        /// Opens a <see cref="ValueCheckpointFile"/> from the given file.
        /// The file stream will be disposed when the checkpoint file is disposed.
        /// </summary>
        /// <param name="filename">The file to open that contains an existing checkpoint file.</param>
        /// <param name="traceType">Tracing information.</param>
        public static async Task <ValueCheckpointFile> OpenAsync(string filename, string traceType)
        {
            FabricEvents.Events.ValueCheckpointFileAsyncOpen(traceType, DiskConstants.state_opening, filename);
            Diagnostics.Assert(FabricFile.Exists(filename), traceType, "File name {0} does not exist", filename);

            ValueCheckpointFile checkpointFile = null;

            try
            {
                checkpointFile = new ValueCheckpointFile(filename);
                await checkpointFile.ReadMetadataAsync().ConfigureAwait(false);
            }
            catch (Exception)
            {
                // Ensure the checkpoint file get disposed quickly if we get an exception.
                if (checkpointFile != null)
                {
                    checkpointFile.Dispose();
                }

                throw;
            }

            FabricEvents.Events.ValueCheckpointFileAsyncOpen(traceType, DiskConstants.state_complete, filename);
            return(checkpointFile);
        }
Exemplo n.º 9
0
 bool CheckIfBackupExists(string fileOrFolderPath)
 {
     if (fileOrFolderPath.EndsWith(ZipFileExtension) || fileOrFolderPath.EndsWith(RecoveryPointMetadataFileExtension))
     {
         return(FabricFile.Exists(fileOrFolderPath));
     }
     return(FabricDirectory.Exists(fileOrFolderPath));
 }
Exemplo n.º 10
0
        public static T ReadXml <T>(string fileName, XmlReaderSettings validatingXmlReaderSettings)
        {
#if !DotNetCoreClr
            // Ensure the XmlResolve is set to null
            validatingXmlReaderSettings.XmlResolver = null;
#endif

            using (var stream = FabricFile.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
                using (var xmlReader = XmlReader.Create(stream, validatingXmlReaderSettings))
                {
                    T v = ReadXml <T>(fileName, xmlReader);
#if DotNetCoreClr
                    try
                    {
                        var applicationManifestType = v as IXmlValidator;
                        if (applicationManifestType != null)
                        {
                            applicationManifestType.Validate();
                        }
                    }
                    catch (InvalidOperationException xmlParseException)
                    {
                        if (FabricFile.Exists(fileName))
                        {
                            ImageBuilder.TraceSource.WriteError(
                                TraceType,
                                "Invalid XML Content. File Size: {0}",
                                FabricFile.GetSize(fileName));
                        }
                        else
                        {
                            ImageBuilder.TraceSource.WriteError(
                                TraceType,
                                "File '{0}' does not exist.",
                                fileName);
                        }

                        TraceAndThrowValidationErrorWithFileName(
                            xmlParseException,
                            TraceType,
                            fileName,
                            StringResources.ImageBuilderError_ErrorParsingXmlFile,
                            fileName);
                    }
                    catch (XmlException xmlException)
                    {
                        TraceAndThrowValidationErrorWithFileName(
                            xmlException,
                            TraceType,
                            fileName,
                            StringResources.ImageBuilderError_ErrorParsingXmlFile,
                            fileName);
                    }
#endif
                    return(v);
                }
        }
Exemplo n.º 11
0
        private static async Task <ConditionalValue <CheckpointManager <T> > > TryReadCheckpointFile(
            string directory,
            string fileName,
            IStateSerializer <T> valueSerializer,
            string traceType)
        {
            var filePath = Path.Combine(directory, fileName);

            if (!FabricFile.Exists(filePath))
            {
                return(new ConditionalValue <CheckpointManager <T> >(false, default(CheckpointManager <T>)));
            }

            using (var stream = FabricFile.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, FileOptions.SequentialScan))
            {
                var intSegment = new ArraySegment <byte>(new byte[sizeof(int)]);

                var versionRead = await SerializationHelper.ReadIntAsync(intSegment, stream).ConfigureAwait(false);

                if (versionRead != FileVersion)
                {
                    throw new InvalidDataException(string.Format("versionRead '{0}' != FileVersion '{1}'", versionRead, FileVersion));
                }

                var nameLength = await SerializationHelper.ReadIntAsync(intSegment, stream).ConfigureAwait(false);

                if (nameLength < 0)
                {
                    throw new InvalidDataException(string.Format("nameLength '{0}' < 0", nameLength));
                }

                if (nameLength == 0)
                {
                    return(new ConditionalValue <CheckpointManager <T> >(true, new CheckpointManager <T>(null, directory, fileName, valueSerializer, traceType)));
                }

                var nameSegment = new ArraySegment <byte>(new byte[nameLength]);
                await SerializationHelper.ReadBytesAsync(nameSegment, nameLength, stream).ConfigureAwait(false);

                string name;

                using (var reader = new InMemoryBinaryReader(new MemoryStream(nameSegment.Array)))
                {
                    name = reader.ReadString();
                }

                var path = Path.Combine(directory, name);
                if (!FabricFile.Exists(path))
                {
                    throw new InvalidDataException(string.Format("Current checkpoint file does not exist: {0}", path));
                }

                return(new ConditionalValue <CheckpointManager <T> >(
                           true,
                           new CheckpointManager <T>(new Checkpoint <T>(directory, name, valueSerializer, traceType), directory, fileName, valueSerializer, traceType)));
            }
        }
Exemplo n.º 12
0
        public void UploadContent(string tag, string sourceSoftLink, IImageStoreProgressHandler handler, TimeSpan timeout, CopyFlag copyFlag, bool acquireSourceReaderLock)
        {
            TimeoutHelper helper = timeout == TimeSpan.MaxValue ? null : new TimeoutHelper(timeout);

            sourceSoftLink = this.GetLocalPath(sourceSoftLink);
            if ((!FabricFile.Exists(sourceSoftLink)) &&
                (!FabricDirectory.Exists(sourceSoftLink)))
            {
                throw new IOException(
                          string.Format(
                              CultureInfo.CurrentCulture,
                              StringResources.ImageStoreError_DoesNotExistError,
                              sourceSoftLink));
            }

            try
            {
                using (XStoreFileOperations xstoreFileOperation =
                           new XStoreFileOperations(new XStoreParameters(this.providerParams.ConnectionString, this.providerParams.SecondaryConnectionString, this.providerParams.ContainerName)))
                {
                    tag = XStoreCommon.FormatXStoreUri(tag);
                    if (copyFlag == CopyFlag.AtomicCopy)
                    {
                        this.DeleteContent(tag, helper == null ? timeout : helper.GetRemainingTime());
                    }

                    if (FabricFile.Exists(sourceSoftLink))
                    {
                        // This is a file copy
                        xstoreFileOperation.CopyFile(
                            sourceSoftLink,
                            tag,
                            XStoreFileOperationType.CopyFromSMBToXStore,
                            helper);
                    }
                    else
                    {
                        // this is a folder copy
                        xstoreFileOperation.CopyFolder(
                            sourceSoftLink,
                            tag,
                            XStoreFileOperationType.CopyFromSMBToXStore,
                            copyFlag,
                            null,
                            null,
                            helper);
                    }
                }
            }
            catch (Exception ex)
            {
                this.HandleException(ex);
                throw;
            }
        }
 public bool FileExists(string filePath)
 {
     if (isArchive)
     {
         return(ImageBuilderUtility.IsInArchive(this.DirectoryOrArchivePath, filePath));
     }
     else
     {
         return(FabricFile.Exists(Path.Combine(this.DirectoryOrArchivePath, filePath)));
     }
 }
Exemplo n.º 14
0
        public void Copy(string targetDirectory, bool overwrite)
        {
            var targetPath = Path.Combine(targetDirectory, this.FileName);

            if (!FabricFile.Exists(this.FilePath))
            {
                throw new InvalidOperationException(string.Format("Checkpoint file not found at path {0}", this.FilePath));
            }

            FabricFile.Copy(this.FilePath, targetPath, overwrite);
        }
        public bool HasEtlFileBeenFullyProcessed(string etlFileName)
        {
            var etlFileFullPath = Path.Combine(
                this.traceDirectory,
                etlFileName);
            var markerFileFullPath = Path.Combine(
                this.markerFileDirectory,
                etlFileName);

            return((false == FabricFile.Exists(etlFileFullPath)) || FabricFile.Exists(markerFileFullPath));
        }
Exemplo n.º 16
0
 public static void DeleteTempLocation(string location)
 {
     if (!string.IsNullOrEmpty(location) && FabricDirectory.Exists(location))
     {
         FabricDirectory.Delete(location, recursive: true, deleteReadOnlyFiles: true);
     }
     else if (!string.IsNullOrEmpty(location) && FabricFile.Exists(location))
     {
         FabricFile.Delete(location, deleteReadonly: true);
     }
 }
Exemplo n.º 17
0
        /// <summary>
        /// Moves the temporary checkpoint file to the checkpoint file.
        /// </summary>
        /// <returns>Asynchronous operation the represents the file replace.</returns>
        /// <remarks>
        /// Code depends on only being called in cases where next (tmp) checkpoint exists.
        /// </remarks>
        public static async Task SafeFileReplaceAsync(
            string checkpointFileName,
            string temporaryCheckpointFileName,
            string backupCheckpointFileName,
            string traceType)
        {
            if (string.IsNullOrEmpty(checkpointFileName))
            {
                throw new ArgumentException("Checkpoint file name is null or empty.", "checkpointFileName");
            }

            if (string.IsNullOrEmpty(temporaryCheckpointFileName))
            {
                throw new ArgumentException("Temporary file name is null or empty.", "temporaryCheckpointFileName");
            }

            if (string.IsNullOrEmpty(backupCheckpointFileName))
            {
                throw new ArgumentException("Backup file name is null or empty.", "backupCheckpointFileName");
            }

            // Delete previous backup, if it exists.
            if (FabricFile.Exists(backupCheckpointFileName))
            {
                FabricFile.Delete(backupCheckpointFileName);
            }

            // Previous replace could have failed in the middle before the next checkpoint file got renamed to current.
            if (!FabricFile.Exists(checkpointFileName))
            {
                // Validate the next file is complete (this will throw InvalidDataException if it's not valid).
                var nextCheckpointFile = await OpenAsync(temporaryCheckpointFileName, traceType, CancellationToken.None).ConfigureAwait(false);

                // Next checkpoint file is valid.  Move it to be current.
                // MCoskun: Note that FabricFile.Move is MOVEFILE_WRITE_THROUGH by default.
                // Note using this flag can cause undetected dataloss.
                FabricFile.Move(temporaryCheckpointFileName, checkpointFileName);
            }
            else
            {
                // Current exists, so we must have gotten here only after writing a valid next checkpoint file.
                // MCoskun: Note that FabricFile.Move is MOVEFILE_WRITE_THROUGH by default.
                // NTFS guarantees that this operation will not be lost as long as MOVEFILE_WRITE_THROUGH is on.
                // If NTFS metadata log's tail is not flushed yet, it will be flushed before this operation is logged with FUA.
                // Note that ReplaceFile is not guaranteed to be persisted even after it returns.
                // #9291020: Using ReplaceFile here instead of MoveFile with MOVEFILE_WRITE_THROUGH can cause data-loss
                FabricFile.Move(checkpointFileName, backupCheckpointFileName);
                FabricFile.Move(temporaryCheckpointFileName, checkpointFileName);

                // Delete the backup file.
                FabricFile.Delete(backupCheckpointFileName);
            }
        }
Exemplo n.º 18
0
        private static ulong GetNewContainerInstanceIdAtomic(
            ContainerDescription containerDesc)
        {
#if DotNetCoreClrLinux
            // There is a file called containerid in
            // /log/application/partitionid/servicepackageactivationid/codepackagename/
            // This file contains the number corresponding to the latest folder for logs
            // /mnt/log/application/partitionid/servicepackageactivationid/codepackagename/number/application.log
            //
            // For the first instance of thecontainer, create a new file and start at 0,
            // For every container afterwards, check the file exists, read from the file
            // and add 1 to the value in the file in order to get the new current instance id
            // and save the value to the file.
            var applicationNamePart      = containerDesc.ApplicationName;
            var applicationNameExtraPart = string.Format("{0}/", RootNamingUriString);
            if (applicationNamePart.StartsWith(applicationNameExtraPart))
            {
                applicationNamePart = applicationNamePart.Substring(applicationNameExtraPart.Length);
            }

            applicationNamePart = applicationNamePart.Replace('/', '_');
            var digestedApplicationName = applicationNamePart + DigestedApplicationNameDockerSuffix;

            var logRoots = "/mnt/logs";

            var logPath = Path.Combine(logRoots, digestedApplicationName, containerDesc.PartitionId, containerDesc.ServicePackageActivationId, containerDesc.CodePackageName);

            if (!FabricDirectory.Exists(logPath))
            {
                FabricDirectory.CreateDirectory(logPath);
            }

            ulong containerId = 0;
            var   containerInstanceIdFilePath = Path.Combine(logPath, CodePackageInstanceIdFileName);
            if (!FabricFile.Exists(containerInstanceIdFilePath))
            {
                using (var containerIdFile = FabricFile.Create(containerInstanceIdFilePath))
                {
                    containerId = 0;
                }
            }
            else
            {
                containerId = ReadContainerIdFromFile(containerInstanceIdFilePath) + 1;
            }

            WriteContainerIdToFile(containerInstanceIdFilePath, containerId);

            return(containerId);
#else
            return(0);
#endif
        }
Exemplo n.º 19
0
        /// <summary>
        /// Get the image store content information including all files and subfolders
        /// </summary>
        /// <param name="storeSource">The relative path to file or folder from image store root</param>
        /// <param name="isRecursive">flag list subhierarchy</param>
        /// <param name="timeout">The timeout for performing the listing operation</param>
        /// <returns>ImageStoreContent object including files and subfolders</returns>
        public ImageStoreContent ListContentWithDetails(string storeSource, bool isRecursive, TimeSpan timeout)
        {
            ImageStoreContent content = null;

            try
            {
                string smbTag = this.ConvertTagToSMBPath(storeSource);
                if (!FabricDirectory.Exists(smbTag))
                {
                    if (FabricFile.Exists(smbTag))
                    {
                        var fullSourcePath = FabricPath.GetFullPath(storeSource);
                        content = new ImageStoreContent()
                        {
                            Files = new List <ImageStoreFile>()
                            {
                                this.ConvertToImageStoreFile(fullSourcePath, storeSource)
                            }
                        };
                    }
                    else
                    {
                        TraceSource.WriteWarning(
                            TraceType,
                            "Directory/File {0} doesn't exist",
                            smbTag);
                    }
                }
                else
                {
                    content = isRecursive
                        ? new ImageStoreContent()
                    {
                        Files = this.GetAllFiles(smbTag, storeSource).ToList()
                    }
                        : this.GetFilesAndSubFolders(smbTag, storeSource, timeout);
                }
            }
            catch (IOException exception)
            {
                if (exception.GetType() == typeof(IOException))
                {
                    throw new FabricImageStoreException(string.Format(CultureInfo.CurrentCulture, StringResources.Error_ImageStoreIOException, exception));
                }
                else
                {
                    throw;
                }
            }

            return(content);
        }
Exemplo n.º 20
0
 public static string EnsureHashFile(string resourcePath, string hashFilePath, bool imageStoreServiceEnabled)
 {
     if (!FabricFile.Exists(hashFilePath))
     {
         string checksum = ChecksumUtility.ComputeHash(resourcePath, imageStoreServiceEnabled);
         ImageBuilderUtility.WriteStringToFile(hashFilePath, checksum);
         return(checksum);
     }
     else
     {
         return(ImageBuilderUtility.ReadStringFromFile(hashFilePath));
     }
 }
Exemplo n.º 21
0
        private bool TryUpdateLocalMap(int retryCount, string localMapDestinationDir, string localMapDestination, DateTime sourceLastWriteTime)
        {
            // Record the source file's last write time based on the snapshot
            // we took before copying the source file. We know that we copied
            // over a version that it at least as new as the timestamp in the
            // snapshot.

            // Figure out in which directory in the local map we will
            // record information about this file. Create that directory
            // if it doesn't exist.
            if ((false == string.IsNullOrEmpty(localMapDestinationDir)) &&
                (false == FabricDirectory.Exists(localMapDestinationDir)))
            {
                try
                {
                    Utility.PerformIOWithRetries(
                        () => { FabricDirectory.CreateDirectory(localMapDestinationDir); },
                        retryCount);
                }
                catch (Exception e)
                {
                    this.TraceSource.WriteExceptionAsError(
                        this.LogSourceId,
                        e,
                        "Failed to create directory {0} in the local map of uploaded files.",
                        localMapDestinationDir);
                    return(false);
                }
            }

            // If the file doesn't exist in the local map, create it.
            if (false == FabricFile.Exists(localMapDestination))
            {
                if (!this.TryCreateLocalMapFile(retryCount, localMapDestination, sourceLastWriteTime))
                {
                    return(false);
                }
            }
            else
            {
                // File already exists in the local map. Set the last
                // write time for the file in the local map to the last
                // write time from the source file snapshot
                // It's a Best Effort operation.
                this.TryUpdateLastWriteTime(localMapDestination, sourceLastWriteTime);
            }

            return(true);
        }
Exemplo n.º 22
0
        /// <summary>
        /// Compare two files and return true if they are different.
        /// </summary>
        /// <param name="firstFilename">The name of the first file to compare.</param>
        /// <param name="secondFilename">The name of the second file to compare.</param>
        /// <returns>True if the files are different, false otherwise </returns>
        public bool AreFilesDifferent(string firstFilename, string secondFilename)
        {
            this.ThrowIfDisposed();

            if (this.copyFlag == CopyFlag.AtomicCopy || this.copyFlag == CopyFlag.AtomicCopySkipIfExists)
            {
                return(true);
            }
            else
            {
                return(FabricFile.Exists(firstFilename) != FabricFile.Exists(secondFilename) ||
                       FabricFile.GetSize(firstFilename) != FabricFile.GetSize(secondFilename) ||
                       FabricFile.GetLastWriteTime(firstFilename) != FabricFile.GetLastWriteTime(firstFilename));
            }
        }
Exemplo n.º 23
0
        internal static void CreateHardLinkOrCopyFile(string sourceFileName, string destinationFileName)
        {
            if (!FabricFile.Exists(sourceFileName))
            {
                return;
            }

            // Since the source file won't be changed, we can simply create a hardlink
            if (!FabricFile.CreateHardLink(destinationFileName, sourceFileName))
            {
                // Hardlink can fail, e.g. if the destination is on another drive or the drive isn't NTFS.
                // Fallback to a full file copy.
                FabricFile.Copy(sourceFileName, destinationFileName, overwrite: true);
            }
        }
Exemplo n.º 24
0
        private static void GenerateChecksumFile(
            string fileOrDirectoryPath,
            BuildLayoutSpecification layoutSpecification,
            bool isImageStoreServiceEnabled)
        {
            var checksumFileName = layoutSpecification.GetChecksumFile(fileOrDirectoryPath);

            if (FabricFile.Exists(checksumFileName))
            {
                FabricFile.Delete(checksumFileName);
            }

            var checksumValue = ChecksumUtility.ComputeHash(fileOrDirectoryPath, isImageStoreServiceEnabled);

            WriteStringToFile(checksumFileName, checksumValue);
        }
Exemplo n.º 25
0
        public static bool TryDeleteCopyFile(string directory, string traceType)
        {
            var filePath = GetCopyFilePath(directory);

            if (!FabricFile.Exists(filePath))
            {
                return(false);
            }

            FabricFile.Delete(filePath);
            if (FabricFile.Exists(filePath))
            {
                TestableAssertHelper.FailInvalidData(traceType, "CheckpointFileHelper.TryDeleteCopyFile", "!FabricFile.Exists(filePath).  filePath: {0}", filePath);
            }
            return(true);
        }
Exemplo n.º 26
0
 /// <summary>
 /// Try to delete the file.
 /// </summary>
 /// <param name="filePath">The complete path of the file to be deleted.</param>
 private static void TryDeleteFile(string filePath)
 {
     try
     {
         if (FabricFile.Exists(filePath))
         {
             FabricFile.Delete(filePath, deleteReadonly: true);
         }
     }
     catch (Exception e)
     {
         if (!ExceptionHandler.IsIOException(e))
         {
             throw;
         }
     }
 }
Exemplo n.º 27
0
        public void Copy(string targetDirectory, bool overwrite)
        {
            var sourcePath = Path.Combine(this.directory, this.FileName);
            var targetPath = Path.Combine(targetDirectory, this.FileName);

            if (!FabricFile.Exists(sourcePath))
            {
                throw new ArgumentException(string.Format("Checkpoint Manager file not found in directory {0}", this.directory), "this.directory");
            }

            if (this.CurrentCheckpoint != null)
            {
                this.CurrentCheckpoint.Copy(targetDirectory, overwrite);
            }

            FabricFile.Copy(sourcePath, targetPath, overwrite);
        }
Exemplo n.º 28
0
        internal bool OkToDeleteFile(FolderTrimmer.FolderDeletionInfo folderInfo, string fileName)
        {
            string relativePath = (string)folderInfo.Context;
            string pathOnLocalNode;

            if (string.IsNullOrEmpty(relativePath))
            {
                pathOnLocalNode = Path.Combine(this.sourceFolder, fileName);
            }
            else
            {
                pathOnLocalNode = Path.Combine(
                    this.sourceFolder,
                    relativePath,
                    fileName);
            }

            return(false == FabricFile.Exists(pathOnLocalNode));
        }
Exemplo n.º 29
0
            public void OpenLastEndTimeFile()
            {
                // Check if file exists as an optimization before trying to open.
                if (this.Mode == FileMode.Open && !FabricFile.Exists(this.FileName))
                {
                    return;
                }

                try
                {
                    this.Fs = FabricFile.Open(this.FileName, this.Mode, this.Access);
#if !DotNetCoreClrLinux
                    Helpers.SetIoPriorityHint(this.Fs.SafeFileHandle, Kernel32Types.PRIORITY_HINT.IoPriorityHintVeryLow);
#endif
                }
                catch (FileNotFoundException)
                {
                    // File was not found. This is not an error.
                }
            }
Exemplo n.º 30
0
 private static void DeleteTargetInformationFile(string targetInformationFile)
 {
     if (FabricFile.Exists(targetInformationFile))
     {
         try
         {
             DeployerTrace.WriteInfo("Attempting to delete TargetInformationFile.");
             FabricFile.Delete(targetInformationFile, true);
         }
         catch (Exception ex)
         {
             DeployerTrace.WriteError("Failed to delete: {0}. Exception: {1}.", targetInformationFile, ex);
             throw;
         }
     }
     else
     {
         DeployerTrace.WriteWarning("TargetInformationFile does not exist.");
     }
 }