Exemplo n.º 1
0
 /// <summary>
 /// Logs an info exception.
 /// </summary>
 /// <param name="log">The log.</param>
 /// <param name="e">The exception.</param>
 public static void LogInfo(this INeonLogger log, Exception e)
 {
     if (log.IsInfoEnabled)
     {
         log.LogInfo(null, e);
     }
 }
Exemplo n.º 2
0
 /// <summary>
 /// Logs a warning message retrieved via a message function.
 /// </summary>
 /// <param name="log">The log.</param>
 /// <param name="messageFunc">The message function.</param>
 /// <param name="activityId">The optional activity ID.</param>
 /// <remarks>
 /// This method is intended mostly to enable the efficient use of interpolated C# strings.
 /// </remarks>
 public static void LogWarn(this INeonLogger log, Func <string> messageFunc, string activityId = null)
 {
     if (log.IsLogWarnEnabled)
     {
         log.LogWarn(messageFunc(), activityId);
     }
 }
Exemplo n.º 3
0
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="sourceModule">Optionally enables transient error logging by identifying the source module (defaults to <c>null</c>).</param>
 public RetryPolicyBase(string sourceModule = null)
 {
     if (!string.IsNullOrEmpty(sourceModule))
     {
         log = LogManager.Default.GetLogger(sourceModule);
     }
 }
Exemplo n.º 4
0
        /// <summary>
        /// <para>
        /// Upserts the cache entry with an expiration time defined by <see cref="Cache.DurationSeconds"/>.
        /// After this period, it's no longer possible to reconnect a Blazor session back to the server,
        /// so we remove the entry from the cache.
        /// </para>
        /// </summary>
        /// <param name="context">The <see cref="HttpContext"/>.</param>
        /// <param name="cache">The Cache.</param>
        /// <param name="cipher">The AES Cipher used to encrypt/decrypt cookies.</param>
        /// <param name="cacheOptions">The Cache options.</param>
        /// <param name="logger">The <see cref="INeonLogger"/></param>
        /// <returns></returns>
        public async Task InvokeAsync(
            HttpContext context,
            Service service,
            IDistributedCache cache,
            AesCipher cipher,
            DistributedCacheEntryOptions cacheOptions,
            INeonLogger logger)
        {
            await SyncContext.Clear;

            await _next(context);

            if (service.CurrentConnections.Contains(context.Connection.Id))
            {
                var cookie    = context.Request.Cookies.Where(c => c.Key == Service.SessionCookieName).First();
                var sessionId = cipher.DecryptStringFrom(cookie.Value);
                var session   = NeonHelper.JsonDeserialize <Session>(await cache.GetAsync(sessionId));

                if (session.ConnectionId == context.Connection.Id)
                {
                    await cache.SetAsync(session.Id, NeonHelper.JsonSerializeToBytes(session), cacheOptions);

                    WebsocketMetrics.CurrentConnections.Dec();
                    service.CurrentConnections.Remove(context.Connection.Id);
                }
            }
        }
Exemplo n.º 5
0
        private INeonLogger neonLogger;         // Non-NULL if [logger] is also an [INeonLogger].

        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="logger">The <see cref="ILogger"/> being wrapped.</param>
        public NeonLoggerShim(ILogger logger)
        {
            Covenant.Requires <ArgumentNullException>(logger == null, nameof(logger));

            this.logger     = logger;
            this.neonLogger = logger as INeonLogger;
        }
Exemplo n.º 6
0
 /// <summary>
 /// Logs a warning exception.
 /// </summary>
 /// <param name="log">The log.</param>
 /// <param name="e">The exception.</param>
 public static void LogWarn(this INeonLogger log, Exception e)
 {
     if (log.IsWarnEnabled)
     {
         log.LogWarn(null, e);
     }
 }
Exemplo n.º 7
0
        /// <summary>
        /// Default constructor.
        /// </summary>
        /// <param name="k8s">The <see cref="IKubernetes"/> client used by the controller.</param>
        /// <param name="options">
        /// Optionally specifies options that customize the resource manager's behavior.  Reasonable
        /// defaults will be used when this isn't specified.
        /// </param>
        /// <param name="filter">
        /// <para>
        /// Optionally specifies a predicate to be use for filtering the resources to be managed.
        /// This can be useful for situations where multiple operator instances will partition
        /// and handle the resources amongst themselves.  A good example is a node based operator
        /// that handles only the resources associated with the node.
        /// </para>
        /// <para>
        /// Your filter should examine the resource passed and return <c>true</c> when the resource
        /// should be managed by this resource manager.  The default filter always returns <c>true</c>.
        /// </para>
        /// </param>
        /// <param name="logger">Optionally specifies the logger to be used by the instance.</param>
        /// <param name="leaderConfig">
        /// Optionally specifies the <see cref="LeaderElectionConfig"/> to be used to control
        /// whether only a single entity is managing a specific resource kind at a time.  See
        /// the <b>LEADER ELECTION SECTION</b> in the <see cref="ResourceManager{TResource, TController}"/>
        /// remarks for more information.
        /// </param>
        public ResourceManager(
            IKubernetes k8s,
            ResourceManagerOptions options    = null,
            Func <TEntity, bool> filter       = null,
            INeonLogger logger                = null,
            LeaderElectionConfig leaderConfig = null)
        {
            Covenant.Requires <ArgumentNullException>(k8s != null, nameof(k8s));

            this.k8s          = k8s;  // $todo(jefflill): Can we obtain this from KubeOps or the [IServiceProvider] somehow?
            this.options      = options ?? new ResourceManagerOptions();
            this.filter       = filter ?? new Func <TEntity, bool>(resource => true);
            this.log          = logger ?? LogManager.Default.GetLogger($"Neon.Kube.Operator.ResourceManager({typeof(TEntity).Name})");
            this.leaderConfig = leaderConfig;

            options.Validate();

            // $todo(jefflill): https://github.com/nforgeio/neonKUBE/issues/1589
            //
            // Locate the controller's constructor that has a single [IKubernetes] parameter.

            var controllerType = typeof(TController);

            this.controllerConstructor = controllerType.GetConstructor(new Type[] { typeof(IKubernetes) });

            if (this.controllerConstructor == null)
            {
                throw new NotSupportedException($"Controller type [{controllerType.FullName}] does not have a constructor accepting a single [{nameof(IKubernetes)}] parameter.  This is currently required.");
            }
        }
Exemplo n.º 8
0
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="k8s">The Kubernetes clien.</param>
 /// <param name="logger">Optionally specifies the logger to use.</param>
 public Watcher(IKubernetes k8s, INeonLogger logger = null)
 {
     this.k8s    = k8s;
     this.logger = logger;
     eventReady  = new AsyncAutoResetEvent();
     eventQueue  = new Queue <WatchEvent <T> >();
 }
Exemplo n.º 9
0
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="log">The inderlying <see cref="INeonLogger"/> implementation.</param>
        public LogRecorder(INeonLogger log)
        {
            Covenant.Requires <ArgumentNullException>(log != null, nameof(log));

            this.log     = log;
            this.capture = new StringBuilder();
        }
Exemplo n.º 10
0
        //---------------------------------------------------------------------
        // ILog implementation.

        /// <summary>
        /// Returns the logger to use for this instance.
        /// </summary>
        /// <returns>The logger.</returns>
        private INeonLogger GetLogger()
        {
            // Lazy load the logger for better performance in the common case
            // where nothing is logged for a request.

            if (log != null)
            {
                return(log);
            }

            // $todo(jeff.lill):
            //
            // I should be getting either an [ILogProvider] or [ILogManager] dynamically via
            // dependency injection rather than hardcoding a call to [LogManager.Default]
            // and then getting an [INeonLogger] from that or wrapping an [ILogger] with
            // a [NeonLoggerShim].
            //
            // I'm not entirely sure how to accomplish this.  I believe the only way is
            // to add a [ILogProvider] parameter to this class' constructor (as well as
            // that of any derived classes) and then inspect the actual instance type
            // passed and then decide whether we need a [NeonLoggerShim] or not.
            //
            // It would be unforunate though to require derived classes to have to handle
            // this.  An alternative might be use property injection, but I don't think
            // the ASP.NET pipeline supports that.
            //
            // See the TODO in [LogManager.cs] for more information.

            return(log = LogManager.Default.GetLogger("Web-" + base.ControllerContext.ActionDescriptor.ControllerName));
        }
Exemplo n.º 11
0
 /// <summary>
 /// Logs an error exception.
 /// </summary>
 /// <param name="log">The log.</param>
 /// <param name="e">The exception.</param>
 public static void LogError(this INeonLogger log, Exception e)
 {
     if (log.IsErrorEnabled)
     {
         log.LogError(null, e);
     }
 }
Exemplo n.º 12
0
 /// <summary>
 /// Logs a transient exception.
 /// </summary>
 /// <param name="log">The log.</param>
 /// <param name="e">The exception.</param>
 /// <param name="activityId">The optional activity ID.</param>
 public static void LogTransient(this INeonLogger log, Exception e, string activityId = null)
 {
     if (log.IsLogTransientEnabled)
     {
         log.LogTransient(null, e, activityId);
     }
 }
Exemplo n.º 13
0
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="sourceModule">Optionally enables transient error logging by identifying the source module (defaults to <c>null</c>).</param>
        /// <param name="timeout">Optionally specifies the maximum time the operation should be retried (defaults to no limit).</param>
        public RetryPolicyBase(string sourceModule = null, TimeSpan?timeout = null)
        {
            if (!string.IsNullOrEmpty(sourceModule))
            {
                this.log = LogManager.Default.GetLogger(sourceModule);
            }

            if (timeout != null && timeout >= TimeSpan.Zero)
            {
                this.Timeout = timeout;

                // Compute the UTC deadline, taking care not not to
                // exceed the end-of-time.

                var utcNow = SysTime.Now;

                if (timeout >= DateTime.MaxValue - utcNow)
                {
                    sysDeadline = DateTime.MaxValue;
                }
                else
                {
                    sysDeadline = utcNow + timeout.Value;
                }
            }
            else
            {
                sysDeadline = DateTime.MaxValue;
            }
        }
Exemplo n.º 14
0
 /// <summary>
 /// Logs a critical exception.
 /// </summary>
 /// <param name="log">The log.</param>
 /// <param name="e">The exception.</param>
 public static void LogCritical(this INeonLogger log, Exception e)
 {
     if (log.IsCriticalEnabled)
     {
         log.LogCritical(null, e);
     }
 }
Exemplo n.º 15
0
 /// <summary>
 /// Logs a critical message retrieved via a message function.
 /// </summary>
 /// <param name="log">The log.</param>
 /// <param name="messageFunc">The message function.</param>
 /// <remarks>
 /// This method is intended mostly to enable the efficient use of interpolated C# strings.
 /// </remarks>
 public static void LogCritical(this INeonLogger log, Func <object> messageFunc)
 {
     if (log.IsCriticalEnabled)
     {
         log.LogCritical(messageFunc());
     }
 }
Exemplo n.º 16
0
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="log">Optionally specifies a <see cref="INeonLogger"/> used for logging.</param>
        /// <param name="gracefulShutdownTimeout">Optionally specifies the termination timeout (defaults to <see cref="GracefulShutdownTimeout"/>).</param>
        /// <param name="minShutdownTime">
        /// Optionally specifies the minimum time to wait before allowing termination to proceed.
        /// This defaults to the minimum of <paramref name="gracefulShutdownTimeout"/> and <see cref="DefaultMinShutdownTime"/>.
        /// See the remarks for more details.
        /// </param>
        /// <remarks>
        /// <para>
        /// <paramref name="gracefulShutdownTimeout"/> defaults to 30 seconds and for environments like Kubernetes, this
        /// should be set to the same value as the host pod's <b>terminationGracePeriodSeconds</b> when
        /// that's different from its default value of 30 seconds.
        /// </para>
        /// <para>
        /// <paramref name="minShutdownTime"/> can be used to control the minimum period the service will continue
        /// to run after receiving a TERM signal.  This can be important for ASPNET based services because
        /// Kubernetes can take something like 10 seconds to remove the pod from the service load balancer
        /// after sending a TERM to the pod.  Having a pod terminate before the load balancer is updated means
        /// that other pods may see request errors during this time.  This blog post goes into this in some
        /// detail:
        /// </para>
        /// <para>
        /// https://blog.markvincze.com/graceful-termination-in-kubernetes-with-asp-net-core/
        /// </para>
        /// <para>
        /// <paramref name="minShutdownTime"/> defaults to the minimum of <paramref name="gracefulShutdownTimeout"/> and
        /// <see cref="GracefulShutdownTimeout"/> to wait for the service load balancer to update.  This applies to both
        /// ASP.NET and headless services so you may wish to reduce <paramref name="minShutdownTime"/> so that headless
        /// services will terminate quicker.  Pass a negative timespan to disable this behavior.
        /// </para>
        /// <note>
        /// The <see cref="Signal"/> method ignores <paramref name="minShutdownTime"/> to improve unit test performance.
        /// </note>
        /// </remarks>
        public ProcessTerminator(INeonLogger log = null, TimeSpan gracefulShutdownTimeout = default, TimeSpan minShutdownTime = default)
        {
            Covenant.Requires <ArgumentException>(gracefulShutdownTimeout >= TimeSpan.Zero, nameof(gracefulShutdownTimeout));
            Covenant.Requires <ArgumentException>(minShutdownTime >= TimeSpan.Zero, nameof(minShutdownTime));

            this.log = log;

            if (gracefulShutdownTimeout <= TimeSpan.Zero)
            {
                gracefulShutdownTimeout = DefaultGracefulTimeout;
            }

            if (minShutdownTime == TimeSpan.Zero)
            {
                minShutdownTime = DefaultMinShutdownTime;
            }

            this.GracefulShutdownTimeout = gracefulShutdownTimeout;
            this.MinShutdownTime         = NeonHelper.Min(gracefulShutdownTimeout, minShutdownTime);
            this.cts      = new CancellationTokenSource();
            this.handlers = new List <Action>();

            AssemblyLoadContext.Default.Unloading +=
                context =>
            {
                ExitInternal();
            };
        }
Exemplo n.º 17
0
 /// <summary>
 /// Logs a warning message retrieved via a message function.
 /// </summary>
 /// <param name="log">The log.</param>
 /// <param name="messageFunc">The message function.</param>
 /// <remarks>
 /// This method is intended mostly to enable the efficient use of interpolated C# strings.
 /// </remarks>
 public static void LogWarn(this INeonLogger log, Func <object> messageFunc)
 {
     if (log.IsWarnEnabled)
     {
         log.LogWarn(messageFunc());
     }
 }
Exemplo n.º 18
0
 /// <summary>
 /// Logs an error message retrieved via a message function.
 /// </summary>
 /// <param name="log">The log.</param>
 /// <param name="messageFunc">The message function.</param>
 /// <remarks>
 /// This method is intended mostly to enable the efficient use of interpolated C# strings.
 /// </remarks>
 public static void LogError(this INeonLogger log, Func <object> messageFunc)
 {
     if (log.IsErrorEnabled)
     {
         log.LogError(messageFunc());
     }
 }
Exemplo n.º 19
0
 /// <summary>
 /// Logs a debug message retrieved via a message function.
 /// </summary>
 /// <param name="log">The log.</param>
 /// <param name="messageFunc">The message function.</param>
 /// <remarks>
 /// This method is intended mostly to enable the efficient use of interpolated C# strings.
 /// </remarks>
 public static void LogDebug(this INeonLogger log, Func <object> messageFunc)
 {
     if (log.IsDebugEnabled)
     {
         log.LogDebug(messageFunc());
     }
 }
Exemplo n.º 20
0
 /// <summary>
 /// Logs an informational message retrieved via a message function.
 /// </summary>
 /// <param name="log">The log.</param>
 /// <param name="messageFunc">The message function.</param>
 /// <remarks>
 /// This method is intended mostly to enable the efficient use of interpolated C# strings.
 /// </remarks>
 public static void LogInfo(this INeonLogger log, Func <object> messageFunc)
 {
     if (log.IsInfoEnabled)
     {
         log.LogInfo(messageFunc());
     }
 }
Exemplo n.º 21
0
 /// <summary>
 /// Logs a critical exception.
 /// </summary>
 /// <param name="log">The log.</param>
 /// <param name="e">The exception.</param>
 /// <param name="activityId">The optional activity ID.</param>
 public static void LogCritical(this INeonLogger log, Exception e, string activityId = null)
 {
     if (log.IsLogCriticalEnabled)
     {
         log.LogCritical(null, e, activityId);
     }
 }
Exemplo n.º 22
0
        /// <summary>
        /// Formats the log message.
        /// </summary>
        /// <param name="neonLogger">The <see cref="INeonLogger"/> implementation or <c>null</c>.</param>
        /// <param name="message">The message object.</param>
        /// <param name="activityId">The optional activiity ID.</param>
        /// <returns>The formatted log event.</returns>
        private static string FormatMessage(INeonLogger neonLogger, object message, string activityId = null)
        {
            string text;

            if (message == null)
            {
                text = string.Empty;
            }
            else
            {
                text = message.ToString();
            }

            if (!string.IsNullOrEmpty(activityId))
            {
                text += $" [activity-id:{activityId}]";
            }

            if (neonLogger != null && !string.IsNullOrEmpty(neonLogger.ContextId))
            {
                text += $" [context-id:{neonLogger.ContextId}]";
            }

            return(text);
        }
Exemplo n.º 23
0
 /// <summary>
 /// Logs a transient message retrieved via a message function.
 /// </summary>
 /// <param name="log">The log.</param>
 /// <param name="messageFunc">The message function.</param>
 /// <param name="activityId">The optional activity ID.</param>
 /// <remarks>
 /// This method is intended mostly to enable the efficient use of interpolated C# strings.
 /// </remarks>
 public static void LogTransient(this INeonLogger log, Func <string> messageFunc, string activityId = null)
 {
     if (log.IsLogDebugEnabled)
     {
         log.LogTransient(messageFunc(), activityId);
     }
 }
Exemplo n.º 24
0
 /// <summary>
 /// Logs a debug exception.
 /// </summary>
 /// <param name="log">The log.</param>
 /// <param name="e">The exception.</param>
 public static void LogDebug(this INeonLogger log, Exception e)
 {
     if (log.IsDebugEnabled)
     {
         log.LogDebug(null, e);
     }
 }
Exemplo n.º 25
0
 /// <summary>
 /// Creates a log activity with the ID specified.
 /// </summary>
 /// <param name="activityId">The activity ID or <c>null</c>,</param>
 /// <param name="log">The optional associated <see cref="INeonLogger"/>.</param>
 /// <returns>The created <see cref="LogActivity"/>.</returns>
 public static LogActivity From(string activityId, INeonLogger log = null)
 {
     return(new LogActivity()
     {
         Id = !string.IsNullOrWhiteSpace(activityId) ? activityId : null,
         log = log
     });
 }
Exemplo n.º 26
0
 /// <summary>
 /// Creates a log activity with a new globally unique ID.
 /// </summary>
 /// <param name="log">The optional associated <see cref="INeonLogger"/>.</param>
 /// <returns>The created <see cref="LogActivity"/>.</returns>
 public static LogActivity Create(INeonLogger log = null)
 {
     return(new LogActivity()
     {
         Id = Guid.NewGuid().ToString("d"),
         log = log
     });
 }
Exemplo n.º 27
0
 public DexClient(Uri baseAddress, INeonLogger logger = null)
 {
     this.jsonClient = new JsonClient()
     {
         BaseAddress = baseAddress
     };
     this.AuthHeaders = new Dictionary <string, BasicAuthenticationHeaderValue>();
     this.Logger      = logger;
 }
Exemplo n.º 28
0
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="neonDashboardService"></param>
 /// <param name="neonLogger"></param>
 /// <param name="cache"></param>
 public LoginModel(
     Service neonDashboardService,
     INeonLogger neonLogger,
     IDistributedCache cache)
 {
     this.neonDashboardService = neonDashboardService;
     this.logger = neonLogger;
     this.cache  = cache;
 }
Exemplo n.º 29
0
        /// <summary>
        /// Application entry point.
        /// </summary>
        /// <param name="args">Command line arguments.</param>
        public static async Task Main(string[] args)
        {
            LogManager.Default.SetLogLevel(Environment.GetEnvironmentVariable("LOG_LEVEL"));
            log = LogManager.Default.GetLogger(typeof(Program));
            log.LogInfo(() => $"Starting [{serviceName}]");
            log.LogInfo(() => $"LOG_LEVEL={LogManager.Default.LogLevel.ToString().ToUpper()}");

            // Create process terminator to handle termination signals.

            terminator = new ProcessTerminator(log);

            try
            {
                var commandLine = new CommandLine(args);
                var command     = commandLine.Arguments.ElementAtOrDefault(0);

                if (command == null)
                {
                    log.LogError("usage: vegomatic COMMAND ARGS...");
                    Program.Exit(1, immediate: true);
                }

                switch (command)
                {
                case "cephfs":

                    await new CephFS().ExecAsync(commandLine.Shift(1));
                    break;

                case "issue-mntc":

                    await new IssueMntc().ExecAsync(commandLine.Shift(1));
                    break;

                default:
                case "test-server":

                    await new TestServer().ExecAsync(commandLine.Shift(1));
                    break;
                }
            }
            catch (Exception e)
            {
                log.LogCritical(e);
                Program.Exit(1);
                return;
            }
            finally
            {
                HiveHelper.CloseHive();
                terminator.ReadyToExit();
            }

            Program.Exit(0);
            return;
        }
Exemplo n.º 30
0
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="sourceModule">Optionally enables transient error logging by identifying the source module (defaults to <c>null</c>).</param>
        /// <param name="timeout">Optionally specifies the maximum time the operation will be retried (defaults to unconstrained)</param>
        public RetryPolicyBase(string sourceModule = null, TimeSpan?timeout = null)
        {
            this.SourceModule = sourceModule;
            this.Timeout      = timeout;

            if (!string.IsNullOrEmpty(sourceModule))
            {
                this.log = LogManager.Default.GetLogger(sourceModule);
            }
        }