コード例 #1
0
        internal virtual UpdateAppResponse UpdateApp(UpdateAppRequest request)
        {
            var marshaller   = UpdateAppRequestMarshaller.Instance;
            var unmarshaller = UpdateAppResponseUnmarshaller.Instance;

            return(Invoke <UpdateAppRequest, UpdateAppResponse>(request, marshaller, unmarshaller));
        }
コード例 #2
0
        public void TestUpdateAppRequest()
        {
            string json = @"{
  ""name"": ""new_name"",
  ""environment_variables"": {
    ""MY_ENV_VAR"": ""foobar"",
    ""FOOBAR"": ""MY_ENV_VAR""
  },
  ""lifecycle"": {
    ""type"": ""buildpack"",
    ""data"": {
      ""buildpack"": ""http://gitwheel.org/my-app"",
      ""stack"": ""redhat""
    }
  }
}";

            UpdateAppRequest request = new UpdateAppRequest();

            request.Name = "new_name";
            request.EnvironmentVariables = TestUtil.GetJsonDictonary(@"{""MY_ENV_VAR"":""foobar"",""FOOBAR"":""MY_ENV_VAR""}");

            request.Lifecycle = TestUtil.GetJsonDictonary(@"{""type"":""buildpack"",""data"":{""buildpack"":""http://gitwheel.org/my-app"",""stack"":""redhat""}}");

            string result = JsonConvert.SerializeObject(request, Formatting.None);

            Assert.AreEqual(TestUtil.ToUnformatedJsonString(json), result);
        }
コード例 #3
0
        /// <summary>
        /// Updating an App
        /// <para>For detailed information, see online documentation at: "http://apidocs.cloudfoundry.org/250/apps/updating_an_app.html"</para>
        /// </summary>
        public async Task <UpdateAppResponse> UpdateApp(Guid?guid, UpdateAppRequest value)
        {
            UriBuilder uriBuilder = new UriBuilder(this.Client.CloudTarget);

            uriBuilder.Path = string.Format(CultureInfo.InvariantCulture, "/v2/apps/{0}", guid);
            var client = this.GetHttpClient();

            client.Uri    = uriBuilder.Uri;
            client.Method = HttpMethod.Put;
            var authHeader = await BuildAuthenticationHeader();

            if (!string.IsNullOrWhiteSpace(authHeader.Key))
            {
                if (client.Headers.ContainsKey(authHeader.Key))
                {
                    client.Headers[authHeader.Key] = authHeader.Value;
                }
                else
                {
                    client.Headers.Add(authHeader);
                }
            }
            client.ContentType = "application/x-www-form-urlencoded";
            client.Content     = ((string)JsonConvert.SerializeObject(value)).ConvertToStream();
            var expectedReturnStatus = 201;
            var response             = await this.SendAsync(client, expectedReturnStatus);

            return(Utilities.DeserializeJson <UpdateAppResponse>(await response.ReadContentAsStringAsync()));
        }
コード例 #4
0
        /// <summary>
        /// Initiates the asynchronous execution of the UpdateApp operation.
        /// </summary>
        ///
        /// <param name="request">Container for the necessary parameters to execute the UpdateApp operation.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        /// <returns>The task object representing the asynchronous operation.</returns>
        /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/amplify-2017-07-25/UpdateApp">REST API Reference for UpdateApp Operation</seealso>
        public virtual Task <UpdateAppResponse> UpdateAppAsync(UpdateAppRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller   = UpdateAppRequestMarshaller.Instance;
            var unmarshaller = UpdateAppResponseUnmarshaller.Instance;

            return(InvokeAsync <UpdateAppRequest, UpdateAppResponse>(request, marshaller,
                                                                     unmarshaller, cancellationToken));
        }
コード例 #5
0
        public void Application_test()
        {
            CreateAppResponse     newApp    = null;
            GetAppSummaryResponse readApp   = null;
            UpdateAppResponse     updateApp = null;

            CreateAppRequest app = new CreateAppRequest();

            app.Name      = Guid.NewGuid().ToString();
            app.SpaceGuid = spaceGuid;
            app.Instances = 1;
            app.Memory    = 256;
            app.StackGuid = stackGuid;

            try
            {
                newApp = client.Apps.CreateApp(app).Result;
            }
            catch (Exception ex)
            {
                Assert.Fail("Error creating app: {0}", ex.ToString());
            }
            Assert.IsNotNull(newApp);

            try
            {
                readApp = client.Apps.GetAppSummary(newApp.EntityMetadata.Guid).Result;
            }
            catch (Exception ex)
            {
                Assert.Fail("Error reading app: {0}", ex.ToString());
            }
            Assert.IsNotNull(readApp);
            Assert.AreEqual(app.Name, readApp.Name);

            UpdateAppRequest updateAppRequest = new UpdateAppRequest();

            updateAppRequest.Memory = 512;
            try
            {
                updateApp = client.Apps.UpdateApp(newApp.EntityMetadata.Guid, updateAppRequest).Result;
            }
            catch (Exception ex)
            {
                Assert.Fail("Error updating app: {0}", ex.ToString());
            }
            Assert.IsNotNull(updateApp);
            Assert.AreEqual(updateAppRequest.Memory, updateApp.Memory);

            try
            {
                client.Apps.DeleteApp(newApp.EntityMetadata.Guid).Wait();
            }
            catch (Exception ex)
            {
                Assert.Fail("Error deleting app: {0}", ex.ToString());
            }
        }
コード例 #6
0
        internal virtual UpdateAppResponse UpdateApp(UpdateAppRequest request)
        {
            var options = new InvokeOptions();

            options.RequestMarshaller    = UpdateAppRequestMarshaller.Instance;
            options.ResponseUnmarshaller = UpdateAppResponseUnmarshaller.Instance;

            return(Invoke <UpdateAppResponse>(request, options));
        }
コード例 #7
0
        private async Task Start()
        {
            var updateAppRequest = new UpdateAppRequest()
            {
                State = "STARTED"
            };

            await this.client.Apps.UpdateApp(this.app.Guid, updateAppRequest);
        }
コード例 #8
0
        /// <summary>
        /// Initiates the asynchronous execution of the UpdateApp operation.
        /// </summary>
        ///
        /// <param name="request">Container for the necessary parameters to execute the UpdateApp operation.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        /// <returns>The task object representing the asynchronous operation.</returns>
        /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/amplify-2017-07-25/UpdateApp">REST API Reference for UpdateApp Operation</seealso>
        public virtual Task <UpdateAppResponse> UpdateAppAsync(UpdateAppRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
        {
            var options = new InvokeOptions();

            options.RequestMarshaller    = UpdateAppRequestMarshaller.Instance;
            options.ResponseUnmarshaller = UpdateAppResponseUnmarshaller.Instance;

            return(InvokeAsync <UpdateAppResponse>(request, options, cancellationToken));
        }
コード例 #9
0
        public void TestUpdateAppRequest()
        {
            string json = @"{
  ""name"": ""new_name""
}";

            UpdateAppRequest request = new UpdateAppRequest();

            request.Name = "new_name";
            string result = JsonConvert.SerializeObject(request, Formatting.None);

            Assert.AreEqual(TestUtil.ToUnformatedJsonString(json), result);
        }
コード例 #10
0
        private void MonitorApp(CloudFoundryClient client, Guid?appGuid)
        {
            GetAppSummaryResponse response = client.Apps.GetAppSummary(appGuid.Value).Result;

            if (response.State != "STOPPED")
            {
                UpdateAppRequest stopReq = new UpdateAppRequest();
                stopReq.State = "STOPPED";
                client.Apps.UpdateApp(appGuid.Value, stopReq).Wait();
            }

            UpdateAppRequest startReq = new UpdateAppRequest();

            startReq.State = "STARTED";
            client.Apps.UpdateApp(appGuid.Value, startReq).Wait();

            // ======= WAIT FOR APP TO COME ONLINE =======
            while (true)
            {
                if (this.CancelToken.IsCancellationRequested == true)
                {
                    break;
                }

                GetAppSummaryResponse appSummary = client.Apps.GetAppSummary(appGuid.Value).Result;

                if (appSummary.RunningInstances > 0)
                {
                    break;
                }

                if (appSummary.PackageState == "FAILED")
                {
                    throw new InvalidOperationException("App staging failed");
                }
                else if (appSummary.PackageState == "PENDING")
                {
                    Logger.LogMessage("App is staging ...");
                }
                else if (appSummary.PackageState == "STAGED")
                {
                    Logger.LogMessage("App staged, waiting for it to come online ...");
                }

                Thread.Sleep(3000);
            }
        }
コード例 #11
0
        /// <summary>
        /// Updating an App
        /// <para>For detailed information, see online documentation at: "http://apidocs.cloudfoundry.org/250/apps/updating_an_app.html"</para>
        /// </summary>
        public async Task <UpdateAppResponse> UpdateApp(Guid?guid, UpdateAppRequest value)
        {
            UriBuilder uriBuilder = new UriBuilder(this.Client.CloudTarget);

            uriBuilder.Path = string.Format(CultureInfo.InvariantCulture, "/v2/apps/{0}", guid);
            var client = this.GetHttpClient();

            client.Uri    = uriBuilder.Uri;
            client.Method = HttpMethod.Put;


            client.Content = ((string)JsonConvert.SerializeObject(value)).ConvertToStream();
            var expectedReturnStatus = 201;
            var response             = await this.SendAsync(client, expectedReturnStatus);

            return(Utilities.DeserializeJson <UpdateAppResponse>(await response.Content.ReadAsStringAsync()));
        }
コード例 #12
0
        public void DoublePush()
        {
            CreateAppResponse app = client.Apps.CreateApp(apprequest).Result;

            client.Apps.Push(app.EntityMetadata.Guid, appPath, false).Wait();

            UpdateAppRequest updateApp = new UpdateAppRequest();

            updateApp.Name      = app.Name;
            updateApp.Memory    = 512;
            updateApp.Instances = 1;

            UpdateAppResponse updatedApp = client.Apps.UpdateApp(app.EntityMetadata.Guid, updateApp).Result;

            client.Apps.Push(app.EntityMetadata.Guid, appPath, false).Wait();

            client.Apps.DeleteApp(app.EntityMetadata.Guid).Wait();
        }
コード例 #13
0
        public async Task <UpdateApplicationResponse> UpdateApplicationValuesAsync(UpdateAppRequest request)
        {
            if (string.IsNullOrEmpty(request.AppSecret) || string.IsNullOrEmpty(request.ApplicationSession))
            {
                throw new ArgumentNullException(nameof(request));
            }

            using (HttpRequestMessage requestMsg = new HttpRequestMessage(HttpMethod.Post, $"set/{request.FieldInfo.Field}")) {
                requestMsg.Content = new FormUrlEncodedContent(new Dictionary <string, string>
                {
                    { "secret", request.AppSecret },
                    { "value", request.FieldInfo.Value.ToString() }
                });

                requestMsg.Headers.Add("Session", request.ApplicationSession);
                return(await Requester.InternalRequestAsObject <UpdateApplicationResponse>(requestMsg, 1).ConfigureAwait(false));
            }
        }
コード例 #14
0
        public void TestUpdateAppRequest()
        {
            string json = @"{
  ""name"": ""new_name"",
  ""environment_variables"": {
    ""MY_ENV_VAR"": ""foobar"",
    ""FOOBAR"": ""MY_ENV_VAR""
  }
}";

            UpdateAppRequest request = new UpdateAppRequest();

            request.Name = "new_name";
            request.EnvironmentVariables = TestUtil.GetJsonDictonary(@"{""MY_ENV_VAR"":""foobar"",""FOOBAR"":""MY_ENV_VAR""}");

            string result = JsonConvert.SerializeObject(request, Formatting.None);

            Assert.AreEqual(TestUtil.ToUnformatedJsonString(json), result);
        }
コード例 #15
0
        public override bool Execute()
        {
            logger = new Microsoft.Build.Utilities.TaskLoggingHelper(this);

            if (CFAppGuid.Length == 0)
            {
                logger.LogError("Application guid must be specified");
                return(false);
            }

            try
            {
                CloudFoundryClient client = InitClient();

                UpdateAppRequest request = new UpdateAppRequest();

                request.Name      = CFAppName;
                request.Memory    = CFAppMemory;
                request.Instances = CFAppInstances;
                request.Buildpack = CFAppBuildpack;
                request.State     = CFAppState;

                if (CFEnvironmentJson != null)
                {
                    request.EnvironmentJson = JsonConvert.DeserializeObject <Dictionary <string, string> >(CFEnvironmentJson);
                }

                UpdateAppResponse response = client.Apps.UpdateApp(new Guid(CFAppGuid), request).Result;

                logger.LogMessage("Updated app {0} with guid {1}", response.Name, CFAppGuid);
            }
            catch (AggregateException exception)
            {
                List <string> messages = new List <string>();
                ErrorFormatter.FormatExceptionMessage(exception, messages);
                this.logger.LogError(string.Join(Environment.NewLine, messages));
                return(false);
            }

            return(true);
        }
コード例 #16
0
        public override bool Execute()
        {
            this.CFOrganization = this.CFOrganization.Trim();
            this.CFSpace        = this.CFSpace.Trim();

            var app = LoadAppFromManifest();

            this.Logger = new TaskLogger(this);
            CloudFoundryClient client = InitClient();

            Guid?spaceGuid = null;
            Guid?stackGuid = null;

            try
            {
                if ((!string.IsNullOrWhiteSpace(this.CFSpace)) && (!string.IsNullOrWhiteSpace(this.CFOrganization)))
                {
                    spaceGuid = Utils.GetSpaceGuid(client, this.Logger, this.CFOrganization, this.CFSpace);
                    if (spaceGuid == null)
                    {
                        return(false);
                    }
                }

                if (!string.IsNullOrWhiteSpace(app.StackName))
                {
                    PagedResponseCollection <ListAllStacksResponse> stackList = client.Stacks.ListAllStacks().Result;

                    var stackInfo = stackList.Where(o => o.Name == app.StackName).FirstOrDefault();

                    if (stackInfo == null)
                    {
                        Logger.LogError("Stack {0} not found", app.StackName);
                        return(false);
                    }

                    stackGuid = new Guid(stackInfo.EntityMetadata.Guid);
                }

                if (stackGuid.HasValue && spaceGuid.HasValue)
                {
                    PagedResponseCollection <ListAllAppsForSpaceResponse> apps = client.Spaces.ListAllAppsForSpace(spaceGuid, new RequestOptions()
                    {
                        Query = "name:" + app.Name
                    }).Result;

                    if (apps.Count() > 0)
                    {
                        this.CFAppGuid = apps.FirstOrDefault().EntityMetadata.Guid;

                        UpdateAppRequest request = new UpdateAppRequest();
                        request.SpaceGuid = spaceGuid;
                        request.StackGuid = stackGuid;

                        request.EnvironmentJson = app.EnvironmentVariables;

                        request.Memory = (int)app.Memory;

                        request.Instances = app.InstanceCount;

                        request.Buildpack = app.BuildpackUrl;

                        request.Command = app.Command;

                        if (app.DiskQuota.HasValue)
                        {
                            request.DiskQuota = app.DiskQuota.Value.ToString(System.Globalization.CultureInfo.InvariantCulture);
                        }

                        UpdateAppResponse response = client.Apps.UpdateApp(new Guid(this.CFAppGuid), request).Result;
                        Logger.LogMessage("Updated app {0} with guid {1}", response.Name, response.EntityMetadata.Guid);
                    }
                    else
                    {
                        CreateAppRequest request = new CreateAppRequest();
                        request.Name      = app.Name;
                        request.SpaceGuid = spaceGuid;
                        request.StackGuid = stackGuid;

                        request.EnvironmentJson = app.EnvironmentVariables;

                        request.Memory = (int)app.Memory;

                        request.Instances = app.InstanceCount;

                        request.Buildpack = app.BuildpackUrl;

                        request.Command = app.Command;

                        if (app.DiskQuota.HasValue)
                        {
                            request.DiskQuota = Convert.ToInt32(app.DiskQuota.Value, System.Globalization.CultureInfo.InvariantCulture);
                        }

                        CreateAppResponse response = client.Apps.CreateApp(request).Result;
                        this.CFAppGuid = response.EntityMetadata.Guid;
                        Logger.LogMessage("Created app {0} with guid {1}", app.Name, this.CFAppGuid);
                    }
                }
            }
            catch (Exception exception)
            {
                this.Logger.LogError("Create App failed", exception);
                return(false);
            }

            return(true);
        }
コード例 #17
0
        /// <summary>
        /// Pushes an application to the cloud.
        /// <remarks>
        /// This method is only available on the .NET 4.5 framework.
        /// Calling this method from a Windows Phone App or a Windows App will throw a <see cref="NotImplementedException"/>.
        /// </remarks>
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        /// <param name="appGuid">Application guid</param>
        /// <param name="appPath">Path of origin from which the application will be deployed</param>
        /// <param name="startApplication">True if the app should be started after upload is complete, false otherwise</param>
        public async Task Push(Guid appGuid, string appPath, bool startApplication)
        {
            if (appPath == null)
            {
                throw new ArgumentNullException("appPath");
            }

            IAppPushTools pushTools = new AppPushTools();
            int           usedSteps = 1;

            // Step 1 - Check if application exists
            this.TriggerPushProgressEvent(usedSteps, "Checking if application exists");
            RetrieveAppResponse app = await this.Client.Apps.RetrieveApp(appGuid);

            usedSteps += 1;

            // Step 2 - Compute fingerprints for local files
            this.TriggerPushProgressEvent(usedSteps, "Calculating file fingerprints ...");
            Dictionary <string, List <FileFingerprint> > fingerprints = await pushTools.GetFileFingerprints(appPath, this.Client.CancellationToken);

            if (this.CheckCancellation())
            {
                return;
            }

            usedSteps += 1;

            // Step 3 - Compare fingerprints of local files with what the server has
            this.TriggerPushProgressEvent(usedSteps, "Comparing file fingerprints ...");
            string[] neededFiles = await this.FilterExistingFiles(fingerprints);

            if (this.CheckCancellation())
            {
                return;
            }

            usedSteps += 1;

            // Step 4 - Zip all needed files and get a stream back from the PushTools
            this.TriggerPushProgressEvent(usedSteps, "Creating zip package ...");
            using (Stream zippedPayload = await pushTools.GetZippedPayload(appPath, neededFiles, this.Client.CancellationToken))
            {
                if (this.CheckCancellation())
                {
                    return;
                }

                usedSteps += 1;

                // Step 5 - Upload zip to CloudFoundry ...
                this.TriggerPushProgressEvent(usedSteps, "Uploading zip package ...");
                UriBuilder uploadEndpoint = new UriBuilder(this.Client.CloudTarget.AbsoluteUri);
                uploadEndpoint.Path = string.Format(CultureInfo.InvariantCulture, "/v2/apps/{0}/bits", appGuid.ToString());

                List <FileFingerprint> fingerPrintList = fingerprints.Values.SelectMany(list => list).ToList();

                string             serializedFingerprints = JsonConvert.SerializeObject(fingerPrintList);
                SimpleHttpResponse uploadResult           = await this.UploadZip(uploadEndpoint.Uri, zippedPayload, serializedFingerprints);

                if (this.CheckCancellation())
                {
                    return;
                }

                usedSteps += 1;
            }

            if (startApplication)
            {
                // Step 6 - Start Application
                UpdateAppRequest updateApp = new UpdateAppRequest()
                {
                    State = "STARTED"
                };
                UpdateAppResponse response = await this.UpdateApp(appGuid, updateApp);

                if (this.CheckCancellation())
                {
                    return;
                }

                usedSteps += 1;
            }

            // Step 7 - Done
            this.TriggerPushProgressEvent(usedSteps, "Application {0} pushed successfully", app.Name);
        }
コード例 #18
0
        /// <summary>
        /// Pushes an application to the cloud.
        /// <remarks>
        /// This method is only available on the .NET 4.5 framework.
        /// Calling this method from a Windows Phone App or a Windows App will throw a <see cref="NotImplementedException"/>.
        /// </remarks>
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        /// <param name="appGuid">Application guid</param>
        /// <param name="appPath">Path of origin from which the application will be deployed</param>
        /// <param name="startApplication">True if the app should be started after upload is complete, false otherwise</param>
        public async Task Push(Guid appGuid, string appPath, bool startApplication)
        {
            if (appPath == null)
            {
                throw new ArgumentNullException("appPath");
            }

            IAppPushTools pushTools = new AppPushTools(appPath);
            int           usedSteps = 1;

            // Step 1 - Check if application exists
            this.TriggerPushProgressEvent(usedSteps, "Checking if application exists");
            RetrieveAppResponse app = await this.Client.Apps.RetrieveApp(appGuid);

            usedSteps += 1;

            // Step 2 - Compute fingerprints for local files
            this.TriggerPushProgressEvent(usedSteps, "Calculating file fingerprints ...");
            Dictionary <string, List <FileFingerprint> > fingerprints = await pushTools.GetFileFingerprints(this.Client.CancellationToken);

            if (this.CheckCancellation())
            {
                return;
            }

            usedSteps += 1;

            // Step 3 - Compare fingerprints of local files with what the server has
            this.TriggerPushProgressEvent(usedSteps, "Comparing file fingerprints ...");
            HashSet <string> neededFiles = await this.FilterExistingFiles(fingerprints);

            if (this.CheckCancellation())
            {
                return;
            }

            usedSteps += 1;

            // Step 4 - Zip all needed files and get a stream back from the PushTools
            this.TriggerPushProgressEvent(usedSteps, "Creating zip package ...");
            using (Stream zippedPayload = await pushTools.GetZippedPayload(neededFiles, this.Client.CancellationToken))
            {
                if (this.CheckCancellation())
                {
                    return;
                }

                usedSteps += 1;

                // Step 5 - Upload zip to CloudFoundry ...
                this.TriggerPushProgressEvent(usedSteps, "Uploading zip package ...");

                List <FileFingerprint> fingerPrintList = fingerprints.Values.SelectMany(list => list).Where(fingerprint => !neededFiles.Contains(fingerprint.FileName)).ToList();

                await this.UploadBits(appGuid, zippedPayload, fingerPrintList);

                if (this.CheckCancellation())
                {
                    return;
                }

                usedSteps += 1;
            }

            if (startApplication)
            {
                // Step 6 - Start Application
                UpdateAppRequest updateApp = new UpdateAppRequest()
                {
                    State = "STARTED"
                };
                UpdateAppResponse response = await this.UpdateApp(appGuid, updateApp);

                if (this.CheckCancellation())
                {
                    return;
                }

                usedSteps += 1;
            }

            // Step 7 - Done
            this.TriggerPushProgressEvent(usedSteps, "Application {0} pushed successfully", app.Name);
        }
コード例 #19
0
        public override bool Execute()
        {
            logger = new Microsoft.Build.Utilities.TaskLoggingHelper(this);
            logger.LogMessage("Restarting application {0}", CFAppGuid);

            try
            {
                if (CFAppGuid.Length == 0)
                {
                    logger.LogError("Application Guid must be specified");
                    return(false);
                }

                CloudFoundryClient client = InitClient();


                // ======= HOOKUP LOGGING =======
                // TODO: detect logyard vs loggregator

                GetV1InfoResponse v1Info = client.Info.GetV1Info().Result;

                using (LogyardLog logyard = new LogyardLog(new Uri(v1Info.AppLogEndpoint), string.Format(CultureInfo.InvariantCulture, "bearer {0}", client.AuthorizationToken), null, CFSkipSslValidation))
                {
                    logyard.ErrorReceived += (sender, error) =>
                    {
                        logger.LogErrorFromException(error.Error, true);
                    };

                    logyard.StreamOpened += (sender, args) =>
                    {
                        logger.LogMessage("Log stream opened.");
                    };

                    logyard.StreamClosed += (sender, args) =>
                    {
                        logger.LogMessage("Log stream closed.");
                    };

                    logyard.MessageReceived += (sender, message) =>
                    {
                        logger.LogMessage("[{0}] - {1}: {2}", message.Message.Value.Source, message.Message.Value.HumanTime, message.Message.Value.Text);
                    };

                    logyard.StartLogStream(CFAppGuid, 0, true);


                    GetAppSummaryResponse response = client.Apps.GetAppSummary(new Guid(CFAppGuid)).Result;

                    if (response.State != "STOPPED")
                    {
                        UpdateAppRequest stopReq = new UpdateAppRequest();
                        stopReq.State = "STOPPED";
                        client.Apps.UpdateApp(new Guid(CFAppGuid), stopReq).Wait();
                    }

                    UpdateAppRequest startReq = new UpdateAppRequest();
                    startReq.State = "STARTED";
                    client.Apps.UpdateApp(new Guid(CFAppGuid), startReq).Wait();

                    // ======= WAIT FOR APP TO COME ONLINE =======
                    while (true)
                    {
                        GetAppSummaryResponse appSummary = client.Apps.GetAppSummary(new Guid(CFAppGuid)).Result;

                        if (appSummary.RunningInstances > 0)
                        {
                            break;
                        }

                        if (appSummary.PackageState == "FAILED")
                        {
                            logger.LogError("App staging failed.");
                            return(false);
                        }
                        else if (appSummary.PackageState == "PENDING")
                        {
                            logger.LogMessage("App is staging ...");
                        }
                        else if (appSummary.PackageState == "STAGED")
                        {
                            logger.LogMessage("App staged, waiting for it to come online ...");
                        }

                        Thread.Sleep(3000);
                    }

                    logyard.StopLogStream();
                }
            }
            catch (AggregateException exception)
            {
                List <string> messages = new List <string>();
                ErrorFormatter.FormatExceptionMessage(exception, messages);
                this.logger.LogError(string.Join(Environment.NewLine, messages));
                return(false);
            }

            return(true);
        }
コード例 #20
0
        /// <summary>
        /// Updating an App
        /// <para>For detailed information, see online documentation at: "http://apidocs.cloudfoundry.org/238/apps__experimental_/updating_an_app.html"</para>
        /// </summary>
        public async Task <UpdateAppResponse> UpdateApp(Guid?guid, UpdateAppRequest value)
        {
            var response = await this.GetNewHttpClient().PatchAsync($"/v3/apps/{guid}", value);

            return(JsonConvert.DeserializeObject <UpdateAppResponse>(await response.Content.ReadAsStringAsync()));
        }
コード例 #21
0
 public App UpdateApp(string appName, UpdateAppRequest updateAppRequest)
 {
     return(_appsApi.UpdateApp(_accessToken, appName, updateAppRequest));
 }
コード例 #22
0
        public override bool Execute()
        {
            logger = new Microsoft.Build.Utilities.TaskLoggingHelper(this);

            try
            {
                CloudFoundryClient client = InitClient();

                Guid?spaceGuid = null;
                Guid?stackGuid = null;

                if (CFSpace.Length > 0 && CFOrganization.Length > 0)
                {
                    spaceGuid = Utils.GetSpaceGuid(client, logger, CFOrganization, CFSpace);
                    if (spaceGuid == null)
                    {
                        return(false);
                    }
                }

                if (CFStack.Length > 0)
                {
                    PagedResponseCollection <ListAllStacksResponse> stackList = client.Stacks.ListAllStacks().Result;

                    var stackInfo = stackList.Where(o => o.Name == CFStack).FirstOrDefault();

                    if (stackInfo == null)
                    {
                        logger.LogError("Stack {0} not found", CFStack);
                        return(false);
                    }
                    stackGuid = new Guid(stackInfo.EntityMetadata.Guid);
                }

                if (stackGuid.HasValue && spaceGuid.HasValue)
                {
                    PagedResponseCollection <ListAllAppsForSpaceResponse> apps = client.Spaces.ListAllAppsForSpace(spaceGuid, new RequestOptions()
                    {
                        Query = "name:" + CFAppName
                    }).Result;

                    if (apps.Count() > 0)
                    {
                        CFAppGuid = apps.FirstOrDefault().EntityMetadata.Guid;

                        UpdateAppRequest request = new UpdateAppRequest();
                        request.SpaceGuid = spaceGuid;
                        request.StackGuid = stackGuid;

                        if (CFEnvironmentJson != null)
                        {
                            request.EnvironmentJson = JsonConvert.DeserializeObject <Dictionary <string, string> >(CFEnvironmentJson);
                        }

                        if (CFAppMemory > 0)
                        {
                            request.Memory = CFAppMemory;
                        }
                        if (CFAppInstances > 0)
                        {
                            request.Instances = CFAppInstances;
                        }
                        if (CFAppBuildpack != null)
                        {
                            request.Buildpack = CFAppBuildpack;
                        }

                        UpdateAppResponse response = client.Apps.UpdateApp(new Guid(CFAppGuid), request).Result;
                        logger.LogMessage("Updated app {0} with guid {1}", response.Name, response.EntityMetadata.Guid);
                    }
                    else
                    {
                        CreateAppRequest request = new CreateAppRequest();
                        request.Name      = CFAppName;
                        request.SpaceGuid = spaceGuid;
                        request.StackGuid = stackGuid;

                        if (CFEnvironmentJson != null)
                        {
                            request.EnvironmentJson = JsonConvert.DeserializeObject <Dictionary <string, string> >(CFEnvironmentJson);
                        }

                        if (CFAppMemory > 0)
                        {
                            request.Memory = CFAppMemory;
                        }
                        if (CFAppInstances > 0)
                        {
                            request.Instances = CFAppInstances;
                        }
                        if (CFAppBuildpack != null)
                        {
                            request.Buildpack = CFAppBuildpack;
                        }

                        CreateAppResponse response = client.Apps.CreateApp(request).Result;
                        CFAppGuid = response.EntityMetadata.Guid;
                        logger.LogMessage("Created app {0} with guid {1}", CFAppName, CFAppGuid);
                    }
                }
            }
            catch (AggregateException exception)
            {
                List <string> messages = new List <string>();
                ErrorFormatter.FormatExceptionMessage(exception, messages);
                this.logger.LogError(string.Join(Environment.NewLine, messages));
                return(false);
            }

            return(true);
        }
コード例 #23
0
 /// <summary>
 ///  更新应用(只传需要变更的参数,不传的参数不会更新)
 /// </summary>
 /// <param name="request">请求参数信息</param>
 /// <returns>请求结果信息</returns>
 public UpdateAppResponse UpdateApp(UpdateAppRequest request)
 {
     return(new UpdateAppExecutor().Client(this).Execute <UpdateAppResponse, UpdateAppResult, UpdateAppRequest>(request));
 }
コード例 #24
0
        public void UpdateAppTest()
        {
            using (ShimsContext.Create())
            {
                MockClients clients = new MockClients();

                string json = @"{
  ""guid"": ""d63f2084-55a3-47e6-87ba-ebe911071132"",
  ""name"": ""new_name"",
  ""desired_state"": ""STOPPED"",
  ""total_desired_instances"": 0,
  ""created_at"": ""2016-07-07T09:16:55Z"",
  ""updated_at"": ""2016-07-07T09:16:55Z"",
  ""lifecycle"": {
    ""type"": ""buildpack"",
    ""data"": {
      ""buildpack"": ""http://gitwheel.org/my-app"",
      ""stack"": ""redhat""
    }
  },
  ""environment_variables"": {
    ""MY_ENV_VAR"": ""foobar"",
    ""FOOBAR"": ""MY_ENV_VAR""
  },
  ""links"": {
    ""self"": {
      ""href"": ""/v3/apps/ace0d3f0-0d6f-4800-b063-8bc3a726cc48""
    },
    ""space"": {
      ""href"": ""/v2/spaces/b27bc6be-cfdc-42e6-9e8d-d2000f9faeae""
    },
    ""processes"": {
      ""href"": ""/v3/apps/ace0d3f0-0d6f-4800-b063-8bc3a726cc48/processes""
    },
    ""routes"": {
      ""href"": ""/v3/apps/ace0d3f0-0d6f-4800-b063-8bc3a726cc48/routes""
    },
    ""packages"": {
      ""href"": ""/v3/apps/ace0d3f0-0d6f-4800-b063-8bc3a726cc48/packages""
    },
    ""droplets"": {
      ""href"": ""/v3/apps/ace0d3f0-0d6f-4800-b063-8bc3a726cc48/droplets""
    },
    ""start"": {
      ""href"": ""/v3/apps/ace0d3f0-0d6f-4800-b063-8bc3a726cc48/start"",
      ""method"": ""PUT""
    },
    ""stop"": {
      ""href"": ""/v3/apps/ace0d3f0-0d6f-4800-b063-8bc3a726cc48/stop"",
      ""method"": ""PUT""
    },
    ""assign_current_droplet"": {
      ""href"": ""/v3/apps/ace0d3f0-0d6f-4800-b063-8bc3a726cc48/current_droplet"",
      ""method"": ""PUT""
    }
  }
}";
                clients.JsonResponse = json;

                clients.ExpectedStatusCode = (HttpStatusCode)200;
                var cfClient = clients.CreateCloudFoundryClient();

                Guid?guid = Guid.NewGuid();

                UpdateAppRequest value = new UpdateAppRequest();


                var obj = cfClient.AppsExperimental.UpdateApp(guid, value).Result;


                Assert.AreEqual("d63f2084-55a3-47e6-87ba-ebe911071132", TestUtil.ToTestableString(obj.Guid), true);
                Assert.AreEqual("new_name", TestUtil.ToTestableString(obj.Name), true);
                Assert.AreEqual("STOPPED", TestUtil.ToTestableString(obj.DesiredState), true);
                Assert.AreEqual("0", TestUtil.ToTestableString(obj.TotalDesiredInstances), true);
                Assert.AreEqual("2016-07-07T09:16:55Z", TestUtil.ToTestableString(obj.CreatedAt), true);
                Assert.AreEqual("2016-07-07T09:16:55Z", TestUtil.ToTestableString(obj.UpdatedAt), true);
            }
        }
コード例 #25
0
 /// <summary>
 ///  更新应用(只传需要变更的参数,不传的参数不会更新)
 /// </summary>
 /// <param name="request">请求参数信息</param>
 /// <returns>请求结果信息</returns>
 public async Task <UpdateAppResponse> UpdateApp(UpdateAppRequest request)
 {
     return(await new UpdateAppExecutor().Client(this).Execute <UpdateAppResponse, UpdateAppResult, UpdateAppRequest>(request).ConfigureAwait(false));
 }
コード例 #26
0
        public void UpdateAppTest()
        {
            using (ShimsContext.Create())
            {
                MockClients clients = new MockClients();

                string json = @"{
  ""guid"": ""guid-6a0f4adc-bdf4-4004-aa56-192e86f213d6"",
  ""name"": ""new_name"",
  ""desired_state"": ""STOPPED"",
  ""total_desired_instances"": 0,
  ""created_at"": ""2015-06-30T07:10:43Z"",
  ""updated_at"": ""2015-06-30T07:10:43Z"",
  ""environment_variables"": {
    ""MY_ENV_VAR"": ""foobar"",
    ""FOOBAR"": ""MY_ENV_VAR""
  },
  ""_links"": {
    ""self"": {
      ""href"": ""/v3/apps/guid-6a0f4adc-bdf4-4004-aa56-192e86f213d6""
    },
    ""processes"": {
      ""href"": ""/v3/apps/guid-6a0f4adc-bdf4-4004-aa56-192e86f213d6/processes""
    },
    ""packages"": {
      ""href"": ""/v3/apps/guid-6a0f4adc-bdf4-4004-aa56-192e86f213d6/packages""
    },
    ""space"": {
      ""href"": ""/v2/spaces/495bd201-eb12-48fa-9a66-ddab71302c15""
    },
    ""start"": {
      ""href"": ""/v3/apps/guid-6a0f4adc-bdf4-4004-aa56-192e86f213d6/start"",
      ""method"": ""PUT""
    },
    ""stop"": {
      ""href"": ""/v3/apps/guid-6a0f4adc-bdf4-4004-aa56-192e86f213d6/stop"",
      ""method"": ""PUT""
    },
    ""assign_current_droplet"": {
      ""href"": ""/v3/apps/guid-6a0f4adc-bdf4-4004-aa56-192e86f213d6/current_droplet"",
      ""method"": ""PUT""
    }
  }
}";
                clients.JsonResponse = json;

                clients.ExpectedStatusCode = (HttpStatusCode)200;
                var cfClient = clients.CreateCloudFoundryClient();

                Guid?guid = Guid.NewGuid();

                UpdateAppRequest value = new UpdateAppRequest();


                var obj = cfClient.Apps.UpdateApp(guid, value).Result;


                Assert.AreEqual("guid-6a0f4adc-bdf4-4004-aa56-192e86f213d6", TestUtil.ToTestableString(obj.Guid), true);
                Assert.AreEqual("new_name", TestUtil.ToTestableString(obj.Name), true);
                Assert.AreEqual("STOPPED", TestUtil.ToTestableString(obj.DesiredState), true);
                Assert.AreEqual("0", TestUtil.ToTestableString(obj.TotalDesiredInstances), true);
                Assert.AreEqual("2015-06-30T07:10:43Z", TestUtil.ToTestableString(obj.CreatedAt), true);
                Assert.AreEqual("2015-06-30T07:10:43Z", TestUtil.ToTestableString(obj.UpdatedAt), true);
            }
        }
コード例 #27
0
 internal static Task <UpdateAppResponse> CustomUpdateApp(CloudController.V2.Client.Base.AbstractAppsEndpoint arg1, Guid?arg2, UpdateAppRequest arg3)
 {
     return(Task.Factory.StartNew <UpdateAppResponse>(() =>
     {
         return new UpdateAppResponse()
         {
             Name = "TestApp"
         };
     }));
 }