public async Task <Response <DeploymentScript> > UpdateAsync(string resourceGroupName, string scriptName, DeploymentScriptUpdateParameter deploymentScript = null, CancellationToken cancellationToken = default)
        {
            if (resourceGroupName == null)
            {
                throw new ArgumentNullException(nameof(resourceGroupName));
            }
            if (scriptName == null)
            {
                throw new ArgumentNullException(nameof(scriptName));
            }

            using var message = CreateUpdateRequest(resourceGroupName, scriptName, deploymentScript);
            await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);

            switch (message.Response.Status)
            {
            case 200:
            {
                DeploymentScript value = default;
                using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);

                if (document.RootElement.ValueKind == JsonValueKind.Null)
                {
                    value = null;
                }
                else
                {
                    value = DeploymentScript.DeserializeDeploymentScript(document.RootElement);
                }
                return(Response.FromValue(value, message.Response));
            }
        private void ExecuteScript(DeploymentScript script, string jobId)
        {
            var proc = new Process
            {
                StartInfo =
                {
                    FileName  = (new FileInfo(script.Path)).FullName,
                    Arguments = script.Arguments,
                    RedirectStandardOutput = true,
                    RedirectStandardError  = true
                }
            };

            _logger.LogInformation($"Starting script {Path.GetFileName(script.Path)}");

            proc.Start();

            _jobsDataAccess.SetInProgress(jobId, $"Running script {Path.GetFileName(script.Path)}", proc);

            // read output and error streams async
            proc.OutputDataReceived += (sender, eventArgs) => LogIfNotEmpty(jobId, eventArgs.Data);
            proc.ErrorDataReceived  += (sender, eventArgs) => LogIfNotEmpty(jobId, eventArgs.Data, LogEventLevel.Error);

            proc.BeginOutputReadLine();
            proc.BeginErrorReadLine();

            proc.WaitForExit();

            // check if the job has failed during deployment.
            if (proc.ExitCode != 0 || _jobsDataAccess.CheckJobStatus(jobId, DeploymentJobStatus.FAIL))
            {
                var message = $"Error running script {Path.GetFileName(script.Path)}, exit code: {proc.ExitCode}";
                throw new DeploymentException(message);
            }
        }
        public Response Create(string resourceGroupName, string scriptName, DeploymentScript deploymentScript, CancellationToken cancellationToken = default)
        {
            if (resourceGroupName == null)
            {
                throw new ArgumentNullException(nameof(resourceGroupName));
            }
            if (scriptName == null)
            {
                throw new ArgumentNullException(nameof(scriptName));
            }
            if (deploymentScript == null)
            {
                throw new ArgumentNullException(nameof(deploymentScript));
            }

            using var message = CreateCreateRequest(resourceGroupName, scriptName, deploymentScript);
            _pipeline.Send(message, cancellationToken);
            switch (message.Response.Status)
            {
            case 200:
            case 201:
                return(message.Response);

            default:
                throw _clientDiagnostics.CreateRequestFailedException(message.Response);
            }
        }
예제 #4
0
        public void RunDeploymentScript(DeploymentScript script)
        {
            try
            {
                if (_db.Exists <MigrationHistory>(script.Name))
                {
                    Log.Debug($"Migration {script.Name} has already been executed");
                    return;
                }

                Log.Info($"Processing migration {script.Name}");

                _db.BeginTransaction();

                var migration = new MigrationHistory
                {
                    ScriptName    = script.Name,
                    Completed     = false,
                    DateProcessed = DateTime.Now
                };

                _db.Insert(migration);
                _db.CompleteTransaction();

                _db.Execute(script.Sql);
                migration.Completed = true;
                _db.Save(migration);
            }
            catch (Exception ex)
            {
                _db.AbortTransaction();
                Log.Error($"Failed to run deployment migration {script.Name}", ex);
                throw;
            }
        }
 private PsDeploymentScript TypeCastDeploymentScript(DeploymentScript deploymentScript)
 {
     switch (deploymentScript)
     {
         case AzurePowerShellScript azurePowerShellScript:
             return PsAzurePowerShellScript.ToPsAzurePowerShellScript(azurePowerShellScript);
         case AzureCliScript azureCliScript:
             return PsAzureCliScript.ToPsAzureCliScript(azureCliScript);
         default:
             throw new NotSupportedException(Properties.Resources.DeploymentScriptKindNotSupported);
     }
 }
        public void GivenAMigrationHasAlreadyRun_WhenRunDeploymentScript_NoDatabaseInteractionIsInvoked()
        {
            var script = new DeploymentScript("Test", "Script");

            var mockDb = new Mock <IDatabase>();

            mockDb.Setup(x => x.Exists <MigrationHistory>(It.IsAny <string>())).Returns(true);

            var mockConfig = new Mock <INPocoLocoConfig>();

            var deployment = new DatabaseDeployment(mockDb.Object, mockConfig.Object);

            deployment.RunDeploymentScript(script);

            mockDb.Verify(x => x.BeginTransaction(), Times.Never);
        }
예제 #7
0
        public async Task CreateOrUpdate()
        {
            string            rgName = Recording.GenerateAssetName("testRg-1-");
            ResourceGroupData rgData = new ResourceGroupData(Location.WestUS2);
            var lro = await Client.DefaultSubscription.GetResourceGroups().CreateOrUpdateAsync(rgName, rgData);

            ResourceGroup        rg = lro.Value;
            string               deployScriptName     = Recording.GenerateAssetName("deployScript-C-");
            DeploymentScriptData deploymentScriptData = await GetDeploymentScriptDataAsync();

            DeploymentScript deploymentScript = (await rg.GetDeploymentScripts().CreateOrUpdateAsync(deployScriptName, deploymentScriptData)).Value;

            Assert.AreEqual(deployScriptName, deploymentScript.Data.Name);
            Assert.ThrowsAsync <ArgumentNullException>(async() => _ = await rg.GetDeploymentScripts().CreateOrUpdateAsync(null, deploymentScriptData));
            Assert.ThrowsAsync <ArgumentNullException>(async() => _ = await rg.GetDeploymentScripts().CreateOrUpdateAsync(deployScriptName, null));
        }
        public async Task Delete()
        {
            string            rgName = Recording.GenerateAssetName("testRg-5-");
            ResourceGroupData rgData = new ResourceGroupData(Location.WestUS2);
            var lro = await Client.DefaultSubscription.GetResourceGroups().CreateOrUpdateAsync(rgName, rgData);

            ResourceGroup        rg = lro.Value;
            string               deployScriptName     = Recording.GenerateAssetName("deployScript-D-");
            DeploymentScriptData deploymentScriptData = await GetDeploymentScriptDataAsync();

            DeploymentScript deploymentScript = (await rg.GetDeploymentScripts().CreateOrUpdateAsync(deployScriptName, deploymentScriptData)).Value;
            await deploymentScript.DeleteAsync();

            var ex = Assert.ThrowsAsync <RequestFailedException>(async() => await deploymentScript.GetAsync());

            Assert.AreEqual(404, ex.Status);
        }
        public void GivenRunDeploymentScriptFails_ExceptionShouldBeCaught()
        {
            var script = new DeploymentScript("Test", "Script");

            var mockDb = new Mock <IDatabase>();

            mockDb.Setup(x => x.Exists <MigrationHistory>(It.IsAny <string>())).Returns(false);
            mockDb.Setup(x => x.Insert(It.IsAny <MigrationHistory>())).Throws <Exception>();

            var mockConfig = new Mock <INPocoLocoConfig>();

            var deployment = new DatabaseDeployment(mockDb.Object, mockConfig.Object);

            Action action = () => deployment.RunDeploymentScript(script);

            action.ShouldThrow <Exception>();
        }
예제 #10
0
        public async Task Get()
        {
            string            rgName = Recording.GenerateAssetName("testRg-4-");
            ResourceGroupData rgData = new ResourceGroupData(Location.WestUS2);
            var lro = await Client.DefaultSubscription.GetResourceGroups().CreateOrUpdateAsync(rgName, rgData);

            ResourceGroup        rg = lro.Value;
            string               deployScriptName     = Recording.GenerateAssetName("deployScript-G-");
            DeploymentScriptData deploymentScriptData = await GetDeploymentScriptDataAsync();

            DeploymentScript      tempDeploymentScript    = (await rg.GetDeploymentScripts().CreateOrUpdateAsync(deployScriptName, deploymentScriptData)).Value;
            AzurePowerShellScript deploymentScript        = tempDeploymentScript.Data as AzurePowerShellScript;
            DeploymentScript      tempGetDeploymentScript = await rg.GetDeploymentScripts().GetAsync(deployScriptName);

            AzurePowerShellScript getdeploymentScript = tempGetDeploymentScript.Data as AzurePowerShellScript;

            AssertValidDeploymentScript(deploymentScript, getdeploymentScript);
        }
        public void GivenRunningDeploymentScriptFails_TransactionIsAborted()
        {
            var script = new DeploymentScript("Test", "Script");

            var mockDb = new Mock <IDatabase>();

            mockDb.Setup(x => x.Exists <MigrationHistory>(It.IsAny <string>())).Returns(false);
            mockDb.Setup(x => x.Insert(It.IsAny <MigrationHistory>())).Throws <Exception>();
            mockDb.Setup(x => x.AbortTransaction()).Verifiable();

            var mockConfig = new Mock <INPocoLocoConfig>();

            var deployment = new DatabaseDeployment(mockDb.Object, mockConfig.Object);

            Action action = () => deployment.RunDeploymentScript(script);

            action.ShouldThrow <Exception>();

            mockDb.Verify(x => x.AbortTransaction(), Times.Once);
        }
        internal Core.HttpMessage CreateCreateRequest(string resourceGroupName, string scriptName, DeploymentScript deploymentScript)
        {
            var message = _pipeline.CreateMessage();
            var request = message.Request;

            request.Method = RequestMethod.Put;
            var uri = new RawRequestUriBuilder();

            uri.Reset(endpoint);
            uri.AppendPath("/subscriptions/", false);
            uri.AppendPath(subscriptionId, true);
            uri.AppendPath("/resourcegroups/", false);
            uri.AppendPath(resourceGroupName, true);
            uri.AppendPath("/providers/Microsoft.Resources/deploymentScripts/", false);
            uri.AppendPath(scriptName, true);
            uri.AppendQuery("api-version", "2019-10-01-preview", true);
            request.Uri = uri;
            request.Headers.Add("Content-Type", "application/json");
            var content = new Utf8JsonRequestContent();

            content.JsonWriter.WriteObjectValue(deploymentScript);
            request.Content = content;
            return(message);
        }
 /// <summary>
 /// Creates a deployment script.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='resourceGroupName'>
 /// The name of the resource group. The name is case insensitive.
 /// </param>
 /// <param name='scriptName'>
 /// Name of the deployment script.
 /// </param>
 /// <param name='deploymentScript'>
 /// Deployment script supplied to the operation.
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <DeploymentScript> CreateAsync(this IDeploymentScriptsOperations operations, string resourceGroupName, string scriptName, DeploymentScript deploymentScript, CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.CreateWithHttpMessagesAsync(resourceGroupName, scriptName, deploymentScript, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
 /// <summary>
 /// Creates a deployment script.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='resourceGroupName'>
 /// The name of the resource group. The name is case insensitive.
 /// </param>
 /// <param name='scriptName'>
 /// Name of the deployment script.
 /// </param>
 /// <param name='deploymentScript'>
 /// Deployment script supplied to the operation.
 /// </param>
 public static DeploymentScript Create(this IDeploymentScriptsOperations operations, string resourceGroupName, string scriptName, DeploymentScript deploymentScript)
 {
     return(operations.CreateAsync(resourceGroupName, scriptName, deploymentScript).GetAwaiter().GetResult());
 }
예제 #15
0
        public async ValueTask <Response> CreateAsync(string resourceGroupName, string scriptName, DeploymentScript deploymentScript, CancellationToken cancellationToken = default)
        {
            if (resourceGroupName == null)
            {
                throw new ArgumentNullException(nameof(resourceGroupName));
            }
            if (scriptName == null)
            {
                throw new ArgumentNullException(nameof(scriptName));
            }
            if (deploymentScript == null)
            {
                throw new ArgumentNullException(nameof(deploymentScript));
            }

            using var message = CreateCreateRequest(resourceGroupName, scriptName, deploymentScript);
            await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);

            switch (message.Response.Status)
            {
            case 201:
            case 200:
                return(message.Response);

            default:
                throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
            }
        }
예제 #16
0
        public virtual DeploymentScriptsCreateOperation StartCreate(string resourceGroupName, string scriptName, DeploymentScript deploymentScript, CancellationToken cancellationToken = default)
        {
            if (resourceGroupName == null)
            {
                throw new ArgumentNullException(nameof(resourceGroupName));
            }
            if (scriptName == null)
            {
                throw new ArgumentNullException(nameof(scriptName));
            }
            if (deploymentScript == null)
            {
                throw new ArgumentNullException(nameof(deploymentScript));
            }

            using var scope = _clientDiagnostics.CreateScope("DeploymentScriptsClient.StartCreate");
            scope.Start();
            try
            {
                var originalResponse = RestClient.Create(resourceGroupName, scriptName, deploymentScript, cancellationToken);
                return(new DeploymentScriptsCreateOperation(_clientDiagnostics, _pipeline, RestClient.CreateCreateRequest(resourceGroupName, scriptName, deploymentScript).Request, originalResponse));
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }