github.com/ferranbt/nomad@v0.9.3-0.20190607002617-85c449b7667c/plugins/shared/structs/plugin_reattach_config.go (about)

     1  package structs
     2  
     3  import (
     4  	"fmt"
     5  	"net"
     6  
     7  	plugin "github.com/hashicorp/go-plugin"
     8  )
     9  
    10  // ReattachConfig is a wrapper around plugin.ReattachConfig to better support
    11  // serialization
    12  type ReattachConfig struct {
    13  	Protocol string
    14  	Network  string
    15  	Addr     string
    16  	Pid      int
    17  }
    18  
    19  // ReattachConfigToGoPlugin converts a ReattachConfig wrapper struct into a go
    20  // plugin ReattachConfig struct
    21  func ReattachConfigToGoPlugin(rc *ReattachConfig) (*plugin.ReattachConfig, error) {
    22  	if rc == nil {
    23  		return nil, fmt.Errorf("nil ReattachConfig cannot be converted")
    24  	}
    25  
    26  	plug := &plugin.ReattachConfig{
    27  		Protocol: plugin.Protocol(rc.Protocol),
    28  		Pid:      rc.Pid,
    29  	}
    30  
    31  	switch rc.Network {
    32  	case "tcp", "tcp4", "tcp6":
    33  		addr, err := net.ResolveTCPAddr(rc.Network, rc.Addr)
    34  		if err != nil {
    35  			return nil, err
    36  		}
    37  		plug.Addr = addr
    38  	case "udp", "udp4", "udp6":
    39  		addr, err := net.ResolveUDPAddr(rc.Network, rc.Addr)
    40  		if err != nil {
    41  			return nil, err
    42  		}
    43  		plug.Addr = addr
    44  	case "unix", "unixgram", "unixpacket":
    45  		addr, err := net.ResolveUnixAddr(rc.Network, rc.Addr)
    46  		if err != nil {
    47  			return nil, err
    48  		}
    49  		plug.Addr = addr
    50  	default:
    51  		return nil, fmt.Errorf("unknown network: %s", rc.Network)
    52  	}
    53  
    54  	return plug, nil
    55  }
    56  
    57  // ReattachConfigFromGoPlugin converts a go plugin ReattachConfig into a
    58  // ReattachConfig wrapper struct
    59  func ReattachConfigFromGoPlugin(plug *plugin.ReattachConfig) *ReattachConfig {
    60  	if plug == nil {
    61  		return nil
    62  	}
    63  
    64  	rc := &ReattachConfig{
    65  		Protocol: string(plug.Protocol),
    66  		Network:  plug.Addr.Network(),
    67  		Addr:     plug.Addr.String(),
    68  		Pid:      plug.Pid,
    69  	}
    70  
    71  	return rc
    72  }