Beispiel #1
0
        public async Task <RestApiResponse> ExecutePost(RestApiRequest apiRequest)
        {
            HttpClient client = new HttpClient();

            foreach (var entry in apiRequest.ReqHeaders)
            {
                client.DefaultRequestHeaders.Add(entry.Key, entry.Value);
            }

            HttpRequestMessage reqMsg =
                new HttpRequestMessage(HttpMethod.Post, new Uri(apiRequest.AzureEndPoint));
            HttpResponseMessage response = await client.SendAsync(reqMsg);

            RestApiResponse apiResponse = new RestApiResponse();

            apiResponse.StatusCode = response.StatusCode;

            if (!response.IsSuccessStatusCode)
            {
                apiResponse.ReasonPhrase = response.ReasonPhrase;
            }

            apiResponse.Response = await response.Content.ReadAsStringAsync();

            apiResponse.ContentHeaders  = response.Content.Headers;
            apiResponse.ResponseHeaders = response.Headers;

            return(apiResponse);
        }
        // public static async Task Run([TimerTrigger("0 */1 * * * *")]TimerInfo myTimer, ILogger log)
        public static async Task Run([TimerTrigger("%VmssTriggerSchedule%")] TimerInfo myTimer, ILogger log)
        {
            log.LogInformation($"***** AksVmssScaleTrigger - Start Time: {DateTime.Now}");

            Dictionary <string, string> envVars = new Dictionary <string, string>();

            new ParseAzureADInputs().GetEnvVars(ref envVars);
            envVars.Add(AzureAdEnvConstants.OAUTH_GRANT_TYPE, "client_credentials");

            string adTokenEpUri =
                envVars[AzureAdEnvConstants.AZURE_AD_TOKEN_EP] + "/" +
                envVars[AzureAdEnvConstants.AZURE_AD_TENANT_ID] + "/oauth2/token";

            log.LogInformation($"***** AksVmssScaleTrigger - AD Endpoint URI: {adTokenEpUri}");

            AdTokenResponse token = await AdTokenFactory.GetToken(envVars);

            log.LogInformation($"***** AksVmssScaleTrigger - Access Token: {token.AccessToken}");

            new ParseAzureInputs().GetEnvVars(ref envVars);
            new ParseAzureVMssInputs().GetEnvVars(ref envVars);

            RestApiRequest request = new RestApiRequest();

            try {
                /* request.AzureEndPoint =
                 * string.Format(AzureEnvConstants.AZURE_MGMT_API_EP,subId,rgName) +
                 * "Microsoft.Compute/virtualMachineScaleSets?api-version=" + vmssVersion; */

                request.AzureEndPoint =
                    string.Format(
                        AzureEnvConstants.AZURE_MGMT_API_EP,
                        envVars[AzureEnvConstants.AZURE_SUBSCRIPTION_ID],
                        envVars[AzureEnvConstants.AZURE_RES_GROUP_NAME]) +
                    "Microsoft.Compute/virtualMachineScaleSets/" +
                    envVars[AzureVMssConstants.AZURE_VMSS_NAME] +
                    string.Format(
                        "/{0}?api-version={1}",
                        envVars[AzureVMssConstants.AZURE_VMSS_ACTION],
                        envVars[AzureVMssConstants.AZURE_VMSS_API_VER]);

                log.LogInformation($"***** AksVmssScaleTrigger - Azure API URI: {request.AzureEndPoint}");

                request.ReqHeaders.Add("Authorization", string.Format("Bearer {0}", token.AccessToken));

                IRestApiOperations vmssApi = new AzVmssApiOperations();
                // RestApiResponse response = await vmssApi.ExecuteGet(request);
                RestApiResponse response = await vmssApi.ExecutePost(request);

                if (!string.IsNullOrEmpty(response.ReasonPhrase))
                {
                    throw new ApiOperationException(string.Format("Azure REST API call failed. Received HTTP status code: {0} ({1}), Response: {2}", (int)response.StatusCode, response.ReasonPhrase, response.Response));
                }

                log.LogInformation($"***** AksVmssScaleTrigger - API Response status: {response.StatusCode}, Response: {response.Response}");
            }
            catch (Exception exp)  // Catch HTTP Exceptions - Server down, connection refused ...
            {
                log.LogError($"***** AksVmssScaleTrigger - Encountered exception: {exp}");
            };

            log.LogInformation($"***** AksVmssScaleTrigger - End Time: {DateTime.Now}");
        }
Beispiel #3
0
        public IRoadStatus GetStatus(string roadId)
        {
            if (string.IsNullOrEmpty(roadId))
            {
                throw new ArgumentNullException(paramName: nameof(roadId), message: $"A valid {nameof(roadId)} must be supplied");
            }

            var roadResource = this._tflApiSettings
                               ?.Resources
                               ?.FirstOrDefault(r => r.Name.Equals("road", StringComparison.OrdinalIgnoreCase))
                               ?.Value;

            if (roadResource == null)
            {
                throw new NullReferenceException($"A valid TFL road resource must be supplied");
            }

            var apiRequestConfig = new RestApiRequest()
            {
                BaseUrl        = this._tflApiSettings.BaseUrl,
                Resource       = roadResource,
                Authentication = new RestAuthentication
                {
                    UsernameIdentifier = this._tflApiSettings.Authentication.UsernameIdentifier,
                    Username           = this._tflApiSettings.Authentication.Username,
                    PasswordIdentifier = this._tflApiSettings.Authentication.PasswordIdentifier,
                    Password           = this._tflApiSettings.Authentication.Password,
                },
                Method      = RestMethod.GET,
                UrlSegments = new Dictionary <string, string> {
                    { "roadId", roadId }
                }
            };

            var lookupResponse = this._restApiCallService.ExecuteGet(apiRequestConfig);

            if (lookupResponse?.StatusCode == System.Net.HttpStatusCode.OK)
            {
                var result = JsonConvert.DeserializeObject <RoadStatusLookupSuccessResponse[]>(lookupResponse.Content);
                if (result != null && result.Length > 0)
                {
                    return(new RoadStatus
                    {
                        RequestedRoad = roadId,
                        DisplayName = result[0].DisplayName,
                        Status = result[0].StatusSeverity,
                        StatusDescription = result[0].StatusSeverityDescription,
                        ErrorCode = 0,
                        ErrorDescription = string.Empty
                    });
                }
            }

            if (lookupResponse?.StatusCode == System.Net.HttpStatusCode.NotFound)
            {
                var result = JsonConvert.DeserializeObject <RoadStatusLookupErrorResponse>(lookupResponse.Content);
                if (result != null)
                {
                    return(new RoadStatus
                    {
                        RequestedRoad = roadId,
                        ValidRoad = false,
                        ErrorCode = result.HttpStatusCode,
                        ErrorDescription = result.Message
                    });
                }
            }

            return(null);
        }