Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions docs/Configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -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."

Expand Down
2 changes: 2 additions & 0 deletions docs/HADeployment.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
|:------------------------:|:--------:|:-----------------:|
Expand Down
1 change: 1 addition & 0 deletions internal/cli/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
29 changes: 26 additions & 3 deletions internal/cli/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -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
Expand All @@ -72,6 +74,7 @@ func startServer(
TLSCert,
node,
clusterConfig,
clusterEnabled,
etcdDataPath,
GeneratorCheckerPeriod,
CronCheckerPeriod,
Expand Down Expand Up @@ -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 != "" {
Expand Down Expand Up @@ -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)
}
Expand All @@ -305,7 +328,7 @@ var serverStartCmd = &cobra.Command{
}

log.Info("Starting HTTP server")
startServer(db, node, clusterConfig, EtcdDataDir)
startServer(db, node, clusterConfig, ClusterEnabled, EtcdDataDir)
},
}

Expand Down
32 changes: 32 additions & 0 deletions pkg/cluster/coordinator.go
Original file line number Diff line number Diff line change
@@ -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)
91 changes: 91 additions & 0 deletions pkg/cluster/local.go
Original file line number Diff line number Diff line change
@@ -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)
59 changes: 59 additions & 0 deletions pkg/cluster/local_test.go
Original file line number Diff line number Diff line change
@@ -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())
}
2 changes: 2 additions & 0 deletions pkg/server/channel_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
Loading