google.golang.org/grpc@v1.72.2/xds/internal/xdsclient/clientimpl_watchers.go (about)

     1  /*
     2   *
     3   * Copyright 2020 gRPC authors.
     4   *
     5   * Licensed under the Apache License, Version 2.0 (the "License");
     6   * you may not use this file except in compliance with the License.
     7   * You may obtain a copy of the License at
     8   *
     9   *     http://www.apache.org/licenses/LICENSE-2.0
    10   *
    11   * Unless required by applicable law or agreed to in writing, software
    12   * distributed under the License is distributed on an "AS IS" BASIS,
    13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    14   * See the License for the specific language governing permissions and
    15   * limitations under the License.
    16   */
    17  
    18  package xdsclient
    19  
    20  import (
    21  	"context"
    22  	"fmt"
    23  	"sync"
    24  
    25  	"google.golang.org/grpc/xds/internal/xdsclient/transport/ads"
    26  	"google.golang.org/grpc/xds/internal/xdsclient/xdsresource"
    27  )
    28  
    29  // wrappingWatcher is a wrapper around an xdsresource.ResourceWatcher that adds
    30  // the node ID to the error messages reported to the watcher.
    31  type wrappingWatcher struct {
    32  	xdsresource.ResourceWatcher
    33  	nodeID string
    34  }
    35  
    36  func (w *wrappingWatcher) OnError(err error, done xdsresource.OnDoneFunc) {
    37  	w.ResourceWatcher.OnError(fmt.Errorf("[xDS node id: %v]: %w", w.nodeID, err), done)
    38  }
    39  
    40  // WatchResource uses xDS to discover the resource associated with the provided
    41  // resource name. The resource type implementation determines how xDS responses
    42  // are are deserialized and validated, as received from the xDS management
    43  // server. Upon receipt of a response from the management server, an
    44  // appropriate callback on the watcher is invoked.
    45  func (c *clientImpl) WatchResource(rType xdsresource.Type, resourceName string, watcher xdsresource.ResourceWatcher) (cancel func()) {
    46  	// Return early if the client is already closed.
    47  	//
    48  	// The client returned from the top-level API is a ref-counted client which
    49  	// contains a pointer to `clientImpl`. When all references are released, the
    50  	// ref-counted client sets its pointer to `nil`. And if any watch APIs are
    51  	// made on such a closed client, we will get here with a `nil` receiver.
    52  	if c == nil || c.done.HasFired() {
    53  		logger.Warningf("Watch registered for name %q of type %q, but client is closed", rType.TypeName(), resourceName)
    54  		return func() {}
    55  	}
    56  
    57  	watcher = &wrappingWatcher{
    58  		ResourceWatcher: watcher,
    59  		nodeID:          c.config.Node().GetId(),
    60  	}
    61  
    62  	if err := c.resourceTypes.maybeRegister(rType); err != nil {
    63  		logger.Warningf("Watch registered for name %q of type %q which is already registered", rType.TypeName(), resourceName)
    64  		c.serializer.TrySchedule(func(context.Context) { watcher.OnError(err, func() {}) })
    65  		return func() {}
    66  	}
    67  
    68  	n := xdsresource.ParseName(resourceName)
    69  	a := c.getAuthorityForResource(n)
    70  	if a == nil {
    71  		logger.Warningf("Watch registered for name %q of type %q, authority %q is not found", rType.TypeName(), resourceName, n.Authority)
    72  		watcher.OnError(fmt.Errorf("authority %q not found in bootstrap config for resource %q", n.Authority, resourceName), func() {})
    73  		return func() {}
    74  	}
    75  	// The watchResource method on the authority is invoked with n.String()
    76  	// instead of resourceName because n.String() canonicalizes the given name.
    77  	// So, two resource names which don't differ in the query string, but only
    78  	// differ in the order of context params will result in the same resource
    79  	// being watched by the authority.
    80  	return a.watchResource(rType, n.String(), watcher)
    81  }
    82  
    83  // Gets the authority for the given resource name.
    84  //
    85  // See examples in this section of the gRFC:
    86  // https://github.com/grpc/proposal/blob/master/A47-xds-federation.md#bootstrap-config-changes
    87  func (c *clientImpl) getAuthorityForResource(name *xdsresource.Name) *authority {
    88  	// For new-style resource names, always lookup the authorities map. If the
    89  	// name does not specify an authority, we will end up looking for an entry
    90  	// in the map with the empty string as the key.
    91  	if name.Scheme == xdsresource.FederationScheme {
    92  		return c.authorities[name.Authority]
    93  	}
    94  
    95  	// For old-style resource names, we use the top-level authority if the name
    96  	// does not specify an authority.
    97  	if name.Authority == "" {
    98  		return c.topLevelAuthority
    99  	}
   100  	return c.authorities[name.Authority]
   101  }
   102  
   103  // A registry of xdsresource.Type implementations indexed by their corresponding
   104  // type URLs. Registration of an xdsresource.Type happens the first time a watch
   105  // for a resource of that type is invoked.
   106  type resourceTypeRegistry struct {
   107  	mu    sync.Mutex
   108  	types map[string]xdsresource.Type
   109  }
   110  
   111  func newResourceTypeRegistry() *resourceTypeRegistry {
   112  	return &resourceTypeRegistry{types: make(map[string]xdsresource.Type)}
   113  }
   114  
   115  func (r *resourceTypeRegistry) get(url string) xdsresource.Type {
   116  	r.mu.Lock()
   117  	defer r.mu.Unlock()
   118  	return r.types[url]
   119  }
   120  
   121  func (r *resourceTypeRegistry) maybeRegister(rType xdsresource.Type) error {
   122  	r.mu.Lock()
   123  	defer r.mu.Unlock()
   124  
   125  	url := rType.TypeURL()
   126  	typ, ok := r.types[url]
   127  	if ok && typ != rType {
   128  		return fmt.Errorf("attempt to re-register a resource type implementation for %v", rType.TypeName())
   129  	}
   130  	r.types[url] = rType
   131  	return nil
   132  }
   133  
   134  func (c *clientImpl) triggerResourceNotFoundForTesting(rType xdsresource.Type, resourceName string) error {
   135  	c.channelsMu.Lock()
   136  	defer c.channelsMu.Unlock()
   137  
   138  	if c.logger.V(2) {
   139  		c.logger.Infof("Triggering resource not found for type: %s, resource name: %s", rType.TypeName(), resourceName)
   140  	}
   141  
   142  	for _, state := range c.xdsActiveChannels {
   143  		if err := state.channel.triggerResourceNotFoundForTesting(rType, resourceName); err != nil {
   144  			return err
   145  		}
   146  	}
   147  	return nil
   148  }
   149  
   150  func (c *clientImpl) resourceWatchStateForTesting(rType xdsresource.Type, resourceName string) (ads.ResourceWatchState, error) {
   151  	c.channelsMu.Lock()
   152  	defer c.channelsMu.Unlock()
   153  
   154  	for _, state := range c.xdsActiveChannels {
   155  		if st, err := state.channel.ads.ResourceWatchStateForTesting(rType, resourceName); err == nil {
   156  			return st, nil
   157  		}
   158  	}
   159  	return ads.ResourceWatchState{}, fmt.Errorf("unable to find watch state for resource type %q and name %q", rType.TypeName(), resourceName)
   160  }