github.com/juju/juju@v0.0.0-20240430160146-1752b71fcf00/jujuclient/proxy.go (about)

     1  // Copyright 2020 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package jujuclient
     5  
     6  import (
     7  	"github.com/juju/errors"
     8  	"gopkg.in/yaml.v3"
     9  
    10  	"github.com/juju/juju/proxy"
    11  	proxyfactory "github.com/juju/juju/proxy/factory"
    12  )
    13  
    14  // For testing purposes.
    15  var NewProxierFactory = newProxierFactory
    16  
    17  func newProxierFactory() (ProxyFactory, error) {
    18  	return proxyfactory.NewDefaultFactory()
    19  }
    20  
    21  // ProxyFactory defines the interface for a factory that can create a proxy.
    22  type ProxyFactory interface {
    23  	ProxierFromConfig(string, map[string]interface{}) (proxy.Proxier, error)
    24  }
    25  
    26  // ProxyConfWrapper is wrapper around proxier interfaces so that they can be
    27  // serialized to json correctly.
    28  type ProxyConfWrapper struct {
    29  	Proxier proxy.Proxier
    30  }
    31  
    32  // MarshalYAML implements marshalling method for yaml. This is so we can make
    33  // sure the proxier type is outputted with the config for later ingestion
    34  func (p *ProxyConfWrapper) MarshalYAML() (interface{}, error) {
    35  	return proxyConfMarshaler{
    36  		Type: p.Proxier.Type(), Config: p.Proxier,
    37  	}, nil
    38  }
    39  
    40  type proxyConfMarshaler struct {
    41  	Type   string         `yaml:"type"`
    42  	Config yaml.Marshaler `yaml:"config"`
    43  }
    44  
    45  type proxyConfUnmarshaler struct {
    46  	Type   string                 `yaml:"type"`
    47  	Config map[string]interface{} `yaml:"config"`
    48  }
    49  
    50  // UnmarshalYAML ingests a previously outputted proxy config. It uses the proxy
    51  // default factory to try and construct the correct proxy based on type.
    52  func (p *ProxyConfWrapper) UnmarshalYAML(unmarshal func(interface{}) error) error {
    53  	factory, err := NewProxierFactory()
    54  	if err != nil {
    55  		return errors.Annotate(err, "building proxy factory for config")
    56  	}
    57  
    58  	var pc proxyConfUnmarshaler
    59  	err = unmarshal(&pc)
    60  	if err != nil {
    61  		return errors.Annotate(err, "unmarshalling raw proxy config")
    62  	}
    63  	p.Proxier, err = factory.ProxierFromConfig(pc.Type, pc.Config)
    64  	if err != nil {
    65  		return errors.Annotatef(err, "cannot make proxier for type %s", pc.Type)
    66  	}
    67  	return nil
    68  }