github.com/anth0d/nomad@v0.0.0-20221214183521-ae3a0a2cad06/nomad/structs/consul.go (about)

     1  package structs
     2  
     3  // Consul represents optional per-group consul configuration.
     4  type Consul struct {
     5  	// Namespace in which to operate in Consul.
     6  	Namespace string
     7  }
     8  
     9  // Copy the Consul block.
    10  func (c *Consul) Copy() *Consul {
    11  	if c == nil {
    12  		return nil
    13  	}
    14  	return &Consul{
    15  		Namespace: c.Namespace,
    16  	}
    17  }
    18  
    19  // Equal returns whether c and o are the same.
    20  func (c *Consul) Equal(o *Consul) bool {
    21  	if c == nil || o == nil {
    22  		return c == o
    23  	}
    24  	return c.Namespace == o.Namespace
    25  }
    26  
    27  // Validate returns whether c is valid.
    28  func (c *Consul) Validate() error {
    29  	// nothing to do here
    30  	return nil
    31  }
    32  
    33  // ConsulUsage is provides meta information about how Consul is used by a job,
    34  // noting which connect services and normal services will be registered, and
    35  // whether the keystore will be read via template.
    36  type ConsulUsage struct {
    37  	Services []string
    38  	KV       bool
    39  }
    40  
    41  // Used returns true if Consul is used for registering services or reading from
    42  // the keystore.
    43  func (cu *ConsulUsage) Used() bool {
    44  	switch {
    45  	case cu.KV:
    46  		return true
    47  	case len(cu.Services) > 0:
    48  		return true
    49  	}
    50  	return false
    51  }
    52  
    53  // ConsulUsages returns a map from Consul namespace to things that will use Consul,
    54  // including ConsulConnect TaskKinds, Consul Services from groups and tasks, and
    55  // a boolean indicating if Consul KV is in use.
    56  func (j *Job) ConsulUsages() map[string]*ConsulUsage {
    57  	m := make(map[string]*ConsulUsage)
    58  
    59  	for _, tg := range j.TaskGroups {
    60  		namespace := j.ConsulNamespace
    61  		if tgNamespace := tg.Consul.GetNamespace(); tgNamespace != "" {
    62  			namespace = tgNamespace
    63  		}
    64  		if _, exists := m[namespace]; !exists {
    65  			m[namespace] = new(ConsulUsage)
    66  		}
    67  
    68  		// Gather group services
    69  		for _, service := range tg.Services {
    70  			if service.Provider == ServiceProviderConsul {
    71  				m[namespace].Services = append(m[namespace].Services, service.Name)
    72  			}
    73  		}
    74  
    75  		// Gather task services and KV usage
    76  		for _, task := range tg.Tasks {
    77  			for _, service := range task.Services {
    78  				if service.Provider == ServiceProviderConsul {
    79  					m[namespace].Services = append(m[namespace].Services, service.Name)
    80  				}
    81  			}
    82  			if len(task.Templates) > 0 {
    83  				m[namespace].KV = true
    84  			}
    85  		}
    86  	}
    87  
    88  	return m
    89  }