Skip to content
Merged
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
5 changes: 4 additions & 1 deletion atlas-lib/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ PROTO_GEN := link/linkv1/link.pb.go link/linkv1/link_grpc.pb.go \
link/sitev1/site.pb.go link/sitev1/site_grpc.pb.go \
storage/storagerpc/storagev1/nvme.pb.go storage/storagerpc/storagev1/nvme_grpc.pb.go \
nfsexport/nfsexportrpc/nfsexportv1/export.pb.go nfsexport/nfsexportrpc/nfsexportv1/export_grpc.pb.go \
nfsexport/nfsexportrpc/nfsexportv1/mds.pb.go nfsexport/nfsexportrpc/nfsexportv1/mds_grpc.pb.go \
conntrack/conntrackrpc/conntrackv1/flow.pb.go conntrack/conntrackrpc/conntrackv1/flow_grpc.pb.go \
placement/placementrpc/placementv1/placement.pb.go placement/placementrpc/placementv1/placement_grpc.pb.go \
netcheck/netcheckrpc/netcheckv1/check.pb.go netcheck/netcheckrpc/netcheckv1/check_grpc.pb.go \
Expand Down Expand Up @@ -80,11 +81,13 @@ storage/storagerpc/storagev1/nvme.pb.go: storage/storagerpc/storagev1/nvme.proto

storage/storagerpc/storagev1/nvme_grpc.pb.go: storage/storagerpc/storagev1/nvme.pb.go

nfsexport/nfsexportrpc/nfsexportv1/export.pb.go: nfsexport/nfsexportrpc/nfsexportv1/export.proto nfsexport/nfsexportrpc/nfsexportv1/buf.gen.yaml nfsexport/nfsexportrpc/nfsexportv1/buf.yaml | buf
nfsexport/nfsexportrpc/nfsexportv1/export.pb.go: nfsexport/nfsexportrpc/nfsexportv1/export.proto nfsexport/nfsexportrpc/nfsexportv1/mds.proto nfsexport/nfsexportrpc/nfsexportv1/buf.gen.yaml nfsexport/nfsexportrpc/nfsexportv1/buf.yaml | buf
cd nfsexport/nfsexportrpc/nfsexportv1 && PATH="$(BIN_DIR):$$PATH" "$(BUF)" generate

nfsexport/nfsexportrpc/nfsexportv1/export_grpc.pb.go: nfsexport/nfsexportrpc/nfsexportv1/export.pb.go

nfsexport/nfsexportrpc/nfsexportv1/mds.pb.go nfsexport/nfsexportrpc/nfsexportv1/mds_grpc.pb.go: nfsexport/nfsexportrpc/nfsexportv1/export.pb.go

conntrack/conntrackrpc/conntrackv1/flow.pb.go: conntrack/conntrackrpc/conntrackv1/flow.proto conntrack/conntrackrpc/conntrackv1/buf.gen.yaml conntrack/conntrackrpc/conntrackv1/buf.yaml | buf
cd conntrack/conntrackrpc/conntrackv1 && PATH="$(BIN_DIR):$$PATH" "$(BUF)" generate

Expand Down
109 changes: 109 additions & 0 deletions atlas-lib/controlplane/volumehosts.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
// The allowed hosts of one volume: which hosts the target lets connect to its
// subsystem. The metadata server's guests connect volumes themselves, each with
// a host NQN of its own, so the operator adds those hosts to every volume that
// restricts them (design-pnfs-mds-standby.md, P0-2).
package controlplane

import (
"context"
"fmt"
"net/http"
"slices"
"strings"

"github.com/simplyblock/atlas/internal/cpapi"
"github.com/simplyblock/atlas/lvol"
)

// HostGrant is what EnsureVolumeHost did.
type HostGrant int

const (
// HostNotNeeded is a volume that lists no allowed hosts, which the control
// plane reads as allowing every host. Nothing was changed.
HostNotNeeded HostGrant = iota + 1
// HostAlreadyAllowed is a host the volume already lists.
HostAlreadyAllowed
// HostAdded is a host the call added to the volume.
HostAdded
)

// The control plane answers a duplicate add and a removal of an unlisted host
// with a 400 whose message is the only thing that tells them from a failure.
const (
messageAlreadyAllowed = "already allowed"
messageNotListed = "not in the allowed list"
)

// EnsureVolumeHost makes hostNQN an allowed host of the volume, when the volume
// restricts hosts at all.
//
// A volume that lists no allowed hosts allows every host, so adding one would
// not grant anything: the control plane appends it to the list, and the next
// time it re-applies the list to the target the volume admits that host and no
// other. That volume is left alone, and the call says so with HostNotNeeded.
func (c *Client) EnsureVolumeHost(ctx context.Context, h lvol.VolumeHandle, hostNQN string) (HostGrant, error) {
cluster, pool, volume, err := h.Split()
if err != nil {
return 0, err
}
if hostNQN == "" {
return 0, fmt.Errorf("allow a host on volume %s: empty host NQN", h)
}
what := fmt.Sprintf("allow host %s on volume %s", hostNQN, h)

detail, err := c.api.ClustersStoragePoolsVolumesDetailApiV2ClustersClusterIdStoragePoolsPoolIdVolumesVolumeIdGetWithResponse(ctx, cluster, pool, volume, nil)
if err != nil {
return 0, fmt.Errorf("%s: %w", what, err)
}
d, err := payload(what, detail.JSON200, detail.StatusCode(), detail.Body)
if err != nil {
return 0, err
}
switch {
case len(d.AllowedHosts) == 0:
return HostNotNeeded, nil
case slices.Contains(d.AllowedHosts, hostNQN):
return HostAlreadyAllowed, nil
}

resp, err := c.api.ClustersStoragePoolsVolumesAddHostApiV2ClustersClusterIdStoragePoolsPoolIdVolumesVolumeIdHostsPostWithResponse(
ctx, cluster, pool, volume, cpapi.UnderscoreAddHostParams{HostNqn: hostNQN})
if err != nil {
return 0, fmt.Errorf("%s: %w", what, err)
}
switch code := resp.StatusCode(); {
case code == http.StatusCreated || code == http.StatusOK:
return HostAdded, nil
case code == http.StatusBadRequest && strings.Contains(string(resp.Body), messageAlreadyAllowed):
return HostAlreadyAllowed, nil
default:
return 0, respError(what, code, resp.Body)
}
}

// RemoveVolumeHost removes hostNQN from the volume's allowed hosts. A host the
// volume does not list, and a volume that is gone, count as done.
func (c *Client) RemoveVolumeHost(ctx context.Context, h lvol.VolumeHandle, hostNQN string) error {
cluster, pool, volume, err := h.Split()
if err != nil {
return err
}
if hostNQN == "" {
return fmt.Errorf("remove a host from volume %s: empty host NQN", h)
}
what := fmt.Sprintf("remove host %s from volume %s", hostNQN, h)
resp, err := c.api.ClustersStoragePoolsVolumesRemoveHostApiV2ClustersClusterIdStoragePoolsPoolIdVolumesVolumeIdHostsHostNqnDeleteWithResponse(
ctx, cluster, pool, volume, hostNQN)
if err != nil {
return fmt.Errorf("%s: %w", what, err)
}
switch code := resp.StatusCode(); {
case code == http.StatusOK || code == http.StatusNoContent || code == http.StatusNotFound:
return nil
case code == http.StatusBadRequest && strings.Contains(string(resp.Body), messageNotListed):
return nil
default:
return respError(what, code, resp.Body)
}
}
176 changes: 176 additions & 0 deletions atlas-lib/controlplane/volumehosts_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,176 @@
// The volume allowed-hosts calls against a control plane that answers as sbcli
// does. The case that matters most is the unrestricted volume: the control plane
// reads an empty allowed-hosts list as `allow every host`, so adding one host to
// such a volume would turn it into a volume that only that host can connect.
package controlplane

import (
"context"
"encoding/json"
"errors"
"net/http"
"strings"
"testing"

"github.com/simplyblock/atlas/errs"
)

const mdsHost = "nqn.2014-08.io.simplyblock:uuid:11111111-2222-4333-8444-555555555555"

// hostsServer answers the volume's detail with the given allowed hosts, records
// every POST and DELETE to the host routes, and answers them with post and del.
type hostsServer struct {
allowed []string
post func(w http.ResponseWriter)
del func(w http.ResponseWriter)
posts []string
deletes []string
}

func (s *hostsServer) handler(t *testing.T) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
switch {
case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/volumes/"+testVolume+"/"):
w.Header().Set("Content-Type", "application/json")
hosts, _ := json.Marshal(s.allowed)
_, _ = w.Write([]byte(`{"id":"` + testVolume + `","name":"vol1","pool_name":"pool1","size":1,` +
`"ns_id":1,"nqn":"nqn.x","allowed_hosts":` + string(hosts) + `}`))
case r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/volumes/"+testVolume+"/hosts"):
var body struct {
HostNQN string `json:"host_nqn"`
}
_ = json.NewDecoder(r.Body).Decode(&body)
s.posts = append(s.posts, body.HostNQN)
s.post(w)
case r.Method == http.MethodDelete && strings.Contains(r.URL.Path, "/volumes/"+testVolume+"/hosts/"):
s.deletes = append(s.deletes, r.URL.Path[strings.LastIndex(r.URL.Path, "/")+1:])
s.del(w)
default:
t.Errorf("unexpected %s %s", r.Method, r.URL.Path)
w.WriteHeader(http.StatusNotFound)
}
}
}

func created(w http.ResponseWriter) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
_, _ = w.Write([]byte(`{"nqn":"` + mdsHost + `"}`))
}

func answer(code int, body string) func(http.ResponseWriter) {
return func(w http.ResponseWriter) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
_, _ = w.Write([]byte(body))
}
}

func TestEnsureVolumeHostLeavesAnUnrestrictedVolumeAlone(t *testing.T) {
s := &hostsServer{allowed: []string{}, post: created}
c := newTestClient(t, s.handler(t))
got, err := c.EnsureVolumeHost(context.Background(), testHandle, mdsHost)
if err != nil {
t.Fatal(err)
}
if got != HostNotNeeded {
t.Errorf("grant = %d, want HostNotNeeded", got)
}
if len(s.posts) != 0 {
t.Errorf("added %v to a volume that allows every host, which would lock the others out", s.posts)
}
}

func TestEnsureVolumeHostAddsAHostToARestrictedVolume(t *testing.T) {
s := &hostsServer{allowed: []string{"nqn.2014-08.io.simplyblock:uuid:csi-node"}, post: created}
c := newTestClient(t, s.handler(t))
got, err := c.EnsureVolumeHost(context.Background(), testHandle, mdsHost)
if err != nil {
t.Fatal(err)
}
if got != HostAdded || len(s.posts) != 1 || s.posts[0] != mdsHost {
t.Errorf("grant = %d, posts = %v", got, s.posts)
}
}

func TestEnsureVolumeHostDoesNotAddAHostTwice(t *testing.T) {
s := &hostsServer{allowed: []string{"nqn.other", mdsHost}, post: created}
c := newTestClient(t, s.handler(t))
got, err := c.EnsureVolumeHost(context.Background(), testHandle, mdsHost)
if err != nil {
t.Fatal(err)
}
if got != HostAlreadyAllowed || len(s.posts) != 0 {
t.Errorf("grant = %d, posts = %v", got, s.posts)
}
}

// Two reconciles can race between the read and the add. The control plane then
// answers 400 `already allowed`, which is the outcome that was wanted.
func TestEnsureVolumeHostTakesALostRaceAsDone(t *testing.T) {
s := &hostsServer{
allowed: []string{"nqn.other"},
post: answer(http.StatusBadRequest, `{"detail":"Host `+mdsHost+` is already allowed"}`),
}
c := newTestClient(t, s.handler(t))
got, err := c.EnsureVolumeHost(context.Background(), testHandle, mdsHost)
if err != nil || got != HostAlreadyAllowed {
t.Errorf("grant = %d, err = %v", got, err)
}
}

func TestEnsureVolumeHostReportsARefusal(t *testing.T) {
s := &hostsServer{
allowed: []string{"nqn.other"},
post: answer(http.StatusBadRequest, `{"detail":"Failed to add host on node n1"}`),
}
c := newTestClient(t, s.handler(t))
_, err := c.EnsureVolumeHost(context.Background(), testHandle, mdsHost)
var se *StatusError
if !errors.As(err, &se) || se.StatusCode != http.StatusBadRequest {
t.Fatalf("err = %v, want a 400 StatusError", err)
}
}

func TestEnsureVolumeHostRefusesAMalformedHandle(t *testing.T) {
c := newTestClient(t, func(http.ResponseWriter, *http.Request) { t.Error("the control plane was called") })
if _, err := c.EnsureVolumeHost(context.Background(), "not-a-handle", mdsHost); err == nil {
t.Error("a malformed handle was accepted")
}
if _, err := c.EnsureVolumeHost(context.Background(), testHandle, ""); err == nil {
t.Error("an empty host NQN was accepted")
}
}

func TestRemoveVolumeHostDeletesTheHost(t *testing.T) {
s := &hostsServer{del: answer(http.StatusNoContent, "")}
c := newTestClient(t, s.handler(t))
if err := c.RemoveVolumeHost(context.Background(), testHandle, mdsHost); err != nil {
t.Fatal(err)
}
if len(s.deletes) != 1 || s.deletes[0] != mdsHost {
t.Errorf("deletes = %v", s.deletes)
}
}

func TestRemoveVolumeHostCountsAnAbsentHostOrVolumeAsDone(t *testing.T) {
for name, del := range map[string]func(http.ResponseWriter){
"host not listed": answer(http.StatusBadRequest, `{"detail":"Host `+mdsHost+` is not in the allowed list"}`),
"volume gone": answer(http.StatusNotFound, `{"detail":"Volume not found"}`),
} {
s := &hostsServer{del: del}
c := newTestClient(t, s.handler(t))
if err := c.RemoveVolumeHost(context.Background(), testHandle, mdsHost); err != nil {
t.Errorf("%s: %v", name, err)
}
}
}

func TestRemoveVolumeHostReportsAFailure(t *testing.T) {
s := &hostsServer{del: answer(http.StatusInternalServerError, `{"detail":"boom"}`)}
c := newTestClient(t, s.handler(t))
err := c.RemoveVolumeHost(context.Background(), testHandle, mdsHost)
if err == nil || errors.Is(err, errs.ErrNotFound) {
t.Errorf("err = %v, want a server error", err)
}
}
3 changes: 3 additions & 0 deletions atlas-lib/doc.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@
//
// nvme Discover and look up local NVMe controllers and namespaces.
// nvmeof Connect and disconnect NVMe-oF (TCP) targets.
// nvmepr Register, acquire, and preempt a namespace's persistent
// reservation, and read who is registered under which host;
// nvmepr/test is an in-memory namespace for tests.
// nqn Build and parse NVMe Qualified Names.
// blockdev What a Linux block device is, and what it carries: the
// reading a formatting decision rests on, plus the scan that
Expand Down
20 changes: 20 additions & 0 deletions atlas-lib/kube/names.go
Original file line number Diff line number Diff line change
Expand Up @@ -277,3 +277,23 @@ const (
// volume is released.
Finalizer = "storage.simplyblock.io/lvol-protection"
)

// The pNFS metadata server's record, kept on its StatefulSet: which pod is the
// active guest, under which boot and epoch, and the state volume the active
// mounts. The driver controller, the state volume, and the takeover all write
// them.
const (
// AnnoMDSActive names the pod that is the active guest.
AnnoMDSActive = "storage.simplyblock.io/mds-active"
// AnnoMDSActiveInstance is the active's pod UID and runner container ID.
AnnoMDSActiveInstance = "storage.simplyblock.io/mds-active-instance"
// AnnoMDSEpoch is the current promotion epoch, a decimal integer.
AnnoMDSEpoch = "storage.simplyblock.io/mds-epoch"
// AnnoMDSStateVolume is the handle of the state volume.
AnnoMDSStateVolume = "storage.simplyblock.io/mds-state-volume"
// AnnoMDSHostOrdinals is how many ordinals' host NQNs the volumes allow,
// so a scale-down knows which hosts to remove.
AnnoMDSHostOrdinals = "storage.simplyblock.io/mds-host-ordinals"
// FinalizerMDSStateVolume deletes the state volume with the StatefulSet.
FinalizerMDSStateVolume = "storage.simplyblock.io/mds-state-volume"
)
Loading
Loading