Ejemplo n.º 1
0
        /// <summary>
        /// Get the full details of the specified Configuration, including the list of MySQL Variables and their values.
        ///
        /// </summary>
        /// <param name="request">The request object containing the details to send. Required.</param>
        /// <param name="retryConfiguration">The retry configuration that will be used by to send this request. Optional.</param>
        /// <param name="cancellationToken">The cancellation token to cancel this operation. Optional.</param>
        /// <returns>A response object containing details about the completed operation</returns>
        /// <example>Click <a href="https://docs.cloud.oracle.com/en-us/iaas/tools/dot-net-examples/latest/mysql/GetConfiguration.cs.html">here</a> to see an example of how to use GetConfiguration API.</example>
        public async Task <GetConfigurationResponse> GetConfiguration(GetConfigurationRequest request, RetryConfiguration retryConfiguration = null, CancellationToken cancellationToken = default)
        {
            logger.Trace("Called getConfiguration");
            Uri                uri            = new Uri(this.restClient.GetEndpoint(), System.IO.Path.Combine(basePathWithoutHost, "/configurations/{configurationId}".Trim('/')));
            HttpMethod         method         = new HttpMethod("GET");
            HttpRequestMessage requestMessage = Converter.ToHttpRequestMessage(uri, method, request);

            requestMessage.Headers.Add("Accept", "application/json");
            GenericRetrier      retryingClient = Retrier.GetPreferredRetrier(retryConfiguration, this.retryConfiguration);
            HttpResponseMessage responseMessage;

            try
            {
                if (retryingClient != null)
                {
                    responseMessage = await retryingClient.MakeRetryingCall(this.restClient.HttpSend, requestMessage, cancellationToken).ConfigureAwait(false);
                }
                else
                {
                    responseMessage = await this.restClient.HttpSend(requestMessage).ConfigureAwait(false);
                }
                this.restClient.CheckHttpResponseMessage(requestMessage, responseMessage);

                return(Converter.FromHttpResponseMessage <GetConfigurationResponse>(responseMessage));
            }
            catch (Exception e)
            {
                logger.Error($"GetConfiguration failed with error: {e.Message}");
                throw;
            }
        }
Ejemplo n.º 2
0
        // TODO:  I think returning a Stream would be better here, but coordinating that
        // with the disposable resources that are contained within could be tricky
        public async Task <FileResponse> GetConfiguration(string configName)
        {
            if (LOG.IsEnabled(LogLevel.Trace))
            {
                LOG.LogTrace(nameof(GetConfiguration));
            }

            AssertInit();

            var serverConfig = Configuration.ConfigurationRepositoryServer;

            AssertServerConfig(serverConfig);

            var dscRequ = new GetConfigurationRequest
            {
                AgentId           = Configuration.AgentId,
                ConfigurationName = configName,
                AcceptHeader      = DscContentTypes.OCTET_STREAM,
            };

            var dscResp = new GetConfigurationResponse();

            using (var bs = new MemoryStream())
                using (var disposable = await SendDscAsync(serverConfig, GetConfigurationRequest.VERB,
                                                           GetConfigurationRequest.ROUTE, dscRequ, dscResp))
                {
                    dscResp.Configuration.CopyTo(bs);
                    return(new FileResponse
                    {
                        ChecksumAlgorithm = dscResp.ChecksumAlgorithmHeader,
                        Checksum = dscResp.ChecksumHeader,
                        Content = bs.ToArray(),
                    });
                }
        }
        public async Task <ActionResult <string> > Get(int id)
        {
            /*
             * try {
             *  //using var p = new RequestResponsePair<GetConfigurationRequest, GetConfigurationResponse>();
             *  //var response2 = await p.ExecuteAsync(
             *  //    new GetConfigurationRequest(),
             *  //    this._MedaitorAccess,
             *  //    null,
             *  //    this.HttpContext.RequestAborted
             *  //    );
             *  var request = new GetConfigurationRequest();
             *  var medaitorAccess = this._MedaitorAccess;
             *  using var client = medaitorAccess.GetMedaitorClient();
             *  using var connected = await client.ConnectAsync(request, this.HttpContext.RequestAborted);
             *  var response = await connected.WaitForAsync(null, this.HttpContext.RequestAborted);
             *  return response.ConvertResponseToActionResult<GetConfigurationResponse, string>((r) => r.Result?.FirstOrDefault());
             * } catch (System.Exception error) {
             *  return this.StatusCode(500, error.Message);
             * }
             */
            var request = new GetConfigurationRequest();

            return(await RequestResponseHelper <GetConfigurationRequest, GetConfigurationResponse> .
                   ExecuteToActionResultAsync <string>(
                       this.GetMedaitorClient(),
                       ActivityId.NewId(),
                       request,
                       (r) => r.Result?.FirstOrDefault(),
                       null,
                       this.HttpContext.RequestAborted
                       ));
        }
Ejemplo n.º 4
0
        public IActionResult GetConfiguration(GetConfigurationRequest input)
        {
            if (_logger.IsEnabled(LogLevel.Trace))
            {
                _logger.LogTrace($"{nameof(GetConfiguration)}:  {GetConfigurationRequest.VERB}");
            }

            if (ModelState.IsValid)
            {
                _logger.LogDebug($"AgentId=[{input.AgentId}] Configuration=[{input.ConfigurationName}]");

                var configContent = _dscHandler.GetConfiguration(input.AgentId.Value,
                                                                 // TODO:
                                                                 // Strictly speaking, this may not be how the DSCPM
                                                                 // protocol is supposed to resolve the config name
                                                                 input.ConfigurationName ?? input.ConfigurationNameHeader);
                if (configContent == null)
                {
                    return(NotFound());
                }

                var response = new GetConfigurationResponse
                {
                    ChecksumAlgorithmHeader = configContent.ChecksumAlgorithm,
                    ChecksumHeader          = configContent.Checksum,
                    Configuration           = configContent.Content,
                };

                return(this.Model(response));
            }

            return(BadRequest(ModelState));
        }
Ejemplo n.º 5
0
        public override void GetConfiguration(IRpcController controller, GetConfigurationRequest request, Action <GetConfigurationResponse> done)
        {
            Logger.Trace("GetConfiguration()");
            var builder = GetConfigurationResponse.CreateBuilder();

            done(builder.Build());
        }
Ejemplo n.º 6
0
 public override void GetConfiguration(IRpcController controller, GetConfigurationRequest request, Action<GetConfigurationResponse> done)
 {
     Logger.Trace("GetConfiguration()");
     //TODO: Figure out what the buyout rules/specialist values are, and if they are related /dustinconrad
     var builder = GetConfigurationResponse.CreateBuilder()
         .AddConfigs(SpecialistConfig.CreateBuilder()
             .SetSpecialist(1)
             .AddAuctionDurations(720)
             .AddAuctionDurations(1440)
             .AddAuctionDurations(2880)
             .AddAuctionStartDelays(5)
             .SetAntiSnipingExtensionDelay(1)
             .AddCurrencyConfig(CurrencyConfig.CreateBuilder()
                 .SetCurrency("D3_GOLD")
                 .SetTickSize(1)
                 .SetFlatOutbidIncr(1)
                 .SetScaleOutbidIncr(10)
                 .SetMinStartingUnitPrice(5)
                 .SetMaxStartingUnitPrice(4294967295)
                 .SetMaxUnitPrice(4294967295)
                 .SetMaxTotalAmount(281474976710655)
                 .SetBuyoutRule(1))
             .AddCurrencyConfig(CurrencyConfig.CreateBuilder()
                 .SetCurrency("USD")
                 .SetTickSize(2)
                 .SetFlatOutbidIncr(2)
                 .SetScaleOutbidIncr(10)
                 .SetMinStartingUnitPrice(30)
                 .SetMaxStartingUnitPrice(4294967295)
                 .SetMaxUnitPrice(4294967295)
                 .SetMaxTotalAmount(281474976710655)
                 .SetBuyoutRule(1)))
         .AddConfigs(SpecialistConfig.CreateBuilder()
             .SetSpecialist(2)
             .AddAuctionDurations(2880)
             .AddAuctionDurations(10080)
             .AddAuctionStartDelays(0)
             .SetAntiSnipingExtensionDelay(0)
             .AddCurrencyConfig(CurrencyConfig.CreateBuilder()
                 .SetCurrency("D3_GOLD")
                 .SetTickSize(1)
                 .SetFlatOutbidIncr(1)
                 .SetScaleOutbidIncr(10)
                 .SetMinStartingUnitPrice(5)
                 .SetMaxStartingUnitPrice(4294967295)
                 .SetMaxUnitPrice(4294967295)
                 .SetMaxTotalAmount(281474976710655)
                 .SetBuyoutRule(2))
             .AddCurrencyConfig(CurrencyConfig.CreateBuilder()
                 .SetCurrency("USD")
                 .SetTickSize(2)
                 .SetFlatOutbidIncr(2)
                 .SetScaleOutbidIncr(10)
                 .SetMinStartingUnitPrice(30)
                 .SetMaxStartingUnitPrice(4294967295)
                 .SetMaxUnitPrice(4294967295)
                 .SetMaxTotalAmount(281474976710655)
                 .SetBuyoutRule(2)));
     done(builder.Build());
 }
Ejemplo n.º 7
0
        public async Task <GetConfigurationResponse> GetConfiguration(GetConfigurationRequest o)
        {
            var result = new GetConfigurationResponse(o.RequestId);

            result.Key   = o.Key;
            result.Value = await Server.GetSettings(o.Application, o.Key);

            return(result);
        }
        public async Task <ActionResult> GetConfig(string key)
        {
            try
            {
                IGetConfigurationRequest  getConfigurationRequest  = new GetConfigurationRequest(key);
                IGetConfigurationResponse getConfigurationResponse = await _configurationProvider.GetConfigurationResponse(getConfigurationRequest);

                return(PrepareResponseAfterGetConfiguration(getConfigurationResponse));
            }
            catch (Exception ex)
            {
                _logger.Log(ex);
                return(StatusCode(500));
            }
        }
        public async Task <GetConfigurationResponse> GetConfigurationResponse()
        {
            //var amazonAppConfigClient = Program.AwsOptions.CreateServiceClient<IAmazonAppConfig>();
            var amazonAppConfigClient = _AmazonAppConfigClient;

            var request = new GetConfigurationRequest
            {
                Application   = AppConstants.AppConfigApplication,
                Environment   = AppConstants.AppConfigEnvironment,
                Configuration = AppConstants.AppConfigConfiguration,
                ClientId      = _clientId.ToString(),
                ClientConfigurationVersion = AppConstants.ClientConfigurationVersion
            };

            return(await amazonAppConfigClient.GetConfigurationAsync(request));
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Get the configuration
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task <GetConfigurationResponse> GetConfiguration(GetConfigurationRequest request)
        {
            var uri = new Uri($"{GetEndPoint(AuditServices.CONFIGURATION, this.Region)}?compartmentId={request.CompartmentId}");

            using (var webResponse = await this.RestClientAsync.Get(uri))
                using (var stream = webResponse.GetResponseStream())
                    using (var reader = new StreamReader(stream))
                    {
                        var response = await reader.ReadToEndAsync();

                        return(new GetConfigurationResponse()
                        {
                            Configuration = JsonSerializer.Deserialize <Configuration>(response)
                        });
                    }
        }
        // returns Amazon.AppConfig.Model.GetConfigurationResponse which includes:
        // string ConfigurationVersion
        // MemoryStream Content (Base64 encoded memory stream)
        public async Task <GetConfigurationResponse> GetConfigurationResponse()
        {
            // creates AmazonAppConfigClient using AWS profile stored in app.config
            var amazonAppConfigClient = Program.AwsOptions.CreateServiceClient <IAmazonAppConfig>();
            // creates AmazonAppConfigClient using AWS programmatic access key and secret string
            //var amazonAppConfigClient = new AmazonAppConfigClient("YOUR ACCESS KEY", "YOUR SECRET STRING");

            var request = new GetConfigurationRequest {
                Application   = AppConstants.AppConfigApplication,
                Environment   = AppConstants.AppConfigEnvironment,
                Configuration = AppConstants.AppConfigConfiguration,
                ClientId      = _clientId.ToString(),
                ClientConfigurationVersion = AppConstants.ClientConfigurationVersion
            };

            return(await amazonAppConfigClient.GetConfigurationAsync(request));
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Returns all the audit events processed for the specified compartment within the specified time range.
        /// </summary>
        /// <param name="listRequest"></param>
        /// <returns></returns>
        //public ListEventsResponse ListEvents(ListEventsRequest listRequest)
        //{
        //    var uri = new Uri($"{GetEndPoint(ContainerService.EVENT, this.Region)}?{listRequest.GetOptionQuery()}");

        //    var webResponse = this.RestClient.Get(uri, new HttpRequestHeaderParam() { OpcRequestId = listRequest.OpcRequestId });

        //    using (var stream = webResponse.GetResponseStream())
        //    using (var reader = new StreamReader(stream))
        //    {
        //        var response = reader.ReadToEnd();
        //        return new ListEventsResponse()
        //        {
        //            Items = JsonSerializer.Deserialize<List<ContainerEvent>>(response),
        //            OpcRequestId = webResponse.Headers.Get("opc-request-id"),
        //            OpcNextPage = webResponse.Headers.Get("opc-next-page")
        //        };
        //    }
        //}

        /// <summary>
        /// Get the configuration
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public GetConfigurationResponse GetConfiguration(GetConfigurationRequest request)
        {
            var uri = new Uri($"{GetEndPoint(ContainerService.CONFIGURATION, this.Region)}?compartmentId={request.CompartmentId}");

            var webResponse = this.RestClient.Get(uri);

            using (var stream = webResponse.GetResponseStream())
                using (var reader = new StreamReader(stream))
                {
                    var response = reader.ReadToEnd();

                    return(new GetConfigurationResponse()
                    {
                        Configuration = JsonSerializer.Deserialize <Configuration>(response)
                    });
                }
        }
Ejemplo n.º 13
0
        private async Task <JanusConfig> LoadConfigFromCloudAsync()
        {
            var get = new GetConfigurationRequest()
            {
                Application   = ConfigAppName,
                Environment   = this.stage,
                Configuration = "OperationalSettings",
                ClientId      = "janus-dotnet",
            };
            var response = await this.appConfig.GetConfigurationAsync(get);

            using var content = response.Content;
            using var reader  = new StreamReader(content);
            string json = await reader.ReadToEndAsync();

            return(JsonSerializer.Deserialize <JanusConfig>(json, SerializerOptions));
        }
Ejemplo n.º 14
0
        public async Task <IActionResult> GetConfiguration([FromRoute] GetConfigurationRequest request)
        {
            IActionResult result = null;

            Ensure.Guid.IsNotEmpty(request.Application);

            var model = await Server.GetSettings(request.Application);

            if (model != null)
            {
                result = Factory.CreateSuccessResponse(model);
            }
            else
            {
                result = Factory.CreateNoContentResponse();
            }

            return(result);
        }
Ejemplo n.º 15
0
        public async Task <ConfigModel> GetConfigAsync()
        {
            var request = new GetConfigurationRequest
            {
                Application   = _configuration.ApplicationId,
                Environment   = _configuration.EnvironmentId,
                ClientId      = _clientId,
                Configuration = _configuration.ConfigProfileId
            };

            var response = await _appConfigClient.GetConfigurationAsync(request);

            using var sr = new StreamReader(response.Content);
            var content = await sr.ReadToEndAsync();

            var rootConfig = JsonSerializer.Deserialize <RootConfigModel>(content);

            return(rootConfig.ApplicationConfig);
        }
Ejemplo n.º 16
0
        public static async void AuditDisplay(ClientConfig config)
        {
            // create client
            AuditClientAsync client = new AuditClientAsync(config)
            {
                Region = Regions.US_ASHBURN_1
            };
            IdentityClient identityClinet = new IdentityClient(config)
            {
                Region = Regions.US_ASHBURN_1
            };

            DateTime now       = DateTime.Now.AddDays(-1);
            var      startDate = now.ToString("yyyy-MM-ddT00:00:00Z");
            var      endDate   = now.ToString("yyyy-MM-ddT10:30:00Z");

            var listCompartmentRequest = new ListCompartmentRequest()
            {
                CompartmentId          = config.TenancyId,
                CompartmentIdInSubtree = true,
                AccessLevel            = ListCompartmentRequest.AccessLevels.ACCESSIBLE
            };
            var compartments = identityClinet.ListCompartment(listCompartmentRequest).Items;

            // get Audit Events
            Console.WriteLine("* Audit Events-------------------");
            foreach (var compartment in compartments)
            {
                // get config
                var configurationRequest = new GetConfigurationRequest()
                {
                    CompartmentId = compartment.Id
                };
                var auditConfig = await client.GetConfiguration(configurationRequest);

                Console.WriteLine($"compartment<{compartment.Name}>---");
                Console.WriteLine($"startTime:{startDate}, endTime:{endDate}");
                Console.WriteLine($"retentionPeriodDays:{auditConfig.Configuration.RetentionPeriodDays}");

                DisplayAudit(config, client, identityClinet, compartment.Id, startDate, endDate, "", "");
            }
        }
Ejemplo n.º 17
0
        private void HandleOutput(GetConfigurationRequest request)
        {
            var waiterConfig = new WaiterConfiguration
            {
                MaxAttempts           = MaxWaitAttempts,
                GetNextDelayInSeconds = (_) => WaitIntervalSeconds
            };

            switch (ParameterSetName)
            {
            case LifecycleStateParamSet:
                response = client.Waiters.ForConfiguration(request, waiterConfig, WaitForLifecycleState).Execute();
                break;

            case Default:
                response = client.GetConfiguration(request).GetAwaiter().GetResult();
                break;
            }
            WriteOutput(response, response.Configuration);
        }
        protected override void ProcessRecord()
        {
            base.ProcessRecord();
            GetConfigurationRequest request;

            try
            {
                request = new GetConfigurationRequest
                {
                    CompartmentId = CompartmentId
                };

                response = client.GetConfiguration(request).GetAwaiter().GetResult();
                WriteOutput(response, response.Configuration);
                FinishProcessing(response);
            }
            catch (Exception ex)
            {
                TerminatingErrorDuringExecution(ex);
            }
        }
Ejemplo n.º 19
0
        protected override void ProcessRecord()
        {
            base.ProcessRecord();
            GetConfigurationRequest request;

            try
            {
                request = new GetConfigurationRequest
                {
                    ConfigurationId = ConfigurationId,
                    OpcRequestId    = OpcRequestId,
                    IfNoneMatch     = IfNoneMatch
                };

                HandleOutput(request);
                FinishProcessing(response);
            }
            catch (Exception ex)
            {
                TerminatingErrorDuringExecution(ex);
            }
        }
Ejemplo n.º 20
0
        public async Task <ActionResult <IEnumerable <string> > > Get()
        {
#if false
            try {
                var medaitorClient = this._MedaitorAccess.GetMedaitorClient();
                var arguments      = new GetConfigurationRequest();
                var ctxt           = medaitorClient.CreateContextByRequest(arguments);
                await medaitorClient.ExecuteAsync(ctxt, null, this.HttpContext.RequestAborted);

                return(ctxt.ReturnAsActionResult <IEnumerable <string> >());
            } catch (System.Exception error) {
                return(this.StatusCode(500, error.Message));
            }
            try {
                var request = new GetConfigurationRequest();
                using var client    = this._MedaitorAccess.GetMedaitorClient();
                using var connected = await client.ConnectAsync(request, this.HttpContext.RequestAborted);

                var response = await connected.WaitForAsync(null, this.HttpContext.RequestAborted);

                return(response.ConvertResponseToActionResult <GetConfigurationResponse, IEnumerable <string> >((r) => r.Result));
            } catch (System.Exception error) {
                return(this.StatusCode(500, error.Message));
            }
#endif
            var request = new GetConfigurationRequest();


            return(await RequestResponseHelper <GetConfigurationRequest, GetConfigurationResponse> .
                   ExecuteToActionResultAsync <IEnumerable <string> >(
                       this.GetMedaitorClient(),
                       ActivityId.NewId(),
                       request,
                       (r) => r.Result,
                       null, //ActivityWaitForSpecification.,
                       this.HttpContext.RequestAborted
                       ));
        }
Ejemplo n.º 21
0
 public override void GetConfiguration(IRpcController controller, GetConfigurationRequest request, Action <GetConfigurationResponse> done)
 {
     ProtoOutputBuffer.Write(request.GetType(), request.ToString());
 }
Ejemplo n.º 22
0
 /// <summary>
 /// Calls the Jetstream v1.1 GetConfiguration REST endpoint
 /// https://www.jetstreamrfid.com/Documentation/GetConfiguration
 /// </summary>
 /// <param name="request">Object that represents the HTTP Jetstream request</param>
 /// <returns>Object that represents the HTTP Jetstream response</returns>
 /// <exception cref="System.ArgumentNullException">
 /// <para><paramref name="request"/> is null</para>
 /// </exception>
 public GetConfigurationResponse GetConfiguration(GetConfigurationRequest request)
 {
     return(Execute <GetConfigurationResponse>(request));
 }
Ejemplo n.º 23
0
 public override void GetConfiguration(IRpcController controller, GetConfigurationRequest request, Action<GetConfigurationResponse> done)
 {
     done(new GetConfigurationResponse.Builder().Build());
 }
Ejemplo n.º 24
0
 public override void GetConfiguration(IRpcController controller, GetConfigurationRequest request, Action<GetConfigurationResponse> done)
 {
     ProtoOutputBuffer.Write(request.GetType(), request.ToString());
 }
Ejemplo n.º 25
0
 public override void GetConfiguration(Google.ProtocolBuffers.IRpcController controller, GetConfigurationRequest request, Action <GetConfigurationResponse> done)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 26
0
 public override void GetConfiguration(IRpcController controller, GetConfigurationRequest request, Action <GetConfigurationResponse> done)
 {
     done(new GetConfigurationResponse.Builder().Build());
 }
Ejemplo n.º 27
0
		public override void GetConfiguration(Google.ProtocolBuffers.IRpcController controller, GetConfigurationRequest request, Action<GetConfigurationResponse> done) {
			throw new NotImplementedException();
		}
Ejemplo n.º 28
0
 public override void GetConfiguration(IRpcController controller, GetConfigurationRequest request, Action<GetConfigurationResponse> done)
 {
     Logger.Trace("GetConfiguration()");
     var builder = GetConfigurationResponse.CreateBuilder();
     done(builder.Build());
 }
Ejemplo n.º 29
0
        /// <summary>
        /// Creates a waiter using the provided configuration.
        /// </summary>
        /// <param name="request">Request to send.</param>
        /// <param name="config">Wait Configuration</param>
        /// <param name="targetStates">Desired resource states. If multiple states are provided then the waiter will return once the resource reaches any of the provided states</param>
        /// <returns>a new Oci.common.Waiter instance</returns>
        public Waiter <GetConfigurationRequest, GetConfigurationResponse> ForConfiguration(GetConfigurationRequest request, WaiterConfiguration config, params Configuration.LifecycleStateEnum[] targetStates)
        {
            var agent = new WaiterAgent <GetConfigurationRequest, GetConfigurationResponse>(
                request,
                request => client.GetConfiguration(request),
                response => targetStates.Contains(response.Configuration.LifecycleState.Value),
                targetStates.Contains(Configuration.LifecycleStateEnum.Deleted)
                );

            return(new Waiter <GetConfigurationRequest, GetConfigurationResponse>(config, agent));
        }
Ejemplo n.º 30
0
 /// <summary>
 /// Creates a waiter using default wait configuration.
 /// </summary>
 /// <param name="request">Request to send.</param>
 /// <param name="targetStates">Desired resource states. If multiple states are provided then the waiter will return once the resource reaches any of the provided states</param>
 /// <returns>a new Oci.common.Waiter instance</returns>
 public Waiter <GetConfigurationRequest, GetConfigurationResponse> ForConfiguration(GetConfigurationRequest request, params Configuration.LifecycleStateEnum[] targetStates)
 {
     return(this.ForConfiguration(request, WaiterConfiguration.DefaultWaiterConfiguration, targetStates));
 }
Ejemplo n.º 31
0
        public static async Task Main()
        {
            logger.Info("Starting example");
            AuditClient client = null;

            try
            {
                // Assumption: the compartment id has been set in environment variable.
                var compartmentId = Environment.GetEnvironmentVariable("OCI_COMPARTMENT_ID");
                logger.Info(compartmentId);

                // ListEvents
                var listEventsRequest = new ListEventsRequest
                {
                    CompartmentId = compartmentId,
                    StartTime     = DateTime.Now.AddDays(-1),
                    EndTime       = DateTime.Now
                };

                // Create AuditClient
                var provider = new ConfigFileAuthenticationDetailsProvider("DEFAULT");

                using (client = new AuditClient(provider, new ClientConfiguration()))
                {
                    logger.Info("AuditClient created.");

                    ListEventsResponse listEventsResp = await NoRetryExample(client, listEventsRequest);

                    logger.Info($"Received {listEventsResp?.Items.Count} items");

                    ListEventsResponse listEventsRespFromRetry = await RetryExample(client, listEventsRequest);

                    logger.Info($"Received {listEventsRespFromRetry?.Items.Count} items");

                    await CancellationTokenExample(client, listEventsRequest);

                    // GetConfiguration
                    var getConfigurationRequest = new GetConfigurationRequest
                    {
                        CompartmentId = compartmentId
                    };

                    logger.Info("GetConfigurationRequest created.");

                    GetConfigurationResponse getConfigurationResp = await client.GetConfiguration(getConfigurationRequest);

                    logger.Info($"Retention period days: {getConfigurationResp?.Configuration.RetentionPeriodDays}");

                    // UpdateConfiguration
                    var updateConfigurationRequest = new UpdateConfigurationRequest
                    {
                        CompartmentId = compartmentId,
                        UpdateConfigurationDetails = new UpdateConfigurationDetails
                        {
                            RetentionPeriodDays = 90
                        }
                    };

                    logger.Info("UpdateConfigurationRequest created.");

                    UpdateConfigurationResponse updateConfigurationResp = await client.UpdateConfiguration(updateConfigurationRequest);

                    logger.Info($"opc work request id: {updateConfigurationResp.OpcRequestId}");
                }
            }
            catch (Exception e)
            {
                logger.Error($"Failed Audit example: {e.Message}");
            }
        }
Ejemplo n.º 32
0
        public async Task <IActionResult> GetConfiguration(GetConfigurationRequest input)
        {
            if (_logger.IsEnabled(LogLevel.Trace))
            {
                _logger.LogTrace($"{nameof(GetConfiguration)}:  {GetConfigurationRequest.VERB}");
            }

            if (!ModelState.IsValid)
            {
                return(base.BadRequest(ModelState));
            }

            if (_logger.IsEnabled(LogLevel.Debug))
            {
                _logger.LogDebug($"AgentId=[{input.AgentId}] Configuration=[{input.ConfigurationName}]");
            }

            // TODO:
            // Strictly speaking, this may not be how the DSCPM
            // protocol is supposed to resolve the config name
            var configName = input.ConfigurationName ?? input.ConfigurationNameHeader;

            if (string.IsNullOrEmpty(configName))
            {
                return(base.BadRequest("empty or missing configuration name"));
            }

            var cfgS3Key = $"{_settings.S3KeyPrefixConfigurations}/{configName}.mof";

            // We can't simply try to get the S3 object that corresponds to the
            // config name being requested because if it doesn't exist, we see
            // Amazon.S3.AmazonS3Exception with an underlying message of Access Denied;
            // instead we try to list the object first, and if it's not there, we
            // can response to the node appropriately with our own error protocol
            var listResp = await _s3.ListObjectsV2Async(new ListObjectsV2Request
            {
                BucketName = _settings.S3Bucket,
                Prefix     = cfgS3Key,
                MaxKeys    = 1,
            });

            var firstS3Obj = listResp.S3Objects.FirstOrDefault();

            if (_logger.IsEnabled(LogLevel.Debug))
            {
                _logger.LogDebug("Request to list S3 objects matching requested config found"
                                 + " [{s3KeyCount}] keys, first is [{s3Key}]", listResp.KeyCount,
                                 firstS3Obj?.Key);
            }

            if (listResp.KeyCount < 1 || firstS3Obj.Key != cfgS3Key)
            {
                _logger.LogWarning($"failed to get configuration by object key [{cfgS3Key}]:");
                return(NotFound());
            }

            using (var getResp = await _s3.GetObjectAsync(_settings.S3Bucket, cfgS3Key))
            {
                // Because of the preceding ListObjects call,
                // this should never happen, but just in case...
                if (getResp == null || getResp.ContentLength == 0 ||
                    getResp.HttpStatusCode != HttpStatusCode.OK)
                {
                    _logger.LogWarning($"failed to get configuration by object key [{cfgS3Key}]:"
                                       + $" contentLen=[{getResp?.ContentLength}]"
                                       + $" httpStatus=[{getResp.HttpStatusCode}]");
                    return(NotFound());
                }

                if (_logger.IsEnabled(LogLevel.Debug))
                {
                    _logger.LogDebug($"got configuration by object key [{cfgS3Key}]:"
                                     + $" contentLen=[{getResp?.ContentLength}]"
                                     + $" httpStatus=[{getResp.HttpStatusCode}]");
                }

                using (var rs = getResp.ResponseStream)
                    using (var rawMs = new MemoryStream())
                    {
                        await rs.CopyToAsync(rawMs);

                        if (_logger.IsEnabled(LogLevel.Debug))
                        {
                            _logger.LogDebug("buffered configuration content of size [{buffLen}]", rawMs.Length);
                        }

                        // Make sure we're at the start of the stream to compute the checksum
                        rawMs.Position = 0;
                        var rawBytes = rawMs.ToArray();
                        var checksum = ComputeChecksum(rawBytes);

                        // This will be disposed of by the MVC framework
                        var b64Ms = new MemoryStream(Encoding.UTF8.GetBytes(
                                                         Convert.ToBase64String(rawBytes)));

                        return(this.Model(new GetConfigurationResponse
                        {
                            ChecksumAlgorithmHeader = ChecksumAlgorithm,
                            ChecksumHeader = checksum,
                            Configuration = b64Ms,
                        }));
                    }
            }
        }