Пример #1
0
 public UploadParameters(BlobUri destinationUri, BlobUri baseImageUri, FileInfo localFilePath, bool overWrite, int numberOfUploaderThreads)
 {
     DestinationUri = destinationUri;
     BaseImageUri = baseImageUri;
     LocalFilePath = localFilePath;
     OverWrite = overWrite;
     NumberOfUploaderThreads = numberOfUploaderThreads;
 }
 public bool CreateContainer(BlobUri destination)
 {
     if (String.IsNullOrEmpty(destination.Uri.Query))
     {
         var destinationBlob = Create(destination);
         return destinationBlob.Container.CreateIfNotExists(this.CreateRequestOptions());
     }
     return true;
 }
 public CloudPageBlob Create(BlobUri destination)
 {
     if(String.IsNullOrEmpty(destination.QueryString))
     {
         StorageService sService = this.channel.GetStorageKeys(subscriptionId, destination.StorageAccountName);
         return new CloudPageBlob(new Uri(destination.BlobPath), new StorageCredentials(destination.StorageAccountName, sService.StorageServiceKeys.Primary));
     }
     return new CloudPageBlob(new Uri(destination.BlobPath), new StorageCredentials(destination.Uri.Query));
 }
Пример #4
0
        protected BlobCreatorBase(FileInfo localVhd, BlobUri blobDestination, ICloudPageBlobObjectFactory blobObjectFactory, bool overWrite)
        {
            this.localVhd = localVhd;
            this.blobObjectFactory = blobObjectFactory;
            this.destination = new Uri(blobDestination.BlobPath);
            this.blobDestination = blobDestination;
            this.overWrite = overWrite;

            this.destinationBlob = blobObjectFactory.Create(blobDestination);
            this.requestOptions = this.blobObjectFactory.CreateRequestOptions();
        }
Пример #5
0
        public UploadParameters ValidateParameters()
        {
            BlobUri destinationUri;

            if (!BlobUri.TryParseUri(Destination, out destinationUri))
            {
                throw new ArgumentOutOfRangeException("Destination", this.Destination.ToString());
            }

            BlobUri baseImageUri = null;

            if (this.BaseImageUriToPatch != null)
            {
                if (!BlobUri.TryParseUri(BaseImageUriToPatch, out baseImageUri))
                {
                    throw new ArgumentOutOfRangeException("BaseImageUriToPatch", this.BaseImageUriToPatch.ToString());
                }

                if (!String.IsNullOrEmpty(destinationUri.Uri.Query))
                {
                    var message = String.Format(Rsrc.AddAzureVhdCommandSASUriNotSupportedInPatchMode, destinationUri.Uri);
                    throw new ArgumentOutOfRangeException("Destination", message);
                }
            }

            var storageCredentialsFactory = CreateStorageCredentialsFactory();

            PathIntrinsics currentPath = SessionState.Path;
            var            filePath    = new FileInfo(currentPath.GetUnresolvedProviderPathFromPSPath(LocalFilePath.ToString()));

            using (var vds = new VirtualDiskStream(filePath.FullName))
            {
                if (vds.DiskType == DiskType.Fixed)
                {
                    long divisor = Convert.ToInt64(Math.Pow(2, 9));
                    long rem     = 0;
                    Math.DivRem(filePath.Length, divisor, out rem);
                    if (rem != 0)
                    {
                        throw new ArgumentOutOfRangeException("LocalFilePath", "Given vhd file is a corrupted fixed vhd");
                    }
                }
            }

            var parameters = new UploadParameters(
                destinationUri, baseImageUri, filePath, OverWrite.IsPresent,
                (NumberOfUploaderThreads) ?? DefaultNumberOfUploaderThreads)
            {
                Cmdlet            = this,
                BlobObjectFactory = new CloudPageBlobObjectFactory(storageCredentialsFactory, TimeSpan.FromMinutes(1))
            };

            return(parameters);
        }
Пример #6
0
        protected BlobCreatorBase(FileInfo localVhd, BlobUri blobDestination, ICloudPageBlobObjectFactory blobObjectFactory, bool overWrite)
        {
            this.localVhd          = localVhd;
            this.blobObjectFactory = blobObjectFactory;
            this.destination       = new Uri(blobDestination.BlobPath);
            this.blobDestination   = blobDestination;
            this.overWrite         = overWrite;

            this.destinationBlob = blobObjectFactory.Create(blobDestination);
            this.requestOptions  = this.blobObjectFactory.CreateRequestOptions();
        }
Пример #7
0
        protected void PopulateFromBlobUrl(string url)
        {
            BlobUri blobUri;

            if (BlobUri.TryParse(url, out blobUri))
            {
                SetProperty(ref containerUrl, blobUri.ContainerUri.ToString(), ValidateContainerUrl, ContainerUrlPropertyName);
                SetProperty(ref accountKey, blobUri.AccountKey, ValidateNonEmptyString, AccountKeyPropertyName);
                SetProperty(ref blobName, blobUri.BlobName, ValidateNonEmptyString, BlobNamePropertyName);
                SetBlobUrl(url);
            }
        }
        private Uri GenerateUriForFile(string url, string filePath)
        {
            // Get the file name (will be used to name the container i.e. files names must be unique or they will be overwritten)
            string fileName = Path.GetFileName(filePath);

            // Added the filename to the uri
            var str    = BlobUri.Split('?');
            var newUri = str[0] + "/" + fileName + "?" + str[1];

            // Generate Uri object
            return(new Uri(newUri));
        }
Пример #9
0
 public StorageCredentials Create(BlobUri destination)
 {
     if (IsChannelRequired(destination.Uri))
     {
         if (currentSubscription == null)
         {
             throw new ArgumentException("Call Set-AzureSubscription and Select-AzureSubscription first.", "SubscriptionId");
         }
         StorageService sService = this.channel.GetStorageKeys(currentSubscription.SubscriptionId, destination.StorageAccountName);
         return(new StorageCredentials(destination.StorageAccountName, sService.StorageServiceKeys.Primary));
     }
     return(new StorageCredentials(destination.Uri.Query));
 }
        private void DownloadFromBlobUri(Uri sourceUri, string localFileInfo)
        {
            BlobUri blobUri;

            if (!BlobUri.TryParseUri(sourceUri, out blobUri))
            {
                throw new ArgumentOutOfRangeException("Source", sourceUri.ToString());
            }

            var blob = new CloudBlob(sourceUri);

            blob.DownloadToFileAsync(localFileInfo, FileMode.Create).ConfigureAwait(false).GetAwaiter().GetResult();
        }
 public StorageCredentials Create(BlobUri destination)
 {
     if (IsChannelRequired(destination.Uri))
     {
         if(currentSubscription == null)
         {
             throw new ArgumentException(Resources.StorageCredentialsFactoryCurrentSubscriptionNotSet, "SubscriptionId");
         }
         StorageService sService = this.channel.GetStorageKeys(currentSubscription.SubscriptionId, destination.StorageAccountName);
         return new StorageCredentials(destination.StorageAccountName, sService.StorageServiceKeys.Primary);
     }
     return new StorageCredentials(destination.Uri.Query);
 }
 public StorageCredentials Create(BlobUri destination)
 {
     if (IsChannelRequired(destination.Uri))
     {
         if(currentSubscription == null)
         {
             throw new ArgumentException("Call Set-AzureSubscription and Select-AzureSubscription first.", "SubscriptionId");
         }
         StorageService sService = this.channel.GetStorageKeys(currentSubscription.SubscriptionId, destination.StorageAccountName);
         return new StorageCredentials(destination.StorageAccountName, sService.StorageServiceKeys.Primary);
     }
     return new StorageCredentials(destination.Uri.Query);
 }
Пример #13
0
 public StorageCredentials Create(BlobUri destination)
 {
     if (IsChannelRequired(destination.Uri))
     {
         if (currentSubscription == null)
         {
             throw new ArgumentException(Resources.StorageCredentialsFactoryCurrentSubscriptionNotSet, "SubscriptionId");
         }
         StorageService sService = this.channel.GetStorageKeys(currentSubscription.SubscriptionId, destination.StorageAccountName);
         return(new StorageCredentials(destination.StorageAccountName, sService.StorageServiceKeys.Primary));
     }
     return(new StorageCredentials(destination.Uri.Query));
 }
Пример #14
0
        internal int?GetDiskSizeGbFromBlobUri(string sBlobUri)
        {
            if (String.IsNullOrEmpty(sBlobUri))
            {
                return(null);
            }

            var blobMatch = Regex.Match(sBlobUri, "https?://(\\S*?)\\..*?/(.*)");

            if (!blobMatch.Success)
            {
                WriteError("Blob URI of disk does not match known pattern {0}", sBlobUri);
                throw new ArgumentException("Blob URI of disk does not match known pattern");
            }
            var accountName = blobMatch.Groups[1].Value;

            BlobUri blobUri;

            if (BlobUri.TryParseUri(new Uri(sBlobUri), out blobUri))
            {
                try
                {
                    var account = this.GetStorageAccountFromCache(accountName);

                    var resGroupName = new ResourceIdentifier(account.Id).ResourceGroupName;
                    StorageCredentialsFactory storageCredentialsFactory = new StorageCredentialsFactory(resGroupName,
                                                                                                        this._StorageClient, this._Subscription);
                    StorageCredentials  sc = storageCredentialsFactory.Create(blobUri);
                    CloudStorageAccount cloudStorageAccount = new CloudStorageAccount(sc, this._StorageEndpoint, true);
                    CloudBlobClient     blobClient          = cloudStorageAccount.CreateCloudBlobClient();
                    CloudBlobContainer  blobContainer       = blobClient.GetContainerReference(blobUri.BlobContainerName);
                    var cloudBlob = blobContainer.GetPageBlobReference(blobUri.BlobName);
                    var sasToken  = cloudBlob.GetSharedAccessSignature(
                        new SharedAccessBlobPolicy()
                    {
                        SharedAccessExpiryTime = DateTime.UtcNow.AddHours(24.0),
                        Permissions            = SharedAccessBlobPermissions.Read
                    });
                    cloudBlob.FetchAttributesAsync()
                    .ConfigureAwait(false).GetAwaiter().GetResult();

                    return((int?)(cloudBlob.Properties.Length / (1024 * 1024 * 1024)));
                }
                catch (Exception)
                {
                    this.WriteWarning("Could not determine OS Disk size.");
                }
            }

            return(null);
        }
Пример #15
0
        public static async Task <IEnumerable <FileVersion> > GetCloudVersionsAsync(BlobUri uri)
        {
            FileVersionList result = null;

            if (uri.Exists())
            {
                result = await AzureXmlSerializerHelper.DownloadAsync <FileVersionList>(uri);
            }
            else
            {
                result = new FileVersionList();
            }
            return(result);
        }
        public StorageCredentials Create(BlobUri destination)
        {
            if (IsChannelRequired(destination.Uri))
            {
                if (currentSubscription == null)
                {
                    throw new ArgumentException(Rsrc.StorageCredentialsFactoryCurrentSubscriptionNotSet, "SubscriptionId");
                }
                var storageKeys = this.client.StorageAccounts.ListKeys(this.resourceGroupName, destination.StorageAccountName);
                return(new StorageCredentials(destination.StorageAccountName, storageKeys.GetKey1()));
            }

            return(new StorageCredentials(destination.Uri.Query));
        }
Пример #17
0
        public static IEnumerable <FileVersion> GetCloudVersions(BlobUri uri)
        {
            FileVersionList result = null;

            if (uri.Exists())
            {
                result = AzureXmlSerializerHelper.Download <FileVersionList>(uri);
            }
            else
            {
                result = new FileVersionList();
            }
            return(result);
        }
Пример #18
0
        protected static BlobReference GetBlobReference(string url)
        {
            BlobUri blobUri;

            if (!BlobUri.TryParse(url, out blobUri))
            {
                throw Errors.InvalidBlobUrl();
            }

            return(new BlobReference(
                       new CloudBlobContainer(
                           blobUri.ContainerUri,
                           new StorageCredentials(blobUri.AccountName, blobUri.AccountKey)),
                       blobUri.BlobName));
        }
 /*
  * If ContinueOnError argument is 'true', return the exception else nope.
  */
 private void UploadToAzureStorage(CodeActivityContext context)
 {
     try {
         AzureParamHelper azureStorageHelper = new AzureParamHelper(StorageConnectionString.Get(context), StorageBlobContainer.Get(context));
         BlobUri.Set(context, AzureHelper.UploadToAzureStorage(SourceFile.Get(context), BlobReference.Get(context), Convert.ToBoolean((int)DeleteSourceAfterUpload)));
     } catch (Exception ex) {
         if (Convert.ToBoolean((int)ContinueOnError))
         {
         }
         else
         {
             throw ex;
         }
     }
 }
Пример #20
0
        private StorageCredentialsFactory CreateStorageCredentialsFactory(BlobUri destinationUri)
        {
            StorageCredentialsFactory storageCredentialsFactory;

            var storageClient = AzureSession.ClientFactory.CreateClient <StorageManagementClient>(
                Profile.Context, AzureEnvironment.Endpoint.ResourceManager);

            if (StorageCredentialsFactory.IsChannelRequired(Destination))
            {
                storageCredentialsFactory = new StorageCredentialsFactory(this.ResourceGroupName, storageClient, this.Profile.Context.Subscription);
            }
            else
            {
                storageCredentialsFactory = new StorageCredentialsFactory();
            }

            return(storageCredentialsFactory);
        }
Пример #21
0
        /// <summary>
        /// find the snapshot with the tags
        /// </summary>
        /// <param name="blobUris"></param>
        /// <param name="snapshotTag"></param>
        /// <param name="taskId"></param>
        /// <param name="storageCredentialsFactory"></param>
        /// <returns></returns>
        public List <CloudPageBlob> FindSnapshot(List <string> blobUris, Dictionary <string, string> snapshotQuery, StorageCredentialsFactory storageCredentialsFactory)
        {
            List <CloudPageBlob> snapshots = new List <CloudPageBlob>();

            for (int i = 0; i < blobUris.Count; i++)
            {
                BlobUri blobUri = null;
                if (BlobUri.TryParseUri(new Uri(blobUris[i]), out blobUri))
                {
                    StorageCredentials          sc = storageCredentialsFactory.Create(blobUri);
                    CloudStorageAccount         cloudStorageAccount = new CloudStorageAccount(sc, true);
                    CloudBlobClient             blobClient          = cloudStorageAccount.CreateCloudBlobClient();
                    CloudBlobContainer          blobContainer       = blobClient.GetContainerReference(blobUri.BlobContainerName);
                    IEnumerable <IListBlobItem> blobs = blobContainer.ListBlobs(null, true, BlobListingDetails.All);
                    foreach (var blob in blobs)
                    {
                        if (blob is CloudPageBlob)
                        {
                            CloudPageBlob pageBlob = blob as CloudPageBlob;
                            if (pageBlob.IsSnapshot && pageBlob.Name == blobUri.BlobName)
                            {
                                bool allMatch = true;
                                foreach (string keyToQuey in snapshotQuery.Keys)
                                {
                                    if (!pageBlob.Metadata.Keys.Contains(keyToQuey))
                                    {
                                        allMatch = false;
                                    }
                                    else if (!string.Equals(pageBlob.Metadata[keyToQuey], snapshotQuery[keyToQuey]))
                                    {
                                        allMatch = false;
                                    }
                                }
                                if (allMatch)
                                {
                                    snapshots.Add(pageBlob);
                                }
                            }
                        }
                    }
                }
            }
            return(snapshots);
        }
Пример #22
0
        private VhdDownloadContext DownloadFromBlobUri(
            ComputeClientBaseCmdlet cmdlet,
            Uri sourceUri,
            FileInfo localFileInfo,
            string storagekey,
            string resourceGroupName,
            int numThreads,
            bool overwrite)
        {
            BlobUri blobUri;

            if (!BlobUri.TryParseUri(sourceUri, out blobUri))
            {
                throw new ArgumentOutOfRangeException("Source", sourceUri.ToString());
            }

            if (storagekey == null)
            {
                var storageClient = AzureSession.Instance.ClientFactory.CreateArmClient <StorageManagementClient>(
                    DefaultProfile.DefaultContext, AzureEnvironment.Endpoint.ResourceManager);


                var storageService = storageClient.StorageAccounts.GetProperties(resourceGroupName, blobUri.StorageAccountName);
                if (storageService != null)
                {
                    var storageKeys = storageClient.StorageAccounts.ListKeys(resourceGroupName, storageService.Name);
                    storagekey = storageKeys.GetKey1();
                }
            }

            var downloaderParameters = new DownloaderParameters
            {
                BlobUri               = blobUri,
                LocalFilePath         = localFileInfo.FullName,
                ConnectionLimit       = numThreads,
                StorageAccountKey     = storagekey,
                ValidateFreeDiskSpace = true,
                OverWrite             = overwrite
            };

            return(VhdDownloaderModel.Download(downloaderParameters, cmdlet));
        }
        public UploadParameters ValidateParameters()
        {
            BlobUri destinationUri;

            if (!BlobUri.TryParseUri(Destination, out destinationUri))
            {
                throw new ArgumentOutOfRangeException("Destination", this.Destination.ToString());
            }

            BlobUri baseImageUri = null;

            if (this.BaseImageUriToPatch != null)
            {
                if (!BlobUri.TryParseUri(BaseImageUriToPatch, out baseImageUri))
                {
                    throw new ArgumentOutOfRangeException("BaseImageUriToPatch", this.BaseImageUriToPatch.ToString());
                }

                if (!String.IsNullOrEmpty(destinationUri.Uri.Query))
                {
                    var message = String.Format(Rsrc.AddAzureVhdCommandSASUriNotSupportedInPatchMode, destinationUri.Uri);
                    throw new ArgumentOutOfRangeException("Destination", message);
                }
            }

            var storageCredentialsFactory = CreateStorageCredentialsFactory();

            PathIntrinsics currentPath = SessionState.Path;
            var            filePath    = new FileInfo(currentPath.GetUnresolvedProviderPathFromPSPath(LocalFilePath.ToString()));

            var parameters = new UploadParameters(
                destinationUri, baseImageUri, filePath, OverWrite.IsPresent,
                (NumberOfUploaderThreads) ?? DefaultNumberOfUploaderThreads)
            {
                Cmdlet            = this,
                BlobObjectFactory = new CloudPageBlobObjectFactory(storageCredentialsFactory, TimeSpan.FromMinutes(1))
            };

            return(parameters);
        }
        public AzureVMBackupBlobSasUris GenerateBlobSasUris(List <string> blobUris, IAzureContext azContext)
        {
            AzureVMBackupBlobSasUris blobSASUris = new AzureVMBackupBlobSasUris();

            for (int i = 0; i < blobUris.Count; i++)
            {
                string  blobUri   = blobUris[i];
                BlobUri osBlobUri = null;
                if (BlobUri.TryParseUri(new Uri(blobUri), out osBlobUri))
                {
                    StorageManagementClient storageClient = AzureSession.Instance.ClientFactory.CreateArmClient <StorageManagementClient>(azContext, AzureEnvironment.Endpoint.ResourceManager);

                    // Need to convert osBlobUri.StorageAccountName into corresponding resource group name

                    var    listResponse      = storageClient.StorageAccounts.List();
                    var    account           = listResponse.First(accTemp => accTemp.Name.Equals(osBlobUri.StorageAccountName, StringComparison.InvariantCultureIgnoreCase));
                    string resourceGroupName = GetResourceGroupFromId(account.Id);

                    StorageCredentialsFactory storageCredentialsFactory = new StorageCredentialsFactory(resourceGroupName, storageClient, azContext.Subscription);

                    CloudPageBlobObjectFactory cloudPageBlobObjectFactory = new CloudPageBlobObjectFactory(storageCredentialsFactory, TimeSpan.FromMinutes(1));

                    CloudPageBlob pageBlob = cloudPageBlobObjectFactory.Create(osBlobUri);

                    SharedAccessBlobPolicy sasConstraints = new SharedAccessBlobPolicy();
                    sasConstraints.SharedAccessExpiryTime = DateTime.UtcNow.AddMinutes(5);
                    sasConstraints.Permissions            = SharedAccessBlobPermissions.Write | SharedAccessBlobPermissions.List;

                    string sasUri = osBlobUri.Uri + pageBlob.GetSharedAccessSignature(sasConstraints);
                    blobSASUris.blobSASUri.Add(sasUri);
                    blobSASUris.pageBlobUri.Add(blobUri);
                    blobSASUris.storageCredentialsFactory.Add(storageCredentialsFactory);
                }
                else
                {
                    throw new AzureVMBackupException(AzureVMBackupErrorCodes.WrongBlobUriFormat, "the blob uri is not in correct format.");
                }
            }
            return(blobSASUris);
        }
Пример #25
0
        async Task StrategyExecuteCmdletAsync(IAsyncCmdlet asyncCmdlet)
        {
            var client = new Client(DefaultProfile.DefaultContext);

            ResourceGroupName   = ResourceGroupName ?? Name;
            VirtualNetworkName  = VirtualNetworkName ?? Name;
            SubnetName          = SubnetName ?? Name;
            PublicIpAddressName = PublicIpAddressName ?? Name;
            SecurityGroupName   = SecurityGroupName ?? Name;

            var resourceClient = AzureSession.Instance.ClientFactory.CreateArmClient <ResourceManagementClient>(
                DefaultProfile.DefaultContext,
                AzureEnvironment.Endpoint.ResourceManager);

            var parameters = new Parameters(this, client, resourceClient);


            if (DiskFile != null)
            {
                if (!resourceClient.ResourceGroups.CheckExistence(ResourceGroupName))
                {
                    Location = Location ?? parameters.DefaultLocation;
                    var st0 = resourceClient.ResourceGroups.CreateOrUpdate(
                        ResourceGroupName,
                        new ResourceGroup
                    {
                        Location = Location,
                        Name     = ResourceGroupName
                    });
                }
                parameters.ImageAndOsType = new ImageAndOsType(
                    Linux ? OperatingSystemTypes.Linux : OperatingSystemTypes.Windows,
                    null,
                    null);
                var storageClient = AzureSession.Instance.ClientFactory.CreateArmClient <StorageManagementClient>(
                    DefaultProfile.DefaultContext,
                    AzureEnvironment.Endpoint.ResourceManager);
                var st1 = storageClient.StorageAccounts.Create(
                    ResourceGroupName,
                    Name,
                    new StorageAccountCreateParameters
                {
                    Sku = new Microsoft.Azure.Management.Storage.Version2017_10_01.Models.Sku
                    {
                        Name = SkuName.PremiumLRS
                    },
                    Location = Location
                });
                var filePath = new FileInfo(SessionState.Path.GetUnresolvedProviderPathFromPSPath(DiskFile));
                using (var vds = new VirtualDiskStream(filePath.FullName))
                {
                    // 2 ^ 9 == 512
                    if (vds.DiskType == DiskType.Fixed && filePath.Length % 512 != 0)
                    {
                        throw new ArgumentOutOfRangeException(
                                  "filePath",
                                  string.Format("Given vhd file '{0}' is a corrupted fixed vhd", filePath));
                    }
                }
                var storageAccount = storageClient.StorageAccounts.GetProperties(ResourceGroupName, Name);
                // BlobUri destinationUri = null;
                BlobUri.TryParseUri(
                    new Uri(string.Format(
                                "{0}{1}/{2}{3}",
                                storageAccount.PrimaryEndpoints.Blob,
                                ResourceGroupName.ToLower(),
                                Name.ToLower(),
                                ".vhd")),
                    out parameters.DestinationUri);
                if (parameters.DestinationUri?.Uri == null)
                {
                    throw new ArgumentNullException("destinationUri");
                }
                var storageCredentialsFactory = new StorageCredentialsFactory(
                    ResourceGroupName, storageClient, DefaultContext.Subscription);
                var uploadParameters = new UploadParameters(parameters.DestinationUri, null, filePath, true, 2)
                {
                    Cmdlet            = this,
                    BlobObjectFactory = new CloudPageBlobObjectFactory(storageCredentialsFactory, TimeSpan.FromMinutes(1))
                };
                if (!string.Equals(
                        Environment.GetEnvironmentVariable("AZURE_TEST_MODE"), "Playback", StringComparison.OrdinalIgnoreCase))
                {
                    var st2 = VhdUploaderModel.Upload(uploadParameters);
                }
            }

            var result = await client.RunAsync(client.SubscriptionId, parameters, asyncCmdlet);

            if (result != null)
            {
                var fqdn     = PublicIPAddressStrategy.Fqdn(DomainNameLabel, Location);
                var psResult = ComputeAutoMapperProfile.Mapper.Map <PSVirtualMachine>(result);
                psResult.FullyQualifiedDomainName = fqdn;
                var connectionString = parameters.ImageAndOsType.GetConnectionString(
                    fqdn,
                    Credential?.UserName);
                asyncCmdlet.WriteVerbose(
                    Resources.VirtualMachineUseConnectionString,
                    connectionString);
                asyncCmdlet.WriteObject(psResult);
            }
        }
Пример #26
0
        async Task StrategyExecuteCmdletAsync(IAsyncCmdlet asyncCmdlet)
        {
            ResourceGroupName   = ResourceGroupName ?? Name;
            VirtualNetworkName  = VirtualNetworkName ?? Name;
            SubnetName          = SubnetName ?? Name;
            PublicIpAddressName = PublicIpAddressName ?? Name;
            SecurityGroupName   = SecurityGroupName ?? Name;

            var imageAndOsType = new ImageAndOsType(OperatingSystemTypes.Windows, null);

            var resourceGroup  = ResourceGroupStrategy.CreateResourceGroupConfig(ResourceGroupName);
            var virtualNetwork = resourceGroup.CreateVirtualNetworkConfig(
                name: VirtualNetworkName, addressPrefix: AddressPrefix);
            var subnet          = virtualNetwork.CreateSubnet(SubnetName, SubnetAddressPrefix);
            var publicIpAddress = resourceGroup.CreatePublicIPAddressConfig(
                name: PublicIpAddressName,
                getDomainNameLabel: () => DomainNameLabel,
                allocationMethod: AllocationMethod);
            var networkSecurityGroup = resourceGroup.CreateNetworkSecurityGroupConfig(
                name: SecurityGroupName,
                openPorts: OpenPorts,
                getOsType: () => imageAndOsType.OsType);
            var networkInterface = resourceGroup.CreateNetworkInterfaceConfig(
                Name, subnet, publicIpAddress, networkSecurityGroup);

            var availabilitySet = AvailabilitySetName == null
                ? null
                : resourceGroup.CreateAvailabilitySetConfig(name: AvailabilitySetName);

            ResourceConfig <VirtualMachine> virtualMachine = null;

            if (DiskFile == null)
            {
                virtualMachine = resourceGroup.CreateVirtualMachineConfig(
                    name: Name,
                    networkInterface: networkInterface,
                    getImageAndOsType: () => imageAndOsType,
                    adminUsername: Credential.UserName,
                    adminPassword: new NetworkCredential(string.Empty, Credential.Password).Password,
                    size: Size,
                    availabilitySet: availabilitySet);
            }
            else
            {
                var resourceClient =
                    AzureSession.Instance.ClientFactory.CreateArmClient <ResourceManagementClient>(DefaultProfile.DefaultContext,
                                                                                                   AzureEnvironment.Endpoint.ResourceManager);
                if (!resourceClient.ResourceGroups.CheckExistence(ResourceGroupName))
                {
                    var st0 = resourceClient.ResourceGroups.CreateOrUpdate(ResourceGroupName, new ResourceGroup
                    {
                        Location = Location,
                        Name     = ResourceGroupName
                    });
                }
                imageAndOsType = new ImageAndOsType(
                    Linux ? OperatingSystemTypes.Linux : OperatingSystemTypes.Windows,
                    null);
                var storageClient =
                    AzureSession.Instance.ClientFactory.CreateArmClient <StorageManagementClient>(DefaultProfile.DefaultContext,
                                                                                                  AzureEnvironment.Endpoint.ResourceManager);
                var st1 = storageClient.StorageAccounts.Create(
                    ResourceGroupName,
                    Name,
                    new StorageAccountCreateParameters
                {
#if !NETSTANDARD
                    AccountType = AccountType.PremiumLRS,
#else
                    Sku = new Microsoft.Azure.Management.Storage.Models.Sku
                    {
                        Name = SkuName.PremiumLRS
                    },
#endif
                    Location = Location
                });
                var filePath = new FileInfo(SessionState.Path.GetUnresolvedProviderPathFromPSPath(DiskFile));
                using (var vds = new VirtualDiskStream(filePath.FullName))
                {
                    if (vds.DiskType == DiskType.Fixed)
                    {
                        long divisor = Convert.ToInt64(Math.Pow(2, 9));
                        long rem     = 0;
                        Math.DivRem(filePath.Length, divisor, out rem);
                        if (rem != 0)
                        {
                            throw new ArgumentOutOfRangeException(
                                      "filePath",
                                      string.Format("Given vhd file '{0}' is a corrupted fixed vhd", filePath));
                        }
                    }
                }
                var     storageAccount = storageClient.StorageAccounts.GetProperties(ResourceGroupName, Name);
                BlobUri destinationUri = null;
                BlobUri.TryParseUri(
                    new Uri(string.Format(
                                "{0}{1}/{2}{3}",
                                storageAccount.PrimaryEndpoints.Blob,
                                ResourceGroupName.ToLower(),
                                Name.ToLower(),
                                ".vhd")),
                    out destinationUri);
                if (destinationUri == null || destinationUri.Uri == null)
                {
                    throw new ArgumentNullException("destinationUri");
                }
                var storageCredentialsFactory = new StorageCredentialsFactory(
                    this.ResourceGroupName, storageClient, DefaultContext.Subscription);
                var parameters = new UploadParameters(destinationUri, null, filePath, true, 2)
                {
                    Cmdlet            = this,
                    BlobObjectFactory = new CloudPageBlobObjectFactory(storageCredentialsFactory, TimeSpan.FromMinutes(1))
                };
                if (!string.Equals(
                        Environment.GetEnvironmentVariable("AZURE_TEST_MODE"), "Playback", StringComparison.OrdinalIgnoreCase))
                {
                    var st2 = VhdUploaderModel.Upload(parameters);
                }
                var disk = resourceGroup.CreateManagedDiskConfig(
                    name: Name,
                    sourceUri: destinationUri.Uri.ToString()
                    );
                virtualMachine = resourceGroup.CreateVirtualMachineConfig(
                    name: Name,
                    networkInterface: networkInterface,
                    osType: imageAndOsType.OsType,
                    disk: disk,
                    size: Size,
                    availabilitySet: availabilitySet);
            }

            var client = new Client(DefaultProfile.DefaultContext);

            // get current Azure state
            var current = await virtualMachine.GetStateAsync(client, new CancellationToken());

            Location = current.UpdateLocation(Location, virtualMachine);

            // generate a domain name label if it's not specified.
            DomainNameLabel = await PublicIPAddressStrategy.UpdateDomainNameLabelAsync(
                domainNameLabel : DomainNameLabel,
                name : Name,
                location : Location,
                client : client);

            var fqdn = PublicIPAddressStrategy.Fqdn(DomainNameLabel, Location);

            if (DiskFile == null)
            {
                imageAndOsType = await client.UpdateImageAndOsTypeAsync(ImageName, Location);
            }

            // create target state
            var target = virtualMachine.GetTargetState(current, client.SubscriptionId, Location);

            if (target.Get(availabilitySet) != null)
            {
                throw new InvalidOperationException("Availability set doesn't exist.");
            }

            // apply target state
            var newState = await virtualMachine
                           .UpdateStateAsync(
                client,
                target,
                new CancellationToken(),
                new ShouldProcess(asyncCmdlet),
                asyncCmdlet.ReportTaskProgress);

            var result = newState.Get(virtualMachine);

            if (result == null)
            {
                result = current.Get(virtualMachine);
            }
            if (result != null)
            {
                var psResult = ComputeAutoMapperProfile.Mapper.Map <PSVirtualMachine>(result);
                psResult.FullyQualifiedDomainName = fqdn;
                asyncCmdlet.WriteVerbose(imageAndOsType.OsType == OperatingSystemTypes.Windows
                    ? "Use 'mstsc /v:" + fqdn + "' to connect to the VM."
                    : "Use 'ssh " + Credential.UserName + "@" + fqdn + "' to connect to the VM.");
                asyncCmdlet.WriteObject(psResult);
            }
        }
Пример #27
0
            base(localVhd, destination, blobObjectFactory, overWrite)
        {
        }
Пример #28
0
 public BlobCreator(FileInfo localVhd, BlobUri destination, ICloudPageBlobObjectFactory blobObjectFactory, bool overWrite) :
     base(localVhd, destination, blobObjectFactory, overWrite)
 {
 }
 public CloudPageBlob Create(BlobUri destination)
 {
     return new CloudPageBlob(new Uri(destination.BlobPath), credentialsFactory.Create(destination));
 }
Пример #30
0
 public PatchingBlobCreator(FileInfo localVhd, BlobUri destination, BlobUri baseVhdBlob, ICloudPageBlobObjectFactory blobObjectFactory, bool overWrite) :
     base(localVhd, destination, blobObjectFactory, overWrite)
 {
     this.baseVhdBlob    = baseVhdBlob.Uri;
     this.baseVhdBlobUri = baseVhdBlob;
 }
Пример #31
0
 public CloudPageBlob Create(BlobUri destination)
 {
     return(new CloudPageBlob(new Uri(destination.BlobPath), credentialsFactory.Create(destination)));
 }
Пример #32
0
        async Task StrategyExecuteCmdletAsync(IAsyncCmdlet asyncCmdlet)
        {
            ResourceGroupName   = ResourceGroupName ?? Name;
            VirtualNetworkName  = VirtualNetworkName ?? Name;
            SubnetName          = SubnetName ?? Name;
            PublicIpAddressName = PublicIpAddressName ?? Name;
            DomainNameLabel     = DomainNameLabel ?? (Name + '-' + ResourceGroupName).ToLower();
            SecurityGroupName   = SecurityGroupName ?? Name;

            bool isWindows;

            Commands.Common.Strategies.Compute.Image image = null;
            if (ImageName.Contains(':'))
            {
                var imageArray = ImageName.Split(':');
                if (imageArray.Length != 4)
                {
                    throw new Exception("Invalid ImageName");
                }
                image = new Commands.Common.Strategies.Compute.Image
                {
                    publisher = imageArray[0],
                    offer     = imageArray[1],
                    sku       = imageArray[2],
                    version   = imageArray[3],
                };
                isWindows = image.publisher.ToLower() == "MicrosoftWindowsServer".ToLower();
            }
            else if (!string.IsNullOrEmpty(DiskFile))
            {
                // disk file parameter set requires the OS type input
                isWindows = !Linux;
            }
            else
            {
                // get image
                var osTypeAndImage = Images
                                     .Instance
                                     .SelectMany(osAndMap => osAndMap
                                                 .Value
                                                 .Where(nameAndImage => nameAndImage.Key.ToLower() == ImageName.ToLower())
                                                 .Select(nameAndImage => new
                {
                    OsType = osAndMap.Key,
                    Image  = nameAndImage.Value
                }))
                                     .FirstOrDefault();
                image     = osTypeAndImage.Image;
                isWindows = osTypeAndImage.OsType == "Windows";
            }

            OpenPorts = OpenPorts ?? (isWindows ? new[] { 3389, 5985 } : new[] { 22 });

            var resourceGroup  = ResourceGroupStrategy.CreateResourceGroupConfig(ResourceGroupName);
            var virtualNetwork = resourceGroup.CreateVirtualNetworkConfig(
                name: VirtualNetworkName, addressPrefix: AddressPrefix);
            var subnet          = virtualNetwork.CreateSubnet(SubnetName, SubnetAddressPrefix);
            var publicIpAddress = resourceGroup.CreatePublicIPAddressConfig(
                name: PublicIpAddressName,
                domainNameLabel: DomainNameLabel,
                allocationMethod: AllocationMethod);
            var networkSecurityGroup = resourceGroup.CreateNetworkSecurityGroupConfig(
                name: SecurityGroupName,
                openPorts: OpenPorts);
            var networkInterface = resourceGroup.CreateNetworkInterfaceConfig(
                Name, subnet, publicIpAddress, networkSecurityGroup);
            ResourceConfig <VirtualMachine> virtualMachine = null;

            if (image != null)
            {
                virtualMachine = resourceGroup.CreateVirtualMachineConfig(
                    name: Name,
                    networkInterface: networkInterface,
                    isWindows: isWindows,
                    adminUsername: Credential.UserName,
                    adminPassword: new NetworkCredential(string.Empty, Credential.Password).Password,
                    image: image,
                    size: Size);
            }
            else
            {
                var storageClient =
                    AzureSession.Instance.ClientFactory.CreateArmClient <StorageManagementClient>(DefaultProfile.DefaultContext,
                                                                                                  AzureEnvironment.Endpoint.ResourceManager);
                var st1 = storageClient.StorageAccounts.Create(ResourceGroupName, Name, new StorageAccountCreateParameters
                {
#if !NETSTANDARD
                    AccountType = AccountType.PremiumLRS,
#else
                    Sku = new SM.Sku
                    {
                        Name = SkuName.PremiumLRS
                    },
#endif
                    Location = Location
                });
                var filePath = new FileInfo(SessionState.Path.GetUnresolvedProviderPathFromPSPath(DiskFile));
                using (var vds = new VirtualDiskStream(filePath.FullName))
                {
                    if (vds.DiskType == DiskType.Fixed)
                    {
                        long divisor = Convert.ToInt64(Math.Pow(2, 9));
                        long rem     = 0;
                        Math.DivRem(filePath.Length, divisor, out rem);
                        if (rem != 0)
                        {
                            throw new ArgumentOutOfRangeException("filePath", string.Format("Given vhd file '{0}' is a corrupted fixed vhd", filePath));
                        }
                    }
                }
                var     storageAccount = storageClient.StorageAccounts.GetProperties(ResourceGroupName, Name);
                BlobUri destinationUri = null;
                BlobUri.TryParseUri(new Uri(string.Format("{0}{1}/{2}{3}", storageAccount.PrimaryEndpoints.Blob, Name.ToLower(), Name.ToLower(), ".vhd")), out destinationUri);
                if (destinationUri == null || destinationUri.Uri == null)
                {
                    throw new ArgumentNullException("destinationUri");
                }
                var storageCredentialsFactory = new StorageCredentialsFactory(this.ResourceGroupName, storageClient, DefaultContext.Subscription);
                var parameters = new UploadParameters(destinationUri, null, filePath, true, 2)
                {
                    Cmdlet            = this,
                    BlobObjectFactory = new CloudPageBlobObjectFactory(storageCredentialsFactory, TimeSpan.FromMinutes(1))
                };
                if (!string.Equals(Environment.GetEnvironmentVariable("AZURE_TEST_MODE"), "Playback", StringComparison.OrdinalIgnoreCase))
                {
                    var st2 = VhdUploaderModel.Upload(parameters);
                }
                var disk = resourceGroup.CreateManagedDiskConfig(
                    name: Name,
                    sourceUri: destinationUri.Uri.ToString()
                    );
                virtualMachine = resourceGroup.CreateVirtualMachineConfig(
                    name: Name,
                    networkInterface: networkInterface,
                    isWindows: isWindows,
                    disk: disk,
                    size: Size);
            }

            var client = new Client(DefaultProfile.DefaultContext);

            // get current Azure state
            var current = await virtualMachine.GetStateAsync(client, new CancellationToken());

            if (Location == null)
            {
                Location = current.GetLocation(virtualMachine);
                if (Location == null)
                {
                    Location = "eastus";
                }
            }

            var fqdn = DomainNameLabel + "." + Location + ".cloudapp.azure.com";

            // create target state
            var target = virtualMachine.GetTargetState(current, client.SubscriptionId, Location);

            // apply target state
            var newState = await virtualMachine
                           .UpdateStateAsync(
                client,
                target,
                new CancellationToken(),
                new ShouldProcess(asyncCmdlet),
                asyncCmdlet.ReportTaskProgress);

            var result = newState.Get(virtualMachine);

            if (result == null)
            {
                result = current.Get(virtualMachine);
            }
            if (result != null)
            {
                var psResult = ComputeAutoMapperProfile.Mapper.Map <PSVirtualMachine>(result);
                psResult.FullyQualifiedDomainName = fqdn;
                asyncCmdlet.WriteVerbose(isWindows
                    ? "Use 'mstsc /v:" + fqdn + "' to connect to the VM."
                    : "Use 'ssh " + Credential.UserName + "@" + fqdn + "' to connect to the VM.");
                asyncCmdlet.WriteObject(psResult);
            }
        }
Пример #33
0
 public PatchingBlobCreator(FileInfo localVhd, BlobUri destination, BlobUri baseVhdBlob, ICloudPageBlobObjectFactory blobObjectFactory, bool overWrite)
     : base(localVhd, destination, blobObjectFactory, overWrite)
 {
     this.baseVhdBlob = baseVhdBlob.Uri;
     this.baseVhdBlobUri = baseVhdBlob;
 }