github.com/hooklift/terraform@v0.11.0-beta1.0.20171117000744-6786c1361ffe/communicator/winrm/communicator.go (about)

     1  package winrm
     2  
     3  import (
     4  	"fmt"
     5  	"io"
     6  	"log"
     7  	"math/rand"
     8  	"strconv"
     9  	"strings"
    10  	"sync"
    11  	"time"
    12  
    13  	"github.com/hashicorp/terraform/communicator/remote"
    14  	"github.com/hashicorp/terraform/terraform"
    15  	"github.com/masterzen/winrm"
    16  	"github.com/packer-community/winrmcp/winrmcp"
    17  
    18  	// This import is a bit strange, but it's needed so `make updatedeps` can see and download it
    19  	_ "github.com/dylanmei/winrmtest"
    20  )
    21  
    22  // Communicator represents the WinRM communicator
    23  type Communicator struct {
    24  	connInfo *connectionInfo
    25  	client   *winrm.Client
    26  	endpoint *winrm.Endpoint
    27  	rand     *rand.Rand
    28  }
    29  
    30  // New creates a new communicator implementation over WinRM.
    31  func New(s *terraform.InstanceState) (*Communicator, error) {
    32  	connInfo, err := parseConnectionInfo(s)
    33  	if err != nil {
    34  		return nil, err
    35  	}
    36  
    37  	endpoint := &winrm.Endpoint{
    38  		Host:     connInfo.Host,
    39  		Port:     connInfo.Port,
    40  		HTTPS:    connInfo.HTTPS,
    41  		Insecure: connInfo.Insecure,
    42  	}
    43  	if len(connInfo.CACert) > 0 {
    44  		endpoint.CACert = []byte(connInfo.CACert)
    45  	}
    46  
    47  	comm := &Communicator{
    48  		connInfo: connInfo,
    49  		endpoint: endpoint,
    50  		// Seed our own rand source so that script paths are not deterministic
    51  		rand: rand.New(rand.NewSource(time.Now().UnixNano())),
    52  	}
    53  
    54  	return comm, nil
    55  }
    56  
    57  // Connect implementation of communicator.Communicator interface
    58  func (c *Communicator) Connect(o terraform.UIOutput) error {
    59  	if c.client != nil {
    60  		return nil
    61  	}
    62  
    63  	params := winrm.DefaultParameters
    64  	params.Timeout = formatDuration(c.Timeout())
    65  
    66  	client, err := winrm.NewClientWithParameters(
    67  		c.endpoint, c.connInfo.User, c.connInfo.Password, params)
    68  	if err != nil {
    69  		return err
    70  	}
    71  
    72  	if o != nil {
    73  		o.Output(fmt.Sprintf(
    74  			"Connecting to remote host via WinRM...\n"+
    75  				"  Host: %s\n"+
    76  				"  Port: %d\n"+
    77  				"  User: %s\n"+
    78  				"  Password: %t\n"+
    79  				"  HTTPS: %t\n"+
    80  				"  Insecure: %t\n"+
    81  				"  CACert: %t",
    82  			c.connInfo.Host,
    83  			c.connInfo.Port,
    84  			c.connInfo.User,
    85  			c.connInfo.Password != "",
    86  			c.connInfo.HTTPS,
    87  			c.connInfo.Insecure,
    88  			c.connInfo.CACert != "",
    89  		))
    90  	}
    91  
    92  	log.Printf("connecting to remote shell using WinRM")
    93  	shell, err := client.CreateShell()
    94  	if err != nil {
    95  		log.Printf("connection error: %s", err)
    96  		return err
    97  	}
    98  
    99  	err = shell.Close()
   100  	if err != nil {
   101  		log.Printf("error closing connection: %s", err)
   102  		return err
   103  	}
   104  
   105  	if o != nil {
   106  		o.Output("Connected!")
   107  	}
   108  
   109  	c.client = client
   110  
   111  	return nil
   112  }
   113  
   114  // Disconnect implementation of communicator.Communicator interface
   115  func (c *Communicator) Disconnect() error {
   116  	c.client = nil
   117  	return nil
   118  }
   119  
   120  // Timeout implementation of communicator.Communicator interface
   121  func (c *Communicator) Timeout() time.Duration {
   122  	return c.connInfo.TimeoutVal
   123  }
   124  
   125  // ScriptPath implementation of communicator.Communicator interface
   126  func (c *Communicator) ScriptPath() string {
   127  	return strings.Replace(
   128  		c.connInfo.ScriptPath, "%RAND%",
   129  		strconv.FormatInt(int64(c.rand.Int31()), 10), -1)
   130  }
   131  
   132  // Start implementation of communicator.Communicator interface
   133  func (c *Communicator) Start(rc *remote.Cmd) error {
   134  	err := c.Connect(nil)
   135  	if err != nil {
   136  		return err
   137  	}
   138  
   139  	shell, err := c.client.CreateShell()
   140  	if err != nil {
   141  		return err
   142  	}
   143  
   144  	log.Printf("starting remote command: %s", rc.Command)
   145  	cmd, err := shell.Execute(rc.Command)
   146  	if err != nil {
   147  		return err
   148  	}
   149  
   150  	go runCommand(shell, cmd, rc)
   151  	return nil
   152  }
   153  
   154  func runCommand(shell *winrm.Shell, cmd *winrm.Command, rc *remote.Cmd) {
   155  	defer shell.Close()
   156  
   157  	var wg sync.WaitGroup
   158  	go func() {
   159  		wg.Add(1)
   160  		io.Copy(rc.Stdout, cmd.Stdout)
   161  		wg.Done()
   162  	}()
   163  	go func() {
   164  		wg.Add(1)
   165  		io.Copy(rc.Stderr, cmd.Stderr)
   166  		wg.Done()
   167  	}()
   168  
   169  	cmd.Wait()
   170  	wg.Wait()
   171  	rc.SetExited(cmd.ExitCode())
   172  }
   173  
   174  // Upload implementation of communicator.Communicator interface
   175  func (c *Communicator) Upload(path string, input io.Reader) error {
   176  	wcp, err := c.newCopyClient()
   177  	if err != nil {
   178  		return err
   179  	}
   180  	log.Printf("Uploading file to '%s'", path)
   181  	return wcp.Write(path, input)
   182  }
   183  
   184  // UploadScript implementation of communicator.Communicator interface
   185  func (c *Communicator) UploadScript(path string, input io.Reader) error {
   186  	return c.Upload(path, input)
   187  }
   188  
   189  // UploadDir implementation of communicator.Communicator interface
   190  func (c *Communicator) UploadDir(dst string, src string) error {
   191  	log.Printf("Uploading dir '%s' to '%s'", src, dst)
   192  	wcp, err := c.newCopyClient()
   193  	if err != nil {
   194  		return err
   195  	}
   196  	return wcp.Copy(src, dst)
   197  }
   198  
   199  func (c *Communicator) newCopyClient() (*winrmcp.Winrmcp, error) {
   200  	addr := fmt.Sprintf("%s:%d", c.endpoint.Host, c.endpoint.Port)
   201  
   202  	config := winrmcp.Config{
   203  		Auth: winrmcp.Auth{
   204  			User:     c.connInfo.User,
   205  			Password: c.connInfo.Password,
   206  		},
   207  		Https:                 c.connInfo.HTTPS,
   208  		Insecure:              c.connInfo.Insecure,
   209  		OperationTimeout:      c.Timeout(),
   210  		MaxOperationsPerShell: 15, // lowest common denominator
   211  	}
   212  
   213  	if c.connInfo.CACert != "" {
   214  		config.CACertBytes = []byte(c.connInfo.CACert)
   215  	}
   216  
   217  	return winrmcp.New(addr, &config)
   218  }