func (s *StepCreateVm) Run(state multistep.StateBag) multistep.StepAction {
	client := state.Get(constants.RequestManager).(management.Client)
	ui := state.Get("ui").(packer.Ui)

	errorMsg := "Error creating temporary Azure VM: %s"

	ui.Say("Creating temporary Azure VM...")

	osImageName := state.Get(constants.OSImageName).(string)
	if len(osImageName) == 0 {
		err := fmt.Errorf(errorMsg, fmt.Errorf("osImageName is empty"))
		state.Put("error", err)
		ui.Error(err.Error())
		return multistep.ActionHalt
	}

	isOSImage := state.Get(constants.IsOSImage).(bool)

	mediaLoc := fmt.Sprintf("https://%s.blob.core.windows.net/%s/%s.vhd", s.StorageAccount, s.StorageContainer, s.TmpVmName)

	role := createRole(isOSImage, s.TmpVmName, s.InstanceSize, s.Username, s.Password, osImageName, mediaLoc)
	if err := retry.ExecuteAsyncOperation(client, func() (management.OperationID, error) {
		return vm.NewClient(client).CreateDeployment(role, s.TmpServiceName, vm.CreateDeploymentOptions{})
	}); err != nil {
		err := fmt.Errorf(errorMsg, err)
		state.Put("error", err)
		ui.Error(err.Error())
		return multistep.ActionHalt
	}
	state.Put(constants.VmExists, 1)
	state.Put(constants.DiskExists, 1)

	return multistep.ActionContinue
}
func TestRoleStateOperations(t *testing.T) {
	client := testutils.GetTestClient(t)
	vmname := GenerateName()
	sa := GetTestStorageAccount(t, client)
	location := sa.StorageServiceProperties.Location

	role := NewVMConfiguration(vmname, "Standard_D3")
	ConfigureDeploymentFromPlatformImage(&role,
		GetLinuxTestImage(t, client).Name,
		fmt.Sprintf("http://%s.blob.core.windows.net/sdktest/%s.vhd", sa.ServiceName, vmname),
		GenerateName())
	ConfigureForLinux(&role, "myvm", "azureuser", GeneratePassword())

	createRoleConfiguration(t, client, role, location)

	vmc := vm.NewClient(client)
	if err := Await(client, func() (management.OperationID, error) {
		return vmc.ShutdownRole(vmname, vmname, vmname, vm.PostShutdownActionStopped)
	}); err != nil {
		t.Error(err)
	}
	if err := Await(client, func() (management.OperationID, error) {
		return vmc.StartRole(vmname, vmname, vmname)
	}); err != nil {
		t.Error(err)
	}
	if err := Await(client, func() (management.OperationID, error) {
		return vmc.RestartRole(vmname, vmname, vmname)
	}); err != nil {
		t.Error(err)
	}

	deleteHostedService(t, client, vmname)
}
Exemple #3
0
func (d *Driver) GetState() (state.State, error) {
	if err := d.setUserSubscription(); err != nil {
		return state.Error, err
	}

	client, err := d.getClient()
	if err != nil {
		return state.Error, err
	}

	dockerVM, err := virtualmachine.NewClient(client).GetDeployment(d.MachineName, d.MachineName)
	if err != nil {
		if strings.Contains(err.Error(), "Code: ResourceNotFound") {
			return state.Error, errors.New("Azure host was not found. Please check your Azure subscription.")
		}

		return state.Error, err
	}

	vmState := dockerVM.RoleInstanceList[0].PowerState
	switch vmState {
	case "Started":
		return state.Running, nil
	case "Starting":
		return state.Starting, nil
	case "Stopped":
		return state.Stopped, nil
	}

	return state.None, nil
}
func (c *comm) updateRoleResourceExtension(
	nameOfReference, nameOfPublisher, nameOfExtension, versionOfExtension, state string,
	params []vm.ResourceExtensionParameter) error {

	client := c.config.ManagementClient

	serviceName := c.config.ServiceName
	vmName := c.config.VmName

	log.Println("Updating Role Resource Extension...")

	role := vm.Role{}
	vmutils.AddAzureVMExtensionConfiguration(&role,
		nameOfExtension, nameOfPublisher, versionOfExtension, nameOfReference, state, []byte{}, []byte{})
	// HACK-paulmey: clean up later
	(*role.ResourceExtensionReferences)[0].ParameterValues = params

	if err := retry.ExecuteAsyncOperation(client, func() (management.OperationID, error) {
		return vm.NewClient(client).UpdateRole(serviceName, vmName, vmName, role)
	}); err != nil {
		return err
	}

	return nil
}
func (c *comm) pollCustomScriptIsUninstalled() error {
	client := c.config.ManagementClient
	log.Println("Polling CustomScript is uninstalled. It may take some time...")

	serviceName := c.config.ServiceName
	vmName := c.config.VmName

	const attemptLimit uint = 30
	repeatCount := attemptLimit
	for ; repeatCount > 0; repeatCount-- {
		deployment, err := vm.NewClient(client).GetDeployment(serviceName, vmName)
		if err != nil {
			return err
		}

		if deployment.RoleInstanceList[0].InstanceStatus == vm.InstanceStatusReadyRole {
			if len(deployment.RoleInstanceList[0].ResourceExtensionStatusList) == 0 {
				break
			}
		}

		c.sleepSec(45)
	}

	if repeatCount == 0 {
		err := fmt.Errorf("InstanceStatus is not 'ReadyRole' or ResourceExtensionStatusList is not empty after %d attempts", attemptLimit)
		return err
	}

	return nil
}
func (*StepCreateVm) Run(state multistep.StateBag) multistep.StepAction {
	client := state.Get(constants.RequestManager).(management.Client)
	ui := state.Get("ui").(packer.Ui)
	config := state.Get(constants.Config).(*Config)

	errorMsg := "Error Creating Temporary Azure VM: %s"

	ui.Say("Creating Temporary Azure VM...")

	role := state.Get("role").(*vm.Role)

	options := vm.CreateDeploymentOptions{}
	if config.VNet != "" && config.Subnet != "" {
		options.VirtualNetworkName = config.VNet
	}

	if err := retry.ExecuteAsyncOperation(client, func() (management.OperationID, error) {
		return vm.NewClient(client).CreateDeployment(*role, config.tmpServiceName, options)
	}); err != nil {
		err := fmt.Errorf(errorMsg, err)
		state.Put("error", err)
		ui.Error(err.Error())
		return multistep.ActionHalt
	}

	state.Put(constants.VmExists, 1)
	state.Put(constants.DiskExists, 1)

	return multistep.ActionContinue
}
Exemple #7
0
// NewClientFromSettingsFile returns a new Azure management
// client created using a publish settings file.
func (c *Config) NewClientFromSettingsFile() (*Client, error) {
	if _, err := os.Stat(c.SettingsFile); os.IsNotExist(err) {
		return nil, fmt.Errorf("Publish Settings file %q does not exist!", c.SettingsFile)
	}

	mc, err := management.ClientFromPublishSettingsFile(c.SettingsFile, c.SubscriptionID)
	if err != nil {
		return nil, nil
	}

	return &Client{
		mgmtClient:           mc,
		affinityGroupClient:  affinitygroup.NewClient(mc),
		hostedServiceClient:  hostedservice.NewClient(mc),
		secGroupClient:       networksecuritygroup.NewClient(mc),
		osImageClient:        osimage.NewClient(mc),
		sqlClient:            sql.NewClient(mc),
		storageServiceClient: storageservice.NewClient(mc),
		vmClient:             virtualmachine.NewClient(mc),
		vmDiskClient:         virtualmachinedisk.NewClient(mc),
		vmImageClient:        virtualmachineimage.NewClient(mc),
		vnetClient:           virtualnetwork.NewClient(mc),
		mutex:                &sync.Mutex{},
	}, nil
}
func main() {
	psPath := "path/to/publishSettings"

	dnsName := "test-vm-from-go"
	storageAccount := "mystorageaccount"
	location := "central us"
	vmSize := "Small"
	vmImage := "b39f27a8b8c64d52b05eac6a62ebad85__Ubuntu-14_04-LTS-amd64-server-20140724-en-us-30GB"
	userName := "******"
	userPassword := "******"

	fmt.Println("Create client")
	client, err := management.ClientFromPublishSettingsFile(fmt.Sprintf("%s.publishsettings", psPath), "")
	if err != nil {
		panic(err)
	}

	fmt.Println("Create hosted service")
	if err := hostedservice.NewClient(client).CreateHostedService(hostedservice.CreateHostedServiceParameters{
		ServiceName: dnsName,
		Location:    location,
		Label:       base64.StdEncoding.EncodeToString([]byte(dnsName))}); err != nil {
		panic(err)
	}

	fmt.Println("Create storage account")
	_, err = storageservice.NewClient(client).CreateStorageService(storageservice.StorageAccountCreateParameters{
		ServiceName: storageAccount,
		Label:       base64.URLEncoding.EncodeToString([]byte(storageAccount)),
		Location:    location,
		AccountType: storageservice.AccountTypeStandardLRS})
	if err != nil {
		panic(err)
	}

	fmt.Println("Create virtual machine")
	role := vmutils.NewVMConfiguration(dnsName, vmSize)
	vmutils.ConfigureDeploymentFromPlatformImage(
		&role,
		vmImage,
		fmt.Sprintf("http://%s.blob.core.windows.net/%s/%s.vhd", storageAccount, dnsName, dnsName),
		"")
	vmutils.ConfigureForLinux(&role, dnsName, userName, userPassword)
	vmutils.ConfigureWithPublicSSH(&role)

	fmt.Println("Deploy")
	operationID, err := virtualmachine.NewClient(client).
		CreateDeployment(role, dnsName, virtualmachine.CreateDeploymentOptions{})
	if err != nil {
		panic(err)
	}
	fmt.Println("Waiting...")
	if err = client.WaitForOperation(operationID, nil); err != nil {
		panic(err)
	}
}
Exemple #9
0
// WaitForDeploymentInstanceStatus blocks until all role instances in deployment
// reach desired InstanceStatus.
func WaitForDeploymentInstanceStatus(client management.Client, cloudServiceName, deploymentName string, desiredInstanceStatus vm.InstanceStatus) error {
	for {
		deployment, err := vm.NewClient(client).GetDeployment(cloudServiceName, deploymentName)
		if err != nil {
			return err
		}
		if allInstancesInInstanceStatus(deployment.RoleInstanceList, desiredInstanceStatus) {
			return nil
		}
		time.Sleep(2 * time.Second)
	}
}
Exemple #10
0
func newMachine(bm *provider.BaseMachine) (provider.Machine, error) {
	m := &Machine{BaseMachine: bm}
	cred := m.Cred()

	c, err := management.ClientFromPublishSettingsDataWithConfig([]byte(cred.PublishSettings), cred.SubscriptionID, management.DefaultConfig())
	if err != nil {
		return nil, err
	}

	vmclient := vm.NewClient(c)

	m.AzureClient = c
	m.AzureVMClient = &vmclient

	return m, nil
}
func createRoleConfiguration(t *testing.T, client management.Client, role vm.Role, location string) {
	vmc := vm.NewClient(client)
	hsc := hostedservice.NewClient(client)
	vmname := role.RoleName

	if err := hsc.CreateHostedService(hostedservice.CreateHostedServiceParameters{
		ServiceName: vmname, Location: location,
		Label: base64.StdEncoding.EncodeToString([]byte(vmname))}); err != nil {
		t.Error(err)
	}

	if err := Await(client, func() (management.OperationID, error) {
		return vmc.CreateDeployment(role, vmname, vm.CreateDeploymentOptions{})
	}); err != nil {
		t.Error(err)
	}
}
Exemple #12
0
func (d *Driver) Stop() error {
	if err := d.setUserSubscription(); err != nil {
		return err
	}

	client, err := d.getClient()
	if err != nil {
		return err
	}

	if _, err := virtualmachine.NewClient(client).ShutdownRole(d.MachineName, d.MachineName, d.MachineName); err != nil {
		return err
	}

	d.IPAddress = ""
	return nil
}
Exemple #13
0
func (d *Driver) Restart() error {
	if err := d.setUserSubscription(); err != nil {
		return err
	}

	client, err := d.getClient()
	if err != nil {
		return err
	}

	if _, err := virtualmachine.NewClient(client).RestartRole(d.MachineName, d.MachineName, d.MachineName); err != nil {
		return err
	}

	d.IPAddress, err = d.GetIP()
	return err
}
func main() {
	dnsName := "test-vm-from-go"
	storageAccount := "gosdktest"
	location := "West US"
	vmSize := "Small"
	vmImage := "b39f27a8b8c64d52b05eac6a62ebad85__Ubuntu-14_04-LTS-amd64-server-20140724-en-us-30GB"
	userName := "******"
	userPassword := "******"

	client, err := management.ClientFromPublishSettingsFile("/Users/niklasg/Downloads/Internal-credentials.publishsettings", "")
	if err != nil {
		panic(err)
	}

	// create hosted service
	if err := hostedservice.NewClient(client).CreateHostedService(hostedservice.CreateHostedServiceParameters{
		ServiceName: dnsName,
		Location:    location,
		Label:       base64.StdEncoding.EncodeToString([]byte(dnsName))}); err != nil {

		if azErr, ok := err.(management.AzureError); !ok || azErr.Code != "ConflictError" {
			panic(err)
		}
	}

	// create virtual machine
	role := vmutils.NewVMConfiguration(dnsName, vmSize)
	vmutils.ConfigureDeploymentFromPlatformImage(
		&role,
		vmImage,
		fmt.Sprintf("http://%s.blob.core.windows.net/sdktest/%s.vhd", storageAccount, dnsName),
		"")
	vmutils.ConfigureForLinux(&role, dnsName, userName, userPassword)
	vmutils.ConfigureWithPublicSSH(&role)

	operationID, err := virtualmachine.NewClient(client).
		CreateDeployment(role, dnsName, virtualmachine.CreateDeploymentOptions{})
	if err != nil {
		panic(err)
	}
	if err := client.WaitForOperation(operationID, nil); err != nil {
		panic(err)
	}
}
Exemple #15
0
func (c *comm) requestCustomScriptExtension() (*vm.ResourceExtension, error) {

	log.Println("Requesting resource extensions...")

	list, err := vm.NewClient(c.config.ManagementClient).GetResourceExtensions()
	if err != nil {
		return nil, err
	}

	log.Println("Searching for CustomScriptExtension...")
	for _, ext := range list {
		if ext.Name == "CustomScriptExtension" {
			log.Printf("CustomScriptExtension: %v\n\n", ext)
			return &ext, nil
		}
	}

	return nil, fmt.Errorf("Couldn't find CustomScriptExtension, am I too old or is Azure broken?")
}
Exemple #16
0
func (d *Driver) getHostname() (string, error) {

	if err := d.setUserSubscription(); err != nil {
		return "", err
	}

	client, err := d.getClient()
	if err != nil {
		return "", err
	}

	dr, err := virtualmachine.NewClient(client).GetDeployment(d.MachineName, d.MachineName)
	if err != nil {
		return "", err
	}

	// remove "http://" and ending "/" from the URL to get the DNS name
	return dr.URL[7 : len(dr.URL)-1], nil
}
Exemple #17
0
func Example() {
	dnsName := "test-vm-from-go"
	storageAccount := "mystorageaccount"
	location := "West US"
	vmSize := "Small"
	vmImage := "b39f27a8b8c64d52b05eac6a62ebad85__Ubuntu-14_04-LTS-amd64-server-20140724-en-us-30GB"
	userName := "******"
	userPassword := "******"

	client, err := management.ClientFromPublishSettingsFile("path/to/downloaded.publishsettings", "")
	if err != nil {
		panic(err)
	}

	// create hosted service
	if err := hostedservice.NewClient(client).CreateHostedService(hostedservice.CreateHostedServiceParameters{
		ServiceName: dnsName,
		Location:    location,
		Label:       base64.StdEncoding.EncodeToString([]byte(dnsName))}); err != nil {
		panic(err)
	}

	// create virtual machine
	role := NewVMConfiguration(dnsName, vmSize)
	ConfigureDeploymentFromPlatformImage(
		&role,
		vmImage,
		fmt.Sprintf("http://%s.blob.core.windows.net/sdktest/%s.vhd", storageAccount, dnsName),
		"")
	ConfigureForLinux(&role, dnsName, userName, userPassword)
	ConfigureWithPublicSSH(&role)

	operationID, err := virtualmachine.NewClient(client).
		CreateDeployment(role, dnsName, virtualmachine.CreateDeploymentOptions{})
	if err != nil {
		panic(err)
	}
	err = client.WaitForOperation(operationID, nil)
	if err != nil {
		panic(err)
	}
}
Exemple #18
0
func (c *Config) NewClientFromSettingsData() (*Client, error) {
	mc, err := management.ClientFromPublishSettingsData(c.Settings, c.SubscriptionID)
	if err != nil {
		return nil, nil
	}

	return &Client{
		mgmtClient:           mc,
		affinityGroupClient:  affinitygroup.NewClient(mc),
		hostedServiceClient:  hostedservice.NewClient(mc),
		secGroupClient:       networksecuritygroup.NewClient(mc),
		osImageClient:        osimage.NewClient(mc),
		sqlClient:            sql.NewClient(mc),
		storageServiceClient: storageservice.NewClient(mc),
		vmClient:             virtualmachine.NewClient(mc),
		vmDiskClient:         virtualmachinedisk.NewClient(mc),
		vmImageClient:        virtualmachineimage.NewClient(mc),
		vnetClient:           virtualnetwork.NewClient(mc),
		mutex:                &sync.Mutex{},
	}, nil
}
Exemple #19
0
func (s *StepStopVm) Run(state multistep.StateBag) multistep.StepAction {
	client := state.Get(constants.RequestManager).(management.Client)
	ui := state.Get(constants.Ui).(packer.Ui)

	errorMsg := "Error Stopping Temporary Azure VM: %s"

	ui.Say("Stopping Temporary Azure VM...")

	if err := retry.ExecuteAsyncOperation(client, func() (management.OperationID, error) {
		return vm.NewClient(client).ShutdownRole(s.TmpServiceName, s.TmpVmName, s.TmpVmName)
	}); err != nil {
		err := fmt.Errorf(errorMsg, err)
		state.Put("error", err)
		ui.Error(err.Error())
		return multistep.ActionHalt
	}

	state.Put(constants.VmRunning, 0)

	return multistep.ActionContinue
}
func (s *StepCreateImage) Run(state multistep.StateBag) multistep.StepAction {
	client := state.Get(constants.RequestManager).(management.Client)
	ui := state.Get(constants.Ui).(packer.Ui)

	errorMsg := "Error Creating Azure Image: %s"

	ui.Say("Creating Azure Image. If Successful, This Will Remove the Temporary VM...")

	if err := retry.ExecuteAsyncOperation(client, func() (management.OperationID, error) {
		return vm.NewClient(client).CaptureRole(s.TmpServiceName, s.TmpVmName, s.TmpVmName,
			s.UserImageName, s.UserImageLabel, nil)
	}); err != nil {
		err := fmt.Errorf(errorMsg, err)
		state.Put("error", err)
		ui.Error(err.Error())
		return multistep.ActionHalt
	}

	// CatpureVMImage removes the VM
	state.Put(constants.ImageCreated, 1)
	state.Put(constants.VmExists, 0)

	return multistep.ActionContinue
}
Exemple #21
0
func (d *Driver) Start() error {
	if err := d.setUserSubscription(); err != nil {
		return err
	}

	if vmState, err := d.GetState(); err != nil {
		return err
	} else if vmState == state.Running || vmState == state.Starting {
		log.Infof("Host is already running or starting")
		return nil
	}

	client, err := d.getClient()
	if err != nil {
		return err
	}

	if _, err := virtualmachine.NewClient(client).StartRole(d.MachineName, d.MachineName, d.MachineName); err != nil {
		return err
	}

	d.IPAddress, err = d.GetIP()
	return err
}
func TestDeployPlatformOSImageCaptureRedeploy(t *testing.T) {
	client := testutils.GetTestClient(t)
	vmname := GenerateName()
	sa := GetTestStorageAccount(t, client)
	location := sa.StorageServiceProperties.Location

	role := NewVMConfiguration(vmname, "Standard_D3")
	ConfigureDeploymentFromPlatformImage(&role,
		GetLinuxTestImage(t, client).Name,
		fmt.Sprintf("http://%s.blob.core.windows.net/sdktest/%s.vhd", sa.ServiceName, vmname),
		GenerateName())
	ConfigureForLinux(&role, "myvm", "azureuser", GeneratePassword())
	ConfigureWithPublicSSH(&role)

	t.Logf("Deploying VM: %s", vmname)
	createRoleConfiguration(t, client, role, location)

	t.Logf("Wait for deployment to enter running state")
	vmc := vm.NewClient(client)
	status := vm.DeploymentStatusDeploying
	for status != vm.DeploymentStatusRunning {
		deployment, err := vmc.GetDeployment(vmname, vmname)
		if err != nil {
			t.Error(err)
			break
		}
		status = deployment.Status
	}

	t.Logf("Shutting down VM: %s", vmname)
	if err := Await(client, func() (management.OperationID, error) {
		return vmc.ShutdownRole(vmname, vmname, vmname, vm.PostShutdownActionStopped)
	}); err != nil {
		t.Error(err)
	}

	if err := WaitForDeploymentPowerState(client, vmname, vmname, vm.PowerStateStopped); err != nil {
		t.Fatal(err)
	}

	imagename := GenerateName()
	t.Logf("Capturing OSImage: %s", imagename)
	if err := Await(client, func() (management.OperationID, error) {
		return vmc.CaptureRole(vmname, vmname, vmname, imagename, imagename, nil)
	}); err != nil {
		t.Error(err)
	}

	im := GetUserOSImage(t, client, imagename)
	t.Logf("Found image: %+v", im)

	newvmname := GenerateName()
	role = NewVMConfiguration(newvmname, "Standard_D3")
	ConfigureDeploymentFromPlatformImage(&role,
		im.Name,
		fmt.Sprintf("http://%s.blob.core.windows.net/sdktest/%s.vhd", sa.ServiceName, newvmname),
		GenerateName())
	ConfigureForLinux(&role, newvmname, "azureuser", GeneratePassword())
	ConfigureWithPublicSSH(&role)

	t.Logf("Deploying new VM from freshly captured OS image: %s", newvmname)
	if err := Await(client, func() (management.OperationID, error) {
		return vmc.CreateDeployment(role, vmname, vm.CreateDeploymentOptions{})
	}); err != nil {
		t.Error(err)
	}

	deleteHostedService(t, client, vmname)
}
Exemple #23
0
func (c *comm) pollCustomScriptExtensionIsReady() (stdOutBuff, stdErrBuff string, err error) {
	client := c.config.ManagementClient
	log.Println("Polling CustomScriptExtension is ready. It may take some time...")

	var deployment vm.DeploymentResponse
	var extStatus *vm.ResourceExtensionStatus // paulmey-BUG #58: should not be pointer
	const statusSuccess = "Success"
	const statusError = "Error"

	//	needUpdateStatus := true

	serviceName := c.config.ServiceName
	vmName := c.config.VmName
	var timeout int64 = int64(c.config.ProvisionTimeoutInMinutes * 60)

	startTime := time.Now().Unix()
	timeoutState := false

	for {
		if timeout != 0 && time.Now().Unix()-startTime > timeout {
			timeoutState = true
			break
		}

		for {
			if timeout != 0 && time.Now().Unix()-startTime > timeout {
				timeoutState = true
				break
			}

			deployment, err = vm.NewClient(client).GetDeployment(serviceName, vmName)

			if err != nil {
				return
			}

			if deployment.RoleInstanceList[0].InstanceStatus == vm.InstanceStatusReadyRole {
				if len(deployment.RoleInstanceList[0].ResourceExtensionStatusList) > 0 {
					break
				}
			}

			c.sleepSec(45)
		}

		if timeoutState {
			err = fmt.Errorf("InstanceStatus is not 'ReadyRole' or CustomScriptExtension ResourceExtensionStatusList is empty after %d minutes", c.config.ProvisionTimeoutInMinutes)
			return
		}

		extHandlerName := extPublisher + "." + extName

		for _, s := range deployment.RoleInstanceList[0].ResourceExtensionStatusList {
			if s.HandlerName == extHandlerName {
				extStatus = &s
			}
		}

		if extStatus == nil {
			err = fmt.Errorf("CustomScriptExtension status not found")
			return
		}

		log.Printf("CustomScriptExtension status: %v", extStatus)

		extensionSettingStatus := extStatus.ExtensionSettingStatus

		if extensionSettingStatus.Status == statusError {
			err = fmt.Errorf("CustomScriptExtension operation '%s' status: %s", extensionSettingStatus.Operation, extensionSettingStatus.FormattedMessage.Message)
			return
		}

		log.Printf("CustomScriptExtension INFO: operation '%s' status: %s", extensionSettingStatus.Operation, extensionSettingStatus.Status)

		var stdOut, stdErr string

		for _, subStatus := range extStatus.ExtensionSettingStatus.SubStatusList {
			if subStatus.Name == "StdOut" {
				if subStatus.Status != statusSuccess {
					stdOut = fmt.Sprintf("StdOut failed with message: '%s'", subStatus.FormattedMessage.Message)
				} else {
					stdOut = subStatus.FormattedMessage.Message
				}
				continue
			}

			if subStatus.Name == "StdErr" {
				if subStatus.Status != statusSuccess {
					stdErr = fmt.Sprintf("StdErr failed with message: '%s'", subStatus.FormattedMessage.Message)
				} else {
					stdErr = subStatus.FormattedMessage.Message
				}
				continue
			}
		}

		log.Printf("StdOut: '%s'\n", stdOut)

		if len(stdOutBuff) == 0 {
			stdOutBuff = stdOut
		} else {
			stdOutBuff = utils.GlueStrings(stdOutBuff, stdOut)
		}

		if len(stdErrBuff) == 0 {
			stdErrBuff = stdErr
		} else {
			stdErrBuff = utils.GlueStrings(stdErrBuff, stdErr)
		}

		if extensionSettingStatus.Status == statusSuccess {
			break
		}

		c.sleepSec(40)
	}

	if timeoutState {
		err = fmt.Errorf("extensionSettingStatus.Status in not 'Success' after %d minutes", c.config.ProvisionTimeoutInMinutes)
		return
	}

	return
}
Exemple #24
0
func (d *Driver) Create() error {

	var vmDeploymentOptions virtualmachine.CreateDeploymentOptions

	if err := d.setUserSubscription(); err != nil {
		return err
	}

	log.Info("Creating Azure machine...")
	client, err := d.getClient()
	if err != nil {
		return err
	}

	dnsName := d.MachineName

	// 1. Create the hosted service
	if err := hostedservice.NewClient(client).CreateHostedService(hostedservice.CreateHostedServiceParameters{
		ServiceName: dnsName,
		Location:    d.Location,
		Label:       base64.StdEncoding.EncodeToString([]byte(dnsName))}); err != nil {
		return err
	}

	// 2. Generate certificates
	log.Debug("Generating certificate for Azure...")
	if err := d.generateCertForAzure(); err != nil {
		return err
	}

	// 3. Setup VM configuration for creation
	log.Debug("Setting up VM configuration...")
	var operationID management.OperationID

	role := vmutils.NewVMConfiguration(dnsName, d.Size)
	if d.OS == drivers.LINUX {
		err := d.configureForLinux(&role, dnsName)
		if err != nil {
			goto fail
		}

	} else {
		d.configureForWindows(&role, dnsName)
	}

	log.Debug("Authorizing docker ports...")
	if err := d.addDockerEndpoints(&role); err != nil {
		goto fail
	}

	// 4. Create the VM
	if d.VNet != "" {
		vmDeploymentOptions = virtualmachine.CreateDeploymentOptions{
			VirtualNetworkName: d.VNet,
		}
	} else {
		vmDeploymentOptions = virtualmachine.CreateDeploymentOptions{}
	}

	operationID, err = virtualmachine.NewClient(client).
		CreateDeployment(role, dnsName, vmDeploymentOptions)
	if err != nil {
		goto fail
	}

	// 5. Wait for operation
	err = client.WaitForOperation(operationID, nil)
	if err != nil {
		goto fail
	}
	goto success

fail:
	hostedservice.NewClient(client).DeleteHostedService(dnsName, true)
	return err

success:
	return nil
}
func (s *StepPollStatus) Run(state multistep.StateBag) multistep.StepAction {
	client := state.Get(constants.RequestManager).(management.Client)
	vmc := vm.NewClient(client)
	ui := state.Get(constants.Ui).(packer.Ui)

	errorMsg := "Error polling temporary Azure VM is ready: %s"

	ui.Say("Polling till temporary Azure VM is ready...")

	if len(s.OSType) == 0 {
		err := fmt.Errorf(errorMsg, "'OSType' param is empty")
		state.Put("error", err)
		ui.Error(err.Error())
		return multistep.ActionHalt
	}

	var count uint = 60
	var duration time.Duration = 40
	sleepTime := time.Second * duration
	total := count * uint(duration)

	var deployment vm.DeploymentResponse

	for count > 0 {
		var err error // deployment needs to be accessed outside of this loop, can't use :=
		deployment, err = vmc.GetDeployment(s.TmpServiceName, s.TmpVmName)
		if err != nil {
			err := fmt.Errorf(errorMsg, err)
			state.Put("error", err)
			ui.Error(err.Error())
			return multistep.ActionHalt
		}

		if len(deployment.RoleInstanceList) > 0 {
			powerState := deployment.RoleInstanceList[0].PowerState
			instanceStatus := deployment.RoleInstanceList[0].InstanceStatus

			if powerState == vm.PowerStateStarted && instanceStatus == vm.InstanceStatusReadyRole {
				break
			}

			if instanceStatus == vm.InstanceStatusFailedStartingRole ||
				instanceStatus == vm.InstanceStatusFailedStartingVM ||
				instanceStatus == vm.InstanceStatusUnresponsiveRole {
				err := fmt.Errorf(errorMsg, "deployment.RoleInstanceList[0].instanceStatus is "+instanceStatus)
				state.Put("error", err)
				ui.Error(err.Error())
				return multistep.ActionHalt
			}
			if powerState == vm.PowerStateStopping ||
				powerState == vm.PowerStateStopped ||
				powerState == vm.PowerStateUnknown {
				err := fmt.Errorf(errorMsg, "deployment.RoleInstanceList[0].PowerState is "+powerState)
				state.Put("error", err)
				ui.Error(err.Error())
				return multistep.ActionHalt
			}
		}

		// powerState_Starting or deployment.RoleInstanceList[0] == 0
		log.Println(fmt.Sprintf("Waiting for another %v seconds...", uint(duration)))
		time.Sleep(sleepTime)
		count--
	}

	if count == 0 {
		err := fmt.Errorf(errorMsg, fmt.Sprintf("time is up (%d seconds)", total))
		state.Put("error", err)
		ui.Error(err.Error())
		return multistep.ActionHalt
	}

	state.Put(constants.VmRunning, 1)

	log.Println("s.OSType = " + s.OSType)

	if s.OSType == Linux {
		endpoints := deployment.RoleInstanceList[0].InstanceEndpoints
		if len(endpoints) == 0 {
			err := fmt.Errorf(errorMsg, "deployment.RoleInstanceList[0].InstanceEndpoints list is empty")
			state.Put("error", err)
			ui.Error(err.Error())
			return multistep.ActionHalt
		}

		vip := endpoints[0].Vip
		state.Put(constants.SSHHost, vip)

		ui.Message("VM Endpoint: " + vip)
	}

	roleList := deployment.RoleList
	if len(roleList) == 0 {
		err := fmt.Errorf(errorMsg, "deployment.RoleList is empty")
		state.Put("error", err)
		ui.Error(err.Error())
		return multistep.ActionHalt
	}

	diskName := roleList[0].OSVirtualHardDisk.DiskName
	ui.Message("VM DiskName: " + diskName)
	state.Put(constants.HardDiskName, diskName)

	mediaLink := roleList[0].OSVirtualHardDisk.MediaLink
	ui.Message("VM MediaLink: " + mediaLink)
	state.Put(constants.MediaLink, mediaLink)

	return multistep.ActionContinue
}