github.com/iqoqo/nomad@v0.11.3-0.20200911112621-d7021c74d101/client/taskenv/services.go (about)

     1  package taskenv
     2  
     3  import (
     4  	"github.com/hashicorp/nomad/nomad/structs"
     5  )
     6  
     7  // InterpolateServices returns an interpolated copy of services and checks with
     8  // values from the task's environment.
     9  func InterpolateServices(taskEnv *TaskEnv, services []*structs.Service) []*structs.Service {
    10  	// Guard against not having a valid taskEnv. This can be the case if the
    11  	// PreKilling or Exited hook is run before Poststart.
    12  	if taskEnv == nil || len(services) == 0 {
    13  		return nil
    14  	}
    15  
    16  	interpolated := make([]*structs.Service, len(services))
    17  
    18  	for i, origService := range services {
    19  		// Create a copy as we need to reinterpolate every time the
    20  		// environment changes
    21  		service := origService.Copy()
    22  
    23  		for _, check := range service.Checks {
    24  			check.Name = taskEnv.ReplaceEnv(check.Name)
    25  			check.Type = taskEnv.ReplaceEnv(check.Type)
    26  			check.Command = taskEnv.ReplaceEnv(check.Command)
    27  			check.Args = taskEnv.ParseAndReplace(check.Args)
    28  			check.Path = taskEnv.ReplaceEnv(check.Path)
    29  			check.Protocol = taskEnv.ReplaceEnv(check.Protocol)
    30  			check.PortLabel = taskEnv.ReplaceEnv(check.PortLabel)
    31  			check.InitialStatus = taskEnv.ReplaceEnv(check.InitialStatus)
    32  			check.Method = taskEnv.ReplaceEnv(check.Method)
    33  			check.GRPCService = taskEnv.ReplaceEnv(check.GRPCService)
    34  			if len(check.Header) > 0 {
    35  				header := make(map[string][]string, len(check.Header))
    36  				for k, vs := range check.Header {
    37  					newVals := make([]string, len(vs))
    38  					for i, v := range vs {
    39  						newVals[i] = taskEnv.ReplaceEnv(v)
    40  					}
    41  					header[taskEnv.ReplaceEnv(k)] = newVals
    42  				}
    43  				check.Header = header
    44  			}
    45  		}
    46  
    47  		service.Name = taskEnv.ReplaceEnv(service.Name)
    48  		service.PortLabel = taskEnv.ReplaceEnv(service.PortLabel)
    49  		service.Tags = taskEnv.ParseAndReplace(service.Tags)
    50  		service.CanaryTags = taskEnv.ParseAndReplace(service.CanaryTags)
    51  
    52  		if len(service.Meta) > 0 {
    53  			meta := make(map[string]string, len(service.Meta))
    54  			for k, v := range service.Meta {
    55  				meta[k] = taskEnv.ReplaceEnv(v)
    56  			}
    57  			service.Meta = meta
    58  		}
    59  
    60  		interpolated[i] = service
    61  	}
    62  
    63  	return interpolated
    64  }