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));
        }
        public async Task <HttpResponseMessage> ExtendResourceExpirationTime()
        {
            var resourceManager = await ResourcesManager.GetInstanceAsync();

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

            try
            {
                resourceGroup = await resourceManager.ExtendResourceExpirationTime(resourceGroup);

                SimpleTrace.TraceInformation("{0}; {1}", AnalyticsEvents.ExtendTrial, resourceGroup.ResourceUniqueId);
                SimpleTrace.ExtendResourceGroup(resourceGroup);
                return(Request.CreateResponse(HttpStatusCode.OK, GetUIResource(resourceGroup)));
            }
            catch (ResourceCanOnlyBeExtendedOnce e)
            {
                SimpleTrace.Diagnostics.Error(e, "Resource Extended Once");
                return(Request.CreateResponse(HttpStatusCode.BadRequest, e.Message));
            }
            catch (Exception e)
            {
                SimpleTrace.Diagnostics.Fatal(e, "Error extending expiration time");
                return(Request.CreateResponse(HttpStatusCode.InternalServerError, Resources.Server.Error_GeneralErrorMessage));
            }
        }
        // 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;
            }));
        }
示例#4
0
        public async Task <ResourceGroup> ActivateJenkinsResource(JenkinsTemplate template, TryWebsitesIdentity userIdentity, string anonymousUserName)
        {
            return(await ActivateResourceGroup(userIdentity, AppService.Jenkins, DeploymentType.CsmDeploy, async (resourceGroup, inProgressOperation) =>
            {
                SimpleTrace.Analytics.Information(AnalyticsEvents.UserCreatedSiteWithLanguageAndTemplateName,
                                                  userIdentity.Name, template, resourceGroup);
                SimpleTrace.TraceInformation("{0}; {1}; {2}; {3}; {4}; {5}; {6}",
                                             AnalyticsEvents.OldUserCreatedSiteWithLanguageAndTemplateName, userIdentity.Name,
                                             "Jenkins", template.Name, resourceGroup.ResourceUniqueId, AppService.Jenkins.ToString(), anonymousUserName);
                SimpleTrace.UserCreatedApp(userIdentity, template, resourceGroup, AppService.Jenkins);

                var csmTemplateString = string.Empty;

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

                csmTemplateString = csmTemplateString.Replace("{{jenkinsPassword}}", SimpleSettings.TryDevOpsVMPassword);

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

                // 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(loadJenkinsResources: true);

                resourceGroup.IsRbacEnabled = false;
                return resourceGroup;
            }));
        }
示例#5
0
        public async Task <ResourceGroup> ActivateContainersResource(ContainersTemplate template, TryWebsitesIdentity userIdentity, string anonymousUserName)
        {
            return(await ActivateResourceGroup(userIdentity, AppService.Containers, true, DeploymentType.CsmDeploy, async (resourceGroup, inProgressOperation) =>
            {
                SimpleTrace.TraceInformation("{0}; {1}; {2}; {3}; {4}",
                                             AnalyticsEvents.OldUserCreatedSiteWithLanguageAndTemplateName,
                                             "Containers", template.Name, resourceGroup.ResourceUniqueId, AppService.Containers.ToString());

                var site = resourceGroup.Sites.First(s => s.IsSimpleWAWSOriginalSite);
                resourceGroup.Tags[Constants.TemplateName] = template.Name;
                resourceGroup = await resourceGroup.Update();
                if (!string.IsNullOrEmpty(template.DockerContainer))
                {
                    var qualifiedContainerName = QualifyContainerName(template.DockerContainer);
                    await site.UpdateConfig(new { properties = new { linuxFxVersion = qualifiedContainerName } });
                }

                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;
            }));
        }
示例#6
0
        // ARM
        public async Task <ResourceGroup> ActivateFunctionApp(FunctionTemplate template, TryWebsitesIdentity userIdentity, string anonymousUserName)
        {
            return(await ActivateResourceGroup(userIdentity, AppService.Function, false, DeploymentType.FunctionDeploy, async (resourceGroup, inProgressOperation) =>
            {
                SimpleTrace.TraceInformation("{0}; {1}; {2}; {3}; {4}",
                                             AnalyticsEvents.OldUserCreatedSiteWithLanguageAndTemplateName,
                                             "Function", template.Name, resourceGroup.ResourceUniqueId, AppService.Function.ToString());

                Util.FireAndForget(resourceGroup.Sites.First(s => s.IsFunctionsContainer).HostName);
                var rbacTask = resourceGroup.AddResourceGroupRbac(userIdentity.Puid, userIdentity.Email, isFunctionContainer: true);
                resourceGroup.Tags[Constants.TemplateName] = template.Name;
                await resourceGroup.Update();
                await resourceGroup.Sites.First(s => s.IsFunctionsContainer).UpdateConfig(new
                {
                    properties =
                        new
                    {
                        cors = new
                        {
                            allowedOrigins = new string[] { "https://functions.azure.com",
                                                            "https://functions-staging.azure.com", "https://functions-next.azure.com",
                                                            "https://localhost:44300", "https://tryfunctions.com", "https://www.tryfunctions.com", "https://tryfunctions.azure.com",
                                                            "https://tryfunctions-staging.azure.com", "https://www.tryfunctions-staging.azure.com" }
                        }
                    }
                });
                resourceGroup.IsRbacEnabled = await rbacTask;
                return resourceGroup;
            }));
        }
示例#7
0
        private async Task <ResourceGroup> LogActiveUsageStatistics(ResourceGroup resourceGroup)
        {
            try
            {
                var site        = resourceGroup.Sites.First(s => s.IsSimpleWAWSOriginalSite);
                var credentials = new NetworkCredential(site.PublishingUserName, site.PublishingPassword);
                var zipManager  = new RemoteZipManager(site.ScmUrl + "zip/", credentials);
                using (var httpContentStream = await zipManager.GetZipFileStreamAsync("LogFiles/http/RawLogs"))
                {
                    await StorageHelper.UploadBlob(resourceGroup.ResourceUniqueId, httpContentStream);
                }
                await StorageHelper.AddQueueMessage(new { BlobName = resourceGroup.ResourceUniqueId });

                SimpleTrace.TraceInformation("{0}; {1}", AnalyticsEvents.SiteIISLogsName, resourceGroup.ResourceUniqueId);
            }
            catch (Exception e)
            {
                if (!(e is HttpRequestException))
                {
                    SimpleTrace.Diagnostics.Error(e, "Error logging active usage numbers");
                }
            }

            return(resourceGroup);
        }
示例#8
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()}"));
            }
        }
示例#9
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);
        }
        // ARM
        public async Task <ResourceGroup> ActivateFunctionApp(BaseTemplate template, TryWebsitesIdentity userIdentity, string anonymousUserName)
        {
            return(await ActivateResourceGroup(userIdentity, AppService.Function, DeploymentType.FunctionDeploy, async (resourceGroup, inProgressOperation) =>
            {
                SimpleTrace.TraceInformation("{0}; {1}; {2}; {3}; {4}",
                                             AnalyticsEvents.OldUserCreatedSiteWithLanguageAndTemplateName,
                                             "Function", template.Name, resourceGroup.ResourceUniqueId, AppService.Function.ToString());

                //var functionApp =  resourceGroup.Site;
                //if (template.Name.Contains(Constants.CSharpLanguage))
                //{
                //    functionApp.AppSettings[Constants.FunctionsRuntimeAppSetting] = Constants.DotNetRuntime;
                //}
                //else if (template.Name.Contains(Constants.JavaScriptLanguage))
                //{
                //    functionApp.AppSettings[Constants.FunctionsRuntimeAppSetting] = Constants.JavaScriptRuntime;
                //}

                //await functionApp.UpdateAppSettings();

                Util.WarmUpSite(resourceGroup.Site);
                //resourceGroup.Tags[Constants.TemplateName] = template.Name;
                //await resourceGroup.Update();
                return resourceGroup;
            }, template));
        }
示例#11
0
        public HttpCookie CreateSessionCookie(IPrincipal user)
        {
            var identity = user.Identity as TryWebsitesIdentity;
            var value    = string.Format(CultureInfo.InvariantCulture, "{0};{1};{2};{3}", identity.Email, identity.Puid, identity.Issuer, DateTime.UtcNow.ToString(CultureInfo.InvariantCulture));

            SimpleTrace.Analytics.Information(AnalyticsEvents.UserLoggedIn, identity);
            SimpleTrace.TraceInformation("{0}; {1}; {2}", AnalyticsEvents.OldUserLoggedIn, identity.Email, identity.Issuer);
            try
            {
                var anonymousUser = HttpContext.Current.Request.Cookies[AuthConstants.AnonymousUser];
                if (anonymousUser != null)
                {
                    var anonymousIdentity = new TryWebsitesIdentity(Uri.UnescapeDataString(anonymousUser.Value).Decrypt(AuthConstants.EncryptionReason), null, "Anonymous");
                    SimpleTrace.TraceInformation("{0}; {1}; {2}",
                                                 AnalyticsEvents.AnonymousUserLogedIn,
                                                 anonymousIdentity.Name,
                                                 identity.Name);
                    SimpleTrace.AnonymousUserLoggedIn(anonymousIdentity, identity);
                }
            }
            catch
            { }
            return(new HttpCookie(AuthConstants.LoginSessionCookie, Uri.EscapeDataString(value.Encrypt(AuthConstants.EncryptionReason)))
            {
                Path = "/", Expires = DateTime.UtcNow.AddDays(2)
            });
        }
示例#12
0
        public string CreateSessionCookieData(IPrincipal user)
        {
            var identity = user.Identity as TryWebsitesIdentity;
            var value    = string.Format(CultureInfo.InvariantCulture, "{0};{1};{2};{3}", identity.Email, identity.Puid, identity.Issuer, DateTime.UtcNow.ToString(CultureInfo.InvariantCulture));

            SimpleTrace.Analytics.Information(AnalyticsEvents.UserLoggedIn, identity);
            SimpleTrace.TraceInformation("{0}; {1}; {2}", AnalyticsEvents.OldUserLoggedIn, identity.Email, identity.Issuer);

            return(Uri.EscapeDataString(value.Encrypt(AuthConstants.EncryptionReason)));
        }
        // ARM
        public async Task <ResourceGroup> ActivateWebApp(BaseTemplate template, TryWebsitesIdentity userIdentity, string anonymousUserName, AppService temp = AppService.Web)
        {
            // Start site specific stuff
            var deploymentType = template != null && template.GithubRepo != null
                ? DeploymentType.GitWithCsmDeploy
                : DeploymentType.ZipDeploy;

            return(await ActivateResourceGroup(userIdentity, temp, deploymentType, async (resourceGroup, inProgressOperation) => {
                SimpleTrace.TraceInformation("{0}; {1}; {2}; {3}; {4}; ",
                                             AnalyticsEvents.OldUserCreatedSiteWithLanguageAndTemplateName, "NA", template.Name, resourceGroup.ResourceUniqueId, temp.ToString());

                var site = resourceGroup.Site;
                //if (template != null && template.FileName != null)
                //{
                //    var credentials = new NetworkCredential(site.PublishingUserName, site.PublishingPassword);
                //    var zipManager = new RemoteZipManager(site.ScmUrl + "zip/", credentials, retryCount: 3);
                //    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);
                //    Task deleteHostingStart = vfsManager.Delete("site/wwwroot/hostingstart.html");

                //    await Task.WhenAll(scmRedirectUpload, deleteHostingStart);
                //}
                resourceGroup.Tags[Constants.TemplateName] = template.Name;
                site.SubscriptionId = resourceGroup.SubscriptionId;
                await site.LoadAppSettings();
                site.AppSettings["LAST_MODIFIED_TIME_UTC"] = DateTime.UtcNow.ToString(CultureInfo.InvariantCulture);
                //site.AppSettings["WEBSITE_TRY_MODE"] = "1";
                //if (site.SubscriptionType != SubscriptionType.VSCodeLinux)
                //{
                //    site.AppSettings["SITE_LIFE_TIME_IN_MINUTES"] = SimpleSettings.SiteExpiryMinutes;
                //}
                //if (site.AppSettings.ContainsKey("FUNCTIONS_EXTENSION_VERSION"))
                //{
                //    site.AppSettings.Remove("FUNCTIONS_EXTENSION_VERSION");
                //}

                //if (template.Name.Equals("ASP.NET with Azure Search Site", StringComparison.OrdinalIgnoreCase))
                //{
                //    site.AppSettings["SearchServiceName"] = SimpleSettings.SearchServiceName;
                //    site.AppSettings["SearchServiceApiKey"] = AzureSearchHelper.GetApiKey();
                //}

                await Task.WhenAll(site.UpdateAppSettings(), resourceGroup.Update());

                //if (template.Name.Equals("WordPress", StringComparison.OrdinalIgnoreCase))
                //{
                //    await site.UpdateConfig(new {properties = new {scmType = "LocalGit", httpLoggingEnabled = true, localMySqlEnabled = true} });
                //}

                Util.WarmUpSite(site);
                return resourceGroup;
            }, template));
        }
 public async Task CheckSiteDeploymentStatusAsync(string path)
 {
     var trial = 1;
     await RetryHelper.Retry(async() =>
     {
         {
             SimpleTrace.TraceInformation($"Checking if site was deployed {trial++} of {_retryCount} for -> {path}");
             await CheckSiteDeploymentStatus(path);
         }
     }, _retryCount, delay : 5000);
 }
示例#15
0
        public async static Task <HttpResponseMessage> EnsureSuccessStatusCodeWithFullError(this HttpResponseMessage response)
        {
            if (!response.IsSuccessStatusCode)
            {
                var content = await response.Content.ReadAsStringAsync();

                SimpleTrace.TraceInformation($"{response.StatusCode}->{response.RequestMessage.RequestUri}->{response.ReasonPhrase}->{content}: Response status code does not indicate success");
                throw new FailedRequestException(response.RequestMessage.RequestUri, content, response.StatusCode, "Response status code does not indicate success");
            }
            return(response);
        }
示例#16
0
 public async Task <Uri> PostZipFileAsync(string path, string localZipPath)
 {
     return(await RetryHelper.Retry(async() =>
     {
         var trial = 0;
         SimpleTrace.TraceInformation($"Site POST Zip Deploy started trial ({++trial}/{_retryCount}): for {localZipPath}->{ServiceUrl}-> size({new FileInfo(localZipPath).Length})");
         using (var stream = File.OpenRead(localZipPath))
         {
             return await PostZipStreamAsync(path, stream);
         }
     }, _retryCount));
 }
 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);
     }
 }
 public async Task PutZipFileAsync(string path, string zipUrl)
 {
     await RetryHelper.Retry(async() =>
     {
         var trial = 0;
         SimpleTrace.TraceInformation($"Site Zip PUT started trial ({++trial}/{_retryCount}): for {zipUrl}->{ServiceUrl}");
         using (var stream = await GetHttpStream(zipUrl))
         {
             await PutZipStreamAsync(path, stream);
         }
     }, _retryCount);
 }
 public async Task <Uri> PostZipFileAsync(string path, string zipUrl)
 {
     return(await RetryHelper.Retry(async() =>
     {
         var trial = 0;
         SimpleTrace.TraceInformation($"Site POST Zip Deploy started trial ({++trial}/{_retryCount}): for {zipUrl}->{ServiceUrl}");
         using (var stream = await GetHttpStream(zipUrl))
         {
             return await PostZipStreamAsync(path, stream);
         }
     }, _retryCount));
 }
        public async Task <ResourceGroup> ActivateMonitoringToolsApp(BaseTemplate template, TryWebsitesIdentity userIdentity, string anonymousUserName)
        {
            return(await ActivateResourceGroup(userIdentity, AppService.MonitoringTools, DeploymentType.RbacOnly, async (resourceGroup, inProgressOperation) =>
            {
                SimpleTrace.TraceInformation("{0}; {1}; {2}; {3}; {4}",
                                             AnalyticsEvents.OldUserCreatedSiteWithLanguageAndTemplateName,
                                             "MonitoringTools", template.Name, resourceGroup.ResourceUniqueId, AppService.MonitoringTools.ToString());

                var rbacTask = resourceGroup.AddResourceGroupRbac(userIdentity.Puid, userIdentity.Email);
                resourceGroup.IsRbacEnabled = await rbacTask;
                return resourceGroup;
            }));
        }
示例#21
0
        public static async Task <string> UpdatePostDeployAppSettings(Site site)
        {
            SimpleTrace.TraceInformation($"Site AppSettings Update started: for {site.SiteName}->{site.ResourceGroupName}->{site.SubscriptionId}");
            await site.LoadAppSettings();

            site.AppSettings["SITE_GIT_URL"]      = site.GitUrlWithCreds;
            site.AppSettings["SITE_BASH_GIT_URL"] = site.BashGitUrlWithCreds;
            var siteguid = Guid.NewGuid().ToString();

            site.AppSettings["SITE_SITEKEY"] = siteguid;
            await site.UpdateAppSettings();

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

                Util.WarmUpSite(resourceGroup.Sites.First(s => s.IsFunctionsContainer));
                var rbacTask = resourceGroup.AddResourceGroupRbac(userIdentity.Puid, userIdentity.Email, isFunctionContainer: true);
                resourceGroup.Tags[Constants.TemplateName] = template.Name;
                await resourceGroup.Update();
                resourceGroup.IsRbacEnabled = await rbacTask;
                return resourceGroup;
            }));
        }
        // ARM

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

                //var site = resourceGroup.Site;
                //resourceGroup.Tags[Constants.TemplateName] = template.Name;
                //resourceGroup = await resourceGroup.Update();
                //site.SubscriptionId = resourceGroup.SubscriptionId;
                //await Util.DeployLinuxTemplateToSite(template, site);

                return resourceGroup;
            }, template));
        }
示例#24
0
 public HttpResponseMessage LogFeedback(Feedback feedback)
 {
     if (feedback != null && !string.IsNullOrWhiteSpace(feedback.Comment))
     {
         var context  = new HttpContextWrapper(HttpContext.Current);
         var userName = User != null && User.Identity != null && !string.IsNullOrEmpty(User.Identity.Name)
             ? User.Identity.Name
             : "-";
         var anonymousUserName = SecurityManager.GetAnonymousUserName(context);
         SimpleTrace.TraceInformation("{0}; {1}; {2};",
                                      AnalyticsEvents.FeedbackComment,
                                      feedback.Comment.Replace(';', '_'),
                                      feedback.ContactMe.ToString());
     }
     return(Request.CreateResponse(HttpStatusCode.Accepted));
 }
        public static SubscriptionStats GetSubscriptionStats(this Subscription subscription)
        {
            var result = new SubscriptionStats();

            result.ToDelete = subscription.ResourceGroups
                              .Where(b =>
                                     string.IsNullOrEmpty(b.DeployedTemplateName) ||
                                     string.IsNullOrEmpty(b.SiteGuid) ||
                                     (b.Tags != null && b.Tags.ContainsKey("Bad")) ||
                                     (!string.IsNullOrEmpty(b.UserId) && b.TimeLeft <= TimeSpan.FromSeconds(0))
                                     );

            //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($"GetSubscriptionStats for: {subscription.Type.ToString()} : {subscription.SubscriptionId} -> Ready:{result.Ready.Count()} -> ToDelete:{result.ToDelete.Count()}");
            return(result);
        }
示例#26
0
        public HttpResponseMessage LogEvent(string telemetryEvent, JObject properties)
        {
            var context = new HttpContextWrapper(HttpContext.Current);

            if (context.IsBrowserRequest())
            {
                var userName = User != null && User.Identity != null && !string.IsNullOrEmpty(User.Identity.Name)
                    ? User.Identity.Name
                    : "-";
                var anonymousUserName = SecurityManager.GetAnonymousUserName(context);

                if (telemetryEvent.Equals("INIT_USER", StringComparison.OrdinalIgnoreCase))
                {
                    var dic = properties != null
                        ? properties.ToObject <Dictionary <string, string> >()
                        : new Dictionary <string, string>();

                    Func <string, string> cleanUp = (s) => string.IsNullOrEmpty(s) ? "-" : s;
                    var referer = cleanUp(dic.Where(p => p.Key == "origin").Select(p => p.Value).FirstOrDefault());
                    var cid     = cleanUp(dic.Where(p => p.Key == "cid").Select(p => p.Value).FirstOrDefault());
                    var sv      = cleanUp(dic.Where(p => p.Key == "sv").Select(p => p.Value).FirstOrDefault());

                    SimpleTrace.TraceInformation("{0}; {1}; {2}; {3}; {4}; {5}",
                                                 AnalyticsEvents.AnonymousUserInit,
                                                 userName,
                                                 ExperimentManager.GetCurrentExperiment(),
                                                 referer,
                                                 cid,
                                                 sv
                                                 );
                    SimpleTrace.InitializeAnonymousUser(userName, ExperimentManager.GetCurrentExperiment(), referer, cid, sv);
                }
                else
                {
                    SimpleTrace.Analytics.Information(AnalyticsEvents.UiEvent, telemetryEvent, properties);

                    var eventProperties = properties != null
                        ? properties.ToObject <Dictionary <string, string> >().Select(e => e.Value).Aggregate((a, b) => string.Join(",", a, b))
                        : string.Empty;

                    SimpleTrace.TraceInformation("{0}; {1}; {2}; {3}; {4}", AnalyticsEvents.OldUiEvent, telemetryEvent, userName, eventProperties, anonymousUserName);
                }
            }
            return(Request.CreateResponse(HttpStatusCode.Accepted));
        }
示例#27
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));
        }
示例#28
0
        public static async Task UpdateVSCodeLinuxAppSettings(Site site)
        {
            SimpleTrace.TraceInformation($"Site AppSettings Update started: for {site.SiteName}->{site.ResourceGroupName}->{site.SubscriptionId}");

            site.AppSettings["SITE_GIT_URL"]      = site.GitUrlWithCreds;
            site.AppSettings["SITE_BASH_GIT_URL"] = site.BashGitUrlWithCreds;
            await Task.WhenAll(site.UpdateConfig(
                                   new
            {
                properties = new
                {
                    appCommandLine     = "process.json",
                    linuxFxVersion     = "NODE|9.4",
                    alwaysOn           = true,
                    httpLoggingEnabled = true
                }
            }), site.UpdateAppSettings());
        }
        public async Task <ResourceGroup> ActivateLinuxResource(BaseTemplate template, TryWebsitesIdentity userIdentity, string anonymousUserName)
        {
            return(await ActivateResourceGroup(userIdentity, AppService.Linux, DeploymentType.CsmDeploy, async (resourceGroup, inProgressOperation) =>
            {
                SimpleTrace.TraceInformation("{0}; {1}; {2}; {3}; {4}",
                                             AnalyticsEvents.OldUserCreatedSiteWithLanguageAndTemplateName, "Linux", template.Name, resourceGroup.ResourceUniqueId, AppService.Linux.ToString());

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

                await Util.DeployLinuxTemplateToSite(template, site);

                var rbacTask = resourceGroup.AddResourceGroupRbac(userIdentity.Puid, userIdentity.Email);
                resourceGroup.IsRbacEnabled = await rbacTask;
                return resourceGroup;
            }));
        }
示例#30
0
        // ARM
        public async Task <ResourceGroup> ActivateApiApp(ApiTemplate template, TryWebsitesIdentity userIdentity, string anonymousUserName)
        {
            return(await ActivateResourceGroup(userIdentity, AppService.Api, DeploymentType.CsmDeploy, async (resourceGroup, inProgressOperation) =>
            {
                SimpleTrace.Analytics.Information(AnalyticsEvents.UserCreatedSiteWithLanguageAndTemplateName,
                                                  userIdentity, template, resourceGroup.CsmId);
                SimpleTrace.TraceInformation("{0}; {1}; {2}; {3}; {4}; {5}; {6}",
                                             AnalyticsEvents.OldUserCreatedSiteWithLanguageAndTemplateName, userIdentity.Name,
                                             "Api", template.ApiTemplateName, resourceGroup.ResourceUniqueId, AppService.Api.ToString(), anonymousUserName);
                //SimpleTrace.UserCreatedApiApp()

                var apiApp = new ApiApp(resourceGroup.SubscriptionId, resourceGroup.ResourceGroupName, Guid.NewGuid().ToString().Replace("-", ""))
                {
                    MicroserviceId = template.ApiTemplateName,
                    Location = resourceGroup.GeoRegion
                };

                var csmTemplate = await apiApp.GenerateCsmTemplate();

                var templateWrapper = new CsmTemplateWrapper
                {
                    properties = new CsmTemplateProperties
                    {
                        mode = "Incremental",
                        parameters = apiApp.GenerateTemplateParameters(),
                        template = csmTemplate
                    }
                };

                await inProgressOperation.CreateDeployment(templateWrapper, block: true);

                // We don't need the original site that we create for Web or Mobile apps, delete it or it'll show up in ibiza
                await resourceGroup.Sites.Where(s => s.IsSimpleWAWSOriginalSite).Select(s => s.Delete()).IgnoreFailures().WhenAll();

                // After a deployment, we have no idea what changes happened in the resource group, we should reload it.
                await resourceGroup.Load();

                var rbacTask = resourceGroup.AddResourceGroupRbac(userIdentity.Puid, userIdentity.Email);
                var publicAccessTask = resourceGroup.ApiApps.Select(a => a.SetAccessLevel("PublicAnonymous"));
                resourceGroup.IsRbacEnabled = await rbacTask;
                await publicAccessTask.WhenAll();
                return resourceGroup;
            }));
        }