2020-08-31 17:19:28 +00:00
|
|
|
package stream
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2020-12-01 16:11:34 +00:00
|
|
|
"errors"
|
2020-10-08 18:27:52 +00:00
|
|
|
"fmt"
|
2020-08-31 17:19:28 +00:00
|
|
|
"sync"
|
2020-12-01 16:11:34 +00:00
|
|
|
"sync/atomic"
|
2020-08-31 17:19:28 +00:00
|
|
|
|
2020-10-08 18:27:52 +00:00
|
|
|
"github.com/armon/go-metrics"
|
2020-12-01 16:11:34 +00:00
|
|
|
"github.com/hashicorp/go-memdb"
|
|
|
|
lru "github.com/hashicorp/golang-lru"
|
|
|
|
"github.com/hashicorp/nomad/acl"
|
2020-10-04 19:12:35 +00:00
|
|
|
"github.com/hashicorp/nomad/nomad/structs"
|
|
|
|
|
2020-08-31 17:19:28 +00:00
|
|
|
"github.com/hashicorp/go-hclog"
|
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
2020-12-01 16:11:34 +00:00
|
|
|
ACLCheckNodeRead = "node-read"
|
|
|
|
ACLCheckManagement = "management"
|
|
|
|
aclCacheSize = 32
|
2020-08-31 17:19:28 +00:00
|
|
|
)
|
|
|
|
|
2020-10-08 18:27:52 +00:00
|
|
|
type EventBrokerCfg struct {
|
2020-08-31 17:19:28 +00:00
|
|
|
EventBufferSize int64
|
2020-09-28 14:13:10 +00:00
|
|
|
Logger hclog.Logger
|
2020-08-31 17:19:28 +00:00
|
|
|
}
|
|
|
|
|
2020-10-08 18:27:52 +00:00
|
|
|
type EventBroker struct {
|
2020-11-02 14:21:32 +00:00
|
|
|
// mu protects subscriptions
|
2020-12-11 15:40:50 +00:00
|
|
|
mu sync.Mutex
|
2020-11-02 14:21:32 +00:00
|
|
|
subscriptions *subscriptions
|
|
|
|
|
2020-08-31 17:19:28 +00:00
|
|
|
// eventBuf stores a configurable amount of events in memory
|
|
|
|
eventBuf *eventBuffer
|
|
|
|
|
|
|
|
// publishCh is used to send messages from an active txn to a goroutine which
|
|
|
|
// publishes events, so that publishing can happen asynchronously from
|
|
|
|
// the Commit call in the FSM hot path.
|
2020-10-06 20:21:58 +00:00
|
|
|
publishCh chan *structs.Events
|
2020-08-31 17:19:28 +00:00
|
|
|
|
2020-12-01 16:11:34 +00:00
|
|
|
aclDelegate ACLDelegate
|
|
|
|
aclCache *lru.TwoQueueCache
|
|
|
|
|
|
|
|
aclCh chan *structs.Event
|
|
|
|
|
2020-10-08 18:27:52 +00:00
|
|
|
logger hclog.Logger
|
2020-08-31 17:19:28 +00:00
|
|
|
}
|
|
|
|
|
2020-10-08 18:27:52 +00:00
|
|
|
// NewEventBroker returns an EventBroker for publishing change events.
|
|
|
|
// A goroutine is run in the background to publish events to an event buffer.
|
|
|
|
// Cancelling the context will shutdown the goroutine to free resources, and stop
|
|
|
|
// all publishing.
|
2020-12-01 16:11:34 +00:00
|
|
|
func NewEventBroker(ctx context.Context, aclDelegate ACLDelegate, cfg EventBrokerCfg) (*EventBroker, error) {
|
2020-09-28 14:13:10 +00:00
|
|
|
if cfg.Logger == nil {
|
|
|
|
cfg.Logger = hclog.NewNullLogger()
|
|
|
|
}
|
|
|
|
|
2020-10-06 20:21:58 +00:00
|
|
|
// Set the event buffer size to a minimum
|
|
|
|
if cfg.EventBufferSize == 0 {
|
|
|
|
cfg.EventBufferSize = 100
|
|
|
|
}
|
|
|
|
|
2020-12-01 16:11:34 +00:00
|
|
|
aclCache, err := lru.New2Q(aclCacheSize)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2020-10-22 16:21:03 +00:00
|
|
|
buffer := newEventBuffer(cfg.EventBufferSize)
|
2020-10-08 18:27:52 +00:00
|
|
|
e := &EventBroker{
|
2020-12-01 16:11:34 +00:00
|
|
|
logger: cfg.Logger.Named("event_broker"),
|
|
|
|
eventBuf: buffer,
|
|
|
|
publishCh: make(chan *structs.Events, 64),
|
|
|
|
aclCh: make(chan *structs.Event, 10),
|
|
|
|
aclDelegate: aclDelegate,
|
|
|
|
aclCache: aclCache,
|
2020-08-31 17:19:28 +00:00
|
|
|
subscriptions: &subscriptions{
|
|
|
|
byToken: make(map[string]map[*SubscribeRequest]*Subscription),
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
|
|
|
go e.handleUpdates(ctx)
|
2020-12-01 16:11:34 +00:00
|
|
|
go e.handleACLUpdates(ctx)
|
2020-08-31 17:19:28 +00:00
|
|
|
|
2020-12-01 16:11:34 +00:00
|
|
|
return e, nil
|
2020-08-31 17:19:28 +00:00
|
|
|
}
|
|
|
|
|
2020-10-08 18:27:52 +00:00
|
|
|
// Returns the current length of the event buffer
|
|
|
|
func (e *EventBroker) Len() int {
|
2020-10-06 15:08:12 +00:00
|
|
|
return e.eventBuf.Len()
|
|
|
|
}
|
|
|
|
|
2020-08-31 17:19:28 +00:00
|
|
|
// Publish events to all subscribers of the event Topic.
|
2020-10-08 18:27:52 +00:00
|
|
|
func (e *EventBroker) Publish(events *structs.Events) {
|
2020-12-01 16:11:34 +00:00
|
|
|
if len(events.Events) == 0 {
|
|
|
|
return
|
2020-08-31 17:19:28 +00:00
|
|
|
}
|
2020-12-01 16:11:34 +00:00
|
|
|
|
|
|
|
// Notify the broker to check running subscriptions against potentially
|
|
|
|
// updated ACL Token or Policy
|
|
|
|
for _, event := range events.Events {
|
|
|
|
if event.Topic == structs.TopicACLToken || event.Topic == structs.TopicACLPolicy {
|
|
|
|
e.aclCh <- &event
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
e.publishCh <- events
|
|
|
|
}
|
|
|
|
|
|
|
|
// SubscribeWithACLCheck validates the SubscribeRequest's token and requested Topics
|
|
|
|
// to ensure that the tokens privileges are sufficient enough.
|
|
|
|
func (e *EventBroker) SubscribeWithACLCheck(req *SubscribeRequest) (*Subscription, error) {
|
|
|
|
aclObj, err := aclObjFromSnapshotForTokenSecretID(e.aclDelegate.TokenProvider(), e.aclCache, req.Token)
|
|
|
|
if err != nil {
|
|
|
|
return nil, structs.ErrPermissionDenied
|
|
|
|
}
|
|
|
|
|
|
|
|
if allowed := aclAllowsSubscription(aclObj, req); !allowed {
|
|
|
|
return nil, structs.ErrPermissionDenied
|
|
|
|
}
|
|
|
|
|
|
|
|
return e.Subscribe(req)
|
2020-08-31 17:19:28 +00:00
|
|
|
}
|
|
|
|
|
2020-10-08 18:27:52 +00:00
|
|
|
// Subscribe returns a new Subscription for a given request. A Subscription
|
|
|
|
// will receive an initial empty currentItem value which points to the first item
|
|
|
|
// in the buffer. This allows the new subscription to call Next() without first checking
|
|
|
|
// for the current Item.
|
|
|
|
//
|
|
|
|
// A Subscription will start at the requested index, or as close as possible to
|
|
|
|
// the requested index if it is no longer in the buffer. If StartExactlyAtIndex is
|
|
|
|
// set and the index is no longer in the buffer or not yet in the buffer an error
|
|
|
|
// will be returned.
|
|
|
|
//
|
|
|
|
// When a caller is finished with the subscription it must call Subscription.Unsubscribe
|
2020-12-01 16:11:34 +00:00
|
|
|
// to free ACL tracking resources.
|
2020-10-08 18:27:52 +00:00
|
|
|
func (e *EventBroker) Subscribe(req *SubscribeRequest) (*Subscription, error) {
|
|
|
|
e.mu.Lock()
|
|
|
|
defer e.mu.Unlock()
|
2020-08-31 17:19:28 +00:00
|
|
|
|
|
|
|
var head *bufferItem
|
|
|
|
var offset int
|
|
|
|
if req.Index != 0 {
|
|
|
|
head, offset = e.eventBuf.StartAtClosest(req.Index)
|
|
|
|
} else {
|
|
|
|
head = e.eventBuf.Head()
|
|
|
|
}
|
2020-10-08 18:27:52 +00:00
|
|
|
if offset > 0 && req.StartExactlyAtIndex {
|
|
|
|
return nil, fmt.Errorf("requested index not in buffer")
|
|
|
|
} else if offset > 0 {
|
|
|
|
metrics.SetGauge([]string{"nomad", "event_broker", "subscription", "request_offset"}, float32(offset))
|
|
|
|
e.logger.Debug("requested index no longer in buffer", "requsted", int(req.Index), "closest", int(head.Events.Index))
|
2020-08-31 17:19:28 +00:00
|
|
|
}
|
|
|
|
|
2020-09-28 14:13:10 +00:00
|
|
|
// Empty head so that calling Next on sub
|
2020-10-06 20:21:58 +00:00
|
|
|
start := newBufferItem(&structs.Events{Index: req.Index})
|
2020-09-28 14:13:10 +00:00
|
|
|
start.link.next.Store(head)
|
2020-11-02 14:21:32 +00:00
|
|
|
close(start.link.nextCh)
|
2020-09-28 14:13:10 +00:00
|
|
|
|
2020-10-08 18:27:52 +00:00
|
|
|
sub := newSubscription(req, start, e.subscriptions.unsubscribeFn(req))
|
2020-08-31 17:19:28 +00:00
|
|
|
|
|
|
|
e.subscriptions.add(req, sub)
|
|
|
|
return sub, nil
|
|
|
|
}
|
|
|
|
|
2020-10-08 18:27:52 +00:00
|
|
|
// CloseAll closes all subscriptions
|
|
|
|
func (e *EventBroker) CloseAll() {
|
2020-10-06 20:21:58 +00:00
|
|
|
e.subscriptions.closeAll()
|
|
|
|
}
|
|
|
|
|
2020-10-08 18:27:52 +00:00
|
|
|
func (e *EventBroker) handleUpdates(ctx context.Context) {
|
2020-08-31 17:19:28 +00:00
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case <-ctx.Done():
|
|
|
|
e.subscriptions.closeAll()
|
|
|
|
return
|
|
|
|
case update := <-e.publishCh:
|
2020-11-02 14:21:32 +00:00
|
|
|
e.eventBuf.Append(update)
|
2020-08-31 17:19:28 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-12-01 16:11:34 +00:00
|
|
|
func (e *EventBroker) handleACLUpdates(ctx context.Context) {
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case <-ctx.Done():
|
|
|
|
return
|
|
|
|
case update := <-e.aclCh:
|
|
|
|
switch payload := update.Payload.(type) {
|
2020-12-11 15:40:50 +00:00
|
|
|
case *structs.ACLTokenEvent:
|
|
|
|
tokenSecretID := payload.SecretID()
|
2020-12-01 16:11:34 +00:00
|
|
|
|
|
|
|
// Token was deleted
|
|
|
|
if update.Type == structs.TypeACLTokenDeleted {
|
|
|
|
e.subscriptions.closeSubscriptionsForTokens([]string{tokenSecretID})
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
// If broker cannot fetch state there is nothing more to do
|
|
|
|
if e.aclDelegate == nil {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
aclObj, err := aclObjFromSnapshotForTokenSecretID(e.aclDelegate.TokenProvider(), e.aclCache, tokenSecretID)
|
|
|
|
if err != nil || aclObj == nil {
|
|
|
|
e.logger.Error("failed resolving ACL for secretID, closing subscriptions", "error", err)
|
|
|
|
e.subscriptions.closeSubscriptionsForTokens([]string{tokenSecretID})
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
e.subscriptions.closeSubscriptionFunc(tokenSecretID, func(sub *Subscription) bool {
|
|
|
|
return !aclAllowsSubscription(aclObj, sub.req)
|
|
|
|
})
|
|
|
|
|
2020-12-11 15:40:50 +00:00
|
|
|
case *structs.ACLPolicyEvent:
|
2020-12-01 16:11:34 +00:00
|
|
|
// Re-evaluate each subscriptions permissions since a policy
|
|
|
|
// change may or may not affect the subscription
|
|
|
|
e.checkSubscriptionsAgainstPolicyChange()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// checkSubscriptionsAgainstPolicyChange iterates over the brokers
|
|
|
|
// subscriptions and evaluates whether the token used for the subscription is
|
|
|
|
// still valid. If it is not valid it closes the subscriptions belonging to the
|
|
|
|
// token.
|
|
|
|
//
|
|
|
|
// A lock must be held to iterate over the map of subscriptions.
|
|
|
|
func (e *EventBroker) checkSubscriptionsAgainstPolicyChange() {
|
|
|
|
e.mu.Lock()
|
|
|
|
defer e.mu.Unlock()
|
|
|
|
|
|
|
|
// If broker cannot fetch state there is nothing more to do
|
|
|
|
if e.aclDelegate == nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
aclSnapshot := e.aclDelegate.TokenProvider()
|
|
|
|
for tokenSecretID := range e.subscriptions.byToken {
|
2020-12-11 15:40:50 +00:00
|
|
|
// if tokenSecretID is empty ACLs were disabled at time of subscribing
|
|
|
|
if tokenSecretID == "" {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2020-12-01 16:11:34 +00:00
|
|
|
aclObj, err := aclObjFromSnapshotForTokenSecretID(aclSnapshot, e.aclCache, tokenSecretID)
|
|
|
|
if err != nil || aclObj == nil {
|
2020-12-11 15:40:50 +00:00
|
|
|
e.logger.Debug("failed resolving ACL for secretID, closing subscriptions", "error", err)
|
2020-12-01 16:11:34 +00:00
|
|
|
e.subscriptions.closeSubscriptionsForTokens([]string{tokenSecretID})
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
e.subscriptions.closeSubscriptionFunc(tokenSecretID, func(sub *Subscription) bool {
|
|
|
|
return !aclAllowsSubscription(aclObj, sub.req)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func aclObjFromSnapshotForTokenSecretID(aclSnapshot ACLTokenProvider, aclCache *lru.TwoQueueCache, tokenSecretID string) (*acl.ACL, error) {
|
|
|
|
aclToken, err := aclSnapshot.ACLTokenBySecretID(nil, tokenSecretID)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
if aclToken == nil {
|
|
|
|
return nil, errors.New("no token for secret ID")
|
|
|
|
}
|
|
|
|
|
|
|
|
// Check if this is a management token
|
|
|
|
if aclToken.Type == structs.ACLManagementToken {
|
|
|
|
return acl.ManagementACL, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
aclPolicies := make([]*structs.ACLPolicy, 0, len(aclToken.Policies))
|
|
|
|
for _, policyName := range aclToken.Policies {
|
|
|
|
policy, err := aclSnapshot.ACLPolicyByName(nil, policyName)
|
|
|
|
if err != nil || policy == nil {
|
|
|
|
return nil, errors.New("error finding acl policy")
|
|
|
|
}
|
|
|
|
aclPolicies = append(aclPolicies, policy)
|
|
|
|
}
|
|
|
|
|
|
|
|
return structs.CompileACLObject(aclCache, aclPolicies)
|
|
|
|
}
|
|
|
|
|
|
|
|
type ACLTokenProvider interface {
|
|
|
|
ACLTokenBySecretID(ws memdb.WatchSet, secretID string) (*structs.ACLToken, error)
|
|
|
|
ACLPolicyByName(ws memdb.WatchSet, policyName string) (*structs.ACLPolicy, error)
|
|
|
|
}
|
|
|
|
|
|
|
|
type ACLDelegate interface {
|
|
|
|
TokenProvider() ACLTokenProvider
|
|
|
|
}
|
|
|
|
|
|
|
|
func aclAllowsSubscription(aclObj *acl.ACL, subReq *SubscribeRequest) bool {
|
|
|
|
for topic := range subReq.Topics {
|
|
|
|
switch topic {
|
|
|
|
case structs.TopicDeployment,
|
2020-12-03 16:48:18 +00:00
|
|
|
structs.TopicEvaluation,
|
|
|
|
structs.TopicAllocation,
|
2020-12-01 16:11:34 +00:00
|
|
|
structs.TopicJob:
|
|
|
|
if ok := aclObj.AllowNsOp(subReq.Namespace, acl.NamespaceCapabilityReadJob); !ok {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
case structs.TopicNode:
|
|
|
|
if ok := aclObj.AllowNodeRead(); !ok {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
default:
|
|
|
|
if ok := aclObj.IsManagement(); !ok {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Subscription) forceClose() {
|
|
|
|
if atomic.CompareAndSwapUint32(&s.state, subscriptionStateOpen, subscriptionStateClosed) {
|
|
|
|
close(s.forceClosed)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-10-08 18:27:52 +00:00
|
|
|
type subscriptions struct {
|
|
|
|
// mu for byToken. If both subscription.mu and EventBroker.mu need
|
|
|
|
// to be held, EventBroker mutex MUST always be acquired first.
|
|
|
|
mu sync.RWMutex
|
|
|
|
|
|
|
|
// byToken is an mapping of active Subscriptions indexed by a token and
|
|
|
|
// a pointer to the request.
|
|
|
|
// When the token is modified all subscriptions under that token will be
|
|
|
|
// reloaded.
|
|
|
|
// A subscription may be unsubscribed by using the pointer to the request.
|
|
|
|
byToken map[string]map[*SubscribeRequest]*Subscription
|
|
|
|
}
|
|
|
|
|
2020-08-31 17:19:28 +00:00
|
|
|
func (s *subscriptions) add(req *SubscribeRequest, sub *Subscription) {
|
2020-10-08 18:27:52 +00:00
|
|
|
s.mu.Lock()
|
|
|
|
defer s.mu.Unlock()
|
2020-08-31 17:19:28 +00:00
|
|
|
|
|
|
|
subsByToken, ok := s.byToken[req.Token]
|
|
|
|
if !ok {
|
|
|
|
subsByToken = make(map[*SubscribeRequest]*Subscription)
|
|
|
|
s.byToken[req.Token] = subsByToken
|
|
|
|
}
|
|
|
|
subsByToken[req] = sub
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *subscriptions) closeSubscriptionsForTokens(tokenSecretIDs []string) {
|
2020-10-08 18:27:52 +00:00
|
|
|
s.mu.RLock()
|
|
|
|
defer s.mu.RUnlock()
|
2020-08-31 17:19:28 +00:00
|
|
|
|
|
|
|
for _, secretID := range tokenSecretIDs {
|
|
|
|
if subs, ok := s.byToken[secretID]; ok {
|
|
|
|
for _, sub := range subs {
|
|
|
|
sub.forceClose()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-12-01 16:11:34 +00:00
|
|
|
func (s *subscriptions) closeSubscriptionFunc(tokenSecretID string, fn func(*Subscription) bool) {
|
|
|
|
s.mu.RLock()
|
|
|
|
defer s.mu.RUnlock()
|
|
|
|
|
|
|
|
for _, sub := range s.byToken[tokenSecretID] {
|
|
|
|
if fn(sub) {
|
|
|
|
sub.forceClose()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-10-08 18:27:52 +00:00
|
|
|
// unsubscribeFn returns a function that the subscription will call to remove
|
2020-08-31 17:19:28 +00:00
|
|
|
// itself from the subsByToken.
|
|
|
|
// This function is returned as a closure so that the caller doesn't need to keep
|
2020-10-08 18:27:52 +00:00
|
|
|
// track of the SubscriptionRequest, and can not accidentally call unsubscribeFn with the
|
2020-08-31 17:19:28 +00:00
|
|
|
// wrong pointer.
|
2020-10-08 18:27:52 +00:00
|
|
|
func (s *subscriptions) unsubscribeFn(req *SubscribeRequest) func() {
|
2020-08-31 17:19:28 +00:00
|
|
|
return func() {
|
2020-10-08 18:27:52 +00:00
|
|
|
s.mu.Lock()
|
|
|
|
defer s.mu.Unlock()
|
2020-08-31 17:19:28 +00:00
|
|
|
|
|
|
|
subsByToken, ok := s.byToken[req.Token]
|
|
|
|
if !ok {
|
|
|
|
return
|
|
|
|
}
|
2020-10-08 18:27:52 +00:00
|
|
|
|
|
|
|
sub := subsByToken[req]
|
|
|
|
if sub == nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// close the subscription
|
|
|
|
sub.forceClose()
|
|
|
|
|
2020-08-31 17:19:28 +00:00
|
|
|
delete(subsByToken, req)
|
|
|
|
if len(subsByToken) == 0 {
|
|
|
|
delete(s.byToken, req.Token)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *subscriptions) closeAll() {
|
2020-10-08 18:27:52 +00:00
|
|
|
s.mu.Lock()
|
|
|
|
defer s.mu.Unlock()
|
2020-08-31 17:19:28 +00:00
|
|
|
|
|
|
|
for _, byRequest := range s.byToken {
|
|
|
|
for _, sub := range byRequest {
|
|
|
|
sub.forceClose()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|