github.com/quay/claircore@v1.5.28/matchers/matchers.go (about)

     1  package matchers
     2  
     3  import (
     4  	"context"
     5  	"errors"
     6  	"fmt"
     7  	"net/http"
     8  
     9  	"github.com/quay/zlog"
    10  
    11  	"github.com/quay/claircore/libvuln/driver"
    12  	_ "github.com/quay/claircore/matchers/defaults"
    13  	"github.com/quay/claircore/matchers/registry"
    14  )
    15  
    16  type Configs map[string]driver.MatcherConfigUnmarshaler
    17  
    18  type Matchers struct {
    19  	// provides run-time matcher construction.
    20  	factories map[string]driver.MatcherFactory
    21  	// configs provided to matchers once constructed.
    22  	configs Configs
    23  	client  *http.Client
    24  	// out-of-tree matchers.
    25  	matchers []driver.Matcher
    26  }
    27  
    28  type MatchersOption func(m *Matchers)
    29  
    30  // NewMatchers will return a slice of Matcher created based on the provided
    31  // MatchersOption.
    32  func NewMatchers(ctx context.Context, client *http.Client, opts ...MatchersOption) ([]driver.Matcher, error) {
    33  	ctx = zlog.ContextWithValues(ctx, "component", "libvuln/matchers/NewMatchers")
    34  	if client == nil {
    35  		return nil, errors.New("invalid *http.Client")
    36  	}
    37  
    38  	m := &Matchers{
    39  		factories: registry.Registered(),
    40  		client:    client,
    41  	}
    42  
    43  	// these options can be ran order independent.
    44  	for _, opt := range opts {
    45  		opt(m)
    46  	}
    47  
    48  	err := registry.Configure(ctx, m.factories, m.configs, m.client)
    49  	if err != nil {
    50  		return nil, fmt.Errorf("failed to configure matchers factory: %w", err)
    51  	}
    52  
    53  	matchers := []driver.Matcher{}
    54  	// constructing matchers may return error,
    55  	// depending on the factory.
    56  	// if construction fails we will simply ignore those matcher.
    57  	for _, factory := range m.factories {
    58  		matcher, err := factory.Matcher(ctx)
    59  		if err != nil {
    60  			zlog.Error(ctx).Err(err).Msg("failed constructing factory, excluding from run")
    61  			continue
    62  		}
    63  		matchers = append(matchers, matcher...)
    64  	}
    65  
    66  	// merge default matchers with any out-of-tree specified.
    67  	matchers = append(matchers, m.matchers...)
    68  
    69  	return matchers, nil
    70  }