func (p *Pluginator) connect() error { defer trace.End(trace.Begin("")) var err error sessionconfig := &session.Config{ Insecure: true, } sessionconfig.Service = p.tURL.String() p.Session = session.NewSession(sessionconfig) p.Session, err = p.Session.Connect(p.Context) if err != nil { return fmt.Errorf("failed to connect: %s", err) } p.Session.Populate(p.Context) em, err := object.GetExtensionManager(p.Session.Client.Client) if err != nil { return fmt.Errorf("failed to get extension manager: %s", err) } p.ExtensionManager = em p.connected = true return nil }
func (i *InteractionHandlersImpl) Configure(api *operations.PortLayerAPI, _ *HandlerContext) { var err error api.InteractionContainerResizeHandler = interaction.ContainerResizeHandlerFunc(i.ContainerResizeHandler) api.InteractionContainerSetStdinHandler = interaction.ContainerSetStdinHandlerFunc(i.ContainerSetStdinHandler) api.InteractionContainerGetStdoutHandler = interaction.ContainerGetStdoutHandlerFunc(i.ContainerGetStdoutHandler) api.InteractionContainerGetStderrHandler = interaction.ContainerGetStderrHandlerFunc(i.ContainerGetStderrHandler) sessionconfig := &session.Config{ Service: options.PortLayerOptions.SDK, Insecure: options.PortLayerOptions.Insecure, Keepalive: options.PortLayerOptions.Keepalive, DatacenterPath: options.PortLayerOptions.DatacenterPath, ClusterPath: options.PortLayerOptions.ClusterPath, PoolPath: options.PortLayerOptions.PoolPath, DatastorePath: options.PortLayerOptions.DatastorePath, } ctx := context.Background() interactionSession, err = session.NewSession(sessionconfig).Create(ctx) if err != nil { log.Fatalf("InteractionHandler ERROR: %s", err) } i.attachServer = attach.NewAttachServer(exec.ManagementHostName, 0) if err := i.attachServer.Start(); err != nil { log.Fatalf("Attach server unable to start: %s", err) } }
func configureAPI(api *operations.PortLayerAPI) http.Handler { if options.PortLayerOptions.Debug { log.SetLevel(log.DebugLevel) } ctx := context.Background() sessionconfig := &session.Config{ Service: options.PortLayerOptions.SDK, Insecure: options.PortLayerOptions.Insecure, Keepalive: options.PortLayerOptions.Keepalive, DatacenterPath: options.PortLayerOptions.DatacenterPath, ClusterPath: options.PortLayerOptions.ClusterPath, PoolPath: options.PortLayerOptions.PoolPath, DatastorePath: options.PortLayerOptions.DatastorePath, } sess, err := session.NewSession(sessionconfig).Create(ctx) if err != nil { log.Fatalf("configure_port_layer ERROR: %s", err) } // Configure the func invoked if the PL panics or is restarted by vic-init api.ServerShutdown = func() { log.Infof("Shutting down port-layer-server") // Logout the session if err := sess.Logout(ctx); err != nil { log.Warnf("unable to log out of session: %s", err) } } // initialize the port layer if err = portlayer.Init(ctx, sess); err != nil { log.Fatalf("could not initialize port layer: %s", err) } // configure the api here api.ServeError = errors.ServeError api.BinConsumer = httpkit.ByteStreamConsumer() api.JSONConsumer = httpkit.JSONConsumer() api.JSONProducer = httpkit.JSONProducer() api.TxtProducer = httpkit.TextProducer() handlerCtx := &handlers.HandlerContext{ Session: sess, } for _, handler := range portlayerhandlers { handler.Configure(api, handlerCtx) } return setupGlobalMiddleware(api.Serve(setupMiddlewares)) }
func CreateNoDCCheck(ctx context.Context, input *data.Data) (*Validator, error) { defer trace.End(trace.Begin("")) var err error v := &Validator{} v.Context = ctx tURL := input.URL // default to https scheme if tURL.Scheme == "" { tURL.Scheme = "https" } // if they specified only an IP address the parser for some reason considers that a path if tURL.Host == "" { tURL.Host = tURL.Path tURL.Path = "" } sessionconfig := &session.Config{ Insecure: input.Insecure, } // if a datacenter was specified, set it v.DatacenterPath = tURL.Path if v.DatacenterPath != "" { sessionconfig.DatacenterPath = v.DatacenterPath // path needs to be stripped before we can use it as a service url tURL.Path = "" } sessionconfig.Service = tURL.String() v.Session = session.NewSession(sessionconfig) v.Session, err = v.Session.Connect(v.Context) if err != nil { return nil, err } // cached here to allow a modicum of testing while session is still in use. v.isVC = v.Session.IsVC() finder := find.NewFinder(v.Session.Client.Client, false) v.Session.Finder = finder v.Session.Populate(ctx) // only allow the datacenter to be specified in the taget url, if any pElems := strings.Split(v.DatacenterPath, "/") if len(pElems) > 2 { detail := "--target should only specify datacenter in the path (e.g. https://addr/datacenter) - specify cluster, resource pool, or folder with --compute-resource" log.Error(detail) v.suggestDatacenter() return nil, errors.New(detail) } return v, nil }
func TestWaitForKeyInExtraConfig(t *testing.T) { ctx := context.Background() m := simulator.ESX() defer m.Remove() err := m.Create() if err != nil { t.Fatal(err) } server := m.Service.NewServer() defer server.Close() config := &session.Config{ Service: server.URL.String(), } s, err := session.NewSession(config).Connect(ctx) if err != nil { t.Fatal(err) } if s, err = s.Populate(ctx); err != nil { t.Fatal(err) } vms, err := s.Finder.VirtualMachineList(ctx, "*") if err != nil { t.Fatal(err) } vm := NewVirtualMachineFromVM(ctx, s, vms[0]) opt := &types.OptionValue{Key: "foo", Value: "bar"} obj := simulator.Map.Get(vm.Reference()).(*simulator.VirtualMachine) obj.Config.ExtraConfig = append(obj.Config.ExtraConfig, opt) val, err := vm.WaitForKeyInExtraConfig(ctx, opt.Key) if err == nil { t.Error("expected error") } obj.Summary.Runtime.PowerState = types.VirtualMachinePowerStatePoweredOn val, err = vm.WaitForKeyInExtraConfig(ctx, opt.Key) if err != nil { t.Fatal(err) } if val != opt.Value { t.Errorf("%s != %s", val, opt.Value) } }
func vSphereSessionGet(sessconfig *session.Config) (*session.Session, error) { session := session.NewSession(sessconfig) ctx := context.Background() _, err := session.Connect(ctx) if err != nil { log.Warnf("Unable to connect: %s", err) return nil, err } _, err = session.Populate(ctx) if err != nil { // not a critical error for vicadmin log.Warnf("Unable to populate session: %s", err) } return session, nil }
func getVPXSession(ctx context.Context, service string) (*session.Session, error) { config := &session.Config{ Service: service, Insecure: true, Keepalive: time.Duration(5) * time.Minute, DatacenterPath: "/DC0", DatastorePath: "/DC0/datastore/LocalDS_0", PoolPath: "/DC0/host/DC0_C0/Resources", ClusterPath: "/DC0/host/DC0_C0", } s, err := session.NewSession(config).Connect(ctx) if err != nil { return nil, err } return s, nil }
func Session(ctx context.Context, t *testing.T) *session.Session { config := &session.Config{ Service: env.URL(t), /// XXX Why does this insist on having this field populated? DatastorePath: env.DS(t), Insecure: true, Keepalive: time.Duration(5) * time.Minute, } s, err := session.NewSession(config).Create(ctx) if err != nil { t.SkipNow() } return s }
// Session returns a session.Session struct func Session(ctx context.Context, t *testing.T) *session.Session { config := &session.Config{ Service: env.URL(t), Insecure: true, Keepalive: time.Duration(5) * time.Minute, DatacenterPath: "", DatastorePath: "/ha-datacenter/datastore/*", HostPath: "/ha-datacenter/host/*/*", NetworkPath: "/ha-datacenter/network/VM Network", PoolPath: "/ha-datacenter/host/*/Resources", } s, err := session.NewSession(config).Create(ctx) if err != nil { t.Errorf("ERROR: %s", err) t.SkipNow() } return s }
func client() (*session.Session, error) { defer trace.End(trace.Begin("")) ctx := context.Background() session := session.NewSession(&config.Config) _, err := session.Connect(ctx) if err != nil { return nil, err } _, err = session.Populate(ctx) if err != nil { // no a critical error for vicadmin log.Warn(err) } return session, nil }
func getESXSession(ctx context.Context, service string) (*session.Session, error) { config := &session.Config{ Service: service, Insecure: true, Keepalive: time.Duration(5) * time.Minute, DatacenterPath: "/ha-datacenter", ClusterPath: "*", DatastorePath: "/ha-datacenter/datastore/LocalDS_0", PoolPath: "/ha-datacenter/host/localhost.localdomain/Resources", } s, err := session.NewSession(config).Connect(ctx) if err != nil { return nil, err } if s, err = s.Populate(ctx); err != nil { return nil, err } return s, nil }
func Session(ctx context.Context, t *testing.T) *session.Session { config := &session.Config{ Service: env.URL(t), DatastorePath: env.DS(t), Insecure: true, Keepalive: time.Duration(5) * time.Minute, } s, err := session.NewSession(config).Create(ctx) // Vsan has special UUID / URI handling of top level directories which // we've implemented at another level. We can't import them here or it'd // be a circular dependency. Also, we already have tests that test these // cases but from a higher level. if err != nil || s.IsVSAN(ctx) { t.SkipNow() } return s }
// Session returns a session.Session struct func Session(ctx context.Context, t *testing.T) *session.Session { config := &session.Config{ Service: env.URL(t), Insecure: true, Keepalive: time.Duration(5) * time.Minute, DatacenterPath: "", DatastorePath: "/ha-datacenter/datastore/*", HostPath: "/ha-datacenter/host/*/*", PoolPath: "/ha-datacenter/host/*/Resources", } s, err := session.NewSession(config).Create(ctx) if err != nil { // FIXME: See session_test.go TestSession for detail. We never get to PickRandomHost in the case of multiple hosts if strings.Contains(err.Error(), "resolves to multiple hosts") { t.SkipNow() } else { t.Errorf("ERROR: %s", err) t.SkipNow() } } return s }
func TestVirtualMachineConfigSpec(t *testing.T) { ctx := context.Background() sessionconfig := &session.Config{ Service: env.URL(t), Insecure: true, Keepalive: time.Duration(5) * time.Minute, DatacenterPath: "", DatastorePath: "/ha-datacenter/datastore/*", HostPath: "/ha-datacenter/host/*/*", PoolPath: "/ha-datacenter/host/*/Resources", } s, err := session.NewSession(sessionconfig).Create(ctx) if err != nil { t.Logf("%+v", err.Error()) if _, ok := err.(*find.MultipleFoundError); !ok { t.Errorf(err.Error()) } else { t.SkipNow() } } defer s.Logout(ctx) specconfig := &VirtualMachineConfigSpecConfig{ NumCPUs: 2, MemoryMB: 2048, VMForkEnabled: true, ID: "zombie_attack", BootMediaPath: s.Datastore.Path("brainz.iso"), VMPathName: fmt.Sprintf("[%s]", s.Datastore.Name()), } // FIXME: find a better way to pass those var scsibus int32 var scsikey int32 = 100 var idekey int32 = 200 root, _ := NewVirtualMachineConfigSpec(ctx, s, specconfig) scsi := NewVirtualSCSIController(scsibus, scsikey) pv := NewParaVirtualSCSIController(scsi) root.AddParaVirtualSCSIController(pv) bl := NewVirtualBusLogicController(scsi) root.AddVirtualBusLogicController(bl) ll := NewVirtualLsiLogicController(scsi) root.AddVirtualLsiLogicController(ll) ls := NewVirtualLsiLogicSASController(scsi) root.AddVirtualLsiLogicSASController(ls) /// ide := NewVirtualIDEController(idekey) root.AddVirtualIDEController(ide) cdrom := NewVirtualCdrom(ide) root.AddVirtualCdrom(cdrom) floppy := NewVirtualFloppy(ide) root.AddVirtualFloppy(floppy) vmxnet3 := NewVirtualVmxnet3() root.AddVirtualVmxnet3(vmxnet3) pcnet32 := NewVirtualPCNet32() root.AddVirtualPCNet32(pcnet32) e1000 := NewVirtualE1000() root.AddVirtualE1000(e1000) for i := 0; i < len(root.DeviceChange); i++ { t.Logf("%+v", root.DeviceChange[i].GetVirtualDeviceConfigSpec().Device) } }
// Configure assigns functions to all the storage api handlers func (handler *StorageHandlersImpl) Configure(api *operations.PortLayerAPI, handlerCtx *HandlerContext) { var err error ctx := context.Background() sessionconfig := &session.Config{ Service: options.PortLayerOptions.SDK, Insecure: options.PortLayerOptions.Insecure, Keepalive: options.PortLayerOptions.Keepalive, DatacenterPath: options.PortLayerOptions.DatacenterPath, ClusterPath: options.PortLayerOptions.ClusterPath, PoolPath: options.PortLayerOptions.PoolPath, DatastorePath: options.PortLayerOptions.DatastorePath, } storageSession, err := session.NewSession(sessionconfig).Create(ctx) if err != nil { log.Fatalf("StorageHandler ERROR: %s", err) } if len(spl.Config.ImageStores) == 0 { log.Panicf("No image stores provided; unable to instantiate storage layer") } imageStoreURL := spl.Config.ImageStores[0] // TODO: support multiple image stores. Right now we only support the first one if len(spl.Config.ImageStores) > 1 { log.Warningf("Multiple image stores found. Multiple image stores are not yet supported. Using [%s] %s", imageStoreURL.Host, imageStoreURL.Path) } ds, err := vsphereSpl.NewImageStore(ctx, storageSession, &imageStoreURL) if err != nil { log.Panicf("Cannot instantiate storage layer: %s", err) } // The imagestore is implemented via a cache which is backed via an // implementation that writes to disks. The cache is used to avoid // expensive metadata lookups. storageImageLayer = spl.NewLookupCache(ds) vsVolumeStore, err := vsphereSpl.NewVolumeStore(context.TODO(), storageSession) if err != nil { log.Panicf("Cannot instantiate the volume store: %s", err) } // Get the datastores for volumes. // Each volume store name maps to a datastore + path, which can be referred to by the name. dstores, err := datastore.GetDatastores(context.TODO(), storageSession, spl.Config.VolumeLocations) if err != nil { log.Panicf("Cannot find datastores: %s", err) } // Add datastores to the vsphere volume store impl for volStoreName, volDatastore := range dstores { log.Infof("Adding volume store %s (%s)", volStoreName, volDatastore.RootURL) _, err := vsVolumeStore.AddStore(context.TODO(), volDatastore, volStoreName) if err != nil { log.Errorf("volume addition error %s", err) } } storageVolumeLayer, err = spl.NewVolumeLookupCache(context.TODO(), vsVolumeStore) if err != nil { log.Panicf("Cannot instantiate the Volume Lookup cache: %s", err) } api.StorageCreateImageStoreHandler = storage.CreateImageStoreHandlerFunc(handler.CreateImageStore) api.StorageGetImageHandler = storage.GetImageHandlerFunc(handler.GetImage) api.StorageGetImageTarHandler = storage.GetImageTarHandlerFunc(handler.GetImageTar) api.StorageListImagesHandler = storage.ListImagesHandlerFunc(handler.ListImages) api.StorageWriteImageHandler = storage.WriteImageHandlerFunc(handler.WriteImage) api.StorageVolumeStoresListHandler = storage.VolumeStoresListHandlerFunc(handler.VolumeStoresList) api.StorageCreateVolumeHandler = storage.CreateVolumeHandlerFunc(handler.CreateVolume) api.StorageRemoveVolumeHandler = storage.RemoveVolumeHandlerFunc(handler.RemoveVolume) api.StorageVolumeJoinHandler = storage.VolumeJoinHandlerFunc(handler.VolumeJoin) api.StorageListVolumesHandler = storage.ListVolumesHandlerFunc(handler.VolumesList) }
func CreateNoDCCheck(ctx context.Context, input *data.Data) (*Validator, error) { defer trace.End(trace.Begin("")) var err error v := &Validator{} v.Context = ctx tURL := input.URL // default to https scheme if tURL.Scheme == "" { tURL.Scheme = "https" } // if they specified only an IP address the parser for some reason considers that a path if tURL.Host == "" { tURL.Host = tURL.Path tURL.Path = "" } if tURL.Scheme == "https" && input.Thumbprint == "" { var cert object.HostCertificateInfo if err = cert.FromURL(tURL, new(tls.Config)); err != nil { return nil, err } if cert.Err != nil { if !input.Force { // TODO: prompt user / check ./known_hosts log.Errorf("Failed to verify certificate for target=%s (thumbprint=%s)", tURL.Host, cert.ThumbprintSHA1) return nil, cert.Err } } input.Thumbprint = cert.ThumbprintSHA1 log.Debugf("Accepting host %q thumbprint %s", tURL.Host, input.Thumbprint) } sessionconfig := &session.Config{ Thumbprint: input.Thumbprint, Insecure: input.Force, } // if a datacenter was specified, set it v.DatacenterPath = tURL.Path if v.DatacenterPath != "" { sessionconfig.DatacenterPath = v.DatacenterPath // path needs to be stripped before we can use it as a service url tURL.Path = "" } sessionconfig.Service = tURL.String() v.Session = session.NewSession(sessionconfig) v.Session, err = v.Session.Connect(v.Context) if err != nil { return nil, err } // cached here to allow a modicum of testing while session is still in use. v.isVC = v.Session.IsVC() finder := find.NewFinder(v.Session.Client.Client, false) v.Session.Finder = finder v.Session.Populate(ctx) // only allow the datacenter to be specified in the taget url, if any pElems := strings.Split(v.DatacenterPath, "/") if len(pElems) > 2 { detail := "--target should only specify datacenter in the path (e.g. https://addr/datacenter) - specify cluster, resource pool, or folder with --compute-resource" log.Error(detail) v.suggestDatacenter() return nil, errors.New(detail) } return v, nil }