diff --git a/docs/Configuration.md b/docs/Configuration.md index 4b312d467..e84c6f939 100644 --- a/docs/Configuration.md +++ b/docs/Configuration.md @@ -49,6 +49,13 @@ export COLONIES_CRON_CHECKER_PERIOD="1000" export COLONIES_GENERATOR_CHECKER_PERIOD="1000" ``` +### Clustering +By default the Colonies server runs an embedded Etcd instance for leader election and coordination between server replicas, see [High-Availability Deployment](HADeployment.md). Single-node deployments can disable clustering, in which case no Etcd or relay ports are opened and the local server is always the leader. The `--cluster=false` flag takes precedence over the variable below. Clustering must not be disabled when several Colonies servers share the same database, and `--initial-cluster` cannot be combined with clustering disabled. + +```console +export COLONIES_CLUSTER="false" +``` + ### Exclusive assign When exclusive assignment is enabled, all assign requests are handled by the elected leader server in the Colonies cluster. This guarantees that a process is assigned to exactly one executor. However, this approach may result in reduced performance as assign requests cannot be evenly distributed across all Colonies server replicas for load balancing purposes." diff --git a/docs/HADeployment.md b/docs/HADeployment.md index 1106217a1..1c34cd21a 100644 --- a/docs/HADeployment.md +++ b/docs/HADeployment.md @@ -7,6 +7,8 @@ The Colonies server uses 3 internal ports. Note: For security reasons, only API port should be exposed externally on the Internet. +Note: Clustering is only needed when running more than one Colonies server against the same database. A single-node deployment can start the server with `--cluster=false` (or `COLONIES_CLUSTER=false`), which skips the embedded Etcd server and the relay port entirely. See [Configuration](Configuration.md#clustering). + # RAFT/Etcd requirements | Colonies Server Replicas | Majority | Failure Tolerance | |:------------------------:|:--------:|:-----------------:| diff --git a/internal/cli/root.go b/internal/cli/root.go index aa0e03b58..44cf071a0 100644 --- a/internal/cli/root.go +++ b/internal/cli/root.go @@ -106,6 +106,7 @@ var Long float64 var Lat float64 var AllowExecutorReregister bool var ExclusiveAssign bool +var ClusterEnabled bool var StaleExecutorDuration int var Approve bool var Waiting bool diff --git a/internal/cli/server.go b/internal/cli/server.go index faa6e8079..1fcb74a42 100644 --- a/internal/cli/server.go +++ b/internal/cli/server.go @@ -27,7 +27,8 @@ func init() { chServerIDCmd.Flags().StringVarP(&TargetServerID, "serverid", "", "", "Server Id") chServerIDCmd.MarkFlagRequired("serverid") - serverCmd.PersistentFlags().StringVarP(&DBType, "dbtype", "", "postgresql", "Database type (postgresql or velocitydb)") + serverCmd.PersistentFlags().StringVarP(&DBType, "dbtype", "", "postgresql", "Database type") + serverCmd.PersistentFlags().BoolVarP(&ClusterEnabled, "cluster", "", true, "Enable etcd-based clustering (disable for single-node deployments, can also use COLONIES_CLUSTER)") serverCmd.PersistentFlags().StringVarP(&DBHost, "dbhost", "", "", "Colonies database host") serverCmd.PersistentFlags().IntVarP(&DBPort, "dbport", "", DefaultDBPort, "Colonies database port") serverCmd.PersistentFlags().StringVarP(&DBUser, "dbuser", "", "", "Colonies database user") @@ -57,6 +58,7 @@ func startServer( db database.Database, node cluster.Node, clusterConfig cluster.Config, + clusterEnabled bool, etcdDataPath string, ) { retentionPeriod := 60000 // Run retention worker once a minute @@ -72,6 +74,7 @@ func startServer( TLSCert, node, clusterConfig, + clusterEnabled, etcdDataPath, GeneratorCheckerPeriod, CronCheckerPeriod, @@ -141,6 +144,26 @@ var serverStartCmd = &cobra.Command{ parseDBEnv() parseEnv() + // Clustering can be disabled with COLONIES_CLUSTER for single-node + // deployments. An explicit --cluster flag takes precedence over the + // environment variable. + if clusterStr := os.Getenv("COLONIES_CLUSTER"); clusterStr != "" && !cmd.Flags().Changed("cluster") { + clusterEnabled, err := strconv.ParseBool(clusterStr) + if err != nil { + CheckError(errors.New("Invalid COLONIES_CLUSTER value: " + clusterStr + " (expected true or false)")) + } + ClusterEnabled = clusterEnabled + log.WithField("ClusterEnabled", ClusterEnabled).Info("Using COLONIES_CLUSTER from environment") + } + + if !ClusterEnabled && len(EtcdCluster) > 0 { + CheckError(errors.New("--initial-cluster cannot be combined with clustering disabled (--cluster=false / COLONIES_CLUSTER=false)")) + } + + log.WithFields(log.Fields{ + "ClusterEnabled": ClusterEnabled, + }).Info("Cluster configuration check") + // Read HTTP server configuration from environment if not set via flags if ServerPort == -1 { if portStr := os.Getenv("COLONIES_SERVER_HTTP_PORT"); portStr != "" { @@ -285,7 +308,7 @@ var serverStartCmd = &cobra.Command{ clusterConfig.AddNode(node) } - if EtcdDataDir == "" { + if EtcdDataDir == "" && ClusterEnabled { EtcdDataDir = "/tmp/colonies/prod/etcd" log.Warning("EtcdDataDir not specified, setting it to " + EtcdDataDir) } @@ -305,7 +328,7 @@ var serverStartCmd = &cobra.Command{ } log.Info("Starting HTTP server") - startServer(db, node, clusterConfig, EtcdDataDir) + startServer(db, node, clusterConfig, ClusterEnabled, EtcdDataDir) }, } diff --git a/pkg/cluster/coordinator.go b/pkg/cluster/coordinator.go new file mode 100644 index 000000000..856541ff8 --- /dev/null +++ b/pkg/cluster/coordinator.go @@ -0,0 +1,32 @@ +package cluster + +// Coordinator abstracts cluster coordination: membership, leader election and +// cross-server coordination state (the assignments-paused flags). +// +// Two implementations exist: +// - *EtcdServer: an embedded etcd cluster; used whenever clustering is enabled. +// - *LocalCoordinator: single-node semantics requiring no etcd. It is only +// valid when the Colonies server runs with clustering disabled. +type Coordinator interface { + // Lifecycle + Start() + WaitToStart() + Stop() + WaitToStop() + // StorageDir returns the on-disk data directory, or "" if the coordinator + // keeps no persistent state. Callers must not remove empty directories. + StorageDir() string + + // Cluster membership + Leader() string + Members() []Node + CurrentCluster() Config + + // Cross-server coordination state + PauseColonyAssignments(colonyName string) error + ResumeColonyAssignments(colonyName string) error + AreColonyAssignmentsPaused(colonyName string) (bool, error) +} + +// The embedded etcd server is one Coordinator implementation. +var _ Coordinator = (*EtcdServer)(nil) diff --git a/pkg/cluster/local.go b/pkg/cluster/local.go new file mode 100644 index 000000000..62da158f4 --- /dev/null +++ b/pkg/cluster/local.go @@ -0,0 +1,91 @@ +package cluster + +import ( + "sync" + + log "github.com/sirupsen/logrus" +) + +// LocalCoordinator is the single-node Coordinator. It requires no etcd and +// provides in-process semantics: +// - the local node is always the leader; +// - the cluster is a singleton; +// - assignments-paused flags live in memory. +// +// The in-memory coordination state is only correct for a single server +// process. Deployments with more than one Colonies server sharing a database +// must use clustering (the etcd Coordinator). The server cannot detect other +// servers on the same database, so the operator must ensure this; the CLI only +// rejects --initial-cluster when clustering is disabled. +type LocalCoordinator struct { + thisNode Node + clusterConfig Config + + pauseMutex sync.Mutex + pausedColonies map[string]bool +} + +// CreateLocalCoordinator creates the single-node Coordinator for the given node. +func CreateLocalCoordinator(thisNode Node) *LocalCoordinator { + config := Config{} + config.AddNode(thisNode) + config.Leader = thisNode + + log.WithFields(log.Fields{ + "Node": thisNode.Name, + "APIPort": thisNode.APIPort, + }).Info("Clustering disabled, using local (single-node) coordinator") + + return &LocalCoordinator{ + thisNode: thisNode, + clusterConfig: config, + pausedColonies: make(map[string]bool), + } +} + +// Lifecycle: a LocalCoordinator holds no resources and no persistent state. +func (c *LocalCoordinator) Start() {} +func (c *LocalCoordinator) WaitToStart() {} +func (c *LocalCoordinator) Stop() {} +func (c *LocalCoordinator) WaitToStop() {} +func (c *LocalCoordinator) StorageDir() string { return "" } + +// Cluster membership: the local node is always the leader. +func (c *LocalCoordinator) Leader() string { + return c.thisNode.Name +} + +func (c *LocalCoordinator) Members() []Node { + return []Node{c.thisNode} +} + +func (c *LocalCoordinator) CurrentCluster() Config { + return c.clusterConfig +} + +// Coordination state: in-memory assignments-paused flags. +func (c *LocalCoordinator) PauseColonyAssignments(colonyName string) error { + c.pauseMutex.Lock() + defer c.pauseMutex.Unlock() + c.pausedColonies[colonyName] = true + + log.WithFields(log.Fields{"Colony": colonyName}).Info("Colony process assignments have been paused") + return nil +} + +func (c *LocalCoordinator) ResumeColonyAssignments(colonyName string) error { + c.pauseMutex.Lock() + defer c.pauseMutex.Unlock() + delete(c.pausedColonies, colonyName) + + log.WithFields(log.Fields{"Colony": colonyName}).Info("Colony process assignments have been resumed") + return nil +} + +func (c *LocalCoordinator) AreColonyAssignmentsPaused(colonyName string) (bool, error) { + c.pauseMutex.Lock() + defer c.pauseMutex.Unlock() + return c.pausedColonies[colonyName], nil +} + +var _ Coordinator = (*LocalCoordinator)(nil) diff --git a/pkg/cluster/local_test.go b/pkg/cluster/local_test.go new file mode 100644 index 000000000..af4f7c70a --- /dev/null +++ b/pkg/cluster/local_test.go @@ -0,0 +1,59 @@ +package cluster + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestLocalCoordinatorIsAlwaysLeader(t *testing.T) { + node := Node{Name: "single", Host: "localhost", EtcdClientPort: 2379, EtcdPeerPort: 2380, RelayPort: 2381, APIPort: 8080} + coordinator := CreateLocalCoordinator(node) + + assert.Equal(t, "single", Coordinator(coordinator).Leader()) + assert.Equal(t, []Node{node}, coordinator.Members()) +} + +func TestLocalCoordinatorClusterConfig(t *testing.T) { + node := Node{Name: "single", Host: "localhost", APIPort: 8080} + coordinator := CreateLocalCoordinator(node) + + config := Coordinator(coordinator).CurrentCluster() + assert.Len(t, config.Nodes, 1) + assert.Equal(t, "single", config.Leader.Name) +} + +func TestLocalCoordinatorPause(t *testing.T) { + coordinator := CreateLocalCoordinator(Node{Name: "single", Host: "localhost", APIPort: 8080}) + + paused, err := coordinator.AreColonyAssignmentsPaused("colony1") + assert.Nil(t, err) + assert.False(t, paused) + + err = coordinator.PauseColonyAssignments("colony1") + assert.Nil(t, err) + + paused, err = coordinator.AreColonyAssignmentsPaused("colony1") + assert.Nil(t, err) + assert.True(t, paused) + + err = coordinator.ResumeColonyAssignments("colony1") + assert.Nil(t, err) + + paused, err = coordinator.AreColonyAssignmentsPaused("colony1") + assert.Nil(t, err) + assert.False(t, paused) +} + +func TestLocalCoordinatorLifecycle(t *testing.T) { + coordinator := CreateLocalCoordinator(Node{Name: "single", Host: "localhost", APIPort: 8080}) + + // Lifecycle calls must be no-ops and safe to call in any order + coordinator.Start() + coordinator.WaitToStart() + coordinator.Stop() + coordinator.WaitToStop() + + // No persistent state: StorageDir is empty so Stop paths never RemoveAll("") + assert.Equal(t, "", coordinator.StorageDir()) +} diff --git a/pkg/server/channel_integration_test.go b/pkg/server/channel_integration_test.go index 128d1a9ef..e08afc463 100644 --- a/pkg/server/channel_integration_test.go +++ b/pkg/server/channel_integration_test.go @@ -60,6 +60,7 @@ func TestChannelEndToEndIntegration(t *testing.T) { "", thisNode, clusterConfig, + true, // clustering enabled: this test exercises etcd maintenance behavior t.TempDir(), 10, // generator period 10, // cron period @@ -264,6 +265,7 @@ func TestChannelCleanupOnProcessFail(t *testing.T) { "", thisNode, clusterConfig, + true, // clustering enabled: this test exercises etcd maintenance behavior t.TempDir(), 10, // generator period 10, // cron period diff --git a/pkg/server/controllers/colonies_controller.go b/pkg/server/controllers/colonies_controller.go index fd3b393eb..6539ba639 100644 --- a/pkg/server/controllers/colonies_controller.go +++ b/pkg/server/controllers/colonies_controller.go @@ -113,7 +113,8 @@ type ColoniesController struct { leaderMutex sync.Mutex thisNode cluster.Node clusterConfig cluster.Config - etcdServer *cluster.EtcdServer + clusterEnabled bool + coordinator cluster.Coordinator leader bool generatorPeriod int cronPeriod int @@ -132,6 +133,7 @@ type ColoniesController struct { func CreateColoniesController(db database.Database, thisNode cluster.Node, clusterConfig cluster.Config, + clusterEnabled bool, etcdDataPath string, generatorPeriod int, cronPeriod int, @@ -159,9 +161,14 @@ func CreateColoniesController(db database.Database, controller.securityDB = db controller.thisNode = thisNode controller.clusterConfig = clusterConfig - controller.etcdServer = cluster.CreateEtcdServer(controller.thisNode, controller.clusterConfig, etcdDataPath) - controller.etcdServer.Start() - controller.etcdServer.WaitToStart() + controller.clusterEnabled = clusterEnabled + if clusterEnabled { + controller.coordinator = cluster.CreateEtcdServer(controller.thisNode, controller.clusterConfig, etcdDataPath) + controller.coordinator.Start() + controller.coordinator.WaitToStart() + } else { + controller.coordinator = cluster.CreateLocalCoordinator(controller.thisNode) + } controller.leader = false controller.generatorPeriod = generatorPeriod controller.cronPeriod = cronPeriod @@ -172,7 +179,9 @@ func CreateColoniesController(db database.Database, controller.pauseChannels = make(map[string][]chan bool) controller.channelRouter = channel.NewRouter() - controller.relayServer = cluster.CreateRelayServer(controller.thisNode, controller.clusterConfig) + if clusterEnabled { + controller.relayServer = cluster.CreateRelayServer(controller.thisNode, controller.clusterConfig) + } factory := backendGin.NewFactory() controller.eventHandler = factory.CreateEventHandler(controller.relayServer) @@ -203,7 +212,16 @@ func (controller *ColoniesController) GetGeneratorPeriod() int { } func (controller *ColoniesController) GetEtcdServer() *cluster.EtcdServer { - return controller.etcdServer + if etcdServer, ok := controller.coordinator.(*cluster.EtcdServer); ok { + return etcdServer + } + return nil +} + +// GetCoordinator returns the cluster coordinator, regardless of whether +// clustering is enabled (etcd-backed) or disabled (local single-node). +func (controller *ColoniesController) GetCoordinator() cluster.Coordinator { + return controller.coordinator } func (controller *ColoniesController) GetEventHandler() backends.RealtimeEventHandler { @@ -1298,11 +1316,11 @@ func (controller *ColoniesController) ResetDatabase() error { } func (controller *ColoniesController) PauseColonyAssignments(colonyName string) error { - return controller.etcdServer.PauseColonyAssignments(colonyName) + return controller.coordinator.PauseColonyAssignments(colonyName) } func (controller *ColoniesController) ResumeColonyAssignments(colonyName string) error { - err := controller.etcdServer.ResumeColonyAssignments(colonyName) + err := controller.coordinator.ResumeColonyAssignments(colonyName) if err != nil { return err } @@ -1313,7 +1331,7 @@ func (controller *ColoniesController) ResumeColonyAssignments(colonyName string) } func (controller *ColoniesController) AreColonyAssignmentsPaused(colonyName string) (bool, error) { - return controller.etcdServer.AreColonyAssignmentsPaused(colonyName) + return controller.coordinator.AreColonyAssignmentsPaused(colonyName) } // createResumeChannel creates a channel that will be signaled when assignments are resumed for a colony @@ -1354,8 +1372,12 @@ func (controller *ColoniesController) Stop() { controller.stopMutex.Unlock() controller.cmdQueue <- &command{stop: true} controller.eventHandler.Stop() - controller.relayServer.Shutdown() - controller.etcdServer.Stop() - controller.etcdServer.WaitToStop() - os.RemoveAll(controller.etcdServer.StorageDir()) + if controller.relayServer != nil { + controller.relayServer.Shutdown() + } + controller.coordinator.Stop() + controller.coordinator.WaitToStop() + if storageDir := controller.coordinator.StorageDir(); storageDir != "" { + os.RemoveAll(storageDir) + } } diff --git a/pkg/server/controllers/colonies_controller_worker.go b/pkg/server/controllers/colonies_controller_worker.go index 1dff0808d..6eb9141e0 100644 --- a/pkg/server/controllers/colonies_controller_worker.go +++ b/pkg/server/controllers/colonies_controller_worker.go @@ -10,7 +10,7 @@ import ( ) func (controller *ColoniesController) IsLeader() bool { - areWeLeader := controller.etcdServer.Leader() == controller.thisNode.Name + areWeLeader := controller.coordinator.Leader() == controller.thisNode.Name if areWeLeader && !controller.leader { log.WithFields(log.Fields{"EtcdNode": controller.thisNode.Name}).Debug("ColoniesServer became leader") controller.leader = true diff --git a/pkg/server/controllers/controller.go b/pkg/server/controllers/controller.go index 5d946ed12..145071708 100644 --- a/pkg/server/controllers/controller.go +++ b/pkg/server/controllers/controller.go @@ -12,7 +12,7 @@ import ( type Controller interface { GetCronPeriod() int GetGeneratorPeriod() int - GetEtcdServer() *cluster.EtcdServer + GetCoordinator() cluster.Coordinator GetEventHandler() backends.RealtimeEventHandler GetThisNode() cluster.Node SubscribeProcesses(executorID string, subscription *backends.RealtimeSubscription) error diff --git a/pkg/server/controllers/mock_test.go b/pkg/server/controllers/mock_test.go index ef9c0d8e2..d52d794b1 100644 --- a/pkg/server/controllers/mock_test.go +++ b/pkg/server/controllers/mock_test.go @@ -625,7 +625,7 @@ func newTestColoniesController(t *testing.T, db database.Database, name string) // CreateColoniesController binds the etcd and relay ports; the API port is // never bound by a bare controller utils.ReleasePorts(reserved) - return CreateColoniesController(db, node, clusterConfig, dataPath, constants.GENERATOR_TRIGGER_PERIOD, constants.CRON_TRIGGER_PERIOD, false, -1, 500, time.Duration(constants.DEFAULT_STALE_EXECUTOR_DURATION)*time.Second) + return CreateColoniesController(db, node, clusterConfig, true, dataPath, constants.GENERATOR_TRIGGER_PERIOD, constants.CRON_TRIGGER_PERIOD, false, -1, 500, time.Duration(constants.DEFAULT_STALE_EXECUTOR_DURATION)*time.Second) } func createFakeColoniesController(t *testing.T) (*ColoniesController, *DatabaseMock) { diff --git a/pkg/server/gin_managed_server.go b/pkg/server/gin_managed_server.go index 17b6470a6..8c213d185 100644 --- a/pkg/server/gin_managed_server.go +++ b/pkg/server/gin_managed_server.go @@ -34,6 +34,7 @@ func NewGinManagedServer(config *ServerConfig, sharedResources *SharedResources) config.TLSCertPath, sharedResources.ThisNode, sharedResources.ClusterConfig, + !config.ClusterDisabled, sharedResources.EtcdDataPath, sharedResources.GeneratorPeriod, sharedResources.CronPeriod, diff --git a/pkg/server/http_managed_server.go b/pkg/server/http_managed_server.go index 298671f46..3d1bde923 100644 --- a/pkg/server/http_managed_server.go +++ b/pkg/server/http_managed_server.go @@ -34,6 +34,7 @@ func NewHTTPManagedServer(config *ServerConfig, sharedResources *SharedResources config.TLSCertPath, sharedResources.ThisNode, sharedResources.ClusterConfig, + !config.ClusterDisabled, sharedResources.EtcdDataPath, sharedResources.GeneratorPeriod, sharedResources.CronPeriod, diff --git a/pkg/server/server.go b/pkg/server/server.go index 07ad96dcc..90cbdcf95 100644 --- a/pkg/server/server.go +++ b/pkg/server/server.go @@ -111,6 +111,7 @@ func CreateServer(db database.Database, tlsCertPath string, thisNode cluster.Node, clusterConfig cluster.Config, + clusterEnabled bool, etcdDataPath string, generatorPeriod int, cronPeriod int, @@ -120,7 +121,7 @@ func CreateServer(db database.Database, retentionPolicy int64, retentionPeriod int, staleExecutorDuration time.Duration) *Server { - return createServerInternal(db, port, tls, tlsPrivateKeyPath, tlsCertPath, thisNode, clusterConfig, etcdDataPath, generatorPeriod, cronPeriod, exclusiveAssign, allowExecutorReregister, retention, retentionPolicy, retentionPeriod, staleExecutorDuration) + return createServerInternal(db, port, tls, tlsPrivateKeyPath, tlsCertPath, thisNode, clusterConfig, clusterEnabled, etcdDataPath, generatorPeriod, cronPeriod, exclusiveAssign, allowExecutorReregister, retention, retentionPolicy, retentionPeriod, staleExecutorDuration) } func createServerInternal(db database.Database, @@ -130,6 +131,7 @@ func createServerInternal(db database.Database, tlsCertPath string, thisNode cluster.Node, clusterConfig cluster.Config, + clusterEnabled bool, etcdDataPath string, generatorPeriod int, cronPeriod int, @@ -163,7 +165,7 @@ func createServerInternal(db database.Database, server.securityDB = db server.locationDB = db - server.controller = controllers.CreateColoniesController(db, thisNode, clusterConfig, etcdDataPath, generatorPeriod, cronPeriod, retention, retentionPolicy, retentionPeriod, staleExecutorDuration) + server.controller = controllers.CreateColoniesController(db, thisNode, clusterConfig, clusterEnabled, etcdDataPath, generatorPeriod, cronPeriod, retention, retentionPolicy, retentionPeriod, staleExecutorDuration) server.tls = tls server.port = port diff --git a/pkg/server/server_adapter.go b/pkg/server/server_adapter.go index 0c03d631f..71d50f136 100644 --- a/pkg/server/server_adapter.go +++ b/pkg/server/server_adapter.go @@ -178,7 +178,7 @@ type processControllerAdapter struct { AreColonyAssignmentsPaused(colonyName string) (bool, error) GetEventHandler() backends.RealtimeEventHandler IsLeader() bool - GetEtcdServer() *cluster.EtcdServer + GetCoordinator() cluster.Coordinator } } @@ -250,16 +250,16 @@ func (c *processControllerAdapter) IsLeader() bool { } func (c *processControllerAdapter) GetEtcdServer() process.EtcdServer { - etcdServer := c.controller.GetEtcdServer() - return &etcdServerAdapter{etcdServer: etcdServer} + coordinator := c.controller.GetCoordinator() + return &etcdServerAdapter{coordinator: coordinator} } type etcdServerAdapter struct { - etcdServer *cluster.EtcdServer + coordinator cluster.Coordinator } func (e *etcdServerAdapter) CurrentCluster() process.Cluster { - clusterConfig := e.etcdServer.CurrentCluster() + clusterConfig := e.coordinator.CurrentCluster() return &clusterAdapter{cluster: &clusterConfig} } @@ -466,21 +466,21 @@ func (s *ServerAdapter) ProcessgraphServer() processgraph.Server { // Server handler controller adapter type serverControllerAdapter struct { controller interface { - GetEtcdServer() *cluster.EtcdServer + GetCoordinator() cluster.Coordinator } } func (c *serverControllerAdapter) GetEtcdServer() serverhandlers.EtcdServer { - etcdServer := c.controller.GetEtcdServer() - return &serverEtcdServerAdapter{etcdServer: etcdServer} + coordinator := c.controller.GetCoordinator() + return &serverEtcdServerAdapter{coordinator: coordinator} } type serverEtcdServerAdapter struct { - etcdServer *cluster.EtcdServer + coordinator cluster.Coordinator } func (e *serverEtcdServerAdapter) CurrentCluster() cluster.Config { - return e.etcdServer.CurrentCluster() + return e.coordinator.CurrentCluster() } func (s *ServerAdapter) ServerController() serverhandlers.Controller { diff --git a/pkg/server/server_manager.go b/pkg/server/server_manager.go index 2216ec9de..d4451acc4 100644 --- a/pkg/server/server_manager.go +++ b/pkg/server/server_manager.go @@ -50,6 +50,11 @@ type ServerConfig struct { RetentionPeriod int StaleExecutorDuration time.Duration Enabled bool + // ClusterDisabled turns off clustering (etcd coordination) for this + // server. The zero value keeps clustering enabled, so existing + // ServerConfigs keep today's behavior. Single-node deployments set it + // to true. + ClusterDisabled bool } // ServerManager manages multiple server backends diff --git a/pkg/server/test_utils.go b/pkg/server/test_utils.go index 1e3c31fb1..082a508fe 100644 --- a/pkg/server/test_utils.go +++ b/pkg/server/test_utils.go @@ -6,6 +6,7 @@ import ( "io/ioutil" "math/rand" "net/http" + "os" "strconv" "strings" "testing" @@ -220,14 +221,37 @@ const ( // interval is still the floor) while cutting the waiting to just over a second. const testCronPeriodMillis = 100 +// testClusterEnabled controls whether test servers start a real embedded etcd. +// Clustering is enabled by default (COLONIES_TEST_CLUSTER unset or "true"), +// preserving historical behavior. Setting COLONIES_TEST_CLUSTER=false runs the +// same single-node coordinator production uses with clustering disabled, which +// is considerably faster for suites that do not exercise clustering. Suites +// that DO exercise clustering (StartCluster, distributed/exclusive assignment) +// always use real etcd regardless of this setting. +func testClusterEnabled() bool { + return os.Getenv("COLONIES_TEST_CLUSTER") != "false" +} + func prepareTestsWithRetention(t *testing.T, retention bool) (*client.ColoniesClient, *Server, string, chan bool) { + clusterEnabled := testClusterEnabled() + // Dynamic ports and a per-test etcd data directory allow test packages to // run in parallel without colliding on fixed ports or /tmp/colonies. The // ports stay reserved until just before each component binds, so parallel // test processes cannot be handed the same port during the slow parts of // the setup (database preparation, etcd startup). - reserved := utils.ReservePortsOrPanic(4) - apiPort, etcdClientPort, etcdPeerPort, relayPort := reserved[0].Port(), reserved[1].Port(), reserved[2].Port(), reserved[3].Port() + // + // With clustering disabled only the API port is needed. + numPorts := 4 + if !clusterEnabled { + numPorts = 1 + } + reserved := utils.ReservePortsOrPanic(numPorts) + apiPort := reserved[0].Port() + etcdClientPort, etcdPeerPort, relayPort := apiPort, apiPort, apiPort + if clusterEnabled { + etcdClientPort, etcdPeerPort, relayPort = reserved[1].Port(), reserved[2].Port(), reserved[3].Port() + } etcdDataPath := t.TempDir() client := client.CreateColoniesClient(constants.TESTHOST, apiPort, Insecure, SkipTLSVerify) @@ -247,10 +271,12 @@ func prepareTestsWithRetention(t *testing.T, retention bool) (*client.ColoniesCl node := cluster.Node{Name: "etcd", Host: "localhost", EtcdClientPort: etcdClientPort, EtcdPeerPort: etcdPeerPort, RelayPort: relayPort, APIPort: apiPort} clusterConfig := cluster.Config{} clusterConfig.AddNode(node) - reserved[1].Release() - reserved[2].Release() - reserved[3].Release() - server := CreateServer(db, apiPort, EnableTLS, "", "", node, clusterConfig, etcdDataPath, constants.GENERATOR_TRIGGER_PERIOD, testCronPeriodMillis, false, false, retention, testRetentionPolicySeconds, testRetentionPeriodMillis, time.Duration(constants.DEFAULT_STALE_EXECUTOR_DURATION)*time.Second) + if clusterEnabled { + reserved[1].Release() + reserved[2].Release() + reserved[3].Release() + } + server := CreateServer(db, apiPort, EnableTLS, "", "", node, clusterConfig, clusterEnabled, etcdDataPath, constants.GENERATOR_TRIGGER_PERIOD, testCronPeriodMillis, false, false, retention, testRetentionPolicySeconds, testRetentionPeriodMillis, time.Duration(constants.DEFAULT_STALE_EXECUTOR_DURATION)*time.Second) done := make(chan bool) reserved[0].Release() @@ -454,7 +480,7 @@ func startCluster(t *testing.T, db database.Database, size int, exclusiveAssign reserved[4*i].Release() reserved[4*i+1].Release() reserved[4*i+2].Release() - server := CreateServer(db, node.APIPort, false, "", "", node, clusterConfig, etcdDataPath+"/etcd"+strconv.Itoa(i), constants.GENERATOR_TRIGGER_PERIOD, constants.CRON_TRIGGER_PERIOD, exclusiveAssign, false, false, -1, 500, time.Duration(constants.DEFAULT_STALE_EXECUTOR_DURATION)*time.Second) + server := CreateServer(db, node.APIPort, false, "", "", node, clusterConfig, true, etcdDataPath+"/etcd"+strconv.Itoa(i), constants.GENERATOR_TRIGGER_PERIOD, constants.CRON_TRIGGER_PERIOD, exclusiveAssign, false, false, -1, 500, time.Duration(constants.DEFAULT_STALE_EXECUTOR_DURATION)*time.Second) done := make(chan struct{}) s := ServerInfo{ServerID: serverID, ServerPrvKey: serverPrvKey, Server: server, Node: node, Done: done} reserved[4*i+3].Release()