github.com/cockroachdb/cockroach@v20.2.0-alpha.1+incompatible/pkg/base/cluster_id.go (about)

     1  // Copyright 2017 The Cockroach Authors.
     2  //
     3  // Use of this software is governed by the Business Source License
     4  // included in the file licenses/BSL.txt.
     5  //
     6  // As of the Change Date specified in that file, in accordance with
     7  // the Business Source License, use of this software will be governed
     8  // by the Apache License, Version 2.0, included in the file
     9  // licenses/APL.txt.
    10  
    11  package base
    12  
    13  import (
    14  	"context"
    15  
    16  	"github.com/cockroachdb/cockroach/pkg/util/log"
    17  	"github.com/cockroachdb/cockroach/pkg/util/syncutil"
    18  	"github.com/cockroachdb/cockroach/pkg/util/uuid"
    19  )
    20  
    21  // ClusterIDContainer is used to share a single Cluster ID instance between
    22  // multiple layers. It allows setting and getting the value. Once a value is
    23  // set, the value cannot change.
    24  //
    25  // The cluster ID is determined on startup as follows:
    26  // - If there are existing stores, their cluster ID is used.
    27  // - If the node is bootstrapping, a new UUID is generated.
    28  // - Otherwise, it is determined via gossip with other nodes.
    29  type ClusterIDContainer struct {
    30  	syncutil.Mutex
    31  
    32  	clusterID uuid.UUID
    33  }
    34  
    35  // String returns the cluster ID, or "?" if it is unset.
    36  func (c *ClusterIDContainer) String() string {
    37  	val := c.Get()
    38  	if val == uuid.Nil {
    39  		return "?"
    40  	}
    41  	return val.String()
    42  }
    43  
    44  // Get returns the current cluster ID; uuid.Nil if it is unset.
    45  func (c *ClusterIDContainer) Get() uuid.UUID {
    46  	c.Lock()
    47  	defer c.Unlock()
    48  	return c.clusterID
    49  }
    50  
    51  // Set sets the current cluster ID. If it is already set, the value must match.
    52  func (c *ClusterIDContainer) Set(ctx context.Context, val uuid.UUID) {
    53  	c.Lock()
    54  	defer c.Unlock()
    55  	if c.clusterID == uuid.Nil {
    56  		c.clusterID = val
    57  		if log.V(2) {
    58  			log.Infof(ctx, "ClusterID set to %s", val)
    59  		}
    60  	} else if c.clusterID != val {
    61  		log.Fatalf(ctx, "different ClusterIDs set: %s, then %s", c.clusterID, val)
    62  	}
    63  }
    64  
    65  // Reset changes the ClusterID regardless of the old value.
    66  //
    67  // Should only be used in testing code.
    68  func (c *ClusterIDContainer) Reset(val uuid.UUID) {
    69  	c.Lock()
    70  	defer c.Unlock()
    71  	c.clusterID = val
    72  }