Sentinel Go

repository·master·Indexed 25 days ago

https://github.com/alibaba/sentinel-golang

A flow-control component for microservices designed to ensure reliability and resiliency. It provides features including flow control, circuit breaking, concurrency limiting, traffic shaping, and system adaptive overload protection. Sentinel Go supports real-time monitoring, Prometheus metrics export, and includes framework adapters for Echo, Fiber, Gear, and Gin, as well as Kubernetes CRD data-source support.

Tokens
10.9K
Snippets
15
Records
103
Agent score
83%

What's inside sentinel-golang

  1. Overview of Sentinel Go features

    master

    Sentinel Go is a reliability and resiliency library for microservices that focuses on managing traffic flow. It provides several key capabilities to protect distributed systems:

    • Flow Control: Managing the rate of incoming requests.
    • Traffic Shaping: Smoothing out burst traffic to match system capacity.
    • Concurrency Limiting: Restricting the number of concurrent requests.
    • Circuit Breaking: Automatically cutting off requests to unreliable downstream services to prevent cascading failures.
    • System Adaptive Overload Protection: Automatically adjusting to system load to prevent crashes.

    Additionally, Sentinel supports real-time monitoring of single-machine runtime information and can export metrics to external components like Prometheus.

  2. Simulate Business Errors in Outlier Detection Test

    master

    To simulate business-level failures (e.g., 5XX errors), set the first argument of setup.sh to false (the default).

    In this mode, the service nodes remain reachable, but specific nodes enter a 'fault period' based on their ID. For each node, the fault starts at startTime + 5s + (id * 5s) and lasts for 20 seconds. During this window, the Ping method in handler.go returns errors.New("internal server error") instead of a successful response.

    This tests Sentinel's ability to remove nodes from the load balancer that are technically online but returning application-level errors, a capability that standard service registries often lack.

  3. Explore Sentinel Go integrations and data-sources

    master

    Sentinel Go provides specialized modules for easier integration into existing ecosystems:

    • Framework Adapters: Out-of-the-box integrations for popular Go web frameworks and microservice components.
    • Dynamic Data-source Modules: Support for dynamic configuration of rules via external data sources.
  4. Simulate Node Crashes in Outlier Detection Test

    master

    To simulate a node crash scenario, set the first argument of setup.sh to true.

    When node_crash=true, the script performs the following sequence:

    1. Start Processes: Launches node_count service processes on unique ports (e.g., 9001 to 9009) using go run . --server_address=:$port.
    2. Stop Processes: After 5 seconds, it kills the processes sequentially using pgrep -f "hello_micro --server_address=:$port" | xargs kill.
    3. Restart Processes: After another 5 seconds, it restarts the processes on the same ports.

    This simulates network-level failures where RPC calls might block or fail due to the node being unreachable.

    cd hello_micro && ./setup.sh true 4
  5. Run the Outlier Detection End-to-End Example

    master

    This example demonstrates Sentinel's outlier detection (outlier removal) capabilities using microservice frameworks like go-micro, kitex, and kratos with etcd as the registry. It simulates both node crashes (network errors) and business errors (5XX responses) to show how Sentinel removes unhealthy nodes from the load balancer and restores them via passive recovery detection.

    Prerequisites

    1. Install etcd: Follow the official etcd installation guide.
    2. Start etcd: Run etcd locally (default port 2379).

    Execution Steps

    1. Start Service Processes: Use the setup.sh script in the framework directory (e.g., hello_micro).
      • The first argument node_crash (boolean) determines if you are simulating node crashes. Default is false (simulates business errors).
      • The second argument node_count specifies the number of service nodes. Default is 9.
      • Example (simulate 4 nodes crashing): cd hello_micro && ./setup.sh true 4
    2. Start Client: Run the client in the client directory. The client performs 200 calls every 500ms to evaluate the effectiveness of the outlier detection.
  6. Configure Outlier Ejection in Kitex

    master

    To enable outlier ejection (ejecting unhealthy nodes) in a Kitex client, you must:

    1. Enable outlier detection in SentinelClientMiddleware via options.
    2. Wrap your existing discovery.Resolver with OutlierClientResolver.

    When EnableOutlier is true, the middleware uses a custom slot chain containing outlier.DefaultSlot and outlier.DefaultMetricStatSlot to track node health and identify nodes to filter.

  7. Integrate Sentinel with go-zero using SentinelRouteMiddleware

    master

    To protect go-zero services with Sentinel, you can use the SentinelRouteMiddleware. This middleware automatically generates a resource name based on the HTTP method and URL path (e.g., GET:/api/user) and applies Sentinel flow control using the ResTypeWeb resource type and Inbound traffic type.

    To use this in a go-zero project, define the middleware in your .api file using the @server directive:

    @server(
        middleware: SentinelRoute
    )
    service your_service {
        // ... routes
    }

    Note: The middleware implementation provided is a template designed to be used with goctl. The Handle method intercepts requests, calls sentinel.Entry, and returns a 429 Too Many Requests error with the message Blocked by Sentinel if the request is throttled.

  8. Configure Hertz Server middleware options

    master

    When using Sentinel with a Hertz server, you can customize how resources are identified and how blocked requests are handled using ServerOption.

    By default:

    • Resource Extraction: Uses the format METHOD:PATH (e.g., GET:/api/user).
    • Block Fallback: Aborts the request with http.StatusTooManyRequests (429).

    Use WithServerResourceExtractor to define a custom function for identifying resources and WithServerBlockFallback to define custom logic when a request is blocked.

  9. Use Sentinel middleware with the Gear framework

    master

    Integrate Sentinel into a Gear-based application using SentinelMiddleware. This middleware automatically creates Sentinel entries for incoming web requests to provide flow control and protection.

    Default Behavior:

    • Resource Name: Uses the pattern {method}:{path} (e.g., GET:/api/users/:id).
    • Block Fallback: If a request is blocked by Sentinel, the middleware returns an http.StatusTooManyRequests (429) status code with the body Blocked by Sentinel.

    Customization: You can customize the middleware behavior by passing Option arguments to SentinelMiddleware to:

    • Provide a custom resourceExtract function to define how the resource name is generated from the gear.Context.
    • Provide a custom blockFallback function to define specific logic (e.g., custom error responses) when a request is blocked.
  10. Initialize a Consul data source for Sentinel

    master

    Use NewDataSource to create a datasource.DataSource that watches a specific key in Consul for configuration updates. You can provide an existing *api.Client from the HashiCorp Consul API or provide a *api.Config to let Sentinel initialize the client for you.

    After creation, call Initialize() to perform the first read and start the background watching process. To stop watching and release resources, call Close().