static object StartServer(string host, int port, ICartStore cartStore)
        {
            // Run the server in a separate thread and make the main thread busy waiting.
            // The busy wait is because when we run in a container, we can't use techniques such as waiting on user input (Console.Readline())
            Task serverTask = Task.Run(async() =>
            {
                try
                {
                    await cartStore.InitializeAsync();

                    var redisCartStore = cartStore as RedisCartStore;

                    if (redisCartStore != null)
                    {
                        tracerProvider = OpenTelemetry.Sdk.CreateTracerProviderBuilder()
                                         .AddRedisInstrumentation(redisCartStore.ConnectionMultiplexer)
                                         .AddSource(CartServiceImpl.ActivitySourceName)
                                         .SetResource(Resources.CreateServiceResource("CartService"))
                                         .AddNewRelicExporter(options =>
                        {
                            options.ApiKey      = Environment.GetEnvironmentVariable("NEW_RELIC_API_KEY");
                            options.EndpointUrl = new Uri(Environment.GetEnvironmentVariable("NEW_RELIC_TRACE_URL"));
                        })
                                         .Build();
                    }


                    Console.WriteLine($"Trying to start a grpc server at  {host}:{port}");
                    Server server = new Server
                    {
                        Services =
                        {
                            // Cart Service Endpoint
                            Hipstershop.CartService.BindService(new CartServiceImpl(cartStore)),

                            // Health Endpoint
                            Grpc.Health.V1.Health.BindService(new HealthImpl(cartStore))
                        },
                        Ports = { new ServerPort(host, port, ServerCredentials.Insecure) }
                    };

                    Console.WriteLine($"Cart server is listening at {host}:{port}");
                    server.Start();

                    Console.WriteLine("Initialization completed");

                    // Keep the server up and running
                    while (true)
                    {
                        Thread.Sleep(TimeSpan.FromMinutes(10));
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
            });

            return(Task.WaitAny(new[] { serverTask }));
        }
Example #2
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            string     redisAddress = Configuration["REDIS_ADDR"];
            ICartStore cartStore    = null;

            if (!string.IsNullOrEmpty(redisAddress))
            {
                cartStore = new RedisCartStore(redisAddress);
            }
            else
            {
                Console.WriteLine("Redis cache host(hostname+port) was not specified. Starting a cart service using local store");
                Console.WriteLine("If you wanted to use Redis Cache as a backup store, you should provide its address via command line or REDIS_ADDRESS environment variable.");
                cartStore = new LocalCartStore();
            }

            // Initialize the redis store
            cartStore.InitializeAsync().GetAwaiter().GetResult();
            Console.WriteLine("Initialization completed");

            services.AddSingleton <ICartStore>(cartStore);

            services.AddGrpc();

            services.AddOpenTelemetryTracing(builder => ConfigureOpenTelemetry(builder, cartStore));
        }
Example #3
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);

            string lsHost      = Environment.GetEnvironmentVariable(LIGHTSTEP_HOST);
            int    lsPort      = Int32.Parse(Environment.GetEnvironmentVariable(LIGHTSTEP_PORT));
            string serviceName = Environment.GetEnvironmentVariable("LS_SERVICE_NAME");
            string accessToken = Environment.GetEnvironmentVariable(LIGHTSTEP_ACCESS_TOKEN);
            // create and register an activity source
            var activitySource = new ActivitySource(serviceName);

            services.AddSingleton(activitySource);

            // from: https://github.com/kellybirr/tracing-demo
            OpenTelemetry.Sdk.SetDefaultTextMapPropagator(new B3Propagator());

            string     redisAddress = Configuration["REDIS_ADDR"];
            ICartStore cartStore    = null;

            if (!string.IsNullOrEmpty(redisAddress))
            {
                cartStore = new RedisCartStore(redisAddress);
            }
            else
            {
                Console.WriteLine("Redis cache host(hostname+port) was not specified. Starting a cart service using local store");
                Console.WriteLine("If you wanted to use Redis Cache as a backup store, you should provide its address via command line or REDIS_ADDR environment variable.");
                cartStore = new LocalCartStore();
            }

            services.AddOpenTelemetryTracing((builder) => builder
                                             .AddSource(activitySource.Name)
                                             .AddAspNetCoreInstrumentation(opt =>
            {
                opt.EnableGrpcAspNetCoreSupport = true;
            })
                                             .AddHttpClientInstrumentation()
                                             .AddGrpcClientInstrumentation()
                                             .AddConsoleExporter()
                                             .AddRedisInstrumentation(cartStore.Connection)
                                             .SetResourceBuilder(ResourceBuilder.CreateDefault().AddService(serviceName))
                                             .AddOtlpExporter(opt => {
                opt.Endpoint = $"{lsHost}:{lsPort}";
                opt.Headers  = new Metadata
                {
                    { "lightstep-access-token", accessToken }
                };
                opt.Credentials = new SslCredentials();
            }));

            // Initialize the redis store
            cartStore.InitializeAsync().GetAwaiter().GetResult();
            Console.WriteLine("Initialization completed");

            services.AddSingleton <ICartStore>(cartStore);

            services.AddGrpc();
        }
        public InstrumentedCartStore(ICartStore cartStore)
        {
            this.cartStore = cartStore;

            // Create Span Builders for tracing
            initializeSpanBuilder = CreateSpanBuilder("Initialize Cart Store");
            addItemSpanBuilder    = CreateSpanBuilder("Add Item");
            emptySpanBuilder      = CreateSpanBuilder("Empty Cart");
            getItemSpanBuilder    = CreateSpanBuilder("Get Cart");
            pingSpanBuilder       = CreateSpanBuilder("Ping");
        }
Example #5
0
        private static void ConfigureOpenTelemetry(TracerProviderBuilder builder, ICartStore cartStore)
        {
            builder.AddAspNetCoreInstrumentation();

            if (cartStore is RedisCartStore redisCartStore)
            {
                builder.AddRedisInstrumentation(redisCartStore.ConnectionMultiplexer);
            }

            var exportType       = Environment.GetEnvironmentVariable("NEW_RELIC_DEMO_EXPORT_TYPE") ?? "newrelic";
            var newRelicApiKey   = Environment.GetEnvironmentVariable("NEW_RELIC_API_KEY");
            var newRelicTraceUrl = Environment.GetEnvironmentVariable("NEW_RELIC_TRACE_URL");
            var serviceName      = "CartService" + (exportType == "newrelic" ? string.Empty : $"-{exportType}");

            builder.SetResourceBuilder(ResourceBuilder.CreateDefault().AddService(serviceName, null, null, false, $"{exportType}-{Guid.NewGuid().ToString()}"));

            switch (exportType)
            {
            case "otlp":
                var otlpEndpoint = Environment.GetEnvironmentVariable("OTEL_EXPORTER_OTLP_SPAN_ENDPOINT")
                                   ?? Environment.GetEnvironmentVariable("OTEL_EXPORTER_OTLP_ENDPOINT");

                if (!otlpEndpoint.StartsWith("http"))
                {
                    otlpEndpoint = $"https://{otlpEndpoint}";
                }

                builder
                .AddOtlpExporter(options => {
                    options.Endpoint = new Uri(otlpEndpoint);
                    options.Headers  = $"x-nr-key={newRelicApiKey}";
                });
                break;

            case "zipkin":
                var zipkinEndpoint = $"{newRelicTraceUrl}?Api-Key={newRelicApiKey}&Data-Format=zipkin&Data-Format-Version=2";
                builder
                .AddZipkinExporter(options => options.Endpoint = new Uri(zipkinEndpoint));
                break;

            case "newrelic":
            default:
                builder
                .AddNewRelicExporter(options =>
                {
                    options.ApiKey   = newRelicApiKey;
                    options.Endpoint = new Uri(newRelicTraceUrl);
                });
                break;
            }
        }
Example #6
0
        static object StartServer(string host, int port, ICartStore cartStore)
        {
            // Run the server in a separate thread and make the main thread busy waiting.
            // The busy wait is because when we run in a container, we can't use techniques such as waiting on user input (Console.Readline())
            Task serverTask = Task.Run(async() =>
            {
                try
                {
                    await cartStore.InitializeAsync();

                    Console.WriteLine($"Trying to start a grpc server at  {host}:{port}");
                    Server server = new Server
                    {
                        Services =
                        {
                            // Cart Service Endpoint
                            Hipstershop.CartService.BindService(new CartServiceImpl(cartStore)),

                            // Health Endpoint
                            Grpc.Health.V1.Health.BindService(new HealthImpl(cartStore))
                        },
                        Ports = { new ServerPort(host, port, ServerCredentials.Insecure) }
                    };

                    Console.WriteLine($"Cart server is listening at {host}:{port}");
                    server.Start();

                    Console.WriteLine("Initialization completed");

                    // zipkinuri = Environment.GetEnvironmentVariable(ZIPKIN_ADDRESS);
                    // if (!string.IsNullOrEmpty(zipkinuri))
                    // {
                    //     Console.WriteLine(zipkinuri);
                    //     Zipkin.Run(zipkinuri);
                    // }

                    // Keep the server up and running
                    while (true)
                    {
                        Thread.Sleep(TimeSpan.FromMinutes(10));
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
            });

            return(Task.WaitAny(new[] { serverTask }));
        }
Example #7
0
        static void Main(string[] args)
        {
            if (args.Length == 0)
            {
                Console.WriteLine("Invalid number of arguments supplied");
                Environment.Exit(-1);
            }

            switch (args[0])
            {
            case "start":
                Parser.Default.ParseArguments <ServerOptions>(args).MapResult(
                    (ServerOptions options) =>
                {
                    Console.WriteLine($"Started as process with id {System.Diagnostics.Process.GetCurrentProcess().Id}");

                    // Set hostname/ip address
                    string hostname = ReadParameter("host address", options.Host, CART_SERVICE_ADDRESS, p => p, "0.0.0.0");

                    // Set the port
                    int port = ReadParameter("cart service port", options.Port, CART_SERVICE_PORT, int.Parse, 8080);

                    string projectId = ReadParameter("cloud service project id", options.ProjectId, PROJECT_ID, p => p, null);

                    // Initialize Stackdriver Exporter - currently for tracing only
                    if (!string.IsNullOrEmpty(projectId))
                    {
                        var exporter = new StackdriverExporter(
                            projectId,
                            Tracing.ExportComponent,
                            viewManager: null);
                        exporter.Start();
                    }

                    // Set redis cache host (hostname+port)
                    string redis = ReadParameter("redis cache address", options.Redis, REDIS_ADDRESS, p => p, null);

                    ICartStore cartStore = InstrumentedCartStore.Create(redis);
                    return(StartServer(hostname, port, cartStore));
                },
                    errs => 1);
                break;

            default:
                Console.WriteLine("Invalid command");
                break;
            }
        }
Example #8
0
        static object StartServer(string host, int port, ICartStore cartStore)
        {
            // Run the server in a separate thread and make the main thread busy waiting.
            // The busy wait is because when we run in a container, we can't use techniques such as waiting on user input (Console.Readline())
            Task serverTask = Task.Run(async() =>
            {
                try
                {
                    await cartStore.InitializeAsync();

                    // setup grpc interceptor
                    var tracingInterceptor = new ServerTracingInterceptor(GlobalTracer.Instance);

                    Console.WriteLine($"Trying to start a grpc server at  {host}:{port}");
                    Server server = new Server
                    {
                        Services =
                        {
                            // Cart Service Endpoint
                            Hipstershop.CartService.BindService(new CartServiceImpl(cartStore)).Intercept(tracingInterceptor),

                            // Health Endpoint
                            Grpc.Health.V1.Health.BindService(new HealthImpl(cartStore)).Intercept(tracingInterceptor),
                        },
                        Ports = { new ServerPort(host, port, ServerCredentials.Insecure) }
                    };

                    Console.WriteLine($"Cart server is listening at {host}:{port}");
                    server.Start();

                    Console.WriteLine("Initialization completed");

                    // Keep the server up and running
                    while (true)
                    {
                        Thread.Sleep(TimeSpan.FromMinutes(10));
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
            });

            return(Task.WaitAny(new[] { serverTask }));
        }
Example #9
0
        public static void AddOpenTelemetry(this IServiceCollection services, ICartStore cartStore)
        {
            services.AddOpenTelemetryTracing(builder => {
                builder.SetResourceBuilder(ResourceBuilder);

                builder.AddAspNetCoreInstrumentation();

                if (cartStore is RedisCartStore redisCartStore)
                {
                    builder.AddRedisInstrumentation(redisCartStore.ConnectionMultiplexer);
                }

                builder
                .AddOtlpExporter(options => {
                    var opts         = GetOptions();
                    options.Endpoint = opts.endpoint;
                    options.Headers  = opts.headers;
                });
            });
        }
        public static ICartStore Create(string redis)
        {
            ICartStore cartStore;

            // Redis was specified
            if (!string.IsNullOrEmpty(redis))
            {
                // If you want to start cart store using local cache in process, you can replace the following line with this:
                // cartStore = new LocalCartStore();
                cartStore = new RedisCartStore(redis);
            }
            else
            {
                Console.WriteLine("Redis cache host(hostname+port) was not specified. Starting a cart service using local store");
                Console.WriteLine("If you wanted to use Redis Cache as a backup store, you should provide its address via command line or REDIS_ADDRESS environment variable.");
                cartStore = new LocalCartStore();
            }

            // We create the cart store wrapped with instrumentation
            return(new InstrumentedCartStore(cartStore));
        }
Example #11
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            string     redisAddress = Configuration["REDIS_ADDR"];
            ICartStore cartStore    = null;

            if (!string.IsNullOrEmpty(redisAddress))
            {
                cartStore = new RedisCartStore(redisAddress);
            }
            else
            {
                Console.WriteLine("Redis cache host(hostname+port) was not specified. Starting a cart service using local store");
                Console.WriteLine("If you wanted to use Redis Cache as a backup store, you should provide its address via command line or REDIS_ADDR environment variable.");
                cartStore = new LocalCartStore();
            }

            // Initialize the redis store
            cartStore.InitializeAsync().GetAwaiter().GetResult();
            Console.WriteLine("Initialization completed");

            services.AddSingleton <ICartStore>(cartStore);
            services.AddGrpc();

            // Adding the OtlpExporter creates a GrpcChannel.
            // This switch must be set before creating a GrpcChannel/HttpClient when calling an insecure gRPC service.
            // See: https://docs.microsoft.com/aspnet/core/grpc/troubleshoot#call-insecure-grpc-services-with-net-core-client
            AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);

            services.AddOpenTelemetryTracing(builder =>
            {
                builder.AddAspNetCoreInstrumentation()
                .AddOtlpExporter(options =>
                                 options.Endpoint = new Uri(Configuration["OTEL_COLLECTOR_ADDR"]));
                if (cartStore is RedisCartStore redisCartStore)
                {
                    builder.AddRedisInstrumentation(redisCartStore.RedisConnectionMultiplexer);
                }
            }
                                             );
        }
Example #12
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            string     redisAddress = Configuration["REDIS_ADDR"];
            ICartStore cartStore    = null;

            if (!string.IsNullOrEmpty(redisAddress))
            {
                cartStore = new RedisCartStore(redisAddress);
            }
            else
            {
                Console.WriteLine("Redis cache host(hostname+port) was not specified. Starting a cart service using local store");
                Console.WriteLine("If you wanted to use Redis Cache as a backup store, you should provide its address via command line or REDIS_ADDR environment variable.");
                cartStore = new LocalCartStore();
            }

            // Initialize the redis store
            cartStore.InitializeAsync().GetAwaiter().GetResult();
            Console.WriteLine("Initialization completed");
            services.AddSingleton <ICartStore>(cartStore);

            services.AddGrpc();
            string otelAddress = Configuration["OTEL_COLLECTOR_ADDR"];

            AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
            services.AddOpenTelemetryTracing((builder) => builder
                                             .SetResourceBuilder(ResourceBuilder.CreateDefault()
                                                                 .AddAttributes(new Dictionary <string, object>
            {
                ["telemetry.sdk.language"] = "dotnet",
            })
                                                                 .AddService(this.Configuration.GetValue <string>("Otel:ServiceName")))
                                             .AddAspNetCoreInstrumentation()
                                             .AddRedisInstrumentation(cartStore.GetConnection())
                                             .AddOtlpExporter(opt => opt.Endpoint = new Uri(otelAddress)));
        }
Example #13
0
 public CartService(ICartStore cartStore)
 {
     _cartStore = cartStore;
 }
Example #14
0
 public CartService(ILogger <CartService> logger, ICartStore cartStore)
 {
     _logger    = logger;
     _cartStore = cartStore;
 }
 public CartService(IProductService productService, ICartStore cartStore)
 {
     _cartStore      = cartStore;
     _productService = productService;
 }
Example #16
0
 public CartService(IProductData productData, ICartStore cartStore)
 {
     this.productData = productData;
     this.cartStore   = cartStore;
 }
Example #17
0
 public CartService(ICartStore CartStore, IProductData ProductData)
 {
     _CartStore   = CartStore;
     _ProductData = ProductData;
 }
Example #18
0
 public HealthCheckService(ICartStore dependency)
 {
     this._dependency = dependency;
 }
Example #19
0
 public CartService(IProductData productData, ICartStore cartStore)
 {
     _productData = productData;
     _cartStore   = cartStore;
 }
Example #20
0
 public HealthImpl(ICartStore dependency)
 {
     this.dependency = dependency;
 }
 public CartServiceImpl(ICartStore cartStore)
 {
     this.cartStore = cartStore;
 }
Example #22
0
 public HealthCheckService(ICartStore cartStore)
 {
     _cartStore = cartStore;
 }
Example #23
0
 public CartService(IProductData productData, ICartStore cartStore, IMapper mapper)
 {
     _mapper      = mapper;
     _productData = productData;
     _cartStore   = cartStore;
 }
Example #24
0
 public InventoryService(IInventoryStore inventoryStore, ICartStore cartStore)
 {
     _inventoryStore = inventoryStore;
     _cartStore      = cartStore;
 }
Example #25
0
 public CartService(ICatalogData catalogData, ICartStore cartStore)
 {
     _catalogData = catalogData;
     _cartStore   = cartStore;
 }
Example #26
0
 public CartService(IProductData ProductData, ICartStore CartStore)
 {
     _ProductData = ProductData;
     _CartStore   = CartStore;
 }
Example #27
0
 public CartService(IProductService productService, ICartStore cartstore)
 {
     cartStore      = cartstore;
     ProductService = productService;
 }
 public CartServiceImpl(ICartStore cartStore)
 {
     this.cartStore = cartStore;
     oneAgentSdk    = OneAgentSdkFactory.CreateInstance();
 }
 public CartServiceController(ICartStore cartStore)
 {
     _cartStore = cartStore;
 }
Example #30
0
 public CartsController(ICartStore store)
 {
     this.store = store;
 }