Example #1
0
        public async Task <HttpResponseMessage> UninstallExtension(string id)
        {
            var startTime = DateTime.UtcNow;
            var tracer    = _traceFactory.GetTracer();
            var manager   = GetSiteExtensionManager();

            try
            {
                HttpResponseMessage response = null;
                bool isUninstalled           = await manager.UninstallExtension(id);

                if (ArmUtils.IsArmRequest(Request))
                {
                    if (isUninstalled)
                    {
                        response = Request.CreateResponse(HttpStatusCode.OK);
                    }
                    else
                    {
                        var extension = new SiteExtensionInfo {
                            Id = id
                        };
                        response = Request.CreateResponse(HttpStatusCode.BadRequest, ArmUtils.AddEnvelopeOnArmRequest <SiteExtensionInfo>(extension, Request));
                    }
                }
                else
                {
                    response = Request.CreateResponse(HttpStatusCode.OK, isUninstalled);
                }

                LogEndEvent(id, (DateTime.UtcNow - startTime), tracer, defaultResult: Constants.SiteExtensionProvisioningStateSucceeded);
                return(response);
            }
            catch (DirectoryNotFoundException ex)
            {
                _analytics.UnexpectedException(
                    ex,
                    method: "DELETE",
                    path: string.Format(CultureInfo.InvariantCulture, "/api/siteextensions/{0}", id),
                    result: Constants.SiteExtensionProvisioningStateFailed,
                    message: null,
                    trace: false);

                tracer.TraceError(ex, "Failed to uninstall {0}", id);
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotFound, ex));
            }
            catch (Exception ex)
            {
                _analytics.UnexpectedException(
                    ex,
                    method: "DELETE",
                    path: string.Format(CultureInfo.InvariantCulture, "/api/siteextensions/{0}", id),
                    result: Constants.SiteExtensionProvisioningStateFailed,
                    message: null,
                    trace: false);

                tracer.TraceError(ex, "Failed to uninstall {0}", id);
                throw ex;
            }
        }
        public IActionResult GetResult(string id)
        {
            using (_tracer.Step("DeploymentService.GetResult"))
            {
                DeployResult pending;
                if (IsLatestPendingDeployment(ref id, out pending))
                {
                    Response.GetTypedHeaders().Location = new Uri(Request.GetDisplayUrl());
                    pending.Status = DeployStatus.Pending;
                    return(Accepted(ArmUtils.AddEnvelopeOnArmRequest(pending, Request)));
                }

                DeployResult result = _deploymentManager.GetResult(id);

                if (result == null)
                {
                    return(NotFound(String.Format(CultureInfo.CurrentCulture,
                                                  Resources.Error_DeploymentNotFound,
                                                  id)));
                }

                if (_deploymentLock.IsHeld)
                {
                    result.Status = DeployStatus.Pending;
                }

                Uri baseUri = kUriHelper.MakeRelative(kUriHelper.GetBaseUri(Request), new Uri(Request.GetDisplayUrl()).AbsolutePath);
                result.Url    = baseUri;
                result.LogUrl = kUriHelper.MakeRelative(baseUri, "log");

                return(Ok(ArmUtils.AddEnvelopeOnArmRequest(result, Request)));
            }
        }
Example #3
0
        public HttpResponseMessage GetResult(string id)
        {
            using (_tracer.Step("DeploymentService.GetResult"))
            {
                DeployResult pending;
                if (IsLatestPendingDeployment(ref id, out pending))
                {
                    var response = Request.CreateResponse(HttpStatusCode.Accepted, ArmUtils.AddEnvelopeOnArmRequest(pending, Request));
                    response.Headers.Location = Request.RequestUri;
                    return(response);
                }

                DeployResult result = _deploymentManager.GetResult(id);

                if (result == null)
                {
                    var response = Request.CreateErrorResponse(HttpStatusCode.NotFound, String.Format(CultureInfo.CurrentCulture,
                                                                                                      Resources.Error_DeploymentNotFound,
                                                                                                      id));
                    throw new HttpResponseException(response);
                }

                Uri baseUri = UriHelper.MakeRelative(UriHelper.GetBaseUri(Request), Request.RequestUri.AbsolutePath);
                result.Url    = baseUri;
                result.LogUrl = UriHelper.MakeRelative(baseUri, "log");

                return(Request.CreateResponse(HttpStatusCode.OK, ArmUtils.AddEnvelopeOnArmRequest(result, Request)));
            }
        }
Example #4
0
        public HttpResponseMessage ExecuteScan(string timeout)
        {
            if (timeout == null || timeout.Length == 0)
            {
                timeout = Constants.ScanTimeOutMillSec;
            }

            //Start async scanning
            String  id     = DateTime.UtcNow.ToString("yyy-MM-dd_HH-mm-ssZ");
            var     result = _scanManager.StartScan(timeout, mainScanDirPath, id, "dummy" /*Request.Headers["Host"]*/);
            ScanUrl obj;

            //Check if files were modified after last scan
            if (result.IsCompleted && result.Result == ScanRequestResult.NoFileModifications)
            {
                Console.WriteLine("Inside no modified controller");
                //Create URL
                obj = new ScanUrl(null, null, id, Resources.NoScanModifiedFiles + " " + Resources.LastScanMsg);
            }
            else if (result.IsCompleted && result.Result == ScanRequestResult.ScanAlreadyInProgress)
            {
                //Create URL
                obj = new ScanUrl(null, null, id, Resources.ScanInProgress);
            }
            else
            {
                //Create URL
                obj = new ScanUrl(UriHelper.GetRequestUri(Request).Authority + String.Format("/api/scan/{0}/track", id), getResultURL(id), id, "");
            }


            //result;
            return(Request.CreateResponse(HttpStatusCode.OK, ArmUtils.AddEnvelopeOnArmRequest(obj, Request)));
        }
Example #5
0
        public HttpResponseMessage GetTriggeredJobHistory(string jobName)
        {
            string etag = GetRequestETag();

            string currentETag;
            TriggeredJobHistory history = _triggeredJobsManager.GetJobHistory(jobName, etag, out currentETag);

            if (history == null && currentETag == null)
            {
                return(Request.CreateResponse(HttpStatusCode.NotFound));
            }

            HttpResponseMessage response;

            if (etag == currentETag)
            {
                response = Request.CreateResponse(HttpStatusCode.NotModified);
            }
            else
            {
                object triggeredJobHistoryResponse =
                    history != null && ArmUtils.IsArmRequest(Request) ? ArmUtils.AddEnvelopeOnArmRequest(history.TriggeredJobRuns, Request) : history;

                response = Request.CreateResponse(HttpStatusCode.OK, triggeredJobHistoryResponse);
            }
            response.Headers.ETag = new EntityTagHeaderValue(currentETag);
            return(response);
        }
        private async Task <HttpResponseMessage> CreateOrUpdateHelper(string name, Task <FunctionEnvelope> functionEnvelopeBuilder)
        {
            if (!FunctionNameValidationRegex.IsMatch(name))
            {
                // it returns the same error object if the PUT request does not come from Arm
                return(ArmUtils.CreateErrorResponse(Request, HttpStatusCode.BadRequest, new ArgumentException($"{name} is not a valid function name")));
            }

            var tracer = _traceFactory.GetTracer();

            using (tracer.Step($"FunctionsController.CreateOrUpdate({name})"))
            {
                var  functionEnvelope = await functionEnvelopeBuilder;
                bool configChanged    = false;
                functionEnvelope = await _manager.CreateOrUpdateAsync(name, functionEnvelope, () => { configChanged = true; });

                AddFunctionAppIdToEnvelope(functionEnvelope);

                if (configChanged)
                {
                    // Fire and forget SyncTrigger request.
                    FireSyncTriggers(tracer);
                }

                return(Request.CreateResponse(HttpStatusCode.Created, ArmUtils.AddEnvelopeOnArmRequest(functionEnvelope, Request)));
            }
        }
        public void ArmUtilsShouldNotCreateArmEntityList()
        {
            var httpRequest = GetMockRequest(url: _defaultArmListRequest, isArmRequest: false);

            TestModel[] modelList =
            {
                new TestModel {
                    Id = _payloadId, Name = _payloadName
                },
                new TestModel {
                    Id = _payloadId, Name = _payloadName
                },
            };

            var results = ArmUtils.AddEnvelopeOnArmRequest <TestModel>(modelList, httpRequest);

            Assert.Null(results as ArmListEntry <TestModel>);
            var models = results as TestModel[];

            foreach (var model in models)
            {
                Assert.Equal(_payloadId, model.Id);
                Assert.Equal(_payloadName, model.Name);
            }
        }
        public IActionResult GetLogEntry(string id)
        {
            using (_tracer.Step("DeploymentService.GetLogEntry"))
            {
                try
                {
                    var deployments = _deploymentManager.GetLogEntries(id).ToList();
                    foreach (var entry in deployments)
                    {
                        if (!entry.HasDetails)
                        {
                            continue;
                        }
                        Uri baseUri = kUriHelper.MakeRelative(kUriHelper.GetBaseUri(Request), new Uri(Request.GetDisplayUrl()).AbsolutePath);
                        entry.DetailsUrl = kUriHelper.MakeRelative(baseUri, entry.Id);
                    }

                    return(Ok(ArmUtils.AddEnvelopeOnArmRequest(deployments, Request)));
                }
                catch (FileNotFoundException ex)
                {
                    return(NotFound(ex));
                }
            }
        }
        public void ArmUtilsShouldCreateArmEntityList()
        {
            string[] urls = { _defaultArmListRequest, _defaultArmListRequest.Replace("/settings", "/settings/") };

            foreach (var url in urls)
            {
                var         httpRequest = GetMockRequest(url: url);
                TestModel[] modelList   =
                {
                    new TestModel {
                        Id = _payloadId, Name = _payloadName
                    },
                    new TestModel {
                        Id = _payloadId, Name = _payloadName
                    },
                };

                var results = ArmUtils.AddEnvelopeOnArmRequest <TestModel>(modelList, httpRequest) as ArmListEntry <TestModel>;
                Assert.NotNull(results);
                foreach (var result in results.Value)
                {
                    Assert.Equal(_defaultArmId.Replace("/bla", "/" + _payloadName), result.Id);
                    Assert.Equal(_defaultArmName.Replace("/bla", "/" + _payloadName), result.Name);
                    Assert.Equal(_defaultArmType, result.Type);
                    Assert.Equal(_defaultGeoLocation, result.Location);
                    Assert.Equal(_payloadId, result.Properties.Id);
                    Assert.Equal(_payloadName, result.Properties.Name);
                }
            }
        }
Example #10
0
        public HttpResponseMessage GetResult(string id)
        {
            using (_tracer.Step("DeploymentService.GetResult"))
            {
                DeployResult pending;
                if (IsLatestPendingDeployment(ref id, out pending))
                {
                    var response = Request.CreateResponse(HttpStatusCode.Accepted, ArmUtils.AddEnvelopeOnArmRequest(pending, Request));
                    if (ArmUtils.IsArmRequest(Request) && Request.Headers.Referrer != null && Request.Headers.Referrer.AbsolutePath.EndsWith(Constants.LatestDeployment, StringComparison.OrdinalIgnoreCase))
                    {
                        response.Headers.Location = Request.Headers.Referrer;
                    }
                    else
                    {
                        response.Headers.Location = Request.RequestUri;
                    }
                    return(response);
                }

                DeployResult result = _deploymentManager.GetResult(id);

                if (result == null)
                {
                    var response = Request.CreateErrorResponse(HttpStatusCode.NotFound, String.Format(CultureInfo.CurrentCulture,
                                                                                                      Resources.Error_DeploymentNotFound,
                                                                                                      id));
                    throw new HttpResponseException(response);
                }

                Uri baseUri = UriHelper.MakeRelative(UriHelper.GetBaseUri(Request), Request.RequestUri.AbsolutePath);
                result.Url    = baseUri;
                result.LogUrl = UriHelper.MakeRelative(baseUri, "log");

                if (ArmUtils.IsArmRequest(Request))
                {
                    switch (result.Status)
                    {
                    case DeployStatus.Building:
                    case DeployStatus.Deploying:
                    case DeployStatus.Pending:
                        result.ProvisioningState = "InProgress";
                        HttpResponseMessage responseMessage = Request.CreateResponse(HttpStatusCode.OK, ArmUtils.AddEnvelopeOnArmRequest(result, Request));
                        responseMessage.Headers.Location = Request.RequestUri;
                        return(responseMessage);

                    case DeployStatus.Failed:
                        result.ProvisioningState = "Failed";
                        break;

                    case DeployStatus.Success:
                        result.ProvisioningState = "Succeeded";
                        break;

                    default:
                        return(Request.CreateResponse(HttpStatusCode.BadRequest, ArmUtils.AddEnvelopeOnArmRequest(result, Request)));
                    }
                }
                return(Request.CreateResponse(HttpStatusCode.OK, ArmUtils.AddEnvelopeOnArmRequest(result, Request)));
            }
        }
Example #11
0
        public async Task <HttpResponseMessage> GetLocalExtensions(string filter = null, bool checkLatest = true)
        {
            var manager = GetSiteExtensionManager();

            return(Request.CreateResponse(
                       HttpStatusCode.OK,
                       ArmUtils.AddEnvelopeOnArmRequest <SiteExtensionInfo>(await manager.GetLocalExtensions(filter, checkLatest), Request)));
        }
Example #12
0
        public async Task <HttpResponseMessage> GetRemoteExtensions(string filter = null, bool allowPrereleaseVersions = false, string feedUrl = null)
        {
            var manager = GetSiteExtensionManager(forceUseV1: !string.IsNullOrEmpty(feedUrl));

            return(Request.CreateResponse(
                       HttpStatusCode.OK,
                       ArmUtils.AddEnvelopeOnArmRequest <SiteExtensionInfo>(await manager.GetRemoteExtensions(filter, allowPrereleaseVersions, feedUrl), Request)));
        }
Example #13
0
 public HttpResponseMessage GetAllModules(int id)
 {
     using (_tracer.Step("ProcessController.GetAllModules"))
     {
         var results = GetModules(GetProcessById(id), Request.RequestUri.AbsoluteUri.TrimEnd('/'));
         return(Request.CreateResponse(HttpStatusCode.OK, ArmUtils.AddEnvelopeOnArmRequest(results, Request)));
     }
 }
Example #14
0
 public HttpResponseMessage GetProcess(int id)
 {
     using (_tracer.Step("ProcessController.GetProcess"))
     {
         var process = GetProcessById(id);
         return(Request.CreateResponse(HttpStatusCode.OK, ArmUtils.AddEnvelopeOnArmRequest(GetProcessInfo(process, Request.GetRequestUri(_settings.GetUseOriginalHostForReference()).AbsoluteUri, details: true), Request)));
     }
 }
        public async Task <HttpResponseMessage> List()
        {
            var tracer = _traceFactory.GetTracer();

            using (tracer.Step("FunctionsController.list()"))
            {
                var functions = (await _manager.ListFunctionsConfigAsync(ArmUtils.IsArmRequest(Request) ? new FunctionTestData() : null)).Select(f => AddFunctionAppIdToEnvelope(f));
                return(Request.CreateResponse(HttpStatusCode.OK, ArmUtils.AddEnvelopeOnArmRequest(functions, Request)));
            }
        }
Example #16
0
        public HttpResponseMessage GetTriggeredJobRun(string jobName, string runId)
        {
            TriggeredJobRun triggeredJobRun = _triggeredJobsManager.GetJobRun(jobName, runId);

            if (triggeredJobRun != null)
            {
                return(Request.CreateResponse(HttpStatusCode.OK, ArmUtils.AddEnvelopeOnArmRequest(triggeredJobRun, Request)));
            }

            return(Request.CreateResponse(HttpStatusCode.NotFound));
        }
Example #17
0
        public HttpResponseMessage GetTriggeredJob(string jobName)
        {
            TriggeredJob triggeredJob = _triggeredJobsManager.GetJob(jobName);

            if (triggeredJob != null)
            {
                return(Request.CreateResponse(HttpStatusCode.OK, ArmUtils.AddEnvelopeOnArmRequest(triggeredJob, Request)));
            }

            return(Request.CreateResponse(HttpStatusCode.NotFound));
        }
Example #18
0
        public HttpResponseMessage GetContinuousJob(string jobName)
        {
            ContinuousJob continuousJob = _continuousJobsManager.GetJob(jobName);

            if (continuousJob != null)
            {
                return(Request.CreateResponse(HttpStatusCode.OK, ArmUtils.AddEnvelopeOnArmRequest(continuousJob, Request)));
            }

            return(Request.CreateResponse(HttpStatusCode.NotFound));
        }
        public async Task <HttpResponseMessage> Get(string name)
        {
            var tracer = _traceFactory.GetTracer();

            using (tracer.Step($"FunctionsController.Get({name})"))
            {
                return(Request.CreateResponse(HttpStatusCode.OK,
                                              ArmUtils.AddEnvelopeOnArmRequest(
                                                  AddFunctionAppIdToEnvelope(await _manager.GetFunctionConfigAsync(name, ArmUtils.IsArmRequest(Request) ? new FunctionTestData() : null)), Request)));
            }
        }
 public HttpResponseMessage GetAllProcesses(bool allUsers = false)
 {
     using (_tracer.Step("ProcessController.GetAllProcesses"))
     {
         var currentUser = Process.GetCurrentProcess().GetUserName();
         var results     = Process.GetProcesses()
                           .Where(p => allUsers || Kudu.Core.Environment.IsAzureEnvironment() || String.Equals(currentUser, SafeGetValue(p.GetUserName, null), StringComparison.OrdinalIgnoreCase))
                           .Select(p => GetProcessInfo(p, Request.RequestUri.GetLeftPart(UriPartial.Path).TrimEnd('/') + '/' + p.Id)).OrderBy(p => p.Name.ToLowerInvariant())
                           .ToList();
         return(Request.CreateResponse(HttpStatusCode.OK, ArmUtils.AddEnvelopeOnArmRequest(results, Request)));
     }
 }
Example #21
0
        public async Task <HttpResponseMessage> GetScanStatus(String scanId)
        {
            using (_tracer.Step("ScanController.getScanStatus"))
            {
                var obj = await _scanManager.GetScanStatus(scanId, mainScanDirPath);

                if (obj == null)
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest));
                }
                return(Request.CreateResponse(HttpStatusCode.OK, ArmUtils.AddEnvelopeOnArmRequest(obj, Request)));
            }
        }
Example #22
0
        public async Task <HttpResponseMessage> GetRemoteExtension(string id, string version = null, string feedUrl = null)
        {
            SiteExtensionInfo extension = await _manager.GetRemoteExtension(id, version, feedUrl);

            if (extension == null)
            {
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotFound, id));
            }

            return(Request.CreateResponse(
                       HttpStatusCode.OK,
                       ArmUtils.AddEnvelopeOnArmRequest <SiteExtensionInfo>(extension, Request)));
        }
Example #23
0
        public async Task <IActionResult> GetScanLog(String scanId)
        {
            using (_tracer.Step("ScanController.getScanStatus"))
            {
                var obj = await _scanManager.GetScanResultFile(scanId, mainScanDirPath);

                if (obj == null)
                {
                    return(BadRequest());
                }
                return(Ok(ArmUtils.AddEnvelopeOnArmRequest(obj, Request)));
            }
        }
Example #24
0
        public void ArmUtilsShouldNotCreateArmEntity()
        {
            var httpRequest = GetMockRequest(isArmRequest: false);
            var result      = ArmUtils.AddEnvelopeOnArmRequest <TestModel>(new TestModel {
                Id = _payloadId, Name = _payloadName
            }, httpRequest);

            Assert.Null(result as ArmEntry <TestModel>);
            var model = result as TestModel;

            Assert.NotNull(model);
            Assert.Equal(_payloadId, model.Id);
            Assert.Equal(_payloadName, model.Name);
        }
        public HttpResponseMessage GetAllThreads(int id)
        {
            using (_tracer.Step("ProcessController.GetAllThreads"))
            {
                var process = GetProcessById(id);
                var results = new List <ProcessThreadInfo>();

                foreach (ProcessThread thread in process.Threads)
                {
                    results.Add(GetProcessThreadInfo(thread, Request.RequestUri.AbsoluteUri.TrimEnd('/') + '/' + thread.Id, false));
                }

                return(Request.CreateResponse(HttpStatusCode.OK, ArmUtils.AddEnvelopeOnArmRequest(results, Request)));
            }
        }
Example #26
0
 public HttpResponseMessage GetLogEntryDetails(string id, string logId)
 {
     using (_tracer.Step("DeploymentService.GetLogEntryDetails"))
     {
         try
         {
             var details = _deploymentManager.GetLogEntryDetails(id, logId).ToList();
             return(Request.CreateResponse(HttpStatusCode.OK, ArmUtils.AddEnvelopeOnArmRequest(details, Request)));
         }
         catch (FileNotFoundException ex)
         {
             throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotFound, ex));
         }
     }
 }
Example #27
0
        public HttpResponseMessage GetAllThreads(int id)
        {
            using (_tracer.Step("ProcessController.GetAllThreads"))
            {
                var process    = GetProcessById(id);
                var results    = new List <ProcessThreadInfo>();
                var requestUri = Request.GetRequestUri(_settings.GetUseOriginalHostForReference()).AbsoluteUri.TrimEnd('/');

                foreach (ProcessThread thread in process.Threads)
                {
                    results.Add(GetProcessThreadInfo(thread, $"{requestUri}/{thread.Id}", false));
                }

                return(Request.CreateResponse(HttpStatusCode.OK, ArmUtils.AddEnvelopeOnArmRequest(results, Request)));
            }
        }
Example #28
0
        public HttpResponseMessage GetScanResults()
        {
            HttpResponseMessage result;

            using (_tracer.Step("ScanService.GetScanResults"))
            {
                List <ScanOverviewResult> results = _scanManager.GetResults(mainScanDirPath).ToList();
                foreach (ScanOverviewResult obj in results)
                {
                    obj.ScanResultsUrl = getResultURL(obj.Status.Id);
                }
                result = Request.CreateResponse(HttpStatusCode.OK, ArmUtils.AddEnvelopeOnArmRequest(results, Request));
            }

            return(result);
        }
Example #29
0
        public IActionResult GetScanResults()
        {
            IActionResult result;

            using (_tracer.Step("ScanService.GetScanResults"))
            {
                List <ScanOverviewResult> results = _scanManager.GetResults(mainScanDirPath).ToList();
                foreach (ScanOverviewResult obj in results)
                {
                    obj.ScanResultsUrl = getResultURL(obj.Status.Id);
                }
                result = Ok(ArmUtils.AddEnvelopeOnArmRequest(results, Request));
            }

            return(result);
        }
Example #30
0
        public async Task <HttpResponseMessage> InstallExtension(string id, SiteExtensionInfo requestInfo)
        {
            var startTime = DateTime.UtcNow;

            if (requestInfo == null)
            {
                requestInfo = new SiteExtensionInfo();
            }

            SiteExtensionInfo result;

            try
            {
                result = await _manager.InstallExtension(id, requestInfo.Version, requestInfo.FeedUrl);
            }
            catch (WebException e)
            {
                // This can happen for example if a bad feed URL is passed
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Site extension download failure", e));
            }
            catch (Exception e)
            {
                // This can happen for example if the exception package is corrupted
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Site extension install exception. The package might be invalid.", e));
            }

            if (result == null)
            {
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotFound, "Could not find " + id));
            }

            // TODO: xiaowu, when update to real csm async, should return "Accepted" instead of "OK"
            var responseMessage = Request.CreateResponse(HttpStatusCode.OK, ArmUtils.AddEnvelopeOnArmRequest <SiteExtensionInfo>(result, Request));

            if (result != null && // result not null indicate instalation success, when move to async operation, will relying on provisionState instead
                result.InstalledDateTime.HasValue &&
                result.InstalledDateTime.Value > startTime &&
                ArmUtils.IsArmRequest(Request))
            {
                // Populate this header if
                //      Request is from ARM
                //      Installation action is performed
                responseMessage.Headers.Add("X-MS-SITE-OPERATION", Constants.SiteOperationRestart);
            }

            return(responseMessage);
        }