public static BackupRestore Find(string Root, string Product, string Id)
 {
     var Result = default(BackupRestore);
     var Dir = Path.Combine(Root, BackupDirectory);
     var FullId = GetFullId(Product, Id);
     if (Directory.Exists(Dir))
     {
         var DirList = new List<DirectoryTag>();
         foreach (var DateItem in Directory.GetDirectories(Dir))
         {
             DateTime date;
             var DateName = new DirectoryInfo(DateItem).Name;
             if (DateTime.TryParseExact(DateName, DateFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
             {
                 foreach (var VersionItem in Directory.GetDirectories(DateItem))
                 {
                     var VersionName = new DirectoryInfo(VersionItem).Name;
                     if (VersionName.StartsWith(FullId, StringComparison.InvariantCultureIgnoreCase))
                     {
                         Version BckpVersion;
                         var StrVersion = VersionName.Substring(FullId.Length);
                         if (Version.TryParse(StrVersion, out BckpVersion))
                             DirList.Add(new DirectoryTag { Name = VersionItem, Date = date, Version = BckpVersion });
                     }
                 }
             }
         }
         var ByVersion = from i in DirList where i.Version == (from v in DirList select v.Version).Max() select i;
         var ByDate = from i in ByVersion where i.Date == (from v in ByVersion select v.Date).Max() select i;
         var SrcTag = ByDate.First();
         Result = new BackupRestore { Id = Id, Root = GetComponentRoot(SrcTag, Id), BackupFile = Path.Combine(SrcTag.Name, AppZip), BackupMainConfigFile = GetMainConfig(SrcTag) };
     }
     return Result;
 }
Beispiel #2
0
        public void Deploy(Deployment deployment)
        {
            var existingDeployment = _deploymentInstances.SingleOrDefault(x => x.DeploymentId == deployment.Id);
            if (existingDeployment != null)
            {
                if (existingDeployment.RollbackCompleted) // Deployment have been rolled back by other server  already.
                {
                    return;
                }

                _deploymentInstances.RemoveAll(x => x.DeploymentId == deployment.Id);
            }

            var sw = new Stopwatch();
            var fullSw = new Stopwatch();

            fullSw.Start();
            SendResponse(deployment.Id, DeploymentResponseType.DeploymentRequestReceived,  "Received deployment request.");
            IisSite site = SiteManager.GetSiteByName(deployment.SiteName);
            var originalPath = site.SitePath;

            var rootPath = site.SitePath;
            var directoryName = new DirectoryInfo(rootPath).Name;

            if (directoryName.StartsWith("servant-"))
            {
                rootPath = rootPath.Substring(0, rootPath.LastIndexOf(@"\", System.StringComparison.Ordinal));
            }
            var newPath = Path.Combine(rootPath, "servant-" + deployment.Guid);

            var fullPath = Environment.ExpandEnvironmentVariables(newPath);
            Directory.CreateDirectory(fullPath);
            SendResponse(deployment.Id, DeploymentResponseType.CreateDirectory, "Created directory: " + fullPath);

            sw.Start();
            var zipFile = DownloadUrl(deployment.Url);
            sw.Stop();
            SendResponse(deployment.Id, DeploymentResponseType.PackageDownload, string.Format("Completed package download in {0} seconds.", sw.Elapsed.TotalSeconds));

            var fastZip = new FastZip();
            var stream = new MemoryStream(zipFile);
            fastZip.ExtractZip(stream, fullPath, FastZip.Overwrite.Always, null, null, null, true, true);
            SendResponse(deployment.Id, DeploymentResponseType.PackageUnzipping, "Completed package extracting.");

            site.SitePath = newPath;
            SiteManager.UpdateSite(site);
            if (site.ApplicationPoolState == InstanceState.Started)
            {
                SiteManager.RecycleApplicationPool(site.ApplicationPool);
            }
            fullSw.Stop();

            SendResponse(deployment.Id, DeploymentResponseType.ChangeSitePath, string.Format("Changed site path to {0}. Deployment completed in {1} seconds.", fullPath, fullSw.Elapsed.TotalSeconds));

            var rollbackCompleted = false;
            if (deployment.WarmupAfterDeploy)
            {
                System.Threading.Thread.Sleep(1000); // Waits for IIS to complete
                var warmupResult = Warmup(site, deployment.WarmupUrl);
                SendResponse(deployment.Id, DeploymentResponseType.WarmupResult, Json.SerializeToString(warmupResult));
                var msg = warmupResult == null ? "Could not contact IIS site" : string.Format("Site locally returned HTTP {0} {1}.", (int) warmupResult.StatusCode, warmupResult.StatusCode);

                SendResponse(deployment.Id, DeploymentResponseType.Warmup, msg, warmupResult.StatusCode == HttpStatusCode.OK);

                if (deployment.RollbackOnError)
                {
                    // Roll-back if not 200 OK
                    if (warmupResult.StatusCode != HttpStatusCode.OK)
                    {
                        site.SitePath = originalPath;
                        SiteManager.UpdateSite(site);
                        if (site.ApplicationPoolState == InstanceState.Started)
                        {
                            SiteManager.RecycleApplicationPool(site.ApplicationPool);
                        }
                        rollbackCompleted = true;
                        Warmup(site, deployment.WarmupUrl);

                        SendResponse(deployment.Id, DeploymentResponseType.Rollback, string.Format("Rollback completed. Site path is now: {0}.", originalPath));
                    }
                }
            }

            _deploymentInstances.Add(new DeploymentInstance() { DeploymentId = deployment.Id, DeploymentGuid = deployment.Guid, NewPath = newPath, OriginalPath = originalPath, RollbackCompleted = rollbackCompleted, IisSiteId = site.IisId });
        }
Beispiel #3
0
        public ApiModule() : base("/api/")
        {
            var configuration = Nancy.TinyIoc.TinyIoCContainer.Current.Resolve<ServantConfiguration>();
            var serializer = new JavaScriptSerializer();

            Before += ctx =>
            {
                if (!configuration.EnableApi && (string) ctx.Request.Query.Key != configuration.ServantIoKey)
                {
                    return new NotFoundResponse();
                }

                return null;
            };

            Get["/"] = p => "Servant API";

            Get["/info/"] = p =>
            {
                var info = new ServantServerInfo();
                info.ApplicationPools = SiteManager.GetApplicationPools();
                info.Certificates = Helpers.SiteManager.GetCertificates().ToList();

                return Response.AsJson(info);
            };

            #region Stats
            Get["/stats/"] = p =>
            {
                var sites = SiteManager.GetSites(true).ToList();
                var drives = DriveInfo.GetDrives().Where(x => x.DriveType == DriveType.Fixed).Select(
                        x => new { x.Name, x.TotalSize, x.AvailableFreeSpace });

                return Response.AsJson(new
                {
                    System.Environment.MachineName,
                    PerformanceData.SystemUpTime,
                    PerformanceData.TotalMemory,
                    PerformanceData.PhysicalAvailableMemory,
                    PerformanceData.AverageCpuUsage,
                    PerformanceData.AverageGetRequestPerSecond,
                    PerformanceData.CurrentConnections,
                    Drives = drives,
                    Sites = sites.Count(),
                    SitesStopped = sites.Count(x => x.SiteState != InstanceState.Started)
                });
            };
            #endregion

            #region Sites
            Get["/sites/{id?}/"] = p =>
            {
                var id = p.id;

                if (id.HasValue)
                {
                    var site = SiteManager.GetSiteById((int) id);

                    return site == null ? new NotFoundResponse() : Response.AsJson(site);
                }

                var sites = SiteManager.GetSites();
                return Response.AsJson(sites);
            };

            Post["/sites/{id}/stop/"] = p =>
            {
                var id = (int?)p.id;

                if (!id.HasValue)
                {
                    return new NotFoundResponse();
                }

                var site = SiteManager.GetSiteById((int)p.id);
                SiteManager.StopSite(site);
                return Response.AsJson(site);
            };

            Post["/sites/{id}/start/"] = p =>
            {
                var id = (int?)p.id;

                if (!id.HasValue)
                {
                    return new NotFoundResponse();
                }

                var site = SiteManager.GetSiteById((int)p.id);
                SiteManager.StartSite(site);
                return Response.AsJson(site);
            };

            Post["/sites/{id}/restart/"] = p =>
            {
                var id = (int?)p.id;

                if (!id.HasValue)
                {
                    return new NotFoundResponse();
                }

                Site site = SiteManager.GetSiteById(p.Id);
                SiteManager.RestartSite(site.IisId);
                return Response.AsJson(site);
            };

            Post["/sites/{id}/recycle/"] = p =>
            {
                var id = (int?)p.id;

                if (!id.HasValue)
                {
                    return new NotFoundResponse();
                }

                Site site = SiteManager.GetSiteById(p.Id);
                SiteManager.RecycleApplicationPoolBySite(site.IisId);
                return Response.AsJson(site);
            };

            Post["/sites/create/"] = p =>
            {
                Site site = serializer.Deserialize<Site>(Request.Form.Data);
                var result = SiteManager.CreateSite(site);

                return Response.AsText(result.IisSiteId.ToString());
            };

            Post["/sites/update/"] = p =>
            {
                string name = Request.Query.Name;

                if (name == null)
                {
                    return new NotFoundResponse();
                }

                Site site = SiteManager.GetSiteByName(name);
                var postedSite = serializer.Deserialize<Site>(Request.Form.Data);

                site.ApplicationPool = postedSite.ApplicationPool;
                site.Name = postedSite.Name;
                site.SiteState = postedSite.SiteState;
                site.Bindings = postedSite.Bindings;
                site.LogFileDirectory = postedSite.LogFileDirectory;
                site.SitePath = postedSite.SitePath;
                site.Bindings = postedSite.Bindings;

                SiteManager.UpdateSite(site);

                return Response.AsJson(site);
            };

            Post["/sites/{id}/delete/"] = p =>
            {
                var id = (int?)p.id;

                if (!id.HasValue)
                {
                    return new NotFoundResponse();
                }
                Site site = SiteManager.GetSiteById(p.Id);

                SiteManager.DeleteSite(site.IisId);

                return Response.AsJson(new { Success = true});
            };

            Post["/sites/{id}/deploy/"] = p =>
            {
                var id = (int?) p.id;
                if (!id.HasValue)
                {
                    return Response.AsText("IIS Site ID is missing.").WithStatusCode(HttpStatusCode.BadRequest);
                }

                if (!Request.Files.Any())
                {
                    return Response.AsText("Zipfile is missing.").WithStatusCode(HttpStatusCode.BadRequest);
                }

                Site site = SiteManager.GetSiteById(p.Id);
                var rootPath = site.SitePath;
                var directoryName = new DirectoryInfo(rootPath).Name;
                if (directoryName.StartsWith("servant-"))
                {
                    rootPath = Directory.GetParent(rootPath).FullName;
                }

                var newPath = Path.Combine(rootPath, "servant-" + Path.GetFileNameWithoutExtension(Request.Files.First().Name));
                Directory.CreateDirectory(newPath);

                var zip = Request.Files.First().Value;
                var fastZip = new FastZip();
                fastZip.ExtractZip(zip, newPath, FastZip.Overwrite.Always, null, null, null, true, true);

                site.SitePath = newPath;
                SiteManager.UpdateSite(site);

                return Response.AsJson(site);
            };
            #endregion
        }
Beispiel #4
0
        private void CheckUntrackedDirectory(string path, string relative_path)
        {
            var files = Directory.GetFiles(path);
            foreach (string file in files)
                CheckUntrackedFile(new FileInfo(file), relative_path);

            var dirs = Directory.GetDirectories(path);
            foreach (string dir in dirs)
            {
                var dirname = new DirectoryInfo(dir).Name;
                if (dirname.StartsWith(".git"))
                    continue;

                CheckUntrackedDirectory(dir, (relative_path.Length == 0 ? dirname : relative_path + "/" + dirname));
            }
        }
Beispiel #5
0
        private static bool IsIgnoredDirectory(string sourcePath)
        {
            var sourcePathLowerAbsolute = new DirectoryInfo(sourcePath).FullName.ToLower();
            var apiPath =
                new DirectoryInfo(
                    Path.Combine(
                        Directory.GetCurrentDirectory(),
                        Settings.Default.SourceDirectory,
                        Settings.Default.APIFolderLocation)).FullName.ToLower();

            return !sourcePathLowerAbsolute.StartsWith(apiPath)
                   && IgnoredFolders.Any(e => sourcePathLowerAbsolute.EndsWith(Path.DirectorySeparatorChar + e));
        }