github.com/hernad/nomad@v1.6.112/nomad/structs/config/plugins.go (about)

     1  // Copyright (c) HashiCorp, Inc.
     2  // SPDX-License-Identifier: MPL-2.0
     3  
     4  package config
     5  
     6  import "github.com/mitchellh/copystructure"
     7  
     8  // PluginConfig is used to configure a plugin explicitly
     9  type PluginConfig struct {
    10  	Name   string                 `hcl:",key"`
    11  	Args   []string               `hcl:"args"`
    12  	Config map[string]interface{} `hcl:"config"`
    13  	// ExtraKeysHCL is used by hcl to surface unexpected keys
    14  	ExtraKeysHCL []string `hcl:",unusedKeys" json:"-"`
    15  }
    16  
    17  func (p *PluginConfig) Merge(o *PluginConfig) *PluginConfig {
    18  	m := *p
    19  
    20  	if len(o.Name) != 0 {
    21  		m.Name = o.Name
    22  	}
    23  	if len(o.Args) != 0 {
    24  		m.Args = o.Args
    25  	}
    26  	if len(o.Config) != 0 {
    27  		m.Config = o.Config
    28  	}
    29  
    30  	return m.Copy()
    31  }
    32  
    33  func (p *PluginConfig) Copy() *PluginConfig {
    34  	c := *p
    35  	if i, err := copystructure.Copy(p.Config); err != nil {
    36  		panic(err.Error())
    37  	} else {
    38  		c.Config = i.(map[string]interface{})
    39  	}
    40  	return &c
    41  }
    42  
    43  // PluginConfigSetMerge merges to sets of plugin configs. For plugins with the
    44  // same name, the configs are merged.
    45  func PluginConfigSetMerge(first, second []*PluginConfig) []*PluginConfig {
    46  	findex := make(map[string]*PluginConfig, len(first))
    47  	for _, p := range first {
    48  		findex[p.Name] = p
    49  	}
    50  
    51  	sindex := make(map[string]*PluginConfig, len(second))
    52  	for _, p := range second {
    53  		sindex[p.Name] = p
    54  	}
    55  
    56  	var out []*PluginConfig
    57  
    58  	// Go through the first set and merge any value that exist in both
    59  	for pluginName, original := range findex {
    60  		second, ok := sindex[pluginName]
    61  		if !ok {
    62  			out = append(out, original.Copy())
    63  			continue
    64  		}
    65  
    66  		out = append(out, original.Merge(second))
    67  	}
    68  
    69  	// Go through the second set and add any value that didn't exist in both
    70  	for pluginName, plugin := range sindex {
    71  		_, ok := findex[pluginName]
    72  		if ok {
    73  			continue
    74  		}
    75  
    76  		out = append(out, plugin)
    77  	}
    78  
    79  	return out
    80  }