k8s.io/perf-tests/clusterloader2@v0.0.0-20240304094227-64bdb12da87e/pkg/measurement/factory.go (about)

     1  /*
     2  Copyright 2018 The Kubernetes Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package measurement
    18  
    19  import (
    20  	"fmt"
    21  	"sync"
    22  )
    23  
    24  // Factory is a default global factory instance.
    25  var factory = newMeasurementFactory()
    26  
    27  func newMeasurementFactory() *measurementFactory {
    28  	return &measurementFactory{
    29  		createFuncs: make(map[string]createMeasurementFunc),
    30  	}
    31  }
    32  
    33  // measurementFactory is a factory that creates measurement instances.
    34  type measurementFactory struct {
    35  	lock        sync.RWMutex
    36  	createFuncs map[string]createMeasurementFunc
    37  }
    38  
    39  func (mc *measurementFactory) register(methodName string, createFunc createMeasurementFunc) error {
    40  	mc.lock.Lock()
    41  	defer mc.lock.Unlock()
    42  	_, exists := mc.createFuncs[methodName]
    43  	if exists {
    44  		return fmt.Errorf("measurement with method %v already exists", methodName)
    45  	}
    46  	mc.createFuncs[methodName] = createFunc
    47  	return nil
    48  }
    49  
    50  func (mc *measurementFactory) createMeasurement(methodName string) (Measurement, error) {
    51  	mc.lock.RLock()
    52  	defer mc.lock.RUnlock()
    53  	createFunc, exists := mc.createFuncs[methodName]
    54  	if !exists {
    55  		return nil, fmt.Errorf("unknown measurement method %s", methodName)
    56  	}
    57  	return createFunc(), nil
    58  }
    59  
    60  // Register registers create measurement function in measurement factory.
    61  func Register(methodName string, createFunc createMeasurementFunc) error {
    62  	return factory.register(methodName, createFunc)
    63  }
    64  
    65  // CreateMeasurement creates measurement instance.
    66  func CreateMeasurement(methodName string) (Measurement, error) {
    67  	return factory.createMeasurement(methodName)
    68  }