github.com/vmware/govmomi@v0.43.0/simulator/feature_test.go (about)

     1  /*
     2  Copyright (c) 2019 VMware, Inc. All Rights Reserved.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package simulator_test
    18  
    19  import (
    20  	"bytes"
    21  	"context"
    22  	"fmt"
    23  	"log"
    24  	"net/url"
    25  	"os"
    26  	"os/exec"
    27  	"path/filepath"
    28  	"strings"
    29  
    30  	"github.com/vmware/govmomi"
    31  	"github.com/vmware/govmomi/find"
    32  	"github.com/vmware/govmomi/object"
    33  	"github.com/vmware/govmomi/simulator"
    34  	"github.com/vmware/govmomi/vim25"
    35  	"github.com/vmware/govmomi/vim25/types"
    36  )
    37  
    38  // Custom username + password authentication
    39  func Example_usernamePasswordLogin() {
    40  	model := simulator.VPX()
    41  
    42  	defer model.Remove()
    43  	err := model.Create()
    44  	if err != nil {
    45  		log.Fatal(err)
    46  	}
    47  
    48  	model.Service.Listen = &url.URL{
    49  		User: url.UserPassword("my-username", "my-password"),
    50  	}
    51  
    52  	s := model.Service.NewServer()
    53  	defer s.Close()
    54  
    55  	c, err := govmomi.NewClient(context.Background(), s.URL, true)
    56  	if err != nil {
    57  		log.Fatal(err)
    58  	}
    59  
    60  	fmt.Printf("login to %s as %s", c.Client.ServiceContent.About.ApiType, s.URL.User)
    61  	// Output: login to VirtualCenter as my-username:my-password
    62  }
    63  
    64  // Set VM properties that the API cannot change in a real vCenter.
    65  func Example_setVirtualMachineProperties() {
    66  	simulator.Test(func(ctx context.Context, c *vim25.Client) {
    67  		vm, err := find.NewFinder(c).VirtualMachine(ctx, "DC0_H0_VM0")
    68  		if err != nil {
    69  			log.Fatal(err)
    70  		}
    71  
    72  		spec := types.VirtualMachineConfigSpec{
    73  			ExtraConfig: []types.BaseOptionValue{
    74  				&types.OptionValue{Key: "SET.guest.ipAddress", Value: "10.0.0.42"},
    75  			},
    76  		}
    77  
    78  		task, _ := vm.Reconfigure(ctx, spec)
    79  
    80  		_ = task.Wait(ctx)
    81  
    82  		ip, _ := vm.WaitForIP(ctx)
    83  		fmt.Printf("ip is %s", ip)
    84  	})
    85  	// Output: ip is 10.0.0.42
    86  }
    87  
    88  // Tie a docker container to the lifecycle of a vcsim VM
    89  func Example_runContainer() {
    90  	simulator.Test(func(ctx context.Context, c *vim25.Client) {
    91  		if _, err := exec.LookPath("docker"); err != nil {
    92  			fmt.Println("0 diff")
    93  			return
    94  		}
    95  
    96  		finder := find.NewFinder(c)
    97  		pool, _ := finder.ResourcePool(ctx, "DC0_H0/Resources")
    98  		dc, err := finder.Datacenter(ctx, "DC0")
    99  		if err != nil {
   100  			log.Fatal(err)
   101  		}
   102  		f, _ := dc.Folders(ctx)
   103  		dir, err := os.MkdirTemp("", "example")
   104  		if err != nil {
   105  			log.Fatal(err)
   106  		}
   107  		os.Chmod(dir, 0755)
   108  		fpath := filepath.Join(dir, "index.html")
   109  		fcontent := "foo"
   110  		os.WriteFile(fpath, []byte(fcontent), 0644)
   111  		// just in case umask gets in the way
   112  		os.Chmod(fpath, 0644)
   113  		defer os.RemoveAll(dir)
   114  
   115  		args := fmt.Sprintf("-v '%s:/usr/share/nginx/html:ro' nginx", dir)
   116  
   117  		spec := types.VirtualMachineConfigSpec{
   118  			Name: "nginx",
   119  			Files: &types.VirtualMachineFileInfo{
   120  				VmPathName: "[LocalDS_0] nginx",
   121  			},
   122  			ExtraConfig: []types.BaseOptionValue{
   123  				&types.OptionValue{Key: "RUN.container", Value: args}, // run nginx
   124  				&types.OptionValue{Key: "RUN.port.80", Value: "8888"}, // test port remap
   125  			},
   126  		}
   127  
   128  		// Create a new VM
   129  		task, err := f.VmFolder.CreateVM(ctx, spec, pool, nil)
   130  
   131  		if err != nil {
   132  			log.Fatal(err)
   133  		}
   134  		info, err := task.WaitForResult(ctx, nil)
   135  		if err != nil {
   136  			log.Fatal(err)
   137  		}
   138  		vm := object.NewVirtualMachine(c, info.Result.(types.ManagedObjectReference))
   139  
   140  		// PowerOn VM starts the nginx container
   141  		task, _ = vm.PowerOn(ctx)
   142  		err = task.Wait(ctx)
   143  		if err != nil {
   144  			log.Fatal(err)
   145  		}
   146  
   147  		ip, _ := vm.WaitForIP(ctx, true) // Returns the docker container's IP
   148  
   149  		// Count the number of bytes in feature_test.go via nginx going direct to the container
   150  		cmd := exec.Command("docker", "run", "--rm", "curlimages/curl", "curl", "-f", fmt.Sprintf("http://%s", ip))
   151  		var buf bytes.Buffer
   152  		cmd.Stdout = &buf
   153  		err = cmd.Run()
   154  		res := buf.String()
   155  
   156  		if err != nil || strings.TrimSpace(res) != fcontent {
   157  			log.Fatal(err, buf.String())
   158  		}
   159  
   160  		// Count the number of bytes in feature_test.go via nginx going via port remap on host
   161  		cmd = exec.Command("curl", "-f", "http://localhost:8888")
   162  		buf.Reset()
   163  		cmd.Stdout = &buf
   164  		err = cmd.Run()
   165  		res = buf.String()
   166  		if err != nil || strings.TrimSpace(res) != fcontent {
   167  			log.Fatal(err, buf.String())
   168  		}
   169  
   170  		// PowerOff stops the container
   171  		task, _ = vm.PowerOff(ctx)
   172  		_ = task.Wait(ctx)
   173  		// Destroy deletes the container
   174  		task, _ = vm.Destroy(ctx)
   175  		_ = task.Wait(ctx)
   176  
   177  		fmt.Printf("%d diff", buf.Len()-len(fcontent))
   178  	})
   179  	// Output: 0 diff
   180  }