//private static async Task<Site> CreateSite(ResourceGroup resourceGroup, Func<string> nameGenerator, string siteKind = null)
        //{
        //    var site = new Site(resourceGroup.SubscriptionId, resourceGroup.ResourceGroupName, nameGenerator(), siteKind);
        //    await resourceGroup.LoadServerFarms(serverFarms: null);
        //    var serverFarm = new ServerFarm(resourceGroup.SubscriptionId, resourceGroup.ResourceGroupName,
        //        Constants.DefaultServerFarmName, resourceGroup.GeoRegion);
        //    if (resourceGroup.ServerFarms.Count() < 1) {
        //        var csmServerFarmResponse =
        //            await
        //                GetClient(resourceGroup.SubscriptionType).HttpInvoke(HttpMethod.Put, ArmUriTemplates.ServerFarmCreate.Bind(serverFarm),
        //                    new
        //                    {
        //                        location = resourceGroup.GeoRegion,
        //                        kind = "app",
        //                        name = serverFarm.ServerFarmName,
        //                        sku= serverFarm.Sku,
        //                        properties = new
        //                        {
        //                            name = serverFarm.ServerFarmName,
        //                            workerSizeId=0,
        //                            numberOfWorkers= 0,
        //                            geoRegion=resourceGroup.GeoRegion,
        //                            kind="app"
        //                        }
        //                    });
        //        await csmServerFarmResponse.EnsureSuccessStatusCodeWithFullError();
        //    }

        //    var csmSiteResponse =
        //        await
        //            GetClient(resourceGroup.SubscriptionType).HttpInvoke(HttpMethod.Put, ArmUriTemplates.SiteCreate.Bind(site),
        //                new
        //                {
        //                    properties =
        //                        new
        //                        {
        //                            serverFarmId = serverFarm.CsmId
        //                        },
        //                    location = resourceGroup.GeoRegion,
        //                    kind = "app",
        //                    name = site.SiteName
        //                });
        //    await csmSiteResponse.EnsureSuccessStatusCodeWithFullError();
        //    var csmSite = await csmSiteResponse.Content.ReadAsAsync<CsmWrapper<CsmSite>>();

        //    return await Load(site, csmSite);
        //}

        private static async Task <Site> CreateLinuxSite(ResourceGroup resourceGroup, Func <string> nameGenerator, string siteKind = null)
        {
            var site = new Site(resourceGroup.SubscriptionId, resourceGroup.ResourceGroupName, nameGenerator(), siteKind);
            var csmTemplateString = string.Empty;
            var template          = TemplatesManager.GetTemplates().FirstOrDefault(t => t.Name == Constants.NodejsWebAppLinuxTemplateName) as LinuxTemplate;

            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)
                                .Replace("{{serverFarmType}}", SimpleSettings.ServerFarmTypeContent);
            var inProgressOperation = new InProgressOperation(resourceGroup, DeploymentType.CsmDeploy);
            await inProgressOperation.CreateDeployment(JsonConvert.DeserializeObject <JToken>(csmTemplateString), block : true, subscriptionType : resourceGroup.SubscriptionType);

            // Dont run this yet. Spot serverfarms clock will start
            //await Util.DeployLinuxTemplateToSite(template, site);

            if (!resourceGroup.Tags.ContainsKey(Constants.LinuxAppDeployed))
            {
                resourceGroup.Tags.Add(Constants.LinuxAppDeployed, "1");
                await resourceGroup.Update();
            }
            await Load(site, null);

            return(site);
        }
        public IEnumerable <BaseTemplate> Get()
        {
            var list = TemplatesManager.GetTemplates().ToList();

            list.Add(WebsiteTemplate.EmptySiteTemplate);
            return(list);
        }
Exemplo n.º 3
0
        public IEnumerable <BaseTemplate> Get()
        {
            var list = TemplatesManager.GetTemplates().ToList();

            list.ForEach(t =>
            {
                if (t.AppService == AppService.Logic)
                {
                    t.Description = Resources.Server.Templates_PingSiteDescription;
                }
                else if (t.AppService == AppService.Mobile)
                {
                    switch (t.Name)
                    {
                    case "Todo List":
                        t.Description = Resources.Server.Templates_TodoListDescription;
                        break;

                    case "Xamarin CRM":
                        t.Description = Resources.Server.Templates_XamarinCrmDescription;
                        break;

                    case "Field Engineer":
                        t.Description = Resources.Server.Templates_FieldEngineerDescription;
                        break;
                    }
                }
            });
            list.Add(WebsiteTemplate.EmptySiteTemplate);
            return(list);
        }
Exemplo n.º 4
0
        private void AddComboboxItems()
        {
            List <String> allTemplates = TemplatesManager.GetTemplates();

            templateCombo.Items.Clear();
            templateCombo.Text = "";
            foreach (String template in allTemplates)
            {
                templateCombo.Items.Add(template);
            }
            templateCombo.Text = allTemplates[0];
        }
Exemplo n.º 5
0
        public HttpResponseMessage GetARMTemplate(string templateName)
        {
            var list          = TemplatesManager.GetTemplates().ToList();
            var emptyTemplate = WebsiteTemplate.EmptySiteTemplate;

            emptyTemplate.MSDeployPackageUrl = $"{SimpleSettings.ZippedRepoUrl}/Default/{Uri.EscapeDataString((emptyTemplate.Name))}.zip";

            list.Add(emptyTemplate);

            var template = list.FirstOrDefault((temp) => string.Equals(temp.Name, templateName, StringComparison.OrdinalIgnoreCase));

            if (template != null)
            {
                var armTemplateJson = TemplatesManager.GetARMTemplate(template);
                return(Request.CreateResponse(HttpStatusCode.OK, armTemplateJson, new MediaTypeHeaderValue("application/json")));
            }
            else
            {
                return(new HttpResponseMessage(HttpStatusCode.NotFound));
            }
        }
        public async Task <HttpResponseMessage> CreateResource(BaseTemplate template)
        {
            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.GetContainersTemplate(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;

                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.Logic:
                    if (identity.Issuer == "OrgId")
                    {
                        return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, Resources.Server.Error_OrgIdNotSupported));
                    }
                    else if (identity.Issuer != "MSA")
                    {
                        return(SecurityManager.RedirectToAAD(tempTemplate.CreateQueryString()));
                    }
                    resourceGroup = await resourceManager.ActivateLogicApp(tempTemplate, identity, anonymousUserName);

                    break;

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

                    break;

                case AppService.Containers:
                    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.ActivateContainersResource(tempTemplate as ContainersTemplate, identity, anonymousUserName);

                    break;

                case AppService.MonitoringTools:
                    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.ActivateMonitoringToolsApp(tempTemplate as MonitoringToolsTemplate, identity, anonymousUserName);

                    break;
                }
                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));
            }
        }
Exemplo n.º 7
0
        public IEnumerable <BaseTemplate> Get()
        {
            var list = TemplatesManager.GetTemplates().ToList();

            return(list);
        }
        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);
        }
        internal async Task CleanupSubscriptions()
        {
            try
            {
                _cleanupOperationsTriggered++;
                var subscriptions = await CsmManager.GetSubscriptions();

                Stopwatch sw = new Stopwatch();
                sw.Start();

                //Delete any duplicate resourcegroups in same subscription loaded in the same region
                //or create any missing resourcegroups in a region
                List <ResourceGroup> toDelete = new List <ResourceGroup>();
                List <ResourceGroup> ready    = new List <ResourceGroup>();

                var deletedDuplicateRGs     = 0;
                var createdMissingRGs       = 0;
                var createdMissingTemplates = 0;
                foreach (var subscription in subscriptions)
                {
                    var sub = new Subscription(subscription);
                    await sub.Load();

                    //sub.ResourceGroups = (await LoadedResourceGroups()).Where(r => r.SubscriptionId == sub.SubscriptionId);
                    var trialsubresult = sub.GetSubscriptionStats();
                    toDelete.AddRange(trialsubresult.ToDelete);
                    ready.AddRange(trialsubresult.Ready);
                }

                var rand = new Random();
                foreach (var resourceGroup in toDelete)
                {
                    //RemoveFromFreeResourcesQueue(resourceGroup);
                    DeleteResourceGroupOperation(resourceGroup);
                    deletedDuplicateRGs++;
                }
                foreach (var template in TemplatesManager.GetTemplates().Where(a => a.QueueSizeToMaintain > 0))
                {
                    var deployedTemplates = ready.Count(a => a.DeployedTemplateName == template.Name);
                    var delta             = template.QueueSizeToMaintain - deployedTemplates;
                    SimpleTrace.TraceInformation($"Template {template.Name} has {deployedTemplates} RGs deployed and requires {template.QueueSizeToMaintain}");

                    for (int i = 1; i <= delta; i++)
                    {
                        SimpleTrace.TraceInformation($"Template {template.Name} creating {i} of {delta}");
                        CreateResourceGroupOperation(template.Config.Subscriptions.OrderBy(a => Guid.NewGuid()).First(), template.Config.Regions.OrderBy(a => Guid.NewGuid()).First(), template.Name);
                        createdMissingTemplates++;
                    }
                    for (int i = 1; i <= -delta; i++)
                    {
                        var resourceGroup = await StorageHelper.GetQueueMessage(template.QueueName);

                        if (resourceGroup != null)
                        {
                            SimpleTrace.TraceInformation($"Template {template.Name} deleting {i} of {-delta}->{resourceGroup.CsmId}");
                            //RemoveFromFreeResourcesQueue(resourceGroup);
                            DeleteResourceGroupOperation(resourceGroup);
                        }
                    }
                }
                AppInsights.TelemetryClient.TrackMetric("createdMissingTemplates", createdMissingTemplates);
                AppInsights.TelemetryClient.TrackMetric("createdMissingRGs", createdMissingRGs);
                AppInsights.TelemetryClient.TrackMetric("deletedDuplicateRGs", deletedDuplicateRGs);
                AppInsights.TelemetryClient.TrackMetric("fullCleanupTime", sw.Elapsed.TotalSeconds);
                sw.Stop();
            }
            catch (Exception e)
            {
                SimpleTrace.Diagnostics.Fatal(e, "CleanupSubscriptions error, Count {Count}", Interlocked.Increment(ref _maintainResourceGroupListErrorCount));
            }
        }
        // ARM
        public async Task <ResourceGroup> ActivateLogicApp(BaseTemplate template, TryWebsitesIdentity userIdentity, string anonymousUserName)
        {
            return(await ActivateResourceGroup(userIdentity, AppService.Logic, DeploymentType.CsmDeploy, async (resourceGroup, inProgressOperation) =>
            {
                SimpleTrace.TraceInformation("{0}; {1}; {2}; {3}; {4}",
                                             AnalyticsEvents.OldUserCreatedSiteWithLanguageAndTemplateName, "Logic", template.Name, resourceGroup.ResourceUniqueId, AppService.Logic.ToString());

                var logicApp = new LogicApp(resourceGroup.SubscriptionId, resourceGroup.ResourceGroupName, Guid.NewGuid().ToString().Replace("-", ""))
                {
                    Location = resourceGroup.GeoRegion
                };

                var csmTemplateString = string.Empty;

                using (var reader = new StreamReader(((SimpleWAWS.Models.LogicTemplate)(TemplatesManager.GetTemplates().FirstOrDefault((a) => a.AppService == AppService.Logic))).CsmTemplateFilePath))
                {
                    csmTemplateString = await reader.ReadToEndAsync();
                }

                csmTemplateString = csmTemplateString.Replace("{{logicAppName}}", logicApp.LogicAppName);
                //csmTemplateString = csmTemplateString.Replace("{{gatewayName}}", Guid.NewGuid().ToString().Replace("-", "")).Replace("{{logicAppName}}", logicApp.LogicAppName);

                await inProgressOperation.CreateDeployment(JsonConvert.DeserializeObject <JToken>(csmTemplateString), block: true, subscriptionType: resourceGroup.SubscriptionType);

                // After a deployment, we have no idea what changes happened in the resource group
                // we should reload it.
                // TODO: consider reloading the resourceGroup along with the deployment itself.
                await resourceGroup.Load();

                var rbacTask = resourceGroup.AddResourceGroupRbac(userIdentity.Puid, userIdentity.Email);
                resourceGroup.IsRbacEnabled = await rbacTask;
                return resourceGroup;
            }));
        }
        public static MakeSubscriptionFreeTrialResult MakeTrialSubscription(this Subscription subscription)
        {
            var result = new MakeSubscriptionFreeTrialResult();

            if (subscription.Type != SubscriptionType.VSCodeLinux)
            {
                result.ToCreateTemplates = new List <TemplateStats>();
                result.ToCreateInRegions = subscription.GeoRegions
                                           .Where(g => !subscription.ResourceGroups
                                                  .Any(rg => rg.ResourceGroupName.StartsWith(string.Format(CultureInfo.InvariantCulture, "{0}_{1}", Constants.TryResourceGroupPrefix, g.Replace(" ", Constants.TryResourceGroupSeparator)), StringComparison.OrdinalIgnoreCase)))
                                           .Concat(subscription.ResourceGroups
                                                   .GroupBy(s => s.GeoRegion)
                                                   .Select(g => new { Region = g.Key, ResourceGroups = g.Select(r => r), RemainingCount = (subscription.ResourceGroupsPerGeoRegion) - g.Count() })
                                                   .Where(g => g.RemainingCount > 0)
                                                   .Select(g => Enumerable.Repeat(g.Region, g.RemainingCount))
                                                   .Select(i => i)
                                                   .SelectMany(i => i)
                                                   );
                result.ToDelete = subscription.ResourceGroups
                                  .GroupBy(s => s.GeoRegion)
                                  .Select(g => new { Region = g.Key, ResourceGroups = g.Select(r => r), Count = g.Count() })
                                  .Where(g => g.Count > subscription.ResourceGroupsPerGeoRegion)
                                  .Select(g => g.ResourceGroups.Where(rg => string.IsNullOrEmpty(rg.UserId)).Skip((subscription.ResourceGroupsPerGeoRegion)))
                                  .SelectMany(i => i);
            }
            else if (subscription.Type == SubscriptionType.VSCodeLinux)
            {
                result.ToCreateInRegions = new List <string>();
                var vscodeTemplates = TemplatesManager.GetTemplates().Where(a => a.AppService == AppService.VSCodeLinux);
                var temp            = subscription.ResourceGroups.GroupBy(a => a.TemplateName)
                                      .Select(g => new
                                              TemplateStats
                {
                    TemplateName   = g.Key,
                    RemainingCount = (subscription.ResourceGroupsPerTemplate) - g.Count()
                })
                                      .Where(g => g.RemainingCount > 0);

                var temp2 = new List <TemplateStats>();
                foreach (var remaining in vscodeTemplates)
                {
                    if (!temp.Any(a => a.TemplateName == remaining.Name))
                    {
                        temp = temp.Union(new List <TemplateStats> {
                            new TemplateStats {
                                TemplateName = remaining.Name, RemainingCount = subscription.ResourceGroupsPerTemplate
                            }
                        });
                    }
                    var count = temp.First(a => a.TemplateName == remaining.Name).RemainingCount;
                    temp2.Add(new TemplateStats {
                        TemplateName = remaining.Name, RemainingCount = count
                    });
                }
                result.ToCreateTemplates = temp2;
                result.ToDelete          = subscription.ResourceGroups
                                           .GroupBy(s => s.DeployedTemplateName)
                                           .Select(g => new { TemplateName = g.Key, ResourceGroups = g.Select(r => r), ExtraCount = g.Count() - (subscription.ResourceGroupsPerTemplate) })
                                           .Where(g => g.ExtraCount > 0)
                                           .Select(g => g.ResourceGroups.Where(rg => string.IsNullOrEmpty(rg.UserId)).Skip((subscription.ResourceGroupsPerGeoRegion)))
                                           .SelectMany(i => i);
            }

            //TODO:Also delete RGs that are not in subscription.GeoRegions
            result.Ready = subscription.ResourceGroups.Where(rg => !result.ToDelete.Any(drg => drg.ResourceGroupName == rg.ResourceGroupName));
            SimpleTrace.TraceInformation($"MakeTrialSubscription for: {subscription.SubscriptionId} -> Ready:{result.Ready.Count()} -> ToCreate:{result.ToCreateInRegions.Count()}  -> ToDelete:{result.ToDelete.Count()} -> result:{JsonConvert.SerializeObject(result)}");
            return(result);
        }
Exemplo n.º 13
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));
            }
        }