public async Task <ResourceGroup> ActivateVSCodeLinuxResource(BaseTemplate template, TryWebsitesIdentity userIdentity, string anonymousUserName)
        {
            return(await ActivateResourceGroup(userIdentity, AppService.VSCodeLinux, DeploymentType.CsmDeploy, async (resourceGroup, inProgressOperation) =>
            {
                SimpleTrace.TraceInformation("{0}; {1}; {2}; {3}; {4}",
                                             AnalyticsEvents.OldUserCreatedSiteWithLanguageAndTemplateName, "VSCodeLinux", template.Name, resourceGroup.ResourceUniqueId, AppService.VSCodeLinux.ToString());

                var site = resourceGroup.Sites.First(s => s.IsSimpleWAWSOriginalSite);
                //if (template.Name.Equals(Constants.NodejsVSCodeWebAppLinuxTemplateName, StringComparison.OrdinalIgnoreCase))
                //{
                await Util.AddTimeStampFile(site);
                var lsm = new LinuxSiteManager.Client.LinuxSiteManager(retryCount: 2);
                Task checkSite = lsm.CheckTimeStampMetaDataDeploymentStatusAsync(site.Url);
                try
                {
                    await checkSite;
                    SimpleTrace.TraceError("Forcing retry");
                }
                catch (Exception ex)
                {
                    //TODO: Alert on this specifically after we add parsing logic
                    SimpleTrace.TraceError("New TimeStamp wasnt deployed" + ex.Message + ex.StackTrace);
                }
                //}
                //else
                //{
                //    await Util.DeployVSCodeLinuxTemplateToSite(template, site, addTimeStampFile:true);
                //}
                return resourceGroup;
            }, template.Name));
        }
Example #2
0
        internal static async Task <bool> PingTillStatusCode(string path, HttpStatusCode statusCode, int tries, int retryInterval)
        {
            var trial = 0;

            while (trial++ < tries)
            {
                await Task.Delay(new TimeSpan(0, 0, 0, retryInterval, 0));

                try
                {
                    using (var httpClient = new HttpClient())
                    {
                        using (var request = new HttpRequestMessage())
                        {
                            request.Method     = HttpMethod.Get;
                            request.RequestUri = new Uri($"http://{path}", UriKind.Absolute);
                            var response = await httpClient.SendAsync(request);

                            if (response.StatusCode == statusCode)
                            {
                                await response.Content.ReadAsStringAsync();

                                SimpleTrace.TraceInformation($"Found StatusCode {statusCode.ToString()} at {path} after {trial} trial of {tries}");
                                return(true);
                            }
                        }
                    }
                } catch (Exception ex)
                {
                    SimpleTrace.TraceError($"Error pinging {path} on {trial} of {tries}-> {ex.Message} -> {ex.StackTrace}");
                }
            }
            SimpleTrace.TraceInformation($"Didnt get StatusCode {statusCode.ToString()} at {path} after {tries} ");
            return(false);
        }
Example #3
0
        public async Task <HttpResponseMessage> GetVSCodeResource()
        {
            try
            {
                var resourceManager = await ResourcesManager.GetInstanceAsync();

                SimpleTrace.TraceInformation($"GetVSCodeResource called with text loginSessionCookie:{Uri.UnescapeDataString(HttpContext.Current.Request.Cookies[AuthConstants.LoginSessionCookie].Value)}");

                var loginSessionCookie = Uri.UnescapeDataString(HttpContext.Current.Request.Cookies[AuthConstants.LoginSessionCookie].Value);
                SimpleTrace.TraceInformation($"GetVSCodeResource called with loginSessionCookie:{loginSessionCookie}");
                {
                    var resourceGroup = (await resourceManager.GetAllInUseResourceGroups()).First(a => a.UIResource.LoginSession.Equals(loginSessionCookie, StringComparison.InvariantCultureIgnoreCase));
                    var returning     = resourceGroup == null ? null : resourceGroup.UIResource;
                    try
                    {
                        SimpleTrace.TraceInformation($"GET Resource. Returning { returning?.SiteName } with template { returning?.TemplateName } for user { ((TryWebsitesIdentity)(HttpContext.Current.User.Identity)).FilteredName}");
                    }
                    catch (Exception ex)
                    {
                        SimpleTrace.TraceError($"Error Logging Get Information: {ex.Message} -> {ex.StackTrace}");
                    }
                    return(Request.CreateResponse(HttpStatusCode.OK, returning));
                }
            }
            catch (Exception ex) {
                return(Request.CreateResponse(HttpStatusCode.InternalServerError, $"key:{Uri.UnescapeDataString(HttpContext.Current.Request.Cookies[AuthConstants.LoginSessionCookie].Value)}. {ex.ToString()}"));
            }
        }
 public async Task DeleteResourceGroup(ResourceGroup resourceGroup)
 {
     ///TODO: Add checks to ensure this is being called only if there RG has expired
     if ((await StorageHelper.UnAssignResourceGroup(resourceGroup.UserId)))
     {
         SimpleTrace.TraceInformation("resourcegroup removed for user {0}", resourceGroup.UserId);
     }
     else
     {
         SimpleTrace.TraceError("No resourcegroup checked out for {0}", resourceGroup.UserId);
     }
 }
Example #5
0
        public static async Task DeployLinuxTemplateToSite(BaseTemplate template, Site site)
        {
            if (template?.MSDeployPackageUrl != null)
            {
                try
                {
                    var  credentials        = new NetworkCredential(site.PublishingUserName, site.PublishingPassword);
                    var  zipManager         = new RemoteZipManager(site.ScmUrl + "zip/", credentials, retryCount: 3);
                    Task zipUpload          = zipManager.PutZipFileAsync("site/wwwroot", template.MSDeployPackageUrl);
                    var  vfsManager         = new RemoteVfsManager(site.ScmUrl + "vfs/", credentials, retryCount: 3);
                    Task deleteHostingStart = vfsManager.Delete("site/wwwroot/hostingstart.html");

                    await Task.WhenAll(zipUpload);

                    if (template.Name.Equals(Constants.PHPWebAppLinuxTemplateName, StringComparison.OrdinalIgnoreCase))
                    {
                        await site.UpdateConfig(
                            new
                        {
                            properties = new
                            {
                                linuxFxVersion     = "PHP|7.2",
                                appCommandLine     = "process.json",
                                alwaysOn           = true,
                                httpLoggingEnabled = true
                            }
                        });
                    }
                    else
                    {
                        await site.UpdateConfig(
                            new
                        {
                            properties = new
                            {
                                linuxFxVersion     = "NODE|9.4",
                                appCommandLine     = "process.json",
                                alwaysOn           = true,
                                httpLoggingEnabled = true
                            }
                        });
                    }
                }
                catch (Exception ex)
                {
                    SimpleTrace.TraceError(ex.Message + ex.StackTrace);
                }
            }
        }
        static async Task <string> HandleOAuthError(HttpResponseMessage response, string requestUri)
        {
            if ((int)response.StatusCode >= 400 && (int)response.StatusCode < 500)
            {
                var error = await response.Content.ReadAsAsync <AADOAuth2Error>();

                if (error != null && !String.IsNullOrEmpty(error.error_description))
                {
                    SimpleTrace.TraceError((String.Format("AUTH POST failed with {0}  POST {1}", response.StatusCode, requestUri)));
                    return(null);
                }
            }
            SimpleTrace.TraceError((String.Format("AUTH POST failed with {0}  POST {1}", response.StatusCode, requestUri)));
            return(null);
        }
        public static IEnumerable <SecurityToken> GetIssuerSigningKeys(string jwt)
        {
            var signingKey = GetSigningKeyFromJWT(jwt);

            if (SigningKeyMap.ContainsKey(signingKey))
            {
                return(SigningKeyMap[signingKey]);
            }
            UpdateKeysMap();
            if (!SigningKeyMap.ContainsKey(signingKey))
            {
                SimpleTrace.TraceError("Unknown signing cert from issuer");
                throw new Exception("Unknown signing cert from issuer");
            }
            return(SigningKeyMap[signingKey]);
        }
Example #8
0
        public async Task <HttpResponseMessage> GetResource()
        {
            var resourceManager = await ResourcesManager.GetInstanceAsync();

            var resourceGroup = await resourceManager.GetResourceGroup(HttpContext.Current.User.Identity.Name);

            var returning = resourceGroup == null ? null : resourceGroup.UIResource;

            try
            {
                SimpleTrace.TraceInformation($"GET Resource. Returning { returning?.SiteName } with template { returning?.TemplateName } for user { ((TryWebsitesIdentity)(HttpContext.Current.User.Identity)).FilteredName}");
            }
            catch (Exception ex)
            {
                SimpleTrace.TraceError($"Error Logging Get Information: {ex.Message} -> {ex.StackTrace}");
            }
            return(Request.CreateResponse(HttpStatusCode.OK, returning));
        }
        public static async Task StartSite(this Site site)
        {
            var csmResponse = await GetClient(site.SubscriptionType).HttpInvoke(HttpMethod.Post, ArmUriTemplates.SiteStart.Bind(site), new { });

            try
            {
                await csmResponse.EnsureSuccessStatusCodeWithFullError();
            }
            catch (Exception ex)
            {
                var message = $"Error Starting site via ARM {site.SiteName} -> {site.ResourceGroupName} -> {site.SubscriptionId} : {ex.Message} -> {ex.StackTrace}";
                SimpleTrace.TraceError(message);
                throw new SiteStartStopFailedException(message);
            }
            if (!await Util.PingTillStatusCode(site.HostName, HttpStatusCode.OK, 35, 5))
            {
                var message = $"Error Pinging site after start {site.SiteName} -> {site.ResourceGroupName} -> {site.SubscriptionId}";
                SimpleTrace.TraceError(message);
                throw new SiteStartStopFailedException(message);
            }
        }
Example #10
0
        public async Task <ResourceGroup> ActivateLinuxResource(LinuxTemplate template, TryWebsitesIdentity userIdentity, string anonymousUserName)
        {
            return(await ActivateResourceGroup(userIdentity, AppService.Web, true, DeploymentType.CsmDeploy, async (resourceGroup, inProgressOperation) =>
            {
                SimpleTrace.TraceInformation("{0}; {1}; {2}; {3}; {4}",
                                             AnalyticsEvents.OldUserCreatedSiteWithLanguageAndTemplateName, "Linux", template.Name, resourceGroup.ResourceUniqueId, AppService.Web.ToString());

                var site = resourceGroup.Sites.First(s => s.IsSimpleWAWSOriginalSite);
                resourceGroup.Tags[Constants.TemplateName] = template.Name;
                resourceGroup = await resourceGroup.Update();

                if (template?.MSDeployPackageUrl != null)
                {
                    try
                    {
                        var credentials = new NetworkCredential(site.PublishingUserName, site.PublishingPassword);
                        var zipManager = new RemoteZipManager(site.ScmUrl + "zip/", credentials, retryCount: 3);
                        Task zipUpload = zipManager.PutZipFileAsync("site/wwwroot", template.MSDeployPackageUrl);
                        var vfsManager = new RemoteVfsManager(site.ScmUrl + "vfs/", credentials, retryCount: 3);
                        Task deleteHostingStart = vfsManager.Delete("site/wwwroot/hostingstart.html");
                        await Task.WhenAll(zipUpload, deleteHostingStart);
                    }
                    catch (Exception ex)
                    {
                        SimpleTrace.TraceError(ex.Message + ex.StackTrace);
                    }
                }
                if (template.Name.Equals(Constants.NodeJSWebAppLinuxTemplateName, StringComparison.OrdinalIgnoreCase))
                {
                    await site.UpdateConfig(new { properties = new { linuxFxVersion = "NODE|6.10", appCommandLine = "process.json" } });
                }
                Util.FireAndForget($"{resourceGroup.Sites.FirstOrDefault().HostName}");
                Util.FireAndForget($"{resourceGroup.Sites.FirstOrDefault().ScmHostName}");

                var rbacTask = resourceGroup.AddResourceGroupRbac(userIdentity.Puid, userIdentity.Email);
                resourceGroup.IsRbacEnabled = await rbacTask;
                return resourceGroup;
            }));
        }
Example #11
0
        public static async Task DeployVSCodeLinuxTemplateToSite(BaseTemplate template, Site site)
        {
            SimpleTrace.TraceInformation($"Site ZipDeploy started: for {template?.MSDeployPackageUrl} on {site.SiteName}->{site.ResourceGroupName}->{site.SubscriptionId}");
            if (template?.MSDeployPackageUrl != null)
            {
                try
                {
                    var        credentials     = new NetworkCredential(site.PublishingUserName, site.PublishingPassword);
                    var        zipManager      = new RemoteZipManager(site.ScmUrl + "api/zipdeploy?isAsync=true", credentials, retryCount: 3);
                    Task <Uri> zipUpload       = zipManager.PostZipFileAsync("", template.MSDeployPackageUrl);
                    var        deploystatusurl = await zipUpload;

                    SimpleTrace.TraceInformation($"Site ZipDeployed: StatusUrl: {deploystatusurl} for {template?.MSDeployPackageUrl} on {site.SiteName}->{site.ResourceGroupName}->{site.SubscriptionId}");

                    var deploycheck      = 0;
                    var deploycheckTimes = 150;
                    while (deploycheck++ < deploycheckTimes)
                    {
                        try
                        {
                            await Task.Delay(10 * 1000);

                            var url        = site.MonacoUrl.Replace(@"/basicauth", deploystatusurl.PathAndQuery);
                            var httpClient = (HttpWebRequest)WebRequest.Create(url);
                            {
                                var creds          = $"{site.PublishingUserName }:{ site.PublishingPassword}";
                                var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(creds);
                                var credsbase64    = System.Convert.ToBase64String(plainTextBytes);
                                httpClient.Headers.Add($"Authorization: Basic {credsbase64}");
                                using (var response = await httpClient.GetResponseAsync())
                                {
                                    using (var content = new StreamReader(response.GetResponseStream()))
                                    {
                                        var message = Newtonsoft.Json.Linq.JObject.Parse(content.ReadToEnd());
                                        if ((bool)message["complete"] == false)
                                        {
                                            var failed = $"Zip Deployment going on: StatusUrl: {deploystatusurl} -{JsonConvert.SerializeObject(message)} for {template?.MSDeployPackageUrl} on {site.SiteName}->{site.ResourceGroupName}->{site.SubscriptionId}";
                                            SimpleTrace.TraceInformation(failed);
                                            File.AppendAllLines(HostingEnvironment.MapPath(string.Format(CultureInfo.InvariantCulture, "~/App_data/filestatus.txt")), new string [] { failed });
                                        }
                                        else
                                        {
                                            var success = ($"Zip Deployment completed: StatusUrl: {deploystatusurl} -{JsonConvert.SerializeObject(message)} for {template?.MSDeployPackageUrl} on {site.SiteName}->{site.ResourceGroupName}->{site.SubscriptionId}");
                                            SimpleTrace.TraceInformation(success);
                                            File.AppendAllLines(HostingEnvironment.MapPath(string.Format(CultureInfo.InvariantCulture, "~/App_data/filestatus.txt")), new string[] { success });

                                            break;
                                        }
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            var exception = ($"Ping post ZipDeployed: StatusUrl: {deploystatusurl} for {template?.MSDeployPackageUrl} on {site.SiteName}->{site.ResourceGroupName}->{site.SubscriptionId} -> {ex.Message}->{ex.StackTrace}s");
                            SimpleTrace.TraceError(exception);
                            File.AppendAllLines(HostingEnvironment.MapPath(string.Format(CultureInfo.InvariantCulture, "~/App_data/filestatus.txt")), new string[] { exception });
                        }
                    }

                    File.AppendAllLines(HostingEnvironment.MapPath(string.Format(CultureInfo.InvariantCulture, "~/App_data/filestatus.txt")), new string[] { "Starting hostingstart file delete" });
                    var vfsManager = new RemoteVfsManager(site.ScmUrl + "vfs/", credentials, retryCount: 3);

                    Task deleteHostingStart = vfsManager.Delete("site/wwwroot/hostingstart.html");

                    List <Task> taskList = new List <Task>();
                    //taskList.Add(zipUpload);
                    taskList.Add(deleteHostingStart);
                    //if (template.Name == Constants.ReactVSCodeWebAppLinuxTemplateName)
                    //{
                    //    Task uploaddeploymentfile = vfsManager.Put("site/wwwroot/deploy.sh", (template?.MSDeployPackageUrl.Replace("ReactVSCodeWebApp.zip", "deploy.sh")));
                    //    Task uploaddeploysh = vfsManager.Put("site/wwwroot/.deployment", (template?.MSDeployPackageUrl.Replace("ReactVSCodeWebApp.zip", ".deployment")));
                    //    taskList.Add(uploaddeploymentfile);
                    //    taskList.Add(uploaddeploysh);
                    //}
                    //if (addTimeStampFile)
                    //{
                    //    SimpleTrace.TraceInformation($"Adding TimeStamp File started: for {site.SiteName}->{site.ResourceGroupName}->{site.SubscriptionId}");
                    //    Task timeStampAdd = AddTimeStampFile(site, "");
                    //    taskList.Add(timeStampAdd);
                    //}
                    await Task.WhenAll(taskList.ToArray());

                    SimpleTrace.TraceInformation($"Site ZipDeploy and Delete HostingStart completed: for {site.SiteName}->{site.ResourceGroupName}->{site.SubscriptionId}");
                    File.AppendAllLines(HostingEnvironment.MapPath(string.Format(CultureInfo.InvariantCulture, "~/App_data/filestatus.txt")), new string[] { "Starting hostingstart file delete" });
                    await Task.Delay(10 * 1000);
                }
                catch (Exception ex)
                {
                    var message = "New Site wasnt deployed: " + ex.Message + ex.StackTrace;
                    SimpleTrace.TraceError(message);
                    throw new ZipDeploymentFailedException(message);
                }
            }
            else
            {
                SimpleTrace.TraceError("New Site wasnt deployed: MsDeployPackageUrl wasnt set");
            }
        }
        private static async Task <Site> CreateVSCodeLinuxSite(ResourceGroup resourceGroup, Func <string> nameGenerator, string siteKind = null)
        {
            var jsonSettings = new JsonSerializerSettings {
                NullValueHandling = NullValueHandling.Ignore
            };
            var site = new Site(resourceGroup.SubscriptionId, resourceGroup.ResourceGroupName, nameGenerator(), siteKind);
            var csmTemplateString = string.Empty;
            var template          = TemplatesManager.GetTemplates().FirstOrDefault(t => t.Name == resourceGroup.TemplateName);

            SimpleTrace.TraceInformation($"Deploying {template.Name} to {site.SiteName}->{resourceGroup.ResourceGroupName}->{resourceGroup.SubscriptionId}");

            csmTemplateString = await GetConfig(template.ARMTemplateLink);

            csmTemplateString = csmTemplateString
                                .Replace("{{appServiceName}}", site.SiteName)
                                .Replace("{{msdeployPackageUrl}}", template.MSDeployPackageUrl)
                                .Replace("{{serverFarmType}}", SimpleSettings.ServerFarmTypeContent)
                                .Replace("{{tryAppserviceUrl}}", SimpleSettings.TryAppServiceSite);

            var inProgressOperation = new InProgressOperation(resourceGroup, DeploymentType.CsmDeploy);
            var token = await inProgressOperation.CreateDeployment(JsonConvert.DeserializeObject <JToken>(csmTemplateString), block : true, subscriptionType : resourceGroup.SubscriptionType);

            SimpleTrace.TraceInformation($"ARM Deployment result: {JsonConvert.SerializeObject(token)} to {site.SiteName}->{resourceGroup.ResourceGroupName}->{resourceGroup.SubscriptionId}");
            var csmSiteResponse =
                await
                GetClient(resourceGroup.SubscriptionType).HttpInvoke(HttpMethod.Get, ArmUriTemplates.SiteCreate.Bind(site));

            await csmSiteResponse.EnsureSuccessStatusCodeWithFullError();

            var csmSite = await csmSiteResponse.Content.ReadAsAsync <CsmWrapper <CsmSite> >();

            await Load(site, csmSite);

            SimpleTrace.TraceInformation($"Site Loaded from ARM : {JsonConvert.SerializeObject(site)} to {site.SiteName}->{resourceGroup.ResourceGroupName}->{resourceGroup.SubscriptionId}");

            var siteguid = await Util.UpdatePostDeployAppSettings(site);

            SimpleTrace.TraceInformation($"Site AppSettings Updated:  for {site.SiteName}->{resourceGroup.ResourceGroupName}->{resourceGroup.SubscriptionId}");

            if (resourceGroup.AppService == AppService.VSCodeLinux)
            {
                await Task.Delay(30 * 1000);

                try
                {
                    var lsm = new LinuxSiteManager.Client.LinuxSiteManager(retryCount: 30);
                    await lsm.CheckSiteDeploymentStatusAsync(site.HttpUrl);
                }
                catch (Exception ex)
                {
                    SimpleTrace.TraceError($"Unable to ping deployed site {site.HostName}. Continuing regardless {ex.Message}->{ex.StackTrace} ");
                }
            }
            if (!resourceGroup.Tags.ContainsKey(Constants.TemplateName))
            {
                resourceGroup.Tags.Add(Constants.TemplateName, resourceGroup.TemplateName);
            }
            if (resourceGroup.SubscriptionType == SubscriptionType.AppService)
            {
                if (template != null && template.FileName != null)
                {
                    var  credentials       = new NetworkCredential(site.PublishingUserName, site.PublishingPassword);
                    var  vfsSCMManager     = new RemoteVfsManager(site.ScmUrl + "vfs/", credentials, retryCount: 3);
                    Task scmRedirectUpload = vfsSCMManager.Put("site/applicationHost.xdt", Path.Combine(HostingEnvironment.MapPath(@"~/App_Data"), "applicationHost.xdt"));
                    var  vfsManager        = new RemoteVfsManager(site.ScmUrl + "vfs/", credentials, retryCount: 3);

                    await Task.WhenAll(scmRedirectUpload);
                }
            }
            if (template.Name.Equals("WordPress", StringComparison.OrdinalIgnoreCase))
            {
                await site.UpdateConfig(new { properties = new { scmType = "LocalGit", httpLoggingEnabled = true, localMySqlEnabled = true } });
            }
            resourceGroup.Tags[Constants.TemplateName] = template.Name;
            site.SubscriptionId = resourceGroup.SubscriptionId;
            //site.AppSettings = new Dictionary<string, string>();
            resourceGroup.Tags.Add(Constants.SiteGuid, siteguid);

            await Task.WhenAll(resourceGroup.Update());

            SimpleTrace.TraceInformation($"ResourceGroup Templates Tag Updated: with SiteGuid: {siteguid} for {site.SiteName} ->{resourceGroup.ResourceGroupName}->{resourceGroup.SubscriptionId}");
            return(site);
        }
        private static async Task <Site> CreateVSCodeLinuxSite(ResourceGroup resourceGroup, Func <string> nameGenerator, string siteKind = null)
        {
            var jsonSettings = new JsonSerializerSettings {
                NullValueHandling = NullValueHandling.Ignore
            };
            var site = new Site(resourceGroup.SubscriptionId, resourceGroup.ResourceGroupName, nameGenerator(), siteKind);
            var csmTemplateString = string.Empty;
            var template          = TemplatesManager.GetTemplates().FirstOrDefault(t => t.Name == resourceGroup.TemplateName) as VSCodeLinuxTemplate;

            SimpleTrace.TraceInformation($"Deploying {template.Name} to {site.SiteName}->{resourceGroup.ResourceGroupName}->{resourceGroup.SubscriptionId}");

            using (var reader = new StreamReader(template.CsmTemplateFilePath))
            {
                csmTemplateString = await reader.ReadToEndAsync();
            }

            csmTemplateString = csmTemplateString
                                .Replace("{{siteName}}", site.SiteName)
                                .Replace("{{aspName}}", site.SiteName + "-plan")
                                .Replace("{{vmLocation}}", resourceGroup.GeoRegion);
            var inProgressOperation = new InProgressOperation(resourceGroup, DeploymentType.CsmDeploy);
            var token = await inProgressOperation.CreateDeployment(JsonConvert.DeserializeObject <JToken>(csmTemplateString), block : true, subscriptionType : resourceGroup.SubscriptionType);

            SimpleTrace.TraceInformation($"ARM Deployment result: {JsonConvert.SerializeObject(token)} to {site.SiteName}->{resourceGroup.ResourceGroupName}->{resourceGroup.SubscriptionId}");
            await Load(site, null);

            SimpleTrace.TraceInformation($"Site Loaded from ARM : {JsonConvert.SerializeObject(site)} to {site.SiteName}->{resourceGroup.ResourceGroupName}->{resourceGroup.SubscriptionId}");

            await Util.UpdateVSCodeLinuxAppSettings(site);

            SimpleTrace.TraceInformation($"Site AppSettings Updated:  for {site.SiteName}->{resourceGroup.ResourceGroupName}->{resourceGroup.SubscriptionId}");

            //await site.StopSite();
            await Util.DeployVSCodeLinuxTemplateToSite(template, site, false);

            //await site.StartSite();

            var  lsm       = new LinuxSiteManager.Client.LinuxSiteManager(retryCount: 6);
            Task checkSite = lsm.CheckSiteDeploymentStatusAsync(site.HttpUrl);

            try
            {
                await checkSite;
            }
            catch (Exception ex)
            {
                //TODO: Alert on this specifically
                var message = "New Site didnt come up after zip deploy: " + ex.Message + ex.StackTrace;
                SimpleTrace.TraceError(message);
                throw new ZipDeploymentFailedException(message);
            }

            SimpleTrace.TraceInformation($"Site Code Zip PUT and restart complete: {site.SiteName}->{resourceGroup.ResourceGroupName}->{resourceGroup.SubscriptionId}");
            if (!resourceGroup.Tags.ContainsKey(Constants.TemplateName))
            {
                resourceGroup.Tags.Add(Constants.TemplateName, resourceGroup.TemplateName);
                await resourceGroup.Update();

                SimpleTrace.TraceInformation($"ResourceGroup Templates Tag Updated: for {site.SiteName}->{resourceGroup.ResourceGroupName}->{resourceGroup.SubscriptionId}");
            }
            return(site);
        }
Example #14
0
        public async Task <HttpResponseMessage> CreateResource(BaseTemplate template)
        {
            try
            {
                var payload = JsonConvert.SerializeObject(template);
                SimpleTrace.TraceInformation($"CREATE {template?.AppService} : {payload}. Request Received");
            }
            catch (Exception ex)
            {
                SimpleTrace.TraceError($"Error Logging Create Start Information: {ex.Message} -> {ex.StackTrace}");
            }
            var tempTemplate = WebsiteTemplate.EmptySiteTemplate;

            if (template == null)
            {
                template = WebsiteTemplate.EmptySiteTemplate;
            }
            else if (template.AppService.Equals(AppService.Function))
            {
                tempTemplate = FunctionTemplate.DefaultFunctionTemplate(template.Name);
            }
            else if (template.AppService.Equals(AppService.Containers))
            {
                var containersTemplate = ContainersTemplate.DefaultContainersTemplate(template.Name);
                containersTemplate.DockerContainer = template.DockerContainer;
                tempTemplate = containersTemplate;
            }
            else if (template.Name != null && !template.Name.Equals("GitHub Repo") && !template.AppService.Equals(AppService.Function))
            {
                var temp = TemplatesManager.GetTemplates()
                           .FirstOrDefault(t => t.Name == template.Name);

                tempTemplate = WebsiteTemplate.DefaultTemplate(temp.Name, temp.AppService, temp.Language, temp.FileName, template.DockerContainer, temp.MSDeployPackageUrl);
            }
            else if (template.Name != null && template.Name.Equals("GitHub Repo"))
            {
                tempTemplate = new WebsiteTemplate
                {
                    AppService = AppService.Web,
                    GithubRepo = template.GithubRepo,
                    Name       = template.Name,
                    Language   = "GitHub"
                };
            }

            var identity          = HttpContext.Current.User.Identity as TryWebsitesIdentity;
            var anonymousUserName = SecurityManager.GetAnonymousUserName(new HttpContextWrapper(HttpContext.Current));

            try
            {
                var resourceManager = await ResourcesManager.GetInstanceAsync();

                if ((await resourceManager.GetResourceGroup(identity.Name)) != null)
                {
                    SimpleTrace.Diagnostics.Fatal(AnalyticsEvents.MoreThanOneError, 1);
                    //This should use the server version of the error, but due to a string bug they are not the same.
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, Resources.Client.Information_YouCantHaveMoreThanOne));
                }

                ResourceGroup resourceGroup = null;
                SimpleTrace.TraceInformation($"Searching for {tempTemplate?.AppService} {tempTemplate?.Name}.");
                switch (tempTemplate.AppService)
                {
                case AppService.Linux:
                    resourceGroup = await resourceManager.ActivateLinuxResource(tempTemplate, identity, anonymousUserName);

                    break;

                case AppService.VSCodeLinux:
                    resourceGroup = await resourceManager.ActivateVSCodeLinuxResource(tempTemplate, identity, anonymousUserName);

                    break;

                case AppService.Web:
                    resourceGroup = await resourceManager.ActivateWebApp(tempTemplate, identity, anonymousUserName);

                    break;

                case AppService.Api:
                    resourceGroup = await resourceManager.ActivateApiApp(tempTemplate, identity, anonymousUserName);

                    break;

                case AppService.Function:
                    resourceGroup = await resourceManager.ActivateFunctionApp(tempTemplate, identity, anonymousUserName);

                    break;

                case AppService.Containers:
                    resourceGroup = await resourceManager.ActivateContainersResource(tempTemplate, identity, anonymousUserName);

                    break;
                }
                try
                {
                    SimpleTrace.TraceInformation($"CREATE {template?.AppService}. Returning { GetUIResource(resourceGroup).SiteName } with template { GetUIResource(resourceGroup).TemplateName } for user {identity.FilteredName}");
                }
                catch (Exception ex)
                {
                    SimpleTrace.TraceError($"Error Logging Create End Information: {ex.Message} -> {ex.StackTrace}");
                }
                return(Request.CreateResponse(HttpStatusCode.OK, resourceGroup == null ? null : GetUIResource(resourceGroup)));
            }
            catch (Exception ex)
            {
                var message = ex is NullReferenceException ? Resources.Server.Error_GeneralErrorMessage : ex.Message;
                SimpleTrace.Diagnostics.Fatal(ex, AnalyticsEvents.UserGotError, message, Interlocked.Increment(ref _userGotErrorErrorCount));
                return(Request.CreateErrorResponse(HttpStatusCode.ServiceUnavailable, message));
            }
        }