前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >虚拟机自动化注意了

虚拟机自动化注意了

作者头像
heidsoft
发布2022-01-11 08:16:11
4320
发布2022-01-11 08:16:11
举报
文章被收录于专栏:云计算与大数据

虚拟化采用了vmware 公司的vsphere产品,版本6.x

使用开源项目:github.com/vmware/govmomi 来实现虚拟机自动化部署流程

虚拟机配置对象是:

代码语言:javascript
复制
type VirtualMachineConfigSpec struct {
  DynamicData

  ChangeVersion                string                                 `xml:"changeVersion,omitempty"`
  Name                         string                                 `xml:"name,omitempty"`
  Version                      string                                 `xml:"version,omitempty"`
  CreateDate                   *time.Time                             `xml:"createDate"`
  Uuid                         string                                 `xml:"uuid,omitempty"`
  InstanceUuid                 string                                 `xml:"instanceUuid,omitempty"`
  NpivNodeWorldWideName        []int64                                `xml:"npivNodeWorldWideName,omitempty"`
  NpivPortWorldWideName        []int64                                `xml:"npivPortWorldWideName,omitempty"`
  NpivWorldWideNameType        string                                 `xml:"npivWorldWideNameType,omitempty"`
  NpivDesiredNodeWwns          int16                                  `xml:"npivDesiredNodeWwns,omitempty"`
  NpivDesiredPortWwns          int16                                  `xml:"npivDesiredPortWwns,omitempty"`
  NpivTemporaryDisabled        *bool                                  `xml:"npivTemporaryDisabled"`
  NpivOnNonRdmDisks            *bool                                  `xml:"npivOnNonRdmDisks"`
  NpivWorldWideNameOp          string                                 `xml:"npivWorldWideNameOp,omitempty"`
  LocationId                   string                                 `xml:"locationId,omitempty"`
  GuestId                      string                                 `xml:"guestId,omitempty"`
  AlternateGuestName           string                                 `xml:"alternateGuestName,omitempty"`
  Annotation                   string                                 `xml:"annotation,omitempty"`
  Files                        *VirtualMachineFileInfo                `xml:"files,omitempty"`
  Tools                        *ToolsConfigInfo                       `xml:"tools,omitempty"`
  Flags                        *VirtualMachineFlagInfo                `xml:"flags,omitempty"`
  ConsolePreferences           *VirtualMachineConsolePreferences      `xml:"consolePreferences,omitempty"`
  PowerOpInfo                  *VirtualMachineDefaultPowerOpInfo      `xml:"powerOpInfo,omitempty"`
  NumCPUs                      int32                                  `xml:"numCPUs,omitempty"`
  VcpuConfig                   []VirtualMachineVcpuConfig             `xml:"vcpuConfig,omitempty"`
  NumCoresPerSocket            int32                                  `xml:"numCoresPerSocket,omitempty"`
  MemoryMB                     int64                                  `xml:"memoryMB,omitempty"`
  MemoryHotAddEnabled          *bool                                  `xml:"memoryHotAddEnabled"`
  CpuHotAddEnabled             *bool                                  `xml:"cpuHotAddEnabled"`
  CpuHotRemoveEnabled          *bool                                  `xml:"cpuHotRemoveEnabled"`
  VirtualICH7MPresent          *bool                                  `xml:"virtualICH7MPresent"`
  VirtualSMCPresent            *bool                                  `xml:"virtualSMCPresent"`
  DeviceChange                 []BaseVirtualDeviceConfigSpec          `xml:"deviceChange,omitempty,typeattr"`
  CpuAllocation                *ResourceAllocationInfo                `xml:"cpuAllocation,omitempty"`
  MemoryAllocation             *ResourceAllocationInfo                `xml:"memoryAllocation,omitempty"`
  LatencySensitivity           *LatencySensitivity                    `xml:"latencySensitivity,omitempty"`
  CpuAffinity                  *VirtualMachineAffinityInfo            `xml:"cpuAffinity,omitempty"`
  MemoryAffinity               *VirtualMachineAffinityInfo            `xml:"memoryAffinity,omitempty"`
  NetworkShaper                *VirtualMachineNetworkShaperInfo       `xml:"networkShaper,omitempty"`
  CpuFeatureMask               []VirtualMachineCpuIdInfoSpec          `xml:"cpuFeatureMask,omitempty"`
  ExtraConfig                  []BaseOptionValue                      `xml:"extraConfig,omitempty,typeattr"`
  SwapPlacement                string                                 `xml:"swapPlacement,omitempty"`
  BootOptions                  *VirtualMachineBootOptions             `xml:"bootOptions,omitempty"`
  VAppConfig                   BaseVmConfigSpec                       `xml:"vAppConfig,omitempty,typeattr"`
  FtInfo                       BaseFaultToleranceConfigInfo           `xml:"ftInfo,omitempty,typeattr"`
  RepConfig                    *ReplicationConfigSpec                 `xml:"repConfig,omitempty"`
  VAppConfigRemoved            *bool                                  `xml:"vAppConfigRemoved"`
  VAssertsEnabled              *bool                                  `xml:"vAssertsEnabled"`
  ChangeTrackingEnabled        *bool                                  `xml:"changeTrackingEnabled"`
  Firmware                     string                                 `xml:"firmware,omitempty"`
  MaxMksConnections            int32                                  `xml:"maxMksConnections,omitempty"`
  GuestAutoLockEnabled         *bool                                  `xml:"guestAutoLockEnabled"`
  ManagedBy                    *ManagedByInfo                         `xml:"managedBy,omitempty"`
  MemoryReservationLockedToMax *bool                                  `xml:"memoryReservationLockedToMax"`
  NestedHVEnabled              *bool                                  `xml:"nestedHVEnabled"`
  VPMCEnabled                  *bool                                  `xml:"vPMCEnabled"`
  ScheduledHardwareUpgradeInfo *ScheduledHardwareUpgradeInfo          `xml:"scheduledHardwareUpgradeInfo,omitempty"`
  VmProfile                    []BaseVirtualMachineProfileSpec        `xml:"vmProfile,omitempty,typeattr"`
  MessageBusTunnelEnabled      *bool                                  `xml:"messageBusTunnelEnabled"`
  Crypto                       BaseCryptoSpec                         `xml:"crypto,omitempty,typeattr"`
  MigrateEncryption            string                                 `xml:"migrateEncryption,omitempty"`
  SgxInfo                      *VirtualMachineSgxInfo                 `xml:"sgxInfo,omitempty"`
  GuestMonitoringModeInfo      *VirtualMachineGuestMonitoringModeInfo `xml:"guestMonitoringModeInfo,omitempty"`
  SevEnabled                   *bool                                  `xml:"sevEnabled"`
}

在基于模版克隆时,会设置客户机操作系统,在开发中,工程师将操作系统设置为

代码语言:javascript
复制
  VirtualMachineGuestOsIdentifierOtherLinux64Guest          = VirtualMachineGuestOsIdentifier("otherLinux64Guest")

测试后发现使用该操作系统,克隆后的虚拟机无法支持cpu 热插拔特性,在vsphere控制台上查看虚拟机配置,发现CpuHotAddEnabled 单选框没有勾选。

调试:

代码语言:javascript
复制
types.VirtualMachineConfigSpec{
   Name:     "test-linux",
   GuestId:  "centos7_64Guest",
   NumCPUs:  4,
   MemoryMB: 6,
   CpuHotAddEnabled: types.NewBool(true),
   MemoryHotAddEnabled: types.NewBool(true),
   CpuHotRemoveEnabled: types.NewBool(true),
}

由于sdk 结构对象类型采用xml 序列化模式,特将该对象转化打印

代码语言:javascript
复制
xml, _ := xml.MarshalIndent(虚拟机模版config, "  ", "    ")

xml 处理参考

代码语言:javascript
复制
package xml_test

import (
  "encoding/xml"
  "fmt"
  "os"
)

func ExampleMarshalIndent() {
  type Address struct {
    City, State string
  }
  type Person struct {
    XMLName   xml.Name `xml:"person"`
    Id        int      `xml:"id,attr"`
    FirstName string   `xml:"name>first"`
    LastName  string   `xml:"name>last"`
    Age       int      `xml:"age"`
    Height    float32  `xml:"height,omitempty"`
    Married   bool
    Address
    Comment string `xml:",comment"`
  }

  v := &Person{Id: 13, FirstName: "John", LastName: "Doe", Age: 42}
  v.Comment = " Need more details. "
  v.Address = Address{"Hanga Roa", "Easter Island"}

  output, err := xml.MarshalIndent(v, "  ", "    ")
  if err != nil {
    fmt.Printf("error: %v\n", err)
  }

  os.Stdout.Write(output)
  // Output:
  //   <person id="13">
  //       <name>
  //           <first>John</first>
  //           <last>Doe</last>
  //       </name>
  //       <age>42</age>
  //       <Married>false</Married>
  //       <City>Hanga Roa</City>
  //       <State>Easter Island</State>
  //       <!-- Need more details. -->
  //   </person>
}

func ExampleEncoder() {
  type Address struct {
    City, State string
  }
  type Person struct {
    XMLName   xml.Name `xml:"person"`
    Id        int      `xml:"id,attr"`
    FirstName string   `xml:"name>first"`
    LastName  string   `xml:"name>last"`
    Age       int      `xml:"age"`
    Height    float32  `xml:"height,omitempty"`
    Married   bool
    Address
    Comment string `xml:",comment"`
  }

  v := &Person{Id: 13, FirstName: "John", LastName: "Doe", Age: 42}
  v.Comment = " Need more details. "
  v.Address = Address{"Hanga Roa", "Easter Island"}

  enc := xml.NewEncoder(os.Stdout)
  enc.Indent("  ", "    ")
  if err := enc.Encode(v); err != nil {
    fmt.Printf("error: %v\n", err)
  }

  // Output:
  //   <person id="13">
  //       <name>
  //           <first>John</first>
  //           <last>Doe</last>
  //       </name>
  //       <age>42</age>
  //       <Married>false</Married>
  //       <City>Hanga Roa</City>
  //       <State>Easter Island</State>
  //       <!-- Need more details. -->
  //   </person>
}

// This example demonstrates unmarshaling an XML excerpt into a value with
// some preset fields. Note that the Phone field isn't modified and that
// the XML <Company> element is ignored. Also, the Groups field is assigned
// considering the element path provided in its tag.
func ExampleUnmarshal() {
  type Email struct {
    Where string `xml:"where,attr"`
    Addr  string
  }
  type Address struct {
    City, State string
  }
  type Result struct {
    XMLName xml.Name `xml:"Person"`
    Name    string   `xml:"FullName"`
    Phone   string
    Email   []Email
    Groups  []string `xml:"Group>Value"`
    Address
  }
  v := Result{Name: "none", Phone: "none"}

  data := `
    <Person>
      <FullName>Grace R. Emlin</FullName>
      <Company>Example Inc.</Company>
      <Email where="home">
        <Addr>gre@example.com</Addr>
      </Email>
      <Email where='work'>
        <Addr>gre@work.com</Addr>
      </Email>
      <Group>
        <Value>Friends</Value>
        <Value>Squash</Value>
      </Group>
      <City>Hanga Roa</City>
      <State>Easter Island</State>
    </Person>
  `
  err := xml.Unmarshal([]byte(data), &v)
  if err != nil {
    fmt.Printf("error: %v", err)
    return
  }
  fmt.Printf("XMLName: %#v\n", v.XMLName)
  fmt.Printf("Name: %q\n", v.Name)
  fmt.Printf("Phone: %q\n", v.Phone)
  fmt.Printf("Email: %v\n", v.Email)
  fmt.Printf("Groups: %v\n", v.Groups)
  fmt.Printf("Address: %v\n", v.Address)
  // Output:
  // XMLName: xml.Name{Space:"", Local:"Person"}
  // Name: "Grace R. Emlin"
  // Phone: "none"
  // Email: [{home gre@example.com} {work gre@work.com}]
  // Groups: [Friends Squash]
  // Address: {Hanga Roa Easter Island}
}

在对结构体对象进行打印时,可使用%v, %+v, %#v 进行对象打印处理

可参考:

代码语言:javascript
复制
package main

import "fmt"

type employee struct {
    name   string
    age    int
    salary int
}

func main() {
    emp := employee{name: "Sam", age: 31, salary: 2000}
    fmt.Printf("Emp: %v\n", emp)
    fmt.Printf("Emp: %+v\n", emp)
    fmt.Printf("Emp: %#v\n", emp)
    fmt.Println(emp)
}

package main

import (
    "encoding/json"
    "fmt"
    "log"
)

type employee struct {
    Name   string
    Age    int
    salary int
}

func main() {
    emp := employee{Name: "Sam", Age: 31, salary: 2000}
    //Marshal
    empJSON, err := json.Marshal(emp)
    if err != nil {
        log.Fatalf(err.Error())
    }
    fmt.Printf("Marshal funnction output %s\n", string(empJSON))

    //MarshalIndent
    empJSON, err = json.MarshalIndent(emp, "", "  ")
    if err != nil {
        log.Fatalf(err.Error())
    }
    fmt.Printf("MarshalIndent funnction output %s\n", string(empJSON))
}

package main

import (
    "encoding/json"
    "fmt"
    "log"
)

type address struct {
    City    string `json:"city"`
    Country string `json:"country"`
}

type employee struct {
    Name    string  `json:"name"`
    Age     int     `json:"age"`
    Salary  int     `json:"salary"`
    Address address `json:"address"`
}

func main() {
    address := address{City: "some_city", Country: "some_country"}
    emp := employee{Name: "Sam", Age: 31, Salary: 2000, Address: address}
    //Converting to json
    empJSON, err := json.MarshalIndent(emp, "", "  ")
    if err != nil {
        log.Fatalf(err.Error())
    }
    fmt.Printf("MarshalIndent funnction output\n %s\n", string(empJSON))
}

https://golangbyexample.com/print-struct-variables-golang/

https://golang.org/src/encoding/xml/example_test.go

https://stackoverflow.com/questions/24512112/how-to-print-struct-variables-in-console

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2021-09-07,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 云数智圈 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档