// Corrupted git where .git/HEAD exists but only contains \0.
        // we've since this issue on a few occasions but don't really understand what causes it
        internal bool TryFixCorruptedGit()
        {
            var headFile = Path.Combine(_gitExe.WorkingDirectory, ".git", "HEAD");

            if (FileSystemHelpers.FileExists(headFile))
            {
                bool isCorrupted;
                using (var stream = FileSystemHelpers.OpenRead(headFile))
                {
                    isCorrupted = stream.ReadByte() == 0;
                }

                if (isCorrupted)
                {
                    ITracer tracer = _tracerFactory.GetTracer();
                    using (tracer.Step(@"Fix corrupted .git\HEAD file"))
                    {
                        FileSystemHelpers.DeleteFile(headFile);
                        Execute(tracer, "init");
                    }

                    return(true);
                }
            }

            return(false);
        }
示例#2
0
        public static void RemoveAppOfflineIfLeft(IEnvironment environment, IOperationLock deploymentLock, ITracer tracer)
        {
            string appOfflineFile = null;

            try
            {
                appOfflineFile = Path.Combine(environment.WebRootPath, Constants.AppOfflineFileName);
                if (FileSystemHelpers.FileExists(appOfflineFile))
                {
                    var appOfflineContent = OperationManager.Attempt(() => FileSystemHelpers.ReadAllText(appOfflineFile));
                    if (appOfflineContent.Contains(Constants.AppOfflineKuduContent))
                    {
                        if (deploymentLock != null && deploymentLock.IsHeld)
                        {
                            tracer.Trace($"Deployment lock is held, will not remove {appOfflineFile}");
                        }
                        else
                        {
                            tracer.Trace($"Removing leftover {appOfflineFile}");
                            OperationManager.Attempt(() => FileSystemHelpers.DeleteFile(appOfflineFile));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                tracer.TraceError($"Error removing leftover {appOfflineFile} with {ex}");
            }
        }
示例#3
0
        public void Save()
        {
            if (String.IsNullOrEmpty(Id))
            {
                throw new InvalidOperationException();
            }

            var document = new XDocument(new XElement("deployment",
                                                      new XElement("id", Id),
                                                      new XElement("author", XmlUtility.Sanitize(Author)),
                                                      new XElement("deployer", Deployer),
                                                      new XElement("authorEmail", AuthorEmail),
                                                      new XElement("message", XmlUtility.Sanitize(Message)),
                                                      new XElement("progress", Progress),
                                                      new XElement("status", Status),
                                                      new XElement("statusText", StatusText),
                                                      new XElement("lastSuccessEndTime", LastSuccessEndTime),
                                                      new XElement("receivedTime", ReceivedTime),
                                                      new XElement("startTime", StartTime),
                                                      new XElement("endTime", EndTime),
                                                      new XElement("complete", Complete.ToString()),
                                                      new XElement("is_temp", IsTemporary.ToString()),
                                                      new XElement("is_readonly", IsReadOnly.ToString())
                                                      ));

            _statusLock.LockOperation(() =>
            {
                using (Stream stream = FileSystemHelpers.CreateFile(_statusFile))
                {
                    document.Save(stream);
                }

                OperationManager.Attempt(() =>
                {
                    // Used for ETAG
                    if (FileSystemHelpers.FileExists(_activeFile))
                    {
                        FileSystemHelpers.SetLastWriteTimeUtc(_activeFile, DateTime.UtcNow);
                    }
                    else
                    {
                        FileSystemHelpers.WriteAllText(_activeFile, String.Empty);
                    }
                });

                OperationManager.Attempt(() =>
                {
                    // enable the feature thru configuration
                    if (ScmHostingConfigurations.DeploymentStatusCompleteFileEnabled && Complete)
                    {
                        FileSystemHelpers.CopyFile(_statusFile, _statusCompleteFile);
                    }
                    else if (FileSystemHelpers.FileExists(_statusCompleteFile))
                    {
                        FileSystemHelpers.DeleteFile(_statusCompleteFile);
                    }
                });
            }, "Updating deployment status", DeploymentStatusManager.LockTimeout);
        }
示例#4
0
        public static DeploymentStatusFile Open(string id, IEnvironment environment, IAnalytics analytics, IOperationLock statusLock)
        {
            // status complete file is created infrequently at deployment completion time
            // once deployment is completed, it is highly unlikely its status will change
            // this helps optimize status read operation avoid taking status lock
            DeploymentStatusFile statusComplete = null;

            OperationManager.SafeExecute(() =>
            {
                string path = Path.Combine(environment.DeploymentsPath, id, StatusCompleteFile);
                if (FileSystemHelpers.FileExists(path))
                {
                    if (ScmHostingConfigurations.DeploymentStatusCompleteFileEnabled)
                    {
                        statusComplete = new DeploymentStatusFile(id, environment, statusLock, FileSystemCache.ReadXml(path));
                    }
                    else
                    {
                        FileSystemHelpers.DeleteFile(path);
                    }
                }
            });

            return(statusComplete ?? statusLock.LockOperation(() =>
            {
                string path = Path.Combine(environment.DeploymentsPath, id, StatusFile);

                if (!FileSystemHelpers.FileExists(path))
                {
                    return null;
                }

                try
                {
                    XDocument document = null;
                    using (var stream = FileSystemHelpers.OpenRead(path))
                    {
                        document = XDocument.Load(stream);
                    }
                    return new DeploymentStatusFile(id, environment, statusLock, document);
                }
                catch (Exception ex)
                {
                    // in the scenario where w3wp is abruptly terminated while xml is being written,
                    // we may end up with corrupted xml.  we will handle the error and remove the problematic directory.
                    analytics.UnexpectedException(ex);

                    FileSystemHelpers.DeleteDirectorySafe(Path.GetDirectoryName(path), ignoreErrors: true);

                    // it is ok to return null as callers already handle null.
                    return null;
                }
            }, "Getting deployment status", DeploymentStatusManager.LockTimeout));
        }
 private static bool TryDelete(string statusFile)
 {
     try
     {
         FileSystemHelpers.DeleteFile(statusFile);
         return(true);
     }
     catch
     {
         return(false);
     }
 }
示例#6
0
 // we cannot use FileSystemHelpers.DeleteFileSafe.
 // it does not handled IOException due to 'file in used'.
 private void DeleteFileSafe()
 {
     // Only clean up lock on Windows Env
     // When running on Mono with SMB share, delete action would cause wierd behavior on later OpenWrite action if a file has already been opened by another process
     try
     {
         FileSystemHelpers.DeleteFile(_path);
     }
     catch (Exception ex)
     {
         TraceIfUnknown(ex);
     }
 }
示例#7
0
 private bool TryDelete(ContinuousJob job, string statusFile)
 {
     try
     {
         FileSystemHelpers.DeleteFile(statusFile);
         Analytics.JobEvent(job.Name, string.Format("Delete stale status file {0}", statusFile), job.JobType, string.Empty);
         return(true);
     }
     catch
     {
         return(false);
     }
 }
示例#8
0
        /// <summary>
        /// Handle both file and folder deletion, and ignore not found exception
        /// </summary>
        private void HandlingDeletion(OneDriveModel.OneDriveChange change, string wwwroot)
        {
            if (!change.IsDeleted)
            {
                return;
            }

            string fullPath = GetDestinationPath(wwwroot, change.Path);

            if (fullPath == null)
            {
                TraceMessage("Ignore folder {0}", change.Path);
                return;
            }

            try
            {
                if (FileSystemHelpers.FileExists(fullPath))
                {
                    FileSystemHelpers.DeleteFile(fullPath);
                    TraceMessage("Deleted file {0}", fullPath);
                    LogMessage(Resources.OneDriveDeletedFile, fullPath);
                }
                else if (FileSystemHelpers.DirectoryExists(fullPath))
                {
                    FileSystemHelpers.DeleteDirectorySafe(fullPath, ignoreErrors: false);
                    TraceMessage("Deleted directory {0}", fullPath);
                    LogMessage(Resources.OneDriveDeletedDirectory, fullPath);
                }
                else
                {
                    TraceMessage("Not found: {0}. Unknown item type, skip deletion!", fullPath);
                }
            }
            catch (DirectoryNotFoundException)
            {
                TraceMessage("Directory Not found: {0}. Skip deletion!", fullPath);
            }
            catch (FileNotFoundException)
            {
                TraceMessage("File Not found: {0}. Skip deletion!", fullPath);
            }
        }
示例#9
0
        private static async Task <ProfileResultInfo> StopProfileInternalAsync(int processId, int profilingSessionId, bool ignoreProfileFile, ITracer tracer = null)
        {
            tracer = tracer ?? NullTracer.Instance;

            using (tracer.Step("ProfileManager.StopProfileInternalAsync"))
            {
                string profileFileFullPath = GetProfilePath(processId);
                string profileFileName     = Path.GetFileName(profileFileFullPath);
                string arguments           = string.Format("stop {0} /output:{1}", profilingSessionId, profileFileFullPath);

                var profileProcessResponse = await ExecuteProfilingCommandAsync(arguments, tracer);

                ProfileInfo removedId;
                if (profileProcessResponse.StatusCode != HttpStatusCode.OK)
                {
                    _profilingList.TryRemove(processId, out removedId);
                    return(profileProcessResponse);
                }

                FileSystemHelpers.EnsureDirectory(Path.GetDirectoryName(profileFileFullPath));
                tracer.Step("profile was saved to {0} successfully.", profileFileFullPath);

                _profilingList.TryRemove(processId, out removedId);

                if (ignoreProfileFile)
                {
                    try
                    {
                        FileSystemHelpers.DeleteFile(profileFileFullPath);
                    }
                    catch
                    {
                    }
                }

                DisposeTimerIfNecessary();

                return(new ProfileResultInfo(HttpStatusCode.OK, string.Empty));
            }
        }
        public static void PurgeZipsIfNecessary(string sitePackagesPath, ITracer tracer, int totalAllowedZips)
        {
            IEnumerable <string> zipFiles = FileSystemHelpers.GetFiles(sitePackagesPath, "*.zip");

            if (zipFiles.Count() > totalAllowedZips)
            {
                // Order the files in descending order of the modified date and remove the last (N - allowed zip files).
                var fileNamesToDelete = zipFiles.OrderByDescending(fileName => FileSystemHelpers.GetLastWriteTimeUtc(fileName)).Skip(totalAllowedZips);
                foreach (var fileName in fileNamesToDelete)
                {
                    using (tracer.Step("Deleting outdated zip file {0}", fileName))
                    {
                        try
                        {
                            FileSystemHelpers.DeleteFile(fileName);
                        }
                        catch (Exception ex)
                        {
                            tracer.TraceError(ex, "Unable to delete zip file {0}", fileName);
                        }
                    }
                }
            }
        }
示例#11
0
 public void EnableJob(ContinuousJob continuousJob)
 {
     OperationManager.Attempt(() => FileSystemHelpers.DeleteFile(_disableFilePath));
     StartJob(continuousJob);
 }
示例#12
0
 public void EnableJob()
 {
     OperationManager.Attempt(() => FileSystemHelpers.DeleteFile(_disableFilePath));
 }
        private void ButtonDeleteFromIsolatedStorage_Click(object sender, RoutedEventArgs e)
        {
            string path = TextBoxWithIsolatedStorageFilePath.Text;

            FileSystemHelpers.DeleteFile(path);
        }