public override void ExecuteCmdlet() { if (ParameterSetName.Equals(InputObjectParameterSet)) { this.ResourceGroupName = this.InputObject.Resourcegroup; this.Name = this.InputObject.Name; } if (ParameterSetName.Equals(ResourceIdParameterSet)) { this.ResourceGroupName = IotHubUtils.GetResourceGroupName(this.ResourceId); this.Name = IotHubUtils.GetIotHubName(this.ResourceId); } if (ShouldProcess(this.Name, Properties.Resources.ManualFailoverIotHub)) { IotHubDescription iotHubDescription = this.IotHubClient.IotHubResource.Get(this.ResourceGroupName, this.Name); PSIotHub psIotHub = IotHubUtils.ToPSIotHub(iotHubDescription); string failoverRegion = psIotHub.Properties.Locations.FirstOrDefault(loc => loc.Role.Equals("secondary", StringComparison.OrdinalIgnoreCase)).Location; FailoverInput failoverInput = new FailoverInput(failoverRegion); this.IotHubClient.IotHub.ManualFailover(this.Name, this.ResourceGroupName, failoverInput.FailoverRegion); if (this.PassThru.IsPresent) { WriteObject(true); } } }
public void TestIotHubCreateLifeCycle() { using (MockContext context = MockContext.Start(this.GetType().FullName)) { this.Initialize(context); // Create Resource Group var resourceGroup = this.CreateResourceGroup(IotHubTestUtilities.DefaultResourceGroupName); // Check if Hub Exists and Delete var operationInputs = new OperationInputs() { Name = IotHubTestUtilities.DefaultIotHubName }; var iotHubNameAvailabilityInfo = this.iotHubClient.IotHubResource.CheckNameAvailability(operationInputs); if (!(bool)iotHubNameAvailabilityInfo.NameAvailable) { this.iotHubClient.IotHubResource.Delete( IotHubTestUtilities.DefaultResourceGroupName, IotHubTestUtilities.DefaultIotHubName); iotHubNameAvailabilityInfo = this.iotHubClient.IotHubResource.CheckNameAvailability(operationInputs); Assert.True(iotHubNameAvailabilityInfo.NameAvailable); } //CreateEH and AuthRule var properties = new IotHubProperties(); properties.Routing = this.GetIotHubRoutingProperties(resourceGroup); var iotHub = this.CreateIotHub(resourceGroup, IotHubTestUtilities.DefaultLocation, IotHubTestUtilities.DefaultIotHubName, properties); Assert.NotNull(iotHub); Assert.Equal(IotHubSku.S1, iotHub.Sku.Name); Assert.Equal(IotHubTestUtilities.DefaultIotHubName, iotHub.Name); // Add and Get Tags IDictionary <string, string> tags = new Dictionary <string, string>(); tags.Add("key1", "value1"); tags.Add("key2", "value2"); var tag = new TagsResource(tags); iotHub = this.iotHubClient.IotHubResource.Update(IotHubTestUtilities.DefaultResourceGroupName, IotHubTestUtilities.DefaultIotHubName, tag); Assert.NotNull(iotHub); Assert.True(iotHub.Tags.Count().Equals(2)); Assert.Equal("value2", iotHub.Tags["key2"]); var subscriptionQuota = this.iotHubClient.ResourceProviderCommon.GetSubscriptionQuota(); Assert.Equal(2, subscriptionQuota.Value.Count); Assert.Equal(1, subscriptionQuota.Value.FirstOrDefault(x => x.Name.Value.Equals("freeIotHubCount")).Limit); Assert.Equal(100, subscriptionQuota.Value.FirstOrDefault(x => x.Name.Value.Equals("paidIotHubCount")).Limit); var endpointHealth = this.iotHubClient.IotHubResource.GetEndpointHealth(IotHubTestUtilities.DefaultResourceGroupName, IotHubTestUtilities.DefaultIotHubName); Assert.Equal(4, endpointHealth.Count()); Assert.Contains(endpointHealth, q => q.EndpointId.Equals("events", StringComparison.OrdinalIgnoreCase)); TestAllRoutesInput testAllRoutesInput = new TestAllRoutesInput(RoutingSource.DeviceMessages, new RoutingMessage(), new RoutingTwin()); TestAllRoutesResult testAllRoutesResult = this.iotHubClient.IotHubResource.TestAllRoutes(testAllRoutesInput, IotHubTestUtilities.DefaultIotHubName, IotHubTestUtilities.DefaultResourceGroupName); Assert.Equal(4, testAllRoutesResult.Routes.Count); TestRouteInput testRouteInput = new TestRouteInput(properties.Routing.Routes[0], new RoutingMessage(), new RoutingTwin()); TestRouteResult testRouteResult = this.iotHubClient.IotHubResource.TestRoute(testRouteInput, IotHubTestUtilities.DefaultIotHubName, IotHubTestUtilities.DefaultResourceGroupName); Assert.Equal("true", testRouteResult.Result); // Get quota metrics var quotaMetrics = this.iotHubClient.IotHubResource.GetQuotaMetrics( IotHubTestUtilities.DefaultResourceGroupName, IotHubTestUtilities.DefaultIotHubName); Assert.True(quotaMetrics.Count() > 0); Assert.Contains(quotaMetrics, q => q.Name.Equals("TotalMessages", StringComparison.OrdinalIgnoreCase) && q.CurrentValue == 0 && q.MaxValue == 400000); Assert.Contains(quotaMetrics, q => q.Name.Equals("TotalDeviceCount", StringComparison.OrdinalIgnoreCase) && q.CurrentValue == 0 && q.MaxValue == 1000000); // Get all Iot Hubs in a resource group var iotHubs = this.iotHubClient.IotHubResource.ListByResourceGroup(IotHubTestUtilities.DefaultResourceGroupName); Assert.True(iotHubs.Count() > 0); // Get all Iot Hubs in a subscription var iotHubBySubscription = this.iotHubClient.IotHubResource.ListBySubscription(); Assert.True(iotHubBySubscription.Count() > 0); // Get Registry Stats var regStats = this.iotHubClient.IotHubResource.GetStats(IotHubTestUtilities.DefaultResourceGroupName, IotHubTestUtilities.DefaultIotHubName); Assert.True(regStats.TotalDeviceCount.Value.Equals(0)); Assert.True(regStats.EnabledDeviceCount.Value.Equals(0)); Assert.True(regStats.DisabledDeviceCount.Value.Equals(0)); // Get Valid Skus var skus = this.iotHubClient.IotHubResource.GetValidSkus( IotHubTestUtilities.DefaultResourceGroupName, IotHubTestUtilities.DefaultIotHubName); Assert.Equal(3, skus.Count()); // Get All Iothub Keys var keys = this.iotHubClient.IotHubResource.ListKeys( IotHubTestUtilities.DefaultResourceGroupName, IotHubTestUtilities.DefaultIotHubName); Assert.True(keys.Count() > 0); Assert.Contains(keys, k => k.KeyName.Equals("iothubowner", StringComparison.OrdinalIgnoreCase)); // Get specific IotHub Key var key = this.iotHubClient.IotHubResource.GetKeysForKeyName( IotHubTestUtilities.DefaultResourceGroupName, IotHubTestUtilities.DefaultIotHubName, "iothubowner"); Assert.Equal("iothubowner", key.KeyName); // Get All EH consumer groups var ehConsumerGroups = this.iotHubClient.IotHubResource.ListEventHubConsumerGroups( IotHubTestUtilities.DefaultResourceGroupName, IotHubTestUtilities.DefaultIotHubName, IotHubTestUtilities.EventsEndpointName); Assert.True(ehConsumerGroups.Count() > 0); Assert.Contains(ehConsumerGroups, e => e.Name.Equals("$Default", StringComparison.OrdinalIgnoreCase)); // Add EH consumer group var ehConsumerGroup = this.iotHubClient.IotHubResource.CreateEventHubConsumerGroup( IotHubTestUtilities.DefaultResourceGroupName, IotHubTestUtilities.DefaultIotHubName, IotHubTestUtilities.EventsEndpointName, "testConsumerGroup"); Assert.Equal("testConsumerGroup", ehConsumerGroup.Name); // Get EH consumer group ehConsumerGroup = this.iotHubClient.IotHubResource.GetEventHubConsumerGroup( IotHubTestUtilities.DefaultResourceGroupName, IotHubTestUtilities.DefaultIotHubName, IotHubTestUtilities.EventsEndpointName, "testConsumerGroup"); Assert.Equal("testConsumerGroup", ehConsumerGroup.Name); // Delete EH consumer group this.iotHubClient.IotHubResource.DeleteEventHubConsumerGroup( IotHubTestUtilities.DefaultResourceGroupName, IotHubTestUtilities.DefaultIotHubName, IotHubTestUtilities.EventsEndpointName, "testConsumerGroup"); // Get all of the available IoT Hub REST API operations var operationList = this.iotHubClient.Operations.List(); Assert.True(operationList.Count() > 0); Assert.Contains(operationList, e => e.Name.Equals("Microsoft.Devices/iotHubs/Read", StringComparison.OrdinalIgnoreCase)); // Get IoT Hub REST API read operation var hubReadOperation = operationList.Where(e => e.Name.Equals("Microsoft.Devices/iotHubs/Read", StringComparison.OrdinalIgnoreCase)); Assert.True(hubReadOperation.Count().Equals(1)); Assert.Equal("Microsoft Devices", hubReadOperation.First().Display.Provider, ignoreCase: true); Assert.Equal("Get IotHub(s)", hubReadOperation.First().Display.Operation, ignoreCase: true); // Initiate manual failover var iotHubBeforeFailover = this.iotHubClient.IotHubResource.Get( IotHubTestUtilities.DefaultResourceGroupName, IotHubTestUtilities.DefaultIotHubName); var failoverInput = new FailoverInput(IotHubTestUtilities.DefaultFailoverLocation); this.iotHubClient.IotHub.ManualFailover(IotHubTestUtilities.DefaultIotHubName, failoverInput, IotHubTestUtilities.DefaultResourceGroupName); var iotHubAfterFailover = this.iotHubClient.IotHubResource.Get( IotHubTestUtilities.DefaultResourceGroupName, IotHubTestUtilities.DefaultIotHubName); Assert.Equal("primary", iotHubBeforeFailover.Properties.Locations[0].Role.ToLower()); Assert.Equal(IotHubTestUtilities.DefaultLocation.ToLower(), iotHubBeforeFailover.Properties.Locations[0].Location.Replace(" ", "").ToLower()); Assert.Equal("secondary", iotHubBeforeFailover.Properties.Locations[1].Role.ToLower()); Assert.Equal(IotHubTestUtilities.DefaultFailoverLocation.ToLower(), iotHubBeforeFailover.Properties.Locations[1].Location.Replace(" ", "").ToLower()); Assert.Equal("primary", iotHubAfterFailover.Properties.Locations[0].Role.ToLower()); Assert.Equal(IotHubTestUtilities.DefaultFailoverLocation.ToLower(), iotHubAfterFailover.Properties.Locations[0].Location.Replace(" ", "").ToLower()); Assert.Equal("secondary", iotHubAfterFailover.Properties.Locations[1].Role.ToLower()); Assert.Equal(IotHubTestUtilities.DefaultLocation.ToLower(), iotHubAfterFailover.Properties.Locations[1].Location.Replace(" ", "").ToLower()); } }
/// <summary> /// Manual Failover Fail over /// </summary> /// <remarks> /// Perform manual fail over of given hub /// </remarks> /// <param name='iotHubName'> /// IotHub to fail over /// </param> /// <param name='failoverInput'> /// Region to failover to. Must be a azure DR pair /// </param> /// <param name='resourceGroupName'> /// resource group which Iot Hub belongs to /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorDetailsException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task <AzureOperationResponse <IotHubDescription> > ManualFailoverWithHttpMessagesAsync(string iotHubName, FailoverInput failoverInput, string resourceGroupName, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (iotHubName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "iotHubName"); } if (failoverInput == null) { throw new ValidationException(ValidationRules.CannotBeNull, "failoverInput"); } if (failoverInput != null) { failoverInput.Validate(); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("iotHubName", iotHubName); tracingParameters.Add("failoverInput", failoverInput); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ManualFailover", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{iotHubName}/failover").ToString(); _url = _url.Replace("{iotHubName}", System.Uri.EscapeDataString(iotHubName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); List <string> _queryParameters = new List <string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach (var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if (failoverInput != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(failoverInput, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorDetailsException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorDetails _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <ErrorDetails>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse <IotHubDescription>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject <IotHubDescription>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
/// <summary> /// Manual Failover Fail over /// </summary> /// <remarks> /// Perform manual fail over of given hub /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='iotHubName'> /// IotHub to fail over /// </param> /// <param name='failoverInput'> /// Region to failover to. Must be a azure DR pair /// </param> /// <param name='resourceGroupName'> /// resource group which Iot Hub belongs to /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task <IotHubDescription> ManualFailoverAsync(this IIotHubOperations operations, string iotHubName, FailoverInput failoverInput, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ManualFailoverWithHttpMessagesAsync(iotHubName, failoverInput, resourceGroupName, null, cancellationToken).ConfigureAwait(false)) { return(_result.Body); } }
/// <summary> /// Manual Failover Fail over /// </summary> /// <remarks> /// Perform manual fail over of given hub /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='iotHubName'> /// IotHub to fail over /// </param> /// <param name='failoverInput'> /// Region to failover to. Must be a azure DR pair /// </param> /// <param name='resourceGroupName'> /// resource group which Iot Hub belongs to /// </param> public static IotHubDescription ManualFailover(this IIotHubOperations operations, string iotHubName, FailoverInput failoverInput, string resourceGroupName) { return(operations.ManualFailoverAsync(iotHubName, failoverInput, resourceGroupName).GetAwaiter().GetResult()); }
/// <summary> /// Manual Failover Fail over /// </summary> /// <remarks> /// Perform manual fail over of given hub /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='iotHubName'> /// IotHub to fail over /// </param> /// <param name='failoverInput'> /// Region to failover to. Must be a azure DR pair /// </param> /// <param name='resourceGroupName'> /// resource group which Iot Hub belongs to /// </param> public static void BeginManualFailover(this IIotHubOperations operations, string iotHubName, FailoverInput failoverInput, string resourceGroupName) { operations.BeginManualFailoverAsync(iotHubName, failoverInput, resourceGroupName).GetAwaiter().GetResult(); }
/// <summary> /// Manual Failover Fail over /// </summary> /// <remarks> /// Perform manual fail over of given hub /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='iotHubName'> /// IotHub to fail over /// </param> /// <param name='failoverInput'> /// Region to failover to. Must be a azure DR pair /// </param> /// <param name='resourceGroupName'> /// resource group which Iot Hub belongs to /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task ManualFailoverAsync(this IIotHubOperations operations, string iotHubName, FailoverInput failoverInput, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.ManualFailoverWithHttpMessagesAsync(iotHubName, failoverInput, resourceGroupName, null, cancellationToken).ConfigureAwait(false)).Dispose(); }
/// <summary> /// Manual Failover Fail over /// </summary> /// <remarks> /// Perform manual fail over of given hub /// </remarks> /// <param name='iotHubName'> /// IotHub to fail over /// </param> /// <param name='failoverInput'> /// Region to failover to. Must be a azure DR pair /// </param> /// <param name='resourceGroupName'> /// resource group which Iot Hub belongs to /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task <AzureOperationResponse> ManualFailoverWithHttpMessagesAsync(string iotHubName, FailoverInput failoverInput, string resourceGroupName, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationResponse _response = await BeginManualFailoverWithHttpMessagesAsync(iotHubName, failoverInput, resourceGroupName, customHeaders, cancellationToken).ConfigureAwait(false); return(await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false)); }