github.com/GoogleContainerTools/kpt@v1.0.0-beta.50.0.20240520170205-c25345ffcbee/pkg/fn/multiruntime.go (about)

     1  // Copyright 2022 The kpt Authors
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package fn
    16  
    17  import (
    18  	"context"
    19  	"errors"
    20  
    21  	v1 "github.com/GoogleContainerTools/kpt/pkg/api/kptfile/v1"
    22  )
    23  
    24  // MultiRuntime is a compound FunctionRuntime that will use the first available runner.
    25  type MultiRuntime struct {
    26  	runtimes []FunctionRuntime
    27  }
    28  
    29  // NewMultiRuntime builds a MultiRuntime.
    30  func NewMultiRuntime(runtimes []FunctionRuntime) *MultiRuntime {
    31  	return &MultiRuntime{
    32  		runtimes: runtimes,
    33  	}
    34  }
    35  
    36  var _ FunctionRuntime = &MultiRuntime{}
    37  
    38  // GetRunner implements FunctionRuntime
    39  func (r *MultiRuntime) GetRunner(ctx context.Context, fn *v1.Function) (FunctionRunner, error) {
    40  	for _, runtime := range r.runtimes {
    41  		runner, err := runtime.GetRunner(ctx, fn)
    42  		if err != nil {
    43  			var notFoundError *NotFoundError
    44  			if !errors.As(err, &notFoundError) {
    45  				return nil, err
    46  			}
    47  		} else {
    48  			return runner, nil
    49  		}
    50  	}
    51  
    52  	return nil, &NotFoundError{Function: *fn}
    53  }
    54  
    55  // Add adds the provided runtime to the end of the MultiRuntime list.
    56  func (r *MultiRuntime) Add(runtime FunctionRuntime) {
    57  	r.runtimes = append(r.runtimes, runtime)
    58  }