Files
01c5cda69b MM-71346 Plugin testhelper: run integration tests against an HA cluster (#39403)
* MM-71346 Plugin testhelper: run integration tests against an HA cluster

Plugins that use cluster events had no way to test their cross-node
behaviour: the testhelper starts a single Mattermost container.

- Add SetupCluster(t, n), which starts n nodes forming a real HA
  cluster. The nodes share one Postgres database, also used as the
  config store (MM_CONFIG), and one file store volume, so the plugin is
  deployed once and runs on every node.
- Expose the servers as TestHelper.Nodes, each with its cluster ID,
  hostname, URL, and admin and user clients aimed at it, plus Exec,
  Pause/Unpause and Stop/Start for fault injection. Setup gets a single
  node.
- Clustering needs a license with the Cluster feature (Mattermost Entry
  has none). Read it from MM_LICENSE, start the nodes with
  MM_SERVICEENVIRONMENT=test, skip without a license, and fail when the
  server rejects it or it lacks the Cluster feature.
- Reset the database through the first node with the others stopped,
  wait for the cluster to form, and wait for the plugin on every node.
- Log the tail of each node's container log when a test fails.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015bYRkFZXxqdgiFMsh8MPVm

* MM-71346 Tidy server/public go.sum

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015bYRkFZXxqdgiFMsh8MPVm

* MM-71346 Fix node state tracking in the cluster testhelper

- Clear a node's paused flag when it is stopped: Docker stops paused
  containers, and a stale flag made waitForCluster skip the node after a
  restart and the Pause cleanup unpause a container that wasn't paused.
- Ignore a restarted node's old member while waiting for the cluster, so
  Start can't return early with the old ID when Docker reuses the address.
- Give stopped nodes an empty ID and let paused nodes keep theirs, rather
  than matching every node by a possibly reused address.
- Start the other nodes in parallel after a database reset.
- Report which node failed to join when the cluster doesn't form.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015bYRkFZXxqdgiFMsh8MPVm

* MM-71346 Simplify the cluster testhelper

- Read whether a node is paused from Docker instead of tracking a flag.
- Record a stopped node's cluster ID as stale in Stop, so waitForCluster
  needs no stale-ID parameter and covers every stop/restart order.
- Make Node.Hostname and Node.URL methods reading the container, so
  Start has nothing to copy.
- Key the shared containers by node count; a cluster is more than one node.
- Share one inParallel helper for starting and stopping nodes, which also
  stops the other nodes in parallel on reset and reports every failed
  start instead of the last.
- Drop the admin creation at container start: every Setup resets the
  database and creates the admin.
- Reuse execInContainer for Node.Exec, share the per-node client helper,
  and poll the cluster status every 250ms.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015bYRkFZXxqdgiFMsh8MPVm

* MM-71346 Docs: test a plugin in high availability mode

Document testhelper.SetupCluster, the Node fault-injection methods and
the MM_LICENSE requirement in the plugin HA guide.

* MM-71346 Docs: trim the Node API list in the HA testing section

* MM-71346 Fix plugin deploy race and stale node ID in the cluster testhelper

deployPlugin removed and re-uploaded the plugin as two separate cluster
messages, which receivers handle concurrently, so a node could apply the
remove after the install and lose the plugin. A forced upload replaces the
existing install in one step.

Node.Start now forgets the node's old cluster ID before starting, so a node
that stopped other than through Stop doesn't keep a dead ID after rejoining.

* MM-71346 Wait for the plugin on each cluster node by ID, and remove the test network on failure

deployPlugin now waits until the plugin runs on every current cluster node,
matched by ID, rather than on as many nodes as there are. A failed container
start also removes the Docker network instead of leaving it to the reaper.
Document that Setup and SetupCluster in one test binary run side by side.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015vpi5iekJF1wHe68kShpjr

---------

Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Mattermost Build <build@mattermost.com>
Co-authored-by: wiggin77 <wiggin77@warpmail.net>
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: mattermost-code <matty-code@mattermost.com>
Co-authored-by: maria.nunez <maria.nunez@mattermost.com>
2026-11-12 09:27:27 +01:00

7.9 KiB

title, sidebar_position
title sidebar_position
High availability 60

Mattermost Enterprise Edition servers with an E20 license have the ability to run in High Availability (HA) mode, meaning a cluster of Mattermost app servers running together as a single Mattermost deployment.

It is important that all plugins consider HA environments when being built.

Plugins are started as subprocesses of the main Mattermost process on each app server. This means a Mattermost deployment that has three app servers will have three separate copies of the same plugin running. Each running copy of the plugin will be isolated from one another on different servers. Therefore, to run properly in HA the plugin's server-side code must be stateless.

To be stateless, the plugin must not retain any information or status in memory that may be needed across multiple events (e.g. HTTP requests or in other hooks). This data should instead be stored in a place that all running copies of the plugin have access to. For example, the key-value store the plugin API provides.

To better explain the problem with having a plugin store data in-memory, consider this case:

Let's say we have two Mattermost app servers running together in HA and an installed plugin with a feature that alerts a user any time a trigger word is posted in a channel.

  1. The user uses the web app side of the plugin to set the word hello as the trigger word
  2. An HTTP request is made to the server-side of the plugin to set hello
  3. The plugin process running on app server 1 handles the request and stores hello in a variable

In this scenario, the trigger word is now only set for the plugin process running on app server 1. The plugin process running on app server 2 is unaware that the trigger word is hello. This means when someone posts a message containing hello and the request is load balanced to app server 2, the plugin is not going to alert our user when it should.

The proper way to deal with this case would be for the plugin to store the trigger word in a global store, such as the KV store. Then any time a user posts the plugin can pull the trigger word from the store and properly alert the user, regardless of which app server handles the request.

Run a scheduled job in high availability mode

Using the mattermost/public/pluginapi/cluster package, we can schedule jobs to perform background activity at regular intervals, without having to explicitly coordinate with other instances of the same plugin. Here's an example from the Demo Plugin:

job, cronErr := cluster.Schedule(
    p.API,
    "BackgroundJob",
    cluster.MakeWaitForRoundedInterval(15*time.Minute),
    p.BackgroundJobFunc,
)
if cronErr != nil {
    return errors.Wrap(cronErr, "failed to schedule background job")
}

p.backgroundJob = job

Discover cluster node identity

From Mattermost v12.2, plugins can discover the cluster topology and identify which node sent a cluster event.

Get the local node ID

API.GetClusterNodeID() returns the cluster ID of the node the plugin is running on. Use this value to tell other nodes where to send targeted cluster events. It returns an empty string until the node has joined the cluster — for example, when clustering is disabled or the node has not yet started.

nodeID := p.API.GetClusterNodeID()
if nodeID == "" {
    // not running in a cluster
}

List connected nodes

API.GetClusterNodes() returns the nodes currently connected to the cluster, including the local node. Every Id in the returned list can be passed directly as PluginClusterEventSendOptions.TargetId. Nodes that are registered but not yet connected are excluded, because their registration ID cannot be used as a target. The method returns an empty list until this node has joined the cluster, consistent with GetClusterNodeID().

GetClusterNodes() may query the database on each call. Avoid calling it on hot paths such as per-message hooks.

nodes, err := p.API.GetClusterNodes()
if err != nil {
    return err
}
for _, node := range nodes {
    p.API.PublishPluginClusterEvent(
        model.PluginClusterEvent{Id: "sync", Data: payload},
        model.PluginClusterEventSendOptions{
            SendType: model.PluginClusterEventSendTypeReliable,
            TargetId: node.Id,
        },
    )
}

Identify the sender of a cluster event

PluginClusterEvent.SourceId is set by the server to the cluster node ID of the sender before the event is delivered to OnPluginClusterEvent. Use it to reply to a specific node or to filter events by origin. Events received from nodes running a server version earlier than 12.2 have an empty SourceId.

func (p *Plugin) OnPluginClusterEvent(_ *plugin.Context, ev model.PluginClusterEvent) {
    if ev.SourceId == "" {
        // sender is on an older server version or clustering is not active
        return
    }
    // reply to the sender
    p.API.PublishPluginClusterEvent(
        model.PluginClusterEvent{Id: "ack", Data: []byte("ok")},
        model.PluginClusterEventSendOptions{
            SendType: model.PluginClusterEventSendTypeReliable,
            TargetId: ev.SourceId,
        },
    )
}

The pluginapi wrappers for these methods are Cluster.GetNodeID() and Cluster.GetNodes().

Test a plugin in high availability mode

The pluginapi/testhelper package runs a plugin's integration tests against a real Mattermost server in Docker. testhelper.SetupCluster(t, n) starts a cluster of n servers instead of a single one, so you can test behavior that spans servers, such as cluster events or state that must not be kept in memory:

func TestTriggerWordAcrossNodes(t *testing.T) {
    th := testhelper.SetupCluster(t, 2)
    a, b := th.Nodes[0], th.Nodes[1]

    // Set the trigger word through a.Client, then post through b.Client
    // and check that the plugin on b alerts the user.
}

The servers share one database, which also holds the configuration, and one file store. The plugin is deployed once and runs on every server, and a configuration change made through one server reaches the others. Each test starts from a freshly formed cluster.

Each entry in th.Nodes is one server. Use its AdminClient and Client to call the plugin on that server, and its ID as PluginClusterEventSendOptions.TargetId. The ID changes whenever the server restarts. To take a server away, Pause(t) freezes it, so it looks hung to the rest of the cluster, and Stop(t) shuts it down, so it leaves the cluster. Start(t) brings it back. See the package source for the full API.

Clustering requires a license with the Cluster feature. Set the MM_LICENSE environment variable to the license when running the tests. The servers run in the test service environment, so a license signed with Mattermost's test key works. Without MM_LICENSE, cluster tests are skipped, so pull requests from forks still pass. A license the server rejects, or one without the Cluster feature, fails the test.

In GitHub Actions, map a repository secret to MM_LICENSE in the step that runs the tests:

- name: Run tests
  env:
    MM_LICENSE: ${{ secrets.MM_E2E_TEST_LICENSE_ONPREM_ENT }}
  run: make test

:::tip Setting up a cluster takes about 20 to 25 seconds per test, compared with about 5 seconds for a single server, because each test restarts the servers and waits for them to rejoin the cluster. Use testhelper.Setup(t) for tests that don't need more than one server. :::