コード例 #1
0
        public async virtual Task <DiskGrantAccessOperation> GrantAccessAsync(GrantAccessData grantAccessData, bool waitForCompletion = true, CancellationToken cancellationToken = default)
        {
            if (grantAccessData == null)
            {
                throw new ArgumentNullException(nameof(grantAccessData));
            }

            using var scope = _clientDiagnostics.CreateScope("Disk.GrantAccess");
            scope.Start();
            try
            {
                var response = await _restClient.GrantAccessAsync(Id.ResourceGroupName, Id.Name, grantAccessData, cancellationToken).ConfigureAwait(false);

                var operation = new DiskGrantAccessOperation(_clientDiagnostics, Pipeline, _restClient.CreateGrantAccessRequest(Id.ResourceGroupName, Id.Name, grantAccessData).Request, response);
                if (waitForCompletion)
                {
                    await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false);
                }
                return(operation);
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }
コード例 #2
0
        public virtual ArmOperation <AccessUri> GrantAccess(bool waitForCompletion, GrantAccessData grantAccessData, CancellationToken cancellationToken = default)
        {
            if (grantAccessData == null)
            {
                throw new ArgumentNullException(nameof(grantAccessData));
            }

            using var scope = _diskRestorePointClientDiagnostics.CreateScope("DiskRestorePoint.GrantAccess");
            scope.Start();
            try
            {
                var response  = _diskRestorePointRestClient.GrantAccess(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Parent.Name, Id.Parent.Name, Id.Name, grantAccessData, cancellationToken);
                var operation = new ComputeArmOperation <AccessUri>(new AccessUriOperationSource(), _diskRestorePointClientDiagnostics, Pipeline, _diskRestorePointRestClient.CreateGrantAccessRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Parent.Name, Id.Parent.Name, Id.Name, grantAccessData).Request, response, OperationFinalStateVia.Location);
                if (waitForCompletion)
                {
                    operation.WaitForCompletion(cancellationToken);
                }
                return(operation);
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }
コード例 #3
0
        public virtual DiskRestorePointGrantAccessOperation GrantAccess(GrantAccessData grantAccessData, bool waitForCompletion = true, CancellationToken cancellationToken = default)
        {
            if (grantAccessData == null)
            {
                throw new ArgumentNullException(nameof(grantAccessData));
            }

            using var scope = _clientDiagnostics.CreateScope("DiskRestorePoint.GrantAccess");
            scope.Start();
            try
            {
                var response  = _restClient.GrantAccess(Id.ResourceGroupName, Id.Parent.Parent.Name, Id.Parent.Name, Id.Name, grantAccessData, cancellationToken);
                var operation = new DiskRestorePointGrantAccessOperation(_clientDiagnostics, Pipeline, _restClient.CreateGrantAccessRequest(Id.ResourceGroupName, Id.Parent.Parent.Name, Id.Parent.Name, Id.Name, grantAccessData).Request, response);
                if (waitForCompletion)
                {
                    operation.WaitForCompletion(cancellationToken);
                }
                return(operation);
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }
コード例 #4
0
        protected PSArgument[] CreateDiskGrantAccessParameters()
        {
            string          resourceGroupName = string.Empty;
            string          diskName          = string.Empty;
            GrantAccessData grantAccessData   = new GrantAccessData();

            return(ConvertFromObjectsToArguments(
                       new string[] { "ResourceGroupName", "DiskName", "GrantAccessData" },
                       new object[] { resourceGroupName, diskName, grantAccessData }));
        }
コード例 #5
0
        private AccessUri GenerateSAS()
        {
            var grantAccessData = new GrantAccessData();

            grantAccessData.Access = "Write";
            long gbInBytes = 1073741824;
            int  gb        = (int)(vhdFileToBeUploaded.Length / gbInBytes);

            grantAccessData.DurationInSeconds = 86400 * Math.Max(gb / 100, 1);   // 24h per 100gb
            var accessUri = this.ComputeClient.ComputeManagementClient.Disks.GrantAccess(this.ResourceGroupName, this.DiskName, grantAccessData);

            return(accessUri);
        }
コード例 #6
0
        ///GENMHASH:DAC486F08AF23F259E630032FC20FAF1:3FE53F300A729DFBC3C1F55BBB117CA1
        public async Task<string> GrantAccessAsync(int accessDurationInSeconds, CancellationToken cancellationToken = default(CancellationToken))
        {
            GrantAccessData grantAccessDataInner = new GrantAccessData();
            grantAccessDataInner.Access = AccessLevel.Read;
            grantAccessDataInner.DurationInSeconds = accessDurationInSeconds;

            AccessUriInner accessUriInner = await Manager.Inner.Disks.GrantAccessAsync(ResourceGroupName, Name, grantAccessDataInner, cancellationToken);
            if (accessUriInner == null)
            {
                return null;
            }
            return accessUriInner.AccessSAS;
        }
コード例 #7
0
        protected void ExecuteDiskGrantAccessMethod(object[] invokeMethodInputParameters)
        {
            string resourceGroupName = (string)ParseParameter(invokeMethodInputParameters[0]);
            string diskName          = (string)ParseParameter(invokeMethodInputParameters[1]);
            var    grantAccessData   = new GrantAccessData();
            var    pAccess           = (string)ParseParameter(invokeMethodInputParameters[2]);

            grantAccessData.Access = pAccess;
            var pDurationInSeconds = (int)ParseParameter(invokeMethodInputParameters[3]);

            grantAccessData.DurationInSeconds = pDurationInSeconds;

            var result = DisksClient.GrantAccess(resourceGroupName, diskName, grantAccessData);

            WriteObject(result);
        }
コード例 #8
0
        protected override void ProcessRecord()
        {
            ExecuteClientAction(() =>
            {
                if (ShouldProcess(this.ResourceGroupName, VerbsSecurity.Grant))
                {
                    string resourceGroupName          = this.ResourceGroupName;
                    string snapshotName               = this.SnapshotName;
                    var grantAccessData               = new GrantAccessData();
                    grantAccessData.Access            = this.Access;
                    grantAccessData.DurationInSeconds = this.DurationInSecond;

                    var result = SnapshotsClient.GrantAccess(resourceGroupName, snapshotName, grantAccessData);
                    WriteObject(result);
                }
            });
        }
コード例 #9
0
        ///GENMHASH:C2E2A5650639245BC0993A33DCAA5D61:7697FA7DB7AB14465F345F0D9BFABB88
        public async Task <string> GrantAccessAsync(
            string resourceGroupName,
            string snapshotName,
            AccessLevel accessLevel,
            int accessDuration,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            GrantAccessData grantAccessDataInner = new GrantAccessData();

            grantAccessDataInner.Access            = accessLevel;
            grantAccessDataInner.DurationInSeconds = accessDuration;
            AccessUriInner accessUriInner = await Inner.GrantAccessAsync(resourceGroupName,
                                                                         snapshotName,
                                                                         grantAccessDataInner,
                                                                         cancellationToken);

            return(accessUriInner.AccessSAS);
        }
コード例 #10
0
        protected override void ProcessRecord()
        {
            ExecuteClientAction(() =>
            {
                if (ShouldProcess(this.SnapshotName, VerbsSecurity.Grant))
                {
                    string resourceGroupName          = this.ResourceGroupName;
                    string snapshotName               = this.SnapshotName;
                    var grantAccessData               = new GrantAccessData();
                    grantAccessData.Access            = this.Access;
                    grantAccessData.DurationInSeconds = this.DurationInSecond;

                    var result   = SnapshotsClient.GrantAccess(resourceGroupName, snapshotName, grantAccessData);
                    var psObject = new PSAccessUri();
                    ComputeAutomationAutoMapperProfile.Mapper.Map <AccessUri, PSAccessUri>(result, psObject);
                    WriteObject(psObject);
                }
            });
        }
コード例 #11
0
        public override void ExecuteCmdlet()
        {
            ExecuteClientAction(() =>
            {
                if (ShouldProcess(this.DiskName, VerbsSecurity.Grant))
                {
                    string resourceGroupName          = this.ResourceGroupName;
                    string diskName                   = this.DiskName;
                    var grantAccessData               = new GrantAccessData();
                    grantAccessData.Access            = this.Access;
                    grantAccessData.DurationInSeconds = this.DurationInSecond;

                    var result   = DisksClient.GrantAccess(resourceGroupName, diskName, grantAccessData);
                    var psObject = new PSAccessUri();
                    ComputeAutomationAutoMapperProfile.Mapper.Map <AccessUri, PSAccessUri>(result, psObject);
                    WriteObject(psObject);
                }
            });
        }
        /// <summary>
        /// This method generates a SAS URI for a snapshot
        /// SAS URI can be used to download the underlying data of the snapshot or to get the changes since the last snapshot
        /// </summary>
        /// <param name="subscriptionId">Your subscriptionId</param>
        /// <param name="resourceGroupName">The name of the resource group where incremental snapshots are created</param>
        /// <param name="snapshotName">The name of the snapshot</param>
        /// <returns></returns>
        private static string GetSASURI(string subscriptionId, string resourceGroupName, string snapshotName)
        {
            var credential = GetClientCredential();

            using (var computeClient = new ComputeManagementClient(credential))
            {
                computeClient.SubscriptionId = subscriptionId;

                //Expiry is set as one day.
                //If you expect the data size is large then please update it to higher value
                int sasExpiryInSec = 60 * 24 * 60 * 60;

                // Setting the access to Read generates a read-only SAS that can be used for downloading or reading the snapshot data.
                GrantAccessData grantAccessData = new GrantAccessData("Read", sasExpiryInSec);

                var getSasResponse = computeClient.Snapshots.GrantAccess(resourceGroupName, snapshotName, grantAccessData);

                return(getSasResponse.AccessSAS);
            }
        }
コード例 #13
0
        // Verify disk restore points.
        private void VerifyDiskRestorePoint(string rgName, string rpcName, string rpName)
        {
            IPage <DiskRestorePoint> listDiskRestorePoint = m_CrpClient.DiskRestorePoint.ListByRestorePoint(rgName, rpcName, rpName);
            GrantAccessData          accessData           = new GrantAccessData {
                Access = AccessLevel.Read, DurationInSeconds = 1000
            };

            foreach (DiskRestorePoint drp in listDiskRestorePoint)
            {
                var getDrp = m_CrpClient.DiskRestorePoint.Get(rgName, rpcName, rpName, drp.Name);
                ValidateDiskRestorePoint(getDrp, drp.Name);

                AccessUri accessUri = m_CrpClient.DiskRestorePoint.GrantAccess(rgName, rpcName, rpName, getDrp.Name, accessData);
                Assert.NotNull(accessUri.AccessSAS);

                getDrp = m_CrpClient.DiskRestorePoint.Get(rgName, rpcName, rpName, drp.Name);
                ValidateDiskRestorePoint(getDrp, drp.Name);

                m_CrpClient.DiskRestorePoint.RevokeAccess(rgName, rpcName, rpName, drp.Name);
            }
        }
コード例 #14
0
        public virtual ArmOperation <AccessUri> GrantAccess(WaitUntil waitUntil, GrantAccessData data, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNull(data, nameof(data));

            using var scope = _managedDiskDisksClientDiagnostics.CreateScope("ManagedDiskResource.GrantAccess");
            scope.Start();
            try
            {
                var response  = _managedDiskDisksRestClient.GrantAccess(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, data, cancellationToken);
                var operation = new ComputeArmOperation <AccessUri>(new AccessUriOperationSource(), _managedDiskDisksClientDiagnostics, Pipeline, _managedDiskDisksRestClient.CreateGrantAccessRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, data).Request, response, OperationFinalStateVia.Location);
                if (waitUntil == WaitUntil.Completed)
                {
                    operation.WaitForCompletion(cancellationToken);
                }
                return(operation);
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }
 /// <summary>
 /// Grants access to a diskRestorePoint.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='resourceGroupName'>
 /// The name of the resource group.
 /// </param>
 /// <param name='restorePointCollectionName'>
 /// The name of the restore point collection that the disk restore point
 /// belongs. Supported characters for the name are a-z, A-Z, 0-9 and _. The
 /// maximum name length is 80 characters.
 /// </param>
 /// <param name='vmRestorePointName'>
 /// The name of the vm restore point that the disk disk restore point belongs.
 /// Supported characters for the name are a-z, A-Z, 0-9 and _. The maximum name
 /// length is 80 characters.
 /// </param>
 /// <param name='diskRestorePointName'>
 /// The name of the disk restore point created. Supported characters for the
 /// name are a-z, A-Z, 0-9 and _. The maximum name length is 80 characters.
 /// </param>
 /// <param name='grantAccessData'>
 /// Access data object supplied in the body of the get disk access operation.
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <AccessUri> GrantAccessAsync(this IDiskRestorePointOperations operations, string resourceGroupName, string restorePointCollectionName, string vmRestorePointName, string diskRestorePointName, GrantAccessData grantAccessData, CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.GrantAccessWithHttpMessagesAsync(resourceGroupName, restorePointCollectionName, vmRestorePointName, diskRestorePointName, grantAccessData, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
コード例 #16
0
        public override void ExecuteCmdlet()
        {
            base.ExecuteCmdlet();
            ExecuteClientAction(() =>
            {
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine("To be compatible with Azure, Add-AzVhd will automatically try to convert VHDX files to VHD, and resize VHD files to N * Mib using Hyper-V Platform, a Windows naitive virtualization product. \nFor more information visit https://aka.ms/usingAdd-AzVhd \n");
                Console.ResetColor();


                Program.SyncOutput = new PSSyncOutputEvents(this);
                // 1.              CONVERT VHDX TO VHD
                if (this.LocalFilePath.Extension == ".vhdx")
                {
                    convertVhd();
                }

                checkForCorruptedAndDynamicallySizedVhd();
                checkVhdFileSize(this.LocalFilePath);

                // 2.            RESIZE VHD
                if (this.skipResizing.IsPresent)
                {
                    Console.WriteLine("Skipping VHD resizing.");
                }
                else
                {
                    if ((this.LocalFilePath.Length - 512) % 1048576 != 0)
                    {
                        resizeVhdFile();
                    }
                    else // does not need resizing
                    {
                        WriteVerbose("Vhd file already sized correctly. Proceeding to uploading.");
                    }
                }

                if (this.ParameterSetName == DirectUploadToManagedDiskSet)
                {
                    // 3. DIRECT UPLOAD TO MANAGED DISK

                    // 3-1. CREATE DISK CONFIG
                    checkForExistingDisk(this.ResourceGroupName, this.DiskName);
                    var diskConfig = CreateDiskConfig();

                    // 3-2: CREATE DISK
                    createManagedDisk(this.ResourceGroupName, this.DiskName, diskConfig);

                    // 3-3: GENERATE SAS
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.WriteLine("Generating SAS");
                    Console.ResetColor();
                    var grantAccessData    = new GrantAccessData();
                    grantAccessData.Access = "Write";
                    long gbInBytes         = 1073741824;
                    int gb = (int)(this.LocalFilePath.Length / gbInBytes);
                    grantAccessData.DurationInSeconds = 86400 * Math.Max(gb / 100, 1);   // 24h per 100gb
                    var accessUri = this.ComputeClient.ComputeManagementClient.Disks.GrantAccess(this.ResourceGroupName, this.DiskName, grantAccessData);
                    Uri sasUri    = new Uri(accessUri.AccessSAS);
                    Console.WriteLine("SAS generated: " + accessUri.AccessSAS);

                    // 3-4: UPLOAD
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.WriteLine("Preparing for Upload");
                    Console.ResetColor();
                    PSPageBlobClient managedDisk        = new PSPageBlobClient(sasUri);
                    DiskUploadCreator diskUploadCreator = new DiskUploadCreator();
                    var uploadContext = diskUploadCreator.Create(this.LocalFilePath, managedDisk, false);
                    var synchronizer  = new DiskSynchronizer(uploadContext, this.NumberOfUploaderThreads ?? DefaultNumberOfUploaderThreads);

                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.WriteLine("Uploading");
                    Console.ResetColor();
                    if (synchronizer.Synchronize())
                    {
                        var result = new VhdUploadContext {
                            LocalFilePath = this.LocalFilePath, DestinationUri = sasUri
                        };
                        WriteObject(result);
                    }
                    else
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine("Upload failed");
                        Console.ResetColor();
                    }

                    // 3-5: REVOKE SAS
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.WriteLine("Revoking SAS");
                    Console.ResetColor();
                    var RevokeResult = this.ComputeClient.ComputeManagementClient.Disks.RevokeAccessWithHttpMessagesAsync(this.ResourceGroupName, this.DiskName).GetAwaiter().GetResult();
                    PSOperationStatusResponse output = new PSOperationStatusResponse
                    {
                        StartTime = this.StartTime,
                        EndTime   = DateTime.Now
                    };
                    if (RevokeResult != null && RevokeResult.Request != null && RevokeResult.Request.RequestUri != null)
                    {
                        output.Name = GetOperationIdFromUrlString(RevokeResult.Request.RequestUri.ToString());
                    }

                    Console.WriteLine("SAS revoked.");
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("\nUpload complete.");
                    Console.ResetColor();
                }
                else
                {
                    var parameters       = ValidateParameters();
                    var vhdUploadContext = VhdUploaderModel.Upload(parameters);
                    WriteObject(vhdUploadContext);
                }
            });
        }
コード例 #17
0
 /// <summary>
 /// Grants access to a disk.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='resourceGroupName'>
 /// The name of the resource group.
 /// </param>
 /// <param name='diskName'>
 /// The name of the managed disk that is being created. The name can't be
 /// changed after the disk is created. Supported characters for the name are
 /// a-z, A-Z, 0-9 and _. The maximum name length is 80 characters.
 /// </param>
 /// <param name='grantAccessData'>
 /// Access data object supplied in the body of the get disk access operation.
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <AccessUriInner> BeginGrantAccessAsync(this IDisksOperations operations, string resourceGroupName, string diskName, GrantAccessData grantAccessData, CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.BeginGrantAccessWithHttpMessagesAsync(resourceGroupName, diskName, grantAccessData, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
コード例 #18
0
        public virtual async Task <SnapshotsGrantAccessOperation> StartGrantAccessAsync(string resourceGroupName, string snapshotName, GrantAccessData grantAccessData, CancellationToken cancellationToken = default)
        {
            if (resourceGroupName == null)
            {
                throw new ArgumentNullException(nameof(resourceGroupName));
            }
            if (snapshotName == null)
            {
                throw new ArgumentNullException(nameof(snapshotName));
            }
            if (grantAccessData == null)
            {
                throw new ArgumentNullException(nameof(grantAccessData));
            }

            using var scope = _clientDiagnostics.CreateScope("SnapshotsOperations.StartGrantAccess");
            scope.Start();
            try
            {
                var originalResponse = await RestClient.GrantAccessAsync(resourceGroupName, snapshotName, grantAccessData, cancellationToken).ConfigureAwait(false);

                return(new SnapshotsGrantAccessOperation(_clientDiagnostics, _pipeline, RestClient.CreateGrantAccessRequest(resourceGroupName, snapshotName, grantAccessData).Request, originalResponse));
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }
コード例 #19
0
        public async virtual Task <ArmOperation <AccessUri> > GrantAccessAsync(bool waitForCompletion, GrantAccessData grantAccessData, CancellationToken cancellationToken = default)
        {
            if (grantAccessData == null)
            {
                throw new ArgumentNullException(nameof(grantAccessData));
            }

            using var scope = _snapshotClientDiagnostics.CreateScope("Snapshot.GrantAccess");
            scope.Start();
            try
            {
                var response = await _snapshotRestClient.GrantAccessAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, grantAccessData, cancellationToken).ConfigureAwait(false);

                var operation = new ComputeArmOperation <AccessUri>(new AccessUriOperationSource(), _snapshotClientDiagnostics, Pipeline, _snapshotRestClient.CreateGrantAccessRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, grantAccessData).Request, response, OperationFinalStateVia.Location);
                if (waitForCompletion)
                {
                    await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false);
                }
                return(operation);
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }
コード例 #20
0
        public virtual async Task <ArmOperation <AccessUri> > GrantAccessAsync(WaitUntil waitUntil, GrantAccessData data, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNull(data, nameof(data));

            using var scope = _diskRestorePointClientDiagnostics.CreateScope("DiskRestorePointResource.GrantAccess");
            scope.Start();
            try
            {
                var response = await _diskRestorePointRestClient.GrantAccessAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Parent.Name, Id.Parent.Name, Id.Name, data, cancellationToken).ConfigureAwait(false);

                var operation = new ComputeArmOperation <AccessUri>(new AccessUriOperationSource(), _diskRestorePointClientDiagnostics, Pipeline, _diskRestorePointRestClient.CreateGrantAccessRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Parent.Name, Id.Parent.Name, Id.Name, data).Request, response, OperationFinalStateVia.Location);
                if (waitUntil == WaitUntil.Completed)
                {
                    await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false);
                }
                return(operation);
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }
 /// <summary>
 /// Grants access to a snapshot.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='resourceGroupName'>
 /// The name of the resource group.
 /// </param>
 /// <param name='snapshotName'>
 /// The name of the snapshot that is being created. The name can't be changed
 /// after the snapshot is created. Supported characters for the name are a-z,
 /// A-Z, 0-9 and _. The max name length is 80 characters.
 /// </param>
 /// <param name='grantAccessData'>
 /// Access data object supplied in the body of the get snapshot access
 /// operation.
 /// </param>
 public static AccessUri GrantAccess(this ISnapshotsOperations operations, string resourceGroupName, string snapshotName, GrantAccessData grantAccessData)
 {
     return(operations.GrantAccessAsync(resourceGroupName, snapshotName, grantAccessData).GetAwaiter().GetResult());
 }
コード例 #22
0
        public virtual SnapshotGrantAccessOperation GrantAccess(bool waitForCompletion, GrantAccessData grantAccessData, CancellationToken cancellationToken = default)
        {
            if (grantAccessData == null)
            {
                throw new ArgumentNullException(nameof(grantAccessData));
            }

            using var scope = _snapshotClientDiagnostics.CreateScope("Snapshot.GrantAccess");
            scope.Start();
            try
            {
                var response  = _snapshotRestClient.GrantAccess(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, grantAccessData, cancellationToken);
                var operation = new SnapshotGrantAccessOperation(_snapshotClientDiagnostics, Pipeline, _snapshotRestClient.CreateGrantAccessRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, grantAccessData).Request, response);
                if (waitForCompletion)
                {
                    operation.WaitForCompletion(cancellationToken);
                }
                return(operation);
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }
コード例 #23
0
        public virtual DisksGrantAccessOperation StartGrantAccess(string resourceGroupName, string diskName, GrantAccessData grantAccessData, CancellationToken cancellationToken = default)
        {
            if (resourceGroupName == null)
            {
                throw new ArgumentNullException(nameof(resourceGroupName));
            }
            if (diskName == null)
            {
                throw new ArgumentNullException(nameof(diskName));
            }
            if (grantAccessData == null)
            {
                throw new ArgumentNullException(nameof(grantAccessData));
            }

            using var scope = _clientDiagnostics.CreateScope("DisksOperations.StartGrantAccess");
            scope.Start();
            try
            {
                var originalResponse = RestClient.GrantAccess(resourceGroupName, diskName, grantAccessData, cancellationToken);
                return(new DisksGrantAccessOperation(_clientDiagnostics, _pipeline, RestClient.CreateGrantAccessRequest(resourceGroupName, diskName, grantAccessData).Request, originalResponse));
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }
コード例 #24
0
        public override void ExecuteCmdlet()
        {
            base.ExecuteCmdlet();
            ExecuteClientAction(() =>
            {
                try
                {
                    WriteVerbose("To be compatible with Azure, Add-AzVhd will automatically try to convert VHDX files to VHD and resize VHD files to N * Mib using Hyper-V Platform, a Windows native virtualization product. During the process the cmdlet will temporarily create a converted/resized file in the same directory as the provided VHD/VHDX file. \nFor more information visit https://aka.ms/usingAdd-AzVhd \n");

                    Program.SyncOutput = new PSSyncOutputEvents(this);

                    // 1.              CONVERT VHDX TO VHD
                    if (this.LocalFilePath.Extension == ".vhdx")
                    {
                        convertVhd();
                    }

                    // 2.              RESIZE VHD
                    CheckForInvalidVhd();

                    if (this.ParameterSetName == DirectUploadToManagedDiskSet)
                    {
                        // 3. DIRECT UPLOAD TO MANAGED DISK


                        // 3-1. CREATE DISK CONFIG
                        checkForExistingDisk(this.ResourceGroupName, this.DiskName);
                        var diskConfig = CreateDiskConfig();

                        // 3-2: CREATE DISK
                        createManagedDisk(this.ResourceGroupName, this.DiskName, diskConfig);

                        // 3-3: GENERATE SAS
                        WriteVerbose("Generating SAS");
                        var grantAccessData    = new GrantAccessData();
                        grantAccessData.Access = "Write";
                        long gbInBytes         = 1073741824;
                        int gb = (int)(this.LocalFilePath.Length / gbInBytes);
                        grantAccessData.DurationInSeconds = 86400 * Math.Max(gb / 100, 1);   // 24h per 100gb
                        var accessUri = this.ComputeClient.ComputeManagementClient.Disks.GrantAccess(this.ResourceGroupName, this.DiskName, grantAccessData);
                        Uri sasUri    = new Uri(accessUri.AccessSAS);
                        WriteVerbose("SAS generated: " + accessUri.AccessSAS);


                        // 3-4: UPLOAD
                        WriteVerbose("Preparing for Upload");
                        PSPageBlobClient managedDisk        = new PSPageBlobClient(sasUri);
                        DiskUploadCreator diskUploadCreator = new DiskUploadCreator();
                        var uploadContext = diskUploadCreator.Create(this.LocalFilePath, managedDisk, false);
                        var synchronizer  = new DiskSynchronizer(uploadContext, this.NumberOfUploaderThreads ?? DefaultNumberOfUploaderThreads);

                        WriteVerbose("Uploading");
                        if (synchronizer.Synchronize())
                        {
                            var result = new VhdUploadContext {
                                LocalFilePath = this.LocalFilePath, DestinationUri = sasUri
                            };
                            WriteObject(result);
                        }
                        else
                        {
                            WriteVerbose("Upload failed");
                        }

                        // 3-5: REVOKE SAS
                        WriteVerbose("Revoking SAS");
                        var RevokeResult = this.ComputeClient.ComputeManagementClient.Disks.RevokeAccessWithHttpMessagesAsync(this.ResourceGroupName, this.DiskName).GetAwaiter().GetResult();
                        PSOperationStatusResponse output = new PSOperationStatusResponse
                        {
                            StartTime = this.StartTime,
                            EndTime   = DateTime.Now
                        };
                        if (RevokeResult != null && RevokeResult.Request != null && RevokeResult.Request.RequestUri != null)
                        {
                            output.Name = GetOperationIdFromUrlString(RevokeResult.Request.RequestUri.ToString());
                        }

                        WriteVerbose("SAS revoked.");
                        WriteVerbose("\nUpload complete.");
                    }
                    else
                    {
                        var parameters       = ValidateParameters();
                        var vhdUploadContext = VhdUploaderModel.Upload(parameters);
                        WriteObject(vhdUploadContext);
                    }
                }
                finally
                {
                    if (temporaryFileCreated)
                    {
                        WriteVerbose("Deleting file: " + this.LocalFilePath.FullName);
                        File.Delete(this.LocalFilePath.FullName);
                    }
                }
            });
        }
コード例 #25
0
 /// <summary>
 /// Grants access to a disk.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='resourceGroupName'>
 /// The name of the resource group.
 /// </param>
 /// <param name='diskName'>
 /// The name of the managed disk that is being created. The name can't be
 /// changed after the disk is created. Supported characters for the name are
 /// a-z, A-Z, 0-9 and _. The maximum name length is 80 characters.
 /// </param>
 /// <param name='grantAccessData'>
 /// Access data object supplied in the body of the get disk access operation.
 /// </param>
 public static AccessUri BeginGrantAccess(this IDisksOperations operations, string resourceGroupName, string diskName, GrantAccessData grantAccessData)
 {
     return(operations.BeginGrantAccessAsync(resourceGroupName, diskName, grantAccessData).GetAwaiter().GetResult());
 }
 /// <summary>
 /// Grants access to a diskRestorePoint.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='resourceGroupName'>
 /// The name of the resource group.
 /// </param>
 /// <param name='restorePointCollectionName'>
 /// The name of the restore point collection that the disk restore point
 /// belongs. Supported characters for the name are a-z, A-Z, 0-9 and _. The
 /// maximum name length is 80 characters.
 /// </param>
 /// <param name='vmRestorePointName'>
 /// The name of the vm restore point that the disk disk restore point belongs.
 /// Supported characters for the name are a-z, A-Z, 0-9 and _. The maximum name
 /// length is 80 characters.
 /// </param>
 /// <param name='diskRestorePointName'>
 /// The name of the disk restore point created. Supported characters for the
 /// name are a-z, A-Z, 0-9 and _. The maximum name length is 80 characters.
 /// </param>
 /// <param name='grantAccessData'>
 /// Access data object supplied in the body of the get disk access operation.
 /// </param>
 public static AccessUri BeginGrantAccess(this IDiskRestorePointOperations operations, string resourceGroupName, string restorePointCollectionName, string vmRestorePointName, string diskRestorePointName, GrantAccessData grantAccessData)
 {
     return(operations.BeginGrantAccessAsync(resourceGroupName, restorePointCollectionName, vmRestorePointName, diskRestorePointName, grantAccessData).GetAwaiter().GetResult());
 }