k8s.io/perf-tests/clusterloader2@v0.0.0-20240304094227-64bdb12da87e/pkg/state/resource_state.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 state
    18  
    19  import (
    20  	"fmt"
    21  	"strconv"
    22  	"sync"
    23  )
    24  
    25  // ResourceTypeIdentifier is a unique identifier for a resource type.
    26  type ResourceTypeIdentifier struct {
    27  	ObjectKind string
    28  	APIGroup   string
    29  }
    30  
    31  // ResourcesVersionsState represents most recent resources versions for a given object types.
    32  // These versions are available only for resource types of objects that were create/updated
    33  // by the clusterloader.
    34  type ResourcesVersionsState struct {
    35  	lock              sync.RWMutex
    36  	resourcesVersions map[ResourceTypeIdentifier]uint64
    37  }
    38  
    39  // newResourcesVersionState creates new resources versions state.
    40  func newResourcesVersionsState() *ResourcesVersionsState {
    41  	return &ResourcesVersionsState{
    42  		resourcesVersions: make(map[ResourceTypeIdentifier]uint64),
    43  	}
    44  }
    45  
    46  // Get returns state of current resource version.
    47  func (rs *ResourcesVersionsState) Get(identifier ResourceTypeIdentifier) (string, bool) {
    48  	rs.lock.RLock()
    49  	defer rs.lock.RUnlock()
    50  	version, exists := rs.resourcesVersions[identifier]
    51  	if !exists {
    52  		return "0", false
    53  	}
    54  	return strconv.FormatUint(version, 10), true
    55  }
    56  
    57  // Set stores information about current resource version.
    58  func (rs *ResourcesVersionsState) Set(identifier ResourceTypeIdentifier, resourceVersion string) error {
    59  	rs.lock.Lock()
    60  	defer rs.lock.Unlock()
    61  	version, err := strconv.ParseUint(resourceVersion, 10, 64)
    62  	if err != nil {
    63  		return fmt.Errorf("incorrect version format")
    64  	}
    65  	if current, exists := rs.resourcesVersions[identifier]; exists && current > version {
    66  		version = current
    67  	}
    68  	rs.resourcesVersions[identifier] = version
    69  	return nil
    70  }