github.com/emc-advanced-dev/unik@v0.0.0-20190717152701-a58d3e8e33b7/pkg/providers/virtualbox/virtualbox_provider.go (about) 1 package virtualbox 2 3 import ( 4 "os" 5 "path/filepath" 6 "strings" 7 8 "github.com/sirupsen/logrus" 9 "github.com/emc-advanced-dev/pkg/errors" 10 "github.com/solo-io/unik/pkg/config" 11 "github.com/solo-io/unik/pkg/providers/common" 12 "github.com/solo-io/unik/pkg/state" 13 "time" 14 ) 15 16 func VirtualboxStateFile() string { 17 return filepath.Join(config.Internal.UnikHome, "virtualbox/state.json") 18 } 19 func virtualboxImagesDirectory() string { 20 return filepath.Join(config.Internal.UnikHome, "virtualbox/images/") 21 } 22 func virtualboxInstancesDirectory() string { 23 return filepath.Join(config.Internal.UnikHome, "virtualbox/instances/") 24 } 25 func virtualboxVolumesDirectory() string { 26 return filepath.Join(config.Internal.UnikHome, "virtualbox/volumes/") 27 } 28 29 const VboxUnikInstanceListener = "VboxUnikInstanceListener" 30 const instanceListenerPrefix = "unik_virtualbox" 31 32 type VirtualboxProvider struct { 33 config config.Virtualbox 34 state state.State 35 instanceListenerIp string 36 } 37 38 func NewVirtualboxProvider(config config.Virtualbox) (*VirtualboxProvider, error) { 39 os.MkdirAll(virtualboxImagesDirectory(), 0755) 40 os.MkdirAll(virtualboxInstancesDirectory(), 0755) 41 os.MkdirAll(virtualboxVolumesDirectory(), 0755) 42 43 p := &VirtualboxProvider{ 44 config: config, 45 state: state.NewBasicState(VirtualboxStateFile()), 46 } 47 48 if err := p.deployInstanceListener(config); err != nil && !strings.Contains(err.Error(), "already exists") { 49 return nil, errors.New("deploying virtualbox instance listener", err) 50 } 51 52 instanceListenerIp, err := common.GetInstanceListenerIp(instanceListenerPrefix, timeout) 53 if err != nil { 54 return nil, errors.New("failed to retrieve instance listener ip. is unik instance listener running?", err) 55 } 56 57 p.instanceListenerIp = instanceListenerIp 58 59 // begin update instances cycle 60 go func() { 61 for { 62 if err := p.syncState(); err != nil { 63 logrus.Error("error updatin virtualbox state:", err) 64 } 65 time.Sleep(time.Second) 66 } 67 }() 68 69 return p, nil 70 } 71 72 func (p *VirtualboxProvider) WithState(state state.State) *VirtualboxProvider { 73 p.state = state 74 return p 75 } 76 77 func getImagePath(imageName string) string { 78 return filepath.Join(virtualboxImagesDirectory(), imageName, "boot.vmdk") 79 } 80 81 func getInstanceDir(instanceName string) string { 82 return filepath.Join(virtualboxInstancesDirectory(), instanceName) 83 } 84 85 func getVolumePath(volumeName string) string { 86 return filepath.Join(virtualboxVolumesDirectory(), volumeName, "data.vmdk") 87 }