Exemple #1
0
        public void RecentWebSockerError()
        {
            using (ShimsContext.Create())
            {
                var errorEvent      = default(EventHandler <ErrorEventArgs>);
                var errorEventFired = new ManualResetEvent(false);

                ShimLogyardWebSocket.AllInstances.ErrorReceivedAddEventHandlerOfErrorEventArgs = (@this, h) => errorEvent = h;
                ShimLogyardWebSocket.AllInstances.OpenUriStringUriBoolean = (@this, appLogEndpoint, authenticationToken, proxy, skipCertValidation) => { };

                LogyardLog logyard = new LogyardLog(logyardEndpoint, string.Empty);
                logyard.ErrorReceived += delegate(object sender, ErrorEventArgs e)
                {
                    Assert.AreEqual("Test error", e.Error.Message);
                    errorEventFired.Set();
                };

                logyard.StartLogStream(Guid.NewGuid().ToString());

                errorEvent(this, new ErrorEventArgs()
                {
                    Error = new LogyardException("Test error")
                });

                Assert.IsTrue(errorEventFired.WaitOne(100));
            }
        }
Exemple #2
0
        public void StopRecentTest()
        {
            using (ShimsContext.Create())
            {
                var closedEvent      = default(EventHandler <EventArgs>);
                var closedEventFired = new ManualResetEvent(false);

                ShimLogyardWebSocket.AllInstances.StreamClosedAddEventHandlerOfEventArgs = (@this, h) => closedEvent = h;
                ShimLogyardWebSocket.AllInstances.OpenUriStringUriBoolean = (@this, appLogEndpoint, authenticationToken, proxy, skipCertValidation) => { };
                ShimLogyardWebSocket.AllInstances.Close = (@this) =>
                {
                    closedEvent(this, EventArgs.Empty);
                };
                ShimLogyardWebSocket.AllInstances.Dispose = (@this) => { };

                LogyardLog logyard = new LogyardLog(logyardEndpoint, string.Empty);
                logyard.StreamClosed += delegate(object sender, EventArgs e)
                {
                    closedEventFired.Set();
                };

                logyard.StartLogStream(Guid.NewGuid().ToString(), 50, false);
                logyard.StopLogStream();

                Assert.IsTrue(closedEventFired.WaitOne(100));
                Assert.AreEqual(ConnectionState.None, logyard.State);
            }
        }
Exemple #3
0
        public void RecentWebSocketOpen()
        {
            using (ShimsContext.Create())
            {
                var openEvent      = default(EventHandler <EventArgs>);
                var state          = ConnectionState.None;
                var openEventFired = new ManualResetEvent(false);

                ShimLogyardWebSocket.AllInstances.StreamOpenedAddEventHandlerOfEventArgs = (@this, h) => openEvent = h;
                ShimLogyardWebSocket.AllInstances.StateGet = (@this) => { return(state); };
                ShimLogyardWebSocket.AllInstances.OpenUriStringUriBoolean = (@this, appLogEndpoint, authenticationToken, proxy, skipCertValidation) => { state = ConnectionState.Open; };

                LogyardLog log = new LogyardLog(logyardEndpoint, string.Empty);
                log.StreamOpened += delegate(object sender, EventArgs e)
                {
                    openEventFired.Set();
                };

                log.StartLogStream(Guid.NewGuid().ToString(), 50);
                openEvent(this, EventArgs.Empty);

                Assert.IsTrue(openEventFired.WaitOne(100));
                Assert.AreEqual(log.State, ConnectionState.Open);
            }
        }
Exemple #4
0
        private void GetLogsUsingLogyard(CloudFoundryClient client, Guid?appGuid, GetV1InfoResponse info)
        {
            using (LogyardLog logyard = new LogyardLog(new Uri(info.AppLogEndpoint), string.Format(CultureInfo.InvariantCulture, "bearer {0}", client.AuthorizationToken), null, CFSkipSslValidation))
            {
                logyard.ErrorReceived += (sender, error) =>
                {
                    Logger.LogErrorFromException(error.Error);
                };

                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(appGuid.Value.ToString(), 0, true);

                this.MonitorApp(client, appGuid);

                logyard.StopLogStream();
            }
        }
Exemple #5
0
        public void LogsTest()
        {
            CreateAppResponse app = client.Apps.CreateApp(apprequest).Result;

            Guid appGuid = app.EntityMetadata.Guid;

            client.Apps.Push(appGuid, appPath, true).Wait();

            while (true)
            {
                var instances = client.Apps.GetInstanceInformationForStartedApp(appGuid).Result;
                if (instances.Count > 0)
                {
                    if (instances[0].State.ToLower() == "running")
                    {
                        break;
                    }
                }
            }

            var logyardClient = new LogyardLog(
                new Uri(client.Info.GetV1Info().Result.AppLogEndpoint),
                string.Format("bearer {0}", client.AuthorizationToken),
                null,
                true);

            var logs = new List <string>();

            logyardClient.MessageReceived += delegate(object sender, MessageEventArgs e)
            {
                Assert.IsTrue(string.IsNullOrEmpty(e.Message.Error));
                logs.Add(e.Message.Value.Text);
            };


            logyardClient.ErrorReceived += delegate(object sender, Logyard.Client.ErrorEventArgs e)
            {
                Assert.Fail("Logyard error: {0}", e.Error.ToString());
            };

            EventWaitHandle stopevent = new EventWaitHandle(false, EventResetMode.ManualReset);

            logyardClient.StreamClosed += delegate { stopevent.Set(); };

            logyardClient.StartLogStream(appGuid.ToString(), 100, false);
            stopevent.WaitOne();

            var conatainsPushedContent = logs.Any((line) => line.Contains("dummy content"));

            Assert.IsTrue(conatainsPushedContent, "Pushed content was not dumped in the output stream");

            var conatainsEnvContent = logs.Any((line) => line.Contains("env-test-1234"));

            Assert.IsTrue(conatainsEnvContent, "Pushed env variable was not dumped in the output stream");

            client.Apps.DeleteApp(appGuid).Wait();
        }
Exemple #6
0
        public void RecentTwiceTest()
        {
            using (ShimsContext.Create())
            {
                ShimLogyardWebSocket.AllInstances.OpenUriStringUriBoolean = (@this, appLogEndpoint, authenticationToken, proxy, skipCertValidation) => { };

                LogyardLog logyard = new LogyardLog(logyardEndpoint, string.Empty);

                string appGuid = Guid.NewGuid().ToString();
                logyard.StartLogStream(appGuid);
                try
                {
                    logyard.StartLogStream(appGuid);
                }
                catch (Exception ex)
                {
                    Assert.IsInstanceOfType(ex, typeof(InvalidOperationException));
                    Assert.IsTrue(ex.Message.Contains("The log stream has already been started."));
                }
            }
        }
Exemple #7
0
        public void RecentNullAppIdTest()
        {
            using (ShimsContext.Create())
            {
                ShimLogyardWebSocket.AllInstances.OpenUriStringUriBoolean = (@this, appLogEndpoint, authenticationToken, proxy, skipCertValidation) => { };

                LogyardLog logyard = new LogyardLog(logyardEndpoint, string.Empty);

                try
                {
                    logyard.StartLogStream(null);
                }
                catch (Exception ex)
                {
                    Assert.IsInstanceOfType(ex, typeof(ArgumentNullException));
                }
            }
        }
Exemple #8
0
        public void RecentWebSocketMessage()
        {
            using (ShimsContext.Create())
            {
                var openEvent         = default(EventHandler <EventArgs>);
                var messageEvent      = default(EventHandler <StringEventArgs>);
                var messageEventFired = new ManualResetEvent(false);

                Guid   appGuid = Guid.NewGuid();
                string text    = "This is a log entry";
                string source  = "app";

                string json = string.Format(@"{{""value"":{{""source"":""{0}"", ""app_guid"":""{1}"", ""text"":""{2}"", ""syslog"":{{ }} }} }}", source, appGuid.ToString(), text);

                Message msg = new Message();
                msg.Value         = new MessageValue();
                msg.Value.AppGuid = appGuid;
                msg.Value.Text    = text;
                msg.Value.Source  = source;
                msg.Value.Syslog  = new ValueSyslog();

                ShimLogyardWebSocket.AllInstances.StreamOpenedAddEventHandlerOfEventArgs       = (@this, h) => openEvent = h;
                ShimLogyardWebSocket.AllInstances.DataReceivedAddEventHandlerOfStringEventArgs = (@this, h) => messageEvent = h;
                ShimLogyardWebSocket.AllInstances.OpenUriStringUriBoolean = (@this, appLogEndpoint, authenticationToken, proxy, skipCertValidation) => { };

                LogyardLog log = new LogyardLog(logyardEndpoint, string.Empty);
                log.MessageReceived += delegate(object sender, MessageEventArgs e)
                {
                    Assert.AreEqual(msg.Value.Source, e.Message.Value.Source);
                    Assert.AreEqual(msg.Value.AppGuid, e.Message.Value.AppGuid);
                    Assert.AreEqual(msg.Value.Text, e.Message.Value.Text);
                    messageEventFired.Set();
                };

                log.StartLogStream(msg.Value.AppGuid.ToString());

                messageEvent(this, new StringEventArgs()
                {
                    Data = json
                });
                Assert.IsTrue(messageEventFired.WaitOne(100));
            }
        }
Exemple #9
0
        public void TailRecentLogsInvalidValueTest()
        {
            using (ShimsContext.Create())
            {
                ShimLogyardWebSocket.AllInstances.OpenUriStringUriBoolean = (@this, appLogEndpoint, authenticationToken, proxy, skipCertValidation) => { };

                LogyardLog logyard = new LogyardLog(logyardEndpoint, string.Empty);

                string appGuid = Guid.NewGuid().ToString();

                try
                {
                    logyard.StartLogStream(appGuid, -100, true);
                }
                catch (Exception ex)
                {
                    Assert.IsInstanceOfType(ex, typeof(ArgumentOutOfRangeException));
                    Assert.IsTrue(ex.Message.Contains(">= -1"));
                }
            }
        }
Exemple #10
0
        public void RecentWebSocketErrorMessage()
        {
            using (ShimsContext.Create())
            {
                var openEvent         = default(EventHandler <EventArgs>);
                var messageEvent      = default(EventHandler <StringEventArgs>);
                var messageEventFired = new ManualResetEvent(false);

                Guid   appGuid = Guid.NewGuid();
                string error   = "This is a error";

                string json = string.Format(@"{{""error"":""{0}""}}", error);

                Message msg = new Message();
                msg.Error = error;

                ShimLogyardWebSocket.AllInstances.StreamOpenedAddEventHandlerOfEventArgs       = (@this, h) => openEvent = h;
                ShimLogyardWebSocket.AllInstances.DataReceivedAddEventHandlerOfStringEventArgs = (@this, h) => messageEvent = h;
                ShimLogyardWebSocket.AllInstances.OpenUriStringUriBoolean = (@this, appLogEndpoint, authenticationToken, proxy, skipCertValidation) => { };

                LogyardLog log = new LogyardLog(logyardEndpoint, string.Empty);
                log.ErrorReceived += delegate(object sender, ErrorEventArgs e)
                {
                    Assert.AreEqual(msg.Error, e.Error.Message);
                    messageEventFired.Set();
                };

                log.StartLogStream(appGuid.ToString());

                messageEvent(this, new StringEventArgs()
                {
                    Data = json
                });
                Assert.IsTrue(messageEventFired.WaitOne(100));
            }
        }
Exemple #11
0
        private void GetLogsUsingLogyard(CloudFoundryClient client, Guid?appGuid, CCV2.Data.GetV1InfoResponse info)
        {
            using (LogyardLog logyard = new LogyardLog(new Uri(info.AppLogEndpoint), string.Format(CultureInfo.InvariantCulture, "bearer {0}", client.AuthorizationToken), null, this.skipSSL))
            {
                logyard.ErrorReceived += (sender, error) =>
                {
                    Program.PrintExceptionMessage(error.Error);
                };

                logyard.StreamOpened += (sender, args) =>
                {
                    new ConsoleString("Log stream opened.", ConsoleColor.Cyan).WriteLine();
                };

                logyard.StreamClosed += (sender, args) =>
                {
                    new ConsoleString("Log stream closed.", ConsoleColor.Cyan).WriteLine();
                };

                logyard.MessageReceived += (sender, message) =>
                {
                    new ConsoleString(
                        string.Format("[{0}] - {1}: {2}",
                                      message.Message.Value.Source,
                                      message.Message.Value.HumanTime,
                                      message.Message.Value.Text),
                        ConsoleColor.White).WriteLine();
                };

                logyard.StartLogStream(appGuid.Value.ToString(), 0, true);

                this.MonitorApp(client, appGuid);

                logyard.StopLogStream();
            }
        }
Exemple #12
0
        public void LogyardRecentTest()
        {
            CreateAppResponse app = client.Apps.CreateApp(apprequest).Result;

            Guid appGuid = app.EntityMetadata.Guid;

            client.Apps.Push(appGuid, tempAppPath, true).Wait();

            while (true)
            {
                var appSummary   = client.Apps.GetAppSummary(appGuid).Result;
                var packageState = appSummary.PackageState.ToLowerInvariant();

                if (packageState != "pending")
                {
                    Assert.AreEqual(packageState, "staged");

                    var instances = client.Apps.GetInstanceInformationForStartedApp(appGuid).Result;

                    if (instances.Count > 0)
                    {
                        if (instances[0].State.ToLower() == "running")
                        {
                            break;
                        }
                    }
                }
            }

            if (client.Info.GetV1Info().Result.AppLogEndpoint == null)
            {
                Assert.Inconclusive("CloudFoundry target does not have a logyard endpoint");
            }

            var logyardClient = new LogyardLog(
                new Uri(client.Info.GetV1Info().Result.AppLogEndpoint),
                string.Format("bearer {0}", client.AuthorizationToken),
                null,
                true);

            var logs = new List <string>();

            logyardClient.MessageReceived += delegate(object sender, MessageEventArgs e)
            {
                Assert.IsTrue(string.IsNullOrEmpty(e.Message.Error));
                logs.Add(e.Message.Value.Text);
            };


            logyardClient.ErrorReceived += delegate(object sender, Logyard.Client.ErrorEventArgs e)
            {
                Assert.Fail("Logyard error: {0}", e.Error.ToString());
            };

            var stopevent = new EventWaitHandle(false, EventResetMode.ManualReset);

            logyardClient.StreamClosed += delegate { stopevent.Set(); };

            // Just wait a bit to get the latest logs
            Thread.Sleep(1000);

            logyardClient.StartLogStream(appGuid.ToString(), 100, false);

            stopevent.WaitOne();

            var conatainsPushedContent = logs.Any((line) => line.Contains("dummy content"));

            Assert.IsTrue(conatainsPushedContent, "Pushed content was not dumped in the output stream: {0}", string.Join(Environment.NewLine, logs));

            var conatainsEnvContent = logs.Any((line) => line.Contains("env-test-1234"));

            Assert.IsTrue(conatainsEnvContent, "Pushed env variable was not dumped in the output stream: {0}", string.Join(Environment.NewLine, logs));

            client.Apps.DeleteApp(appGuid).Wait();
            Directory.Delete(tempAppPath, true);
        }
        public void Push(PushArgs pushArgs)
        {
            if (!Directory.Exists(pushArgs.Dir))
            {
                throw new DirectoryNotFoundException(string.Format("Directory '{0}' not found", pushArgs.Dir));
            }

            CloudFoundryClient client = SetTargetInfoFromFile();

            // ======= GRAB FIRST SPACE AVAILABLE =======

            new ConsoleString("Looking up spaces ...", ConsoleColor.Cyan).WriteLine();

            PagedResponseCollection <ListAllSpacesResponse> spaces = client.Spaces.ListAllSpaces().Result;

            if (spaces.Count() == 0)
            {
                throw new InvalidOperationException("Couldn't find any spaces");
            }

            ListAllSpacesResponse space = spaces.First();

            new ConsoleString(string.Format("Will be using space {0}", space.Name), ConsoleColor.Green).WriteLine();

            // ======= CREATE AN APPLICATION =======

            new ConsoleString("Creating app ...", ConsoleColor.Cyan).WriteLine();


            PagedResponseCollection <ListAllStacksResponse> stacks = client.Stacks.ListAllStacks(new RequestOptions()
            {
                Query = string.Format("name:{0}", pushArgs.Stack)
            }).Result;

            if (stacks.Count() == 0)
            {
                throw new InvalidOperationException(string.Format("Couldn't find the stack {0}", pushArgs.Stack));
            }

            CreateAppRequest createAppRequest = new CreateAppRequest()
            {
                Name      = pushArgs.Name,
                Memory    = pushArgs.Memory,
                StackGuid = new Guid(stacks.First().EntityMetadata.Guid),
                SpaceGuid = new Guid(space.EntityMetadata.Guid)
            };

            CreateAppResponse appCreateResponse = client.Apps.CreateApp(createAppRequest).Result;

            new ConsoleString(string.Format("Created app with guid '{0}'", appCreateResponse.EntityMetadata.Guid), ConsoleColor.Green).WriteLine();

            // ======= CREATE A ROUTE =======

            new ConsoleString("Creating a route ...", ConsoleColor.Cyan).WriteLine();

            PagedResponseCollection <ListAllSharedDomainsResponse> allDomains = client.SharedDomains.ListAllSharedDomains().Result;

            if (allDomains.Count() == 0)
            {
                throw new InvalidOperationException("Could not find any shared domains");
            }

            string url = string.Format("{0}.{1}", pushArgs.Name, allDomains.First().Name);

            CreateRouteResponse createRouteResponse = client.Routes.CreateRoute(new CreateRouteRequest()
            {
                DomainGuid = new Guid(allDomains.First().EntityMetadata.Guid),
                Host       = pushArgs.Name,
                SpaceGuid  = new Guid(space.EntityMetadata.Guid)
            }).Result;

            new ConsoleString(string.Format("Created route '{0}.{1}'", pushArgs.Name, allDomains.First().Name), ConsoleColor.Green).WriteLine();

            // ======= BIND THE ROUTE =======

            new ConsoleString("Associating the route ...", ConsoleColor.Cyan).WriteLine();

            client.Routes.AssociateAppWithRoute(
                new Guid(createRouteResponse.EntityMetadata.Guid),
                new Guid(appCreateResponse.EntityMetadata.Guid)).Wait();

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

            GetV1InfoResponse v1Info  = client.Info.GetV1Info().Result;
            LogyardLog        logyard = new LogyardLog(new Uri(v1Info.AppLogEndpoint), string.Format("bearer {0}", client.AuthorizationToken));

            logyard.ErrorReceived += (sender, error) =>
            {
                Program.PrintExceptionMessage(error.Error);
            };

            logyard.StreamOpened += (sender, args) =>
            {
                new ConsoleString("Log stream opened.", ConsoleColor.Cyan).WriteLine();
            };

            logyard.StreamClosed += (sender, args) =>
            {
                new ConsoleString("Log stream closed.", ConsoleColor.Cyan).WriteLine();
            };

            logyard.MessageReceived += (sender, message) =>
            {
                new ConsoleString(
                    string.Format("[{0}] - {1}: {2}",
                                  message.Message.Value.Source,
                                  message.Message.Value.HumanTime,
                                  message.Message.Value.Text),
                    ConsoleColor.White).WriteLine();
            };

            logyard.StartLogStream(appCreateResponse.EntityMetadata.Guid, 0, true);

            // ======= PUSH THE APP =======
            new ConsoleString("Pushing the app ...", ConsoleColor.Cyan).WriteLine();
            client.Apps.PushProgress += (sender, progress) =>
            {
                new ConsoleString(string.Format("Push at {0}%", progress.Percent), ConsoleColor.Yellow).WriteLine();
                new ConsoleString(string.Format("{0}", progress.Message), ConsoleColor.DarkYellow).WriteLine();
            };

            client.Apps.Push(new Guid(appCreateResponse.EntityMetadata.Guid), pushArgs.Dir, true).Wait();

            // ======= WAIT FOR APP TO COME ONLINE =======
            bool done = false;

            while (true)
            {
                GetAppSummaryResponse appSummary = client.Apps.GetAppSummary(new Guid(appCreateResponse.EntityMetadata.Guid)).Result;

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

                if (appSummary.PackageState == "FAILED")
                {
                    throw new Exception("App staging failed.");
                }
                else if (appSummary.PackageState == "PENDING")
                {
                    new ConsoleString("[cfcmd] - App is staging ...", ConsoleColor.DarkCyan).WriteLine();
                }
                else if (appSummary.PackageState == "STAGED")
                {
                    new ConsoleString("[cfcmd] - App staged, waiting for it to come online ...", ConsoleColor.DarkCyan).WriteLine();
                }

                Thread.Sleep(2000);
            }

            logyard.StopLogStream();

            new ConsoleString(string.Format("App is running, done. You can browse it here: http://{0}.{1}", pushArgs.Name, allDomains.First().Name), ConsoleColor.Green).WriteLine();
        }
Exemple #14
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);
        }