github.com/fafucoder/cilium@v1.6.11/pkg/endpoint/id/allocator.go (about)

     1  // Copyright 2018 Authors of Cilium
     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 id
    16  
    17  import (
    18  	"fmt"
    19  
    20  	"github.com/cilium/cilium/pkg/idpool"
    21  	"github.com/cilium/cilium/pkg/logging"
    22  	"github.com/cilium/cilium/pkg/logging/logfields"
    23  )
    24  
    25  const (
    26  	minID = idpool.ID(1)
    27  	maxID = idpool.ID(4095)
    28  )
    29  
    30  var (
    31  	pool = idpool.NewIDPool(minID, maxID)
    32  	log  = logging.DefaultLogger.WithField(logfields.LogSubsys, "endpoint")
    33  )
    34  
    35  // ReallocatePool starts over with a new pool.
    36  func ReallocatePool() {
    37  	pool = idpool.NewIDPool(minID, maxID)
    38  }
    39  
    40  // Allocate returns a new random ID from the pool
    41  func Allocate() uint16 {
    42  	id := pool.AllocateID()
    43  
    44  	// Out of endpoint IDs
    45  	if id == idpool.NoID {
    46  		return uint16(0)
    47  	}
    48  
    49  	return uint16(id)
    50  }
    51  
    52  // Reuse grabs a specific endpoint ID for reuse. This can be used when
    53  // restoring endpoints.
    54  func Reuse(id uint16) error {
    55  	if idpool.ID(id) < minID {
    56  		return fmt.Errorf("unable to reuse endpoint: %d < %d", id, minID)
    57  	}
    58  
    59  	// When restoring endpoints, the existing endpoint ID can be outside of
    60  	// the range. This is fine (tm) and we can just skip to reserve the ID
    61  	// from the pool as the pool will not cover it.
    62  	if idpool.ID(id) > maxID {
    63  		return nil
    64  	}
    65  
    66  	if !pool.Remove(idpool.ID(id)) {
    67  		return fmt.Errorf("endpoint ID %d is already in use", id)
    68  	}
    69  
    70  	return nil
    71  }
    72  
    73  // Release releases an endpoint ID that was previously allocated or reused
    74  func Release(id uint16) error {
    75  	if !pool.Insert(idpool.ID(id)) {
    76  		return fmt.Errorf("Unable to release endpoint ID %d", id)
    77  	}
    78  
    79  	return nil
    80  }