Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Kingson4Wu/light_master

Repository files navigation

light_master

light_master is a Java library for automatic master node election and detection in distributed systems. It provides a simple, HTTP-based mechanism for determining the master node among multiple instances, with flexible configuration and easy integration.

Technical Principle

  • Each instance generates a unique UUID at startup.
  • All instances periodically check each other via HTTP to determine the master node.
  • The node with the smallest UUID is considered the master.
  • HTTP endpoints are used for mutual checking and status reporting.
  • Token-based authentication is supported for security.

Design

  • LightMasterManager: Core logic for master election and status management.
  • InstanceInfo: Represents peer node information (IP, port).
  • LightMasterHttpChecker: Interface for HTTP-based status checking.
  • DefaultLightMasterHttpChecker: Default implementation using Java HttpURLConnection.
  • LightMasterServlet: Provides HTTP endpoints for master check and health check.
  • Configurable: All parameters (peers, timeout, URI, token) can be set via properties or environment variables.
  • Event Callback: Supports master switch event notification via listener interface.

Usage

Installation

Add the following dependencies to your build.gradle:

dependencies {
    implementation 'org.slf4j:slf4j-api:2.0.13'
    implementation 'com.fasterxml.jackson.core:jackson-databind:2.15.3'
    compileOnly 'jakarta.servlet:jakarta.servlet-api:5.0.0'
    testImplementation 'org.mockito:mockito-core:5.12.0'
}

Configuration

Edit lib/src/main/resources/application.properties:

lightmaster.instances=127.0.0.2:8080,127.0.0.3:8080
lightmaster.checkUri=/check
lightmaster.contextPath=
lightmaster.timeoutMs=1000
lightmaster.token=changeme

Or set via environment variables (e.g. LIGHTMASTER_TOKEN).

Integration Example

LightMasterConfig config = new LightMasterConfig();
DefaultLightMasterHttpChecker checker = new DefaultLightMasterHttpChecker(config);
LightMasterManager manager = LightMasterManager.fromConfig(config, checker);
manager.setMasterSwitchListener(isMaster -> {
    if (isMaster) {
        System.out.println("This node becomes master");
    } else {
        System.out.println("This node lost master status");
    }
});

// Integrate with Servlet
LightMasterServlet servlet = new LightMasterServlet(manager, config.getToken());
// Register servlet to your container, mapping /check and /health endpoints

HTTP API

1. Master Node Check

  • Path: /check
  • Method: GET/POST
  • Parameters:
    • method=CHECK_MASTER
    • uuid=local node UUID
    • token=configured token
  • Response:
{"master":true}

2. Health Check

  • Path: /health
  • Method: GET/POST
  • Response:
{"status":"UP"}

Testing

Run all tests:

./gradlew test

Limitations & Consistency Notice

light_master is a lightweight master election SDK that provides best-effort, unreliable master selection. It does NOT guarantee:

  • There is always exactly one master (multiple nodes may consider themselves master in case of network partition, delays, or split-brain situations).
  • There is always at least one master (in extreme cases, all nodes may consider themselves non-master).
  • Atomic or unique master switch events.

This SDK is suitable for scenarios where weak consistency is acceptable, such as non-critical leader election, scheduled job preemption, or auxiliary master indication. It is NOT suitable for strong consistency requirements, distributed transactions, or distributed locks.

Recommended Use Cases

light_master is ideal for scenarios where only one node should perform a certain action at a time, but strong consistency is not required. For example:

  • Scheduled job notifications: Only one node sends notifications to avoid duplicates.
  • Monitoring and alerting: Only one node pushes alerts to prevent repeated alarms.
  • Auxiliary leader-based operations: Non-critical master-backup switching, cache refresh, log archiving, etc.

Dynamic Instance List

light_master supports dynamic updates of the instance list at runtime. You can update the participating nodes via code, for example integrating with service discovery or registry. Users can implement their own node update strategy by calling:

manager.updateInstances(newInstanceList);

This allows you to keep the master election in sync with your actual cluster topology.

Advanced: Automatic & Event-Driven Instance Updates

You can implement your own instance discovery logic by providing an InstanceProvider and let light_master refresh the instance list automatically:

manager.setInstanceProvider(() -> myServiceDiscovery.getInstances(), 10); // refresh every 10 seconds

You can also call updateInstances() manually in response to service registry events for event-driven updates.

To stop the periodic refresh:

manager.stopInstanceProvider();

Project Roadmap & Future Plans

  • Support for gossip protocol as an optional node state synchronization mechanism for large-scale clusters (planned, not implemented yet).
  • More pluggable node discovery and election strategies.
  • Integration with mainstream service discovery (e.g., Nacos, Consul, Eureka).
  • More advanced master election algorithms (e.g., Raft, etcd integration) as optional modules.
  • Community feedback and contributions are welcome!

License

light_master is licensed under the Apache 2.0 License

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages