public static JObject GetARMTemplate(BaseTemplate template)
        {
            //Using JObject.FromObject to deep clone the base ARM template for modifications
            //based on the requested website. Its needed since we dont want to make changes
            //to the main _baseARMTemplate. This is also thread safe.
            var armTemplate = JObject.FromObject(_baseARMTemplate);

            UpdateParameters(armTemplate, template as WebsiteTemplate);
            UpdateConfig(armTemplate, template as WebsiteTemplate);
            return(armTemplate);
        }
예제 #2
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);
                }
            }
        }
        public static string GetFullPath(this BaseTemplate value)
        {
            var language = value.Language ?? ((value.AppService == AppService.Api) ? "Api" : "Mobile");

            return(Path.Combine(TemplatesManager.TemplatesFolder, language, value.FileName));
        }
예제 #4
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");
            }
        }
        public async Task<HttpResponseMessage> CreateResource(BaseTemplate template)
        {
            if (template.Name != null && !template.Name.Equals("Github Repo"))
            {
                template = TemplatesManager.GetTemplates()
                    .FirstOrDefault(t => t.Name == template.Name && t.AppService == template.AppService);

                template = template ?? WebsiteTemplate.EmptySiteTemplate;
            }
            else if (template.Name != null && template.Name.Equals("Github Repo"))
            {
                template = 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, identity, 1);

                    return Request.CreateErrorResponse(HttpStatusCode.BadRequest, Resources.Server.Error_MoreThanOneFreeResource);
                }

                ResourceGroup resourceGroup = null;

                switch (template.AppService)
                {
                    case AppService.Web:
                        resourceGroup = await resourceManager.ActivateWebApp(template as WebsiteTemplate, identity, anonymousUserName);
                        break;
                    case AppService.Mobile:
                        resourceGroup = await resourceManager.ActivateMobileApp(template as WebsiteTemplate, identity, anonymousUserName);
                        break;
                    case AppService.Api:
                        if (identity.Issuer == "OrgId")
                        {
                            return Request.CreateErrorResponse(HttpStatusCode.BadRequest, Resources.Server.Error_OrgIdNotSupported);
                        }
                        else if (identity.Issuer != "MSA")
                        {
                            return SecurityManager.RedirectToAAD(template.CreateQueryString());
                        }
                        resourceGroup = await resourceManager.ActivateApiApp(template as ApiTemplate, identity, anonymousUserName);
                        break;
                    case AppService.Logic:
                        if (identity.Issuer == "OrgId")
                        {
                            return Request.CreateErrorResponse(HttpStatusCode.BadRequest, Resources.Server.Error_OrgIdNotSupported);
                        }
                        else if (identity.Issuer != "MSA")
                        {
                            return SecurityManager.RedirectToAAD(template.CreateQueryString());
                        }
                        resourceGroup = await resourceManager.ActivateLogicApp(template as LogicTemplate, identity, anonymousUserName);
                        break;
                }

                return Request.CreateResponse(HttpStatusCode.OK, resourceGroup == null ? null : resourceGroup.UIResource);
            }
            catch (Exception ex)
            {
                SimpleTrace.Diagnostics.Fatal(ex, AnalyticsEvents.UserGotError, identity, ex.Message, Interlocked.Increment(ref _userGotErrorErrorCount));
                return Request.CreateErrorResponse(HttpStatusCode.ServiceUnavailable, ex.Message);
            }
        }