silas / node-consul

Consul client
https://www.npmjs.com/package/consul
MIT License
562 stars 83 forks source link
consul javascript nodejs

Consul

This is a Consul client.

Documentation

See the official HTTP API docs for more information.

Consul([options])

Initialize a new Consul client.

Options

Advanced options

Usage

import Consul from "consul";

const consul = new Consul();

Common Method Call Options

These options can be included with any method call, although only certain endpoints support them. See the HTTP API for more information.

These options work for all methods.

consul.acl

consul.acl.bootstrap()

Creates one-time management token if not configured.

Usage

await consul.acl.bootstrap();

Result

{
  "ID": "adf4238a-882b-9ddc-4a9d-5b6758e4159e"
}

consul.acl.replication([options])

Get the status of the ACL replication process in the datacenter.

Usage

await consul.acl.replication();

Result

{
  "Enabled": true,
  "Running": true,
  "SourceDatacenter": "dc1",
  "ReplicatedIndex": 1976,
  "LastSuccess": "2016-08-05T06:28:58Z",
  "LastError": "2016-08-05T06:28:28Z"
}

consul.acl.legacy

consul.acl.legacy.create([options])

Creates a new token with policy.

Options

Usage

await consul.acl.legacy.create();

Result

{
  "ID": "b1f4c10e-b61b-e1de-de95-218c9fefdd3e"
}

consul.acl.legacy.update(options)

Update the policy of a token.

Options

Usage

await consul.acl.legacy.update({
  id: "63e1d82e-f718-eb92-3b7d-61f0c71d45b4",
  name: "test",
});

consul.acl.legacy.destroy(options)

Destroys a given token.

Options

Usage

await consul.acl.legacy.destroy("b1f4c10e-b61b-e1de-de95-218c9fefdd3e");

consul.acl.legacy.get(options)

Queries the policy of a given token.

Options

Usage

await consul.acl.legacy.get("63e1d82e-f718-eb92-3b7d-61f0c71d45b4");

Result

{
  "CreateIndex": 7,
  "ModifyIndex": 7,
  "ID": "63e1d82e-f718-eb92-3b7d-61f0c71d45b4",
  "Name": "Read only",
  "Type": "client",
  "Rules": "{\"key\":{\"\":{\"policy\":\"read\"}}}"
}

consul.acl.legacy.clone(options)

Creates a new token by cloning an existing token.

Options

Usage

await consul.acl.legacy.clone("63e1d82e-f718-eb92-3b7d-61f0c71d45b4");

Result

{
  "ID": "9fb8b20b-2636-adbb-9b99-d879df3305ec"
}

consul.acl.legacy.list([options])

Lists all the active tokens.

Usage

await consul.acl.legacy.list();

Result

[
  {
    "CreateIndex": 2,
    "ModifyIndex": 2,
    "ID": "anonymous",
    "Name": "Anonymous Token",
    "Type": "client",
    "Rules": ""
  }
  {
    "CreateIndex": 3,
    "ModifyIndex": 3,
    "ID": "root",
    "Name": "Master Token",
    "Type": "management",
    "Rules": ""
  }
]

consul.agent

consul.agent.members([options])

Returns the members as seen by the consul agent.

Options

Usage

await consul.agent.members();

Result

[
  {
    "Name": "node1",
    "Addr": "127.0.0.1",
    "Port": 8301,
    "Tags": {
      "bootstrap": "1",
      "build": "0.3.0:441d613e",
      "dc": "dc1",
      "port": "8300",
      "role": "consul",
      "vsn": "2",
      "vsn_max": "2",
      "vsn_min": "1"
    },
    "Status": 1,
    "ProtocolMin": 1,
    "ProtocolMax": 2,
    "ProtocolCur": 2,
    "DelegateMin": 2,
    "DelegateMax": 4,
    "DelegateCur": 4
  }
]

consul.agent.reload([options])

Reload agent configuration.

Usage

await consul.agent.reload();

consul.agent.self()

Returns the agent node configuration.

Usage

await consul.agent.self();

Result

{
  "Config": {
    "Bootstrap": true,
    "Server": true,
    "Datacenter": "dc1",
    "DataDir": "/tmp/node1/data",
    "DNSRecursor": "",
    "DNSConfig": {
      "NodeTTL": 0,
      "ServiceTTL": null,
      "AllowStale": false,
      "MaxStale": 5000000000
    },
    "Domain": "consul.",
    "LogLevel": "INFO",
    "NodeName": "node1",
    "ClientAddr": "127.0.0.1",
    "BindAddr": "127.0.0.1",
    "AdvertiseAddr": "127.0.0.1",
    "Ports": {
      "DNS": 8600,
      "HTTP": 8500,
      "RPC": 8400,
      "SerfLan": 8301,
      "SerfWan": 8302,
      "Server": 8300
    },
    "LeaveOnTerm": false,
    "SkipLeaveOnInt": false,
    "StatsiteAddr": "",
    "Protocol": 2,
    "EnableDebug": false,
    "VerifyIncoming": false,
    "VerifyOutgoing": false,
    "CAFile": "",
    "CertFile": "",
    "KeyFile": "",
    "ServerName": "",
    "StartJoin": [],
    "UiDir": "",
    "PidFile": "/tmp/node1/pid",
    "EnableSyslog": false,
    "SyslogFacility": "LOCAL0",
    "RejoinAfterLeave": false,
    "CheckUpdateInterval": 300000000000,
    "Revision": "441d613e1bd96254c78c46ee7c1b35c161fc7295+CHANGES",
    "Version": "0.3.0",
    "VersionPrerelease": ""
  },
  "Member": {
    "Name": "node1",
    "Addr": "127.0.0.1",
    "Port": 8301,
    "Tags": {
      "bootstrap": "1",
      "build": "0.3.0:441d613e",
      "dc": "dc1",
      "port": "8300",
      "role": "consul",
      "vsn": "2",
      "vsn_max": "2",
      "vsn_min": "1"
    },
    "Status": 1,
    "ProtocolMin": 1,
    "ProtocolMax": 2,
    "ProtocolCur": 2,
    "DelegateMin": 2,
    "DelegateMax": 4,
    "DelegateCur": 4
  }
}

consul.agent.maintenance(options)

Set node maintenance mode.

Options

Usage

await consul.agent.maintenance(true);

consul.agent.join(options)

Trigger agent to join a node.

Options

Usage

await consul.agent.join("127.0.0.2");

consul.agent.forceLeave(options)

Force remove node.

Options

Usage

await consul.agent.forceLeave("node2");

consul.agent.check

consul.agent.check.list()

Returns the checks the agent is managing.

Usage

await consul.agent.check.list();

Result

{
  "example": {
    "Node": "node1",
    "CheckID": "example",
    "Name": "example",
    "Status": "passing",
    "Notes": "This is an example check.",
    "Output": "",
    "ServiceID": "",
    "ServiceName": ""
  }
}

consul.agent.check.register(options)

Registers a new check.

Options

Usage

await consul.agent.check.register({
  name: "example",
  ttl: "15s",
  notes: "This is an example check.",
});

consul.agent.check.deregister(options)

Deregister a check.

Options

Usage

await consul.agent.check.deregister("example");

consul.agent.check.pass(options)

Mark a test as passing.

Options

Usage

await consul.agent.check.pass("example");

consul.agent.check.warn(options)

Mark a test as warning.

Options

Usage

await consul.agent.check.warn("example");

consul.agent.check.fail(options)

Mark a test as critical.

Options

Usage

await consul.agent.check.fail("example");

consul.agent.service

consul.agent.service.list()

Returns the services the agent is managing.

Usage

await consul.agent.service.list();

Result

{
  "example": {
    "ID": "example",
    "Service": "example",
    "Tags": ["dev", "web"],
    "Port": 80
  }
}

consul.agent.service.register(options)

Registers a new service.

Options

Usage

await consul.agent.service.register("example");

consul.agent.service.deregister(options)

Deregister a service.

Options

Usage

await consul.agent.service.deregister("example");

consul.agent.service.maintenance(options)

Set service maintenance mode.

Options

Usage

await consul.agent.service.maintenance({ id: "example", enable: true });

consul.catalog

consul.catalog.register(options)

Registers or updates entries in the catalog.

NOTE: this endpoint is a low-level mechanism for registering or updating entries in the catalog. It is usually preferable to instead use the agent endpoints for registration as they are simpler and perform anti-entropy. It is suggested to read the catalog API documentation before using that.

Options

Usage

await consul.catalog.register("example");

consul.catalog.deregister(options)

Deregister entries in the catalog.

NOTE:This endpoint is a low-level mechanism for directly removing entries from the Catalog. It is usually preferable to instead use the agent endpoints for deregistration as they are simpler and perform anti-entropy. It is suggested to read the catalog API documentation before using that.

Options

Usage

await consul.catalog.deregister("example");

or

await consul.catalog.deregister({ id: "example" });

consul.catalog.datacenters()

Lists known datacenters.

Usage

await consul.catalog.datacenters();

Result

["dc1"]

consul.catalog.connect

consul.catalog.connect.nodes(options)

Lists the nodes for a given Connect-capable service.

Options

Usage

await consul.catalog.connect.nodes("example");

Result

[
  {
    "ID": "40e4a748-2192-161a-0510-9bf59fe950b5",
    "Node": "foobar",
    "Address": "192.168.10.10",
    "Datacenter": "dc1",
    "TaggedAddresses": {
      "lan": "192.168.10.10",
      "wan": "10.0.10.10"
    },
    "NodeMeta": {
      "somekey": "somevalue"
    },
    "CreateIndex": 51,
    "ModifyIndex": 51,
    "ServiceAddress": "172.17.0.3",
    "ServiceEnableTagOverride": false,
    "ServiceID": "32a2a47f7992:nodea:5000",
    "ServiceName": "foobar",
    "ServiceKind": "connect-proxy",
    "ServiceProxyDestination": "my-service",
    "ServicePort": 5000,
    "ServiceMeta": {
      "foobar_meta_value": "baz"
    },
    "ServiceTags": ["tacos"]
  }
]

consul.catalog.node

consul.catalog.node.list([options])

Lists nodes in a given datacenter.

Options

Usage

await consul.catalog.node.list();

Result

[
  {
    "Node": "node1",
    "Address": "127.0.0.1"
  }
]

consul.catalog.node.services(options)

Lists the services provided by a node.

Options

Usage

await consul.catalog.node.services("node1");

Result

{
  "Node": {
    "Node": "node1",
    "Address": "127.0.0.1"
  },
  "Services": {
    "consul": {
      "ID": "consul",
      "Service": "consul",
      "Tags": [],
      "Port": 8300
    },
    "example": {
      "ID": "example",
      "Service": "example",
      "Tags": ["dev", "web"],
      "Port": 80
    }
  }
}

consul.catalog.service

consul.catalog.service.list([options])

Lists services in a given datacenter.

Options

Usage

await consul.catalog.service.list();

Result

{
  "consul": [],
  "example": ["dev", "web"]
}

consul.catalog.service.nodes(options)

Lists the nodes for a given service.

Options

Usage

await consul.catalog.service.nodes("example");

Result

[
  {
    "Node": "node1",
    "Address": "127.0.0.1",
    "ServiceID": "example",
    "ServiceName": "example",
    "ServiceTags": ["dev", "web"],
    "ServicePort": 80
  }
]

consul.event

consul.event.fire(options)

Fires a new user event.

Options

Usage

await consul.event.fire("deploy", "53");

Result

{
  "ID": "4730953b-3135-7ff2-47a7-9d9fc9c4e5a2",
  "Name": "deploy",
  "Payload": "53",
  "NodeFilter": "",
  "ServiceFilter": "",
  "TagFilter": "",
  "Version": 1,
  "LTime": 0
}

consul.event.list([options])

Lists the most recent events an agent has seen.

Options

Usage

await consul.event.list("deploy");

Result

[
  {
    "ID": "4730953b-3135-7ff2-47a7-9d9fc9c4e5a2",
    "Name": "deploy",
    "Payload": "53",
    "NodeFilter": "",
    "ServiceFilter": "",
    "TagFilter": "",
    "Version": 1,
    "LTime": 2
  }
]

consul.health

consul.health.node(options)

Returns the health info of a node.

Options

Usage

await consul.health.node("node1");

Result

[
  {
    "Node": "node1",
    "CheckID": "serfHealth",
    "Name": "Serf Health Status",
    "Status": "passing",
    "Notes": "",
    "Output": "Agent alive and reachable",
    "ServiceID": "",
    "ServiceName": ""
  },
  {
    "Node": "node1",
    "CheckID": "service:example",
    "Name": "Service 'example' check",
    "Status": "critical",
    "Notes": "",
    "Output": "",
    "ServiceID": "example",
    "ServiceName": "example"
  }
]

consul.health.checks(options)

Returns the checks of a service.

Options

Usage

await consul.health.checks("example");

Result

[
  {
    "Node": "node1",
    "CheckID": "service:example",
    "Name": "Service 'example' check",
    "Status": "critical",
    "Notes": "",
    "Output": "",
    "ServiceID": "example",
    "ServiceName": "example"
  }
]

consul.health.service(options)

Returns the nodes and health info of a service.

Options

Usage

await consul.health.service("example");

Result

[
  {
    "Node": {
      "Node": "node1",
      "Address": "127.0.0.1"
    },
    "Service": {
      "ID": "example",
      "Service": "example",
      "Tags": [],
      "Port": 0
    },
    "Checks": [
      {
        "Node": "node1",
        "CheckID": "service:example",
        "Name": "Service 'example' check",
        "Status": "critical",
        "Notes": "",
        "Output": "",
        "ServiceID": "example",
        "ServiceName": "example"
      },
      {
        "Node": "node1",
        "CheckID": "serfHealth",
        "Name": "Serf Health Status",
        "Status": "passing",
        "Notes": "",
        "Output": "Agent alive and reachable",
        "ServiceID": "",
        "ServiceName": ""
      }
    ]
  }
]

consul.health.state(options)

Returns the checks in a given state.

Options

Usage

await consul.health.state("critical");

Result

[
  {
    "Node": "node1",
    "CheckID": "service:example",
    "Name": "Service 'example' check",
    "Status": "critical",
    "Notes": "",
    "Output": "",
    "ServiceID": "example",
    "ServiceName": "example"
  }
]

consul.kv

consul.kv.get(options)

Return key/value (kv) pair(s) or undefined if key not found.

Options

Usage

await consul.kv.get("hello");

Result

{
  "CreateIndex": 6,
  "ModifyIndex": 6,
  "LockIndex": 0,
  "Key": "hello",
  "Flags": 0,
  "Value": "world"
}

consul.kv.keys(options)

Return keys for a given prefix.

Options

Usage

await consul.kv.keys("a/");

Result

["a/b", "a/c"]

consul.kv.set(options)

Set key/value (kv) pair.

Options

Usage

await consul.kv.set("hello", "world");

Result

true

consul.kv.del(options)

Delete key/value (kv) pair(s).

Options

Usage

await consul.kv.del("hello");

consul.query

consul.query.list()

List prepared query.

Usage

await consul.query.list();

Result

[
  {
    "ID": "422b14b9-874b-4520-bd2e-e149a42b0066",
    "Name": "redis",
    "Session": "",
    "Token": "",
    "Template": {
      "Type": "",
      "Regexp": ""
    },
    "Service": {
      "Service": "redis",
      "Failover": {
        "NearestN": 3,
        "Datacenters": ["dc1", "dc2"]
      },
      "OnlyPassing": false,
      "Tags": ["master", "!experimental"]
    },
    "DNS": {
      "TTL": "10s"
    },
    "RaftIndex": {
      "CreateIndex": 23,
      "ModifyIndex": 42
    }
  }
]

consul.query.create(options)

Create a new prepared query.

Options

Usage

await consul.query.create({
  name: 'redis',
  service: {
    service: 'redis'
    onlypassing: true
  },
});

Result

{
  "ID": "422b14b9-874b-4520-bd2e-e149a42b0066"
}

consul.query.update(options)

Update existing prepared query.

Options

And all [create options][query-create].

Usage

await consul.query.update({
  query: '422b14b9-874b-4520-bd2e-e149a42b0066',
  name: 'redis',
  service: {
    service: 'redis'
    onlypassing: false
  },
});

consul.query.get(options)

Get prepared query.

Options

Usage

await consul.query.get("6119cabf-c052-48fe-9f07-711762e52931");

Result

{
  "ID": "6119cabf-c052-48fe-9f07-711762e52931",
  "Name": "redis",
  "Session": "",
  "Token": "",
  "Template": {
    "Type": "",
    "Regexp": ""
  },
  "Service": {
    "Service": "redis",
    "Failover": {
      "NearestN": 3,
      "Datacenters": ["dc1", "dc2"]
    },
    "OnlyPassing": false,
    "Tags": ["master", "!experimental"]
  },
  "DNS": {
    "TTL": "10s"
  },
  "RaftIndex": {
    "CreateIndex": 23,
    "ModifyIndex": 42
  }
}

consul.query.destroy(options)

Delete prepared query.

Options

Usage

await consul.query.destroy("422b14b9-874b-4520-bd2e-e149a42b0066");

consul.query.execute(options)

Execute prepared query.

Options

Usage

await consul.query.execute("6119cabf-c052-48fe-9f07-711762e52931");

Result

{
  "Service": "redis",
  "Nodes": [
    {
      "Node": {
        "Node": "foobar",
        "Address": "10.1.10.12",
        "TaggedAddresses": {
          "lan": "10.1.10.12",
          "wan": "10.1.10.12"
        }
      },
      "Service": {
        "ID": "redis",
        "Service": "redis",
        "Tags": null,
        "Port": 8000
      },
      "Checks": [
        {
          "Node": "foobar",
          "CheckID": "service:redis",
          "Name": "Service 'redis' check",
          "Status": "passing",
          "Notes": "",
          "Output": "",
          "ServiceID": "redis",
          "ServiceName": "redis"
        },
        {
          "Node": "foobar",
          "CheckID": "serfHealth",
          "Name": "Serf Health Status",
          "Status": "passing",
          "Notes": "",
          "Output": "",
          "ServiceID": "",
          "ServiceName": ""
        }
      ],
      "DNS": {
        "TTL": "10s"
      },
      "Datacenter": "dc3",
      "Failovers": 2
    }
  ]
}

consul.query.explain(options)

Explain prepared query.

Options

Usage

await consul.query.explain("422b14b9-874b-4520-bd2e-e149a42b0066");

Result

{
  "Query": {
    "ID": "422b14b9-874b-4520-bd2e-e149a42b0066",
    "Name": "redis",
    "Session": "",
    "Token": "",
    "Template": {
      "Type": "",
      "Regexp": ""
    },
    "Service": {
      "Service": "redis",
      "Failover": {
        "NearestN": 3,
        "Datacenters": ["dc1", "dc2"]
      },
      "OnlyPassing": false,
      "Tags": ["master", "!experimental"]
    },
    "DNS": {
      "TTL": "10s"
    },
    "RaftIndex": {
      "CreateIndex": 23,
      "ModifyIndex": 42
    }
  }
}

consul.session

consul.session.create([options])

Create a new session.

Options

Usage

await consul.session.create();

Result

{
  "ID": "a0f5dc05-84c3-5f5a-1d88-05b875e524e1"
}

consul.session.destroy(options)

Destroy a given session.

Options

Usage

await consul.session.destroy("a0f5dc05-84c3-5f5a-1d88-05b875e524e1");

consul.session.get(options)

Queries a given session.

Options

Usage

await consul.session.get("a0f5dc05-84c3-5f5a-1d88-05b875e524e1");

Result

{
  "CreateIndex": 11,
  "ID": "a0f5dc05-84c3-5f5a-1d88-05b875e524e1",
  "Name": "",
  "Node": "node1",
  "Checks": ["serfHealth"],
  "LockDelay": 15000000000
}

consul.session.node(options)

Lists sessions belonging to a node.

Options

Usage

await consul.session.node("node1");

Result

[
  {
    "CreateIndex": 13,
    "ID": "a0f5dc05-84c3-5f5a-1d88-05b875e524e1",
    "Name": "",
    "Node": "node1",
    "Checks": ["serfHealth"],
    "LockDelay": 15000000000
  }
]

consul.session.list([options])

Lists all the active sessions.

Options

Usage

await consul.session.list();

Result

[
  {
    "CreateIndex": 15,
    "ID": "a0f5dc05-84c3-5f5a-1d88-05b875e524e1",
    "Name": "",
    "Node": "node1",
    "Checks": ["serfHealth"],
    "LockDelay": 15000000000
  }
]

consul.session.renew(options)

Renew a given session.

Options

Usage

await consul.session.renew("a0f5dc05-84c3-5f5a-1d88-05b875e524e1");

Result

[
  {
    "CreateIndex": 15,
    "ID": "a0f5dc05-84c3-5f5a-1d88-05b875e524e1",
    "Name": "",
    "Node": "node1",
    "Checks": ["serfHealth"],
    "LockDelay": 15000000000,
    "Behavior": "release",
    "TTL": ""
  }
]

consul.status

consul.status.leader()

Returns the current Raft leader.

Usage

await consul.status.leader();

Result

"127.0.0.1:8300"

consul.status.peers()

Returns the current Raft peer set.

Usage

await consul.status.peers();

Result

["127.0.0.1:8300"]

consul.transaction.create(operations)

operations: The body of the request should be a list of operations to perform inside the atomic transaction. Up to 64 operations may be present in a single transaction.

Usage

await consul.transaction.create([
  {
    {
      KV: {
        Verb: 'set',
        Key: 'key1',
        Value: Buffer.from('value1').toString('base64')
      }
    },{
      KV: {
        Verb: 'delete',
        Key: 'key2'
      }
    }
  }
]);

consul.watch(options)

Watch an endpoint for changes.

The watch relies on blocking queries, adding the index and wait parameters as per Consul's documentation

If a blocking query is dropped due to a Consul crash or disconnect, watch will attempt to reinitiate the blocking query with logarithmic backoff.

Upon reconnect, unlike the first call to watch() in which the latest x-consul-index is unknown, the last known x-consul-index will be reused, thus not emitting the change event unless it has been incremented since.

NOTE: If you specify an alternative options.timeout keep in mind that a small random amount of additional wait is added to all requests (wait / 16). The default timeout is currently set to (wait + wait * 0.1), you should use something similar to avoid issues.

Options

Usage

const watch = consul.watch({
  method: consul.kv.get,
  options: { key: "test" },
  backoffFactor: 1000,
});

watch.on("change", (data, res) => {
  console.log("data:", data);
});

watch.on("error", (err) => {
  console.log("error:", err);
});

setTimeout(() => {
  watch.end();
}, 30 * 1000);

Acceptance Tests

  1. Install Consul into your PATH

    $ brew install consul
  2. Attach required IPs

    $ sudo ifconfig lo0 alias 127.0.0.2 up
    $ sudo ifconfig lo0 alias 127.0.0.3 up
  3. Install client dependencies

    $ npm install
  4. Run tests

    $ npm run acceptance

License

This work is licensed under the MIT License (see the LICENSE file).

Parts of the Documentation were copied from the official Consul website, see the NOTICE file for license information.