private static void SetApplication(Application app, dynamic model) { string path = DynamicHelper.Value(model.path); if (!string.IsNullOrEmpty(path)) { // Make sure path starts with '/' if (path[0] != '/') { path = '/' + path; } app.Path = path; } DynamicHelper.If((object)model.enabled_protocols, v => app.EnabledProtocols = v); string physicalPath = DynamicHelper.Value(model.physical_path); if (physicalPath != null) { if (!Directory.Exists(System.Environment.ExpandEnvironmentVariables(physicalPath))) { throw new ApiArgumentException("physical_path", "Directory does not exist."); } var rootVDir = app.VirtualDirectories["/"]; if (rootVDir == null) { throw new ApiArgumentException("application/physical_path", "Root virtual directory does not exist."); } rootVDir.PhysicalPath = physicalPath.Replace('/', '\\'); } if (model.application_pool != null) { // Change application pool if (model.application_pool.id == null) { throw new ApiArgumentException("application_pool.id"); } string poolName = AppPools.AppPoolId.CreateFromUuid(DynamicHelper.Value(model.application_pool.id)).Name; ApplicationPool pool = AppPoolHelper.GetAppPool(poolName); if (pool != null) { app.ApplicationPoolName = pool.Name; } } }
public object Get() { IEnumerable <ApplicationInfo> apps = null; // // Filter by AppPool string appPoolUuid = Context.Request.Query[AppPools.Defines.IDENTIFIER]; if (!string.IsNullOrEmpty(appPoolUuid)) { ApplicationPool pool = AppPoolHelper.GetAppPool(AppPoolId.CreateFromUuid(appPoolUuid).Name); if (pool == null) { return(NotFound()); } apps = ApplicationHelper.GetApplications(pool); } // // Filter by Site if (apps == null) { Site site = SiteHelper.ResolveSite(); if (site == null) { return(NotFound()); } apps = site.Applications.Select(app => new ApplicationInfo { Application = app, Site = site }); } // Set HTTP header for total count this.Context.Response.SetItemsCount(apps.Count()); Fields fields = Context.Request.GetFields(); return(new { webapps = apps.Select(app => ApplicationHelper.ToJsonModelRef(app.Application, app.Site, fields)) }); }
public static IEnumerable <ApplicationInfo> GetApplications(WorkerProcess wp) { if (wp == null) { throw new ArgumentNullException(nameof(wp)); } List <ApplicationInfo> result = new List <ApplicationInfo>(); // // Get AppPool var appPool = AppPoolHelper.GetAppPool(wp.AppPoolName); if (appPool == null) { return(result); } // // Find all apps in the app pool var apps = Applications.ApplicationHelper.GetApplications(appPool); // // Match Site Id and App Path foreach (var app in apps) { foreach (var ad in wp.ApplicationDomains) { if (ad.Id.Contains($"/{app.Site.Id}/")) { string appPath = app.Application.Path; string adPath = ad.VirtualPath; if (appPath.Equals(adPath, StringComparison.OrdinalIgnoreCase) || appPath.Equals(adPath.TrimEnd('/'), StringComparison.OrdinalIgnoreCase)) { result.Add(app); break; } } } } return(result); }
public static IEnumerable <Request> GetRequests(Site site, Filter filter = null) { if (site == null) { throw new ArgumentNullException(nameof(site)); } // Get all application pools for the site Dictionary <string, ApplicationPool> pools = new Dictionary <string, ApplicationPool>(); foreach (var app in site.Applications) { if (!string.IsNullOrEmpty(app.ApplicationPoolName) && !pools.ContainsKey(app.ApplicationPoolName)) { var pool = AppPoolHelper.GetAppPool(app.ApplicationPoolName); if (pool != null) { pools[app.ApplicationPoolName] = pool; } } } // Get all worker processes running in the app pools List <WorkerProcess> wps = new List <WorkerProcess>(); foreach (var pool in pools.Values) { wps.Concat(WorkerProcessHelper.GetWorkerProcesses(pool)); } var result = new List <Request>(); foreach (var wp in wps) { foreach (var req in GetRequests(wp, filter)) { if (req.SiteId == site.Id) { result.Add(req); } } } return(result); }
public object Get() { IEnumerable <WorkerProcess> wps = null; // // Filter by AppPool string appPoolUuid = Context.Request.Query[AppPools.Defines.IDENTIFIER]; if (!string.IsNullOrEmpty(appPoolUuid)) { ApplicationPool pool = AppPoolHelper.GetAppPool(AppPoolId.CreateFromUuid(appPoolUuid).Name); if (pool == null) { return(NotFound()); } wps = WorkerProcessHelper.GetWorkerProcesses(pool); } // // All if (wps == null) { wps = WorkerProcessHelper.GetWorkerProcesses(); } // // Set HTTP header for total count this.Context.Response.SetItemsCount(wps.Count()); Fields fields = Context.Request.GetFields(); var obj = new { worker_processes = wps.Select(wp => WorkerProcessHelper.ToJsonModelRef(wp, fields)) }; return(obj); }
public object Get() { IEnumerable <Site> sites = null; // // Filter by AppPool string appPoolUuid = Context.Request.Query[AppPools.Defines.IDENTIFIER]; if (!string.IsNullOrEmpty(appPoolUuid)) { ApplicationPool pool = AppPoolHelper.GetAppPool(AppPoolId.CreateFromUuid(appPoolUuid).Name); if (pool == null) { return(NotFound()); } sites = SiteHelper.GetSites(pool); } // // Get All Sites if (sites == null) { sites = ManagementUnit.ServerManager.Sites; } // Set HTTP header for total count this.Context.Response.SetItemsCount(sites.Count()); Fields fields = Context.Request.GetFields(); // Return the site reference model collection return(new { websites = sites.Select(s => SiteHelper.ToJsonModelRef(s, fields)) }); }
public static IEnumerable <Site> GetSites(WorkerProcess wp) { if (wp == null) { throw new ArgumentNullException(nameof(wp)); } List <Site> result = new List <Site>(); // // Get AppPool var appPool = AppPoolHelper.GetAppPool(wp.AppPoolName); if (appPool == null) { return(result); } // // Find all sites in the app pool var sites = Sites.SiteHelper.GetSites(appPool); // // Match Site Id foreach (var s in sites) { foreach (var ad in wp.ApplicationDomains) { if (ad.Id.Contains($"/{s.Id}/")) { result.Add(s); break; } } } return(result); }
internal static object WpToJsonModel(WorkerProcess wp, Fields fields = null, bool full = true) { if (wp == null) { throw new ArgumentNullException(nameof(wp)); } if (fields == null) { fields = Fields.All; } Process p = Process.GetProcessById(wp.ProcessId); dynamic obj = new ExpandoObject(); // // name if (fields.Exists("name")) { obj.name = p.ProcessName; } // // id obj.id = new WorkerProcessId(p.Id, Guid.Parse(wp.ProcessGuid)).Uuid; // // status if (fields.Exists("status")) { obj.status = Enum.GetName(typeof(WorkerProcessState), wp.State).ToLower(); } // // process_id if (fields.Exists("process_id")) { obj.process_id = p.Id; } // // process_guid if (fields.Exists("process_guid")) { obj.process_guid = wp.ProcessGuid; } // // start_time if (fields.Exists("start_time")) { obj.start_time = p.StartTime; } // // working_set if (fields.Exists("working_set")) { obj.working_set = p.WorkingSet64; } // // peak_working_set if (fields.Exists("peak_working_set")) { obj.peak_working_set = p.PeakWorkingSet64; } // // private_memory_size if (fields.Exists("private_memory_size")) { obj.private_memory_size = p.PrivateMemorySize64; } // // virtual_memory_size if (fields.Exists("virtual_memory_size")) { obj.virtual_memory_size = p.VirtualMemorySize64; } // // peak_virtual_memory_size if (fields.Exists("peak_virtual_memory_size")) { obj.peak_virtual_memory_size = p.PeakVirtualMemorySize64; } // // total_processor_time if (fields.Exists("total_processor_time")) { obj.total_processor_time = p.TotalProcessorTime; } // // application_pool if (fields.Exists("application_pool")) { ApplicationPool pool = AppPoolHelper.GetAppPool(wp.AppPoolName); obj.application_pool = AppPoolHelper.ToJsonModelRef(pool); } return(Core.Environment.Hal.Apply(Defines.Resource.Guid, obj, full)); }
private static Site SetSite(Site site, dynamic model, IFileProvider fileProvider) { Debug.Assert(site != null); Debug.Assert((bool)(model != null)); // // Name DynamicHelper.If((object)model.name, v => { site.Name = v; }); // // Server Auto Start site.ServerAutoStart = DynamicHelper.To <bool>(model.server_auto_start) ?? site.ServerAutoStart; // // Physical Path string physicalPath = DynamicHelper.Value(model.physical_path); if (physicalPath != null) { physicalPath = physicalPath.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar); var expanded = System.Environment.ExpandEnvironmentVariables(physicalPath); if (!PathUtil.IsFullPath(expanded)) { throw new ApiArgumentException("physical_path"); } if (!fileProvider.IsAccessAllowed(expanded, FileAccess.Read)) { throw new ForbiddenArgumentException("physical_path", physicalPath); } if (!Directory.Exists(expanded)) { throw new NotFoundException("physical_path"); } var rootApp = site.Applications["/"]; if (rootApp != null) { var rootVDir = rootApp.VirtualDirectories["/"]; if (rootVDir != null) { rootVDir.PhysicalPath = physicalPath; } } } // // Enabled Protocols string enabledProtocols = DynamicHelper.Value(model.enabled_protocols); if (enabledProtocols != null) { var rootApp = site.Applications["/"]; if (rootApp != null) { rootApp.EnabledProtocols = enabledProtocols; } } // // Limits if (model.limits != null) { dynamic limits = model.limits; site.Limits.MaxBandwidth = DynamicHelper.To(limits.max_bandwidth, 0, uint.MaxValue) ?? site.Limits.MaxBandwidth; site.Limits.MaxConnections = DynamicHelper.To(limits.max_connections, 0, uint.MaxValue) ?? site.Limits.MaxConnections; if (site.Limits.Schema.HasAttribute(MaxUrlSegmentsAttribute)) { site.Limits.MaxUrlSegments = DynamicHelper.To(limits.max_url_segments, 0, 16383) ?? site.Limits.MaxUrlSegments; } long?connectionTimeout = DynamicHelper.To(limits.connection_timeout, 0, ushort.MaxValue); site.Limits.ConnectionTimeout = (connectionTimeout != null) ? TimeSpan.FromSeconds(connectionTimeout.Value) : site.Limits.ConnectionTimeout; } // // Bindings if (model.bindings != null) { IEnumerable <dynamic> bindings = (IEnumerable <dynamic>)model.bindings; // If the user passes an object for the bindings property rather than an array we will hit an exception when we try to access any property in // the foreach loop. // This means that the bindings collection won't be deleted, so the bindings are safe from harm. List <Binding> newBindings = new List <Binding>(); // Iterate over the bindings to create a new binding list foreach (dynamic b in bindings) { Binding binding = site.Bindings.CreateElement(); SetBinding(binding, b); foreach (Binding addedBinding in newBindings) { if (addedBinding.Protocol.Equals(binding.Protocol, StringComparison.OrdinalIgnoreCase) && addedBinding.BindingInformation.Equals(binding.BindingInformation, StringComparison.OrdinalIgnoreCase)) { throw new AlreadyExistsException("binding"); } } // Add to bindings list newBindings.Add(binding); } // All bindings have been verified and added to the list // Clear the old list, and add the new site.Bindings.Clear(); newBindings.ForEach(binding => site.Bindings.Add(binding)); } // // App Pool if (model.application_pool != null) { // Extract the uuid from the application_pool object provided in model string appPoolUuid = DynamicHelper.Value(model.application_pool.id); // It is an error to provide an application pool object without specifying its id property if (appPoolUuid == null) { throw new ApiArgumentException("application_pool.id"); } // Create application pool id object from uuid provided, use this to obtain the application pool AppPoolId appPoolId = AppPoolId.CreateFromUuid(appPoolUuid); ApplicationPool pool = AppPoolHelper.GetAppPool(appPoolId.Name); Application rootApp = site.Applications["/"]; if (rootApp == null) { throw new ApiArgumentException("application_pool", "Root application does not exist."); } // REVIEW: Should we create the root application if it doesn't exist and they specify an application pool? // We decided not to do this for physical_path. // Application pool for a site is extracted from the site's root application rootApp.ApplicationPoolName = pool.Name; } return(site); }
internal static object ToJsonModel(Site site, Fields fields = null, bool full = true) { if (site == null) { return(null); } if (fields == null) { fields = Fields.All; } dynamic obj = new ExpandoObject(); var siteId = new SiteId(site.Id); // // name if (fields.Exists("name")) { obj.name = site.Name; } // // id obj.id = siteId.Uuid; // // physical_path if (fields.Exists("physical_path")) { string physicalPath = string.Empty; Application rootApp = site.Applications["/"]; if (rootApp != null && rootApp.VirtualDirectories["/"] != null) { physicalPath = rootApp.VirtualDirectories["/"].PhysicalPath; } obj.physical_path = physicalPath; } // // key if (fields.Exists("key")) { obj.key = siteId.Id; } // // status if (fields.Exists("status")) { // Prepare state Status state = Status.Unknown; try { state = StatusExtensions.FromObjectState(site.State); } catch (COMException) { // Problem getting state of site. Possible reasons: // 1. Site's application pool was deleted. // 2. Site was just created and the status is not accessible yet. } obj.status = Enum.GetName(typeof(Status), state).ToLower(); } // // server_auto_start if (fields.Exists("server_auto_start")) { obj.server_auto_start = site.ServerAutoStart; } // // enabled_protocols if (fields.Exists("enabled_protocols")) { Application rootApp = site.Applications["/"]; obj.enabled_protocols = rootApp == null ? string.Empty : rootApp.EnabledProtocols; } // // limits if (fields.Exists("limits")) { dynamic limits = new ExpandoObject(); limits.connection_timeout = site.Limits.ConnectionTimeout.TotalSeconds; limits.max_bandwidth = site.Limits.MaxBandwidth; limits.max_connections = site.Limits.MaxConnections; if (site.Limits.Schema.HasAttribute(MaxUrlSegmentsAttribute)) { limits.max_url_segments = site.Limits.MaxUrlSegments; } obj.limits = limits; } // // bindings if (fields.Exists("bindings")) { obj.bindings = site.Bindings.Select(b => ToJsonModel(b)); } // // application_pool if (fields.Exists("application_pool")) { Application rootApp = site.Applications["/"]; var pool = rootApp != null?AppPoolHelper.GetAppPool(rootApp.ApplicationPoolName) : null; obj.application_pool = (pool == null) ? null : AppPoolHelper.ToJsonModelRef(pool, fields.Filter("application_pool")); } return(Core.Environment.Hal.Apply(Defines.Resource.Guid, obj, full)); }
private static Site SetSite(Site site, dynamic model) { Debug.Assert(site != null); Debug.Assert((bool)(model != null)); DynamicHelper.If((object)model.name, v => { site.Name = v; }); site.ServerAutoStart = DynamicHelper.To <bool>(model.server_auto_start) ?? site.ServerAutoStart; string physicalPath = DynamicHelper.Value(model.physical_path); if (physicalPath != null) { if (!Directory.Exists(System.Environment.ExpandEnvironmentVariables(physicalPath))) { throw new ApiArgumentException("physical_path", "Directory does not exist."); } var rootApp = site.Applications["/"]; if (rootApp == null) { throw new ApiArgumentException("site/physical_path", "Root application does not exist."); } var rootVDir = rootApp.VirtualDirectories["/"]; if (rootVDir == null) { throw new ApiArgumentException("site/physical_path", "Root virtual directory does not exist."); } rootVDir.PhysicalPath = physicalPath.Replace('/', '\\'); } string enabledProtocols = DynamicHelper.Value(model.enabled_protocols); if (enabledProtocols != null) { var rootApp = site.Applications["/"]; if (rootApp != null) { rootApp.EnabledProtocols = enabledProtocols; } } // Limits if (model.limits != null) { dynamic limits = model.limits; site.Limits.MaxBandwidth = DynamicHelper.To(limits.max_bandwidth, 0, uint.MaxValue) ?? site.Limits.MaxBandwidth; site.Limits.MaxConnections = DynamicHelper.To(limits.max_connections, 0, uint.MaxValue) ?? site.Limits.MaxConnections; if (site.Limits.Schema.HasAttribute(MaxUrlSegmentsAttribute)) { site.Limits.MaxUrlSegments = DynamicHelper.To(limits.max_url_segments, 0, 16383) ?? site.Limits.MaxUrlSegments; } long?connectionTimeout = DynamicHelper.To(limits.connection_timeout, 0, ushort.MaxValue); site.Limits.ConnectionTimeout = (connectionTimeout != null) ? TimeSpan.FromSeconds(connectionTimeout.Value) : site.Limits.ConnectionTimeout; } // Bindings if (model.bindings != null) { IEnumerable <dynamic> bindings = (IEnumerable <dynamic>)model.bindings; // If the user passes an object for the bindings property rather than an array we will hit an exception when we try to access any property in // the foreach loop. // This means that the bindings collection won't be deleted, so the bindings are safe from harm. List <Binding> newBindings = new List <Binding>(); // Iterate over the bindings to create a new binding list foreach (dynamic binding in bindings) { // Extract data from binding string ipAddress = DynamicHelper.Value(binding.ip_address); long? port = DynamicHelper.To(binding.port, 1, 65535); string hostname = DynamicHelper.Value(binding.hostname) ?? ""; bool? isHttps = DynamicHelper.To <bool>(binding.is_https); string certificateHash = null; string certificateStoreName = null; byte[] hashBytes = null; // Validate that data forms valid binding if (ipAddress == null) { throw new ApiArgumentException("binding.ip_address"); } else if (port == null) { throw new ApiArgumentException("binding.port"); } else if (isHttps == null) { throw new ApiArgumentException("binding.is_https"); } if (isHttps.Value) { if (binding.certificate == null || !(binding.certificate is JObject)) { throw new ApiArgumentException("certificate"); } dynamic certificate = binding.certificate; string uuid = DynamicHelper.Value(certificate.id); if (string.IsNullOrEmpty(uuid)) { throw new ApiArgumentException("certificate.id"); } CertificateId id = new CertificateId(uuid); certificateHash = id.Thumbprint; certificateStoreName = Enum.GetName(typeof(StoreName), id.StoreName); List <byte> bytes = new List <byte>(); // Decode the hex string of the certificate hash into bytes for (int i = 0; i < id.Thumbprint.Length; i += 2) { bytes.Add(Convert.ToByte(id.Thumbprint.Substring(i, 2), 16)); } hashBytes = bytes.ToArray(); } // Create binding Binding newBinding = site.Bindings.CreateElement(); // If format of the information is incorrect throws ArgumentException but does not populate ParamName newBinding.BindingInformation = $"{ipAddress}:{port}:{hostname}"; newBinding.Protocol = isHttps.Value ? "https" : "http"; // Attempting to get or set the certificate hash when the protocol is not https will raise an error -msdn if (isHttps.Value) { // The specified certificate must be in the store with a private key or else there will be an exception when we commit newBinding.CertificateHash = hashBytes; newBinding.CertificateStoreName = certificateStoreName; } // Add to bindings list newBindings.Add(newBinding); } // All bindings have been verified and added to the list // Clear the old list, and add the new site.Bindings.Clear(); newBindings.ForEach(binding => site.Bindings.Add(binding)); } // Set the app pool if (model.application_pool != null) { // Extract the uuid from the application_pool object provided in model string appPoolUuid = DynamicHelper.Value(model.application_pool.id); // It is an error to provide an application pool object without specifying its id property if (appPoolUuid == null) { throw new ApiArgumentException("application_pool.id"); } // Create application pool id object from uuid provided, use this to obtain the application pool AppPools.AppPoolId appPoolId = AppPoolId.CreateFromUuid(appPoolUuid); ApplicationPool pool = AppPoolHelper.GetAppPool(appPoolId.Name); Application rootApp = site.Applications["/"]; if (rootApp == null) { throw new ApiArgumentException("application_pool", "Root application does not exist."); } // REVIEW: Should we create the root application if it doesn't exist and they specify an application pool? // We decided not to do this for physical_path. // Application pool for a site is extracted from the site's root application rootApp.ApplicationPoolName = pool.Name; } return(site); }
internal static object ToJsonModel(Application app, Site site, Fields fields = null, bool full = true) { if (app == null) { return(null); } if (site == null) { throw new ArgumentNullException("site"); } if (fields == null) { fields = Fields.All; } dynamic obj = new ExpandoObject(); // location if (fields.Exists("location")) { obj.location = $"{site.Name}{app.Path}"; } // // path if (fields.Exists("path")) { obj.path = app.Path; } // // id obj.id = new ApplicationId(app.Path, site.Id).Uuid; // // physical_path if (fields.Exists("physical_path")) { // Obtain path from the root vdir VirtualDirectory vdir = app.VirtualDirectories["/"]; if (vdir != null) { obj.physical_path = vdir.PhysicalPath; } } // // enabled_protocols if (fields.Exists("enabled_protocols")) { obj.enabled_protocols = app.EnabledProtocols; } // website if (fields.Exists("website")) { obj.website = SiteHelper.ToJsonModelRef(site, fields.Filter("website")); } // // application_pool if (fields.Exists("application_pool")) { ApplicationPool pool = AppPoolHelper.GetAppPool(app.ApplicationPoolName); obj.application_pool = pool != null?AppPoolHelper.ToJsonModelRef(pool, fields.Filter("application_pool")) : null; } return(Core.Environment.Hal.Apply(Defines.Resource.Guid, obj, full)); }
private static void SetApplication(Application app, dynamic model, IFileProvider fileProvider) { string path = DynamicHelper.Value(model.path); if (!string.IsNullOrEmpty(path)) { // Make sure path starts with '/' if (path[0] != '/') { path = '/' + path; } app.Path = path; } DynamicHelper.If((object)model.enabled_protocols, v => app.EnabledProtocols = v); string physicalPath = DynamicHelper.Value(model.physical_path); if (physicalPath != null) { physicalPath = physicalPath.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar); var expanded = System.Environment.ExpandEnvironmentVariables(physicalPath); if (!PathUtil.IsFullPath(expanded)) { throw new ApiArgumentException("physical_path"); } if (!fileProvider.IsAccessAllowed(expanded, FileAccess.Read)) { throw new ForbiddenArgumentException("physical_path", physicalPath); } if (!Directory.Exists(expanded)) { throw new NotFoundException("physical_path"); } var rootVDir = app.VirtualDirectories["/"]; if (rootVDir != null) { rootVDir.PhysicalPath = physicalPath; } } if (model.application_pool != null) { // Change application pool if (model.application_pool.id == null) { throw new ApiArgumentException("application_pool.id"); } string poolName = AppPools.AppPoolId.CreateFromUuid(DynamicHelper.Value(model.application_pool.id)).Name; ApplicationPool pool = AppPoolHelper.GetAppPool(poolName); if (pool != null) { app.ApplicationPoolName = pool.Name; } } }