Giter Club home page Giter Club logo

service-fabric-client-dotnet's Introduction

Service Fabric Client Library for .NET and PowerShell module

REST based Client library and PowerShell module for managing Service Fabric clusters and applications.

This repo builds the following nuget packages and powershell modules:

For more Service Fabric open source projects, visit the Service Fabric home repo.

Getting Started

Prerequesites

Each project is a normal C# Visual Studio 2019 project. At minimum, you need MSBuild 16, PowerShell, .NET Core SDK and .NET Framework 4.6 to build and generate NuGet packages.

We recommend installing Visual Studio 2019 which will set you up with all the .NET build tools and allow you to open the solution files. Community Edition is free and can be used to build everything here.

Build

To build everything and generate NuGet packages, run the build.ps1 script. NuGet packages and PowerShell module will be dropped in a drop directory at the repo root.

Each project can also be built individually directly through Visual Studio or by running the solution file through MSBuild.

For branches, please see Branching Information

Releases and Support

Official releases from Microsoft of the NuGet packages in this repo are released directly to NuGet.org.

Only officially released NuGet packages from Microsoft are supported. If you have a feature or bug fix that you would like to use in your application, please issue a pull request so we can get it into an official release.

Contributing code

If you would like to become an active contributor to this project please follow the instructions provided in Microsoft Azure Projects Contribution Guidelines.

For details on contributing to Service Fabric projects, please refer to Contributing.md at the Service Fabric home repo for details on contributing code.

Documentation

Service Fabric has conceptual and reference documentation available at https://docs.microsoft.com/azure/service-fabric.

service-fabric-client-dotnet's People

Contributors

al3891 avatar allanfunrock avatar amanbha avatar anantshankar17 avatar craftyhouse avatar dependabot[bot] avatar fedeoliv avatar geperez avatar jeffj6123 avatar jijohn14 avatar microsoft-github-policy-service[bot] avatar microsoftopensource avatar msftgits avatar ndrwrbgs avatar olegkarasik avatar pepijngramberg avatar samneirinck avatar thomas-hammond avatar vladalex1000 avatar vturecek avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

service-fabric-client-dotnet's Issues

"A task was canceled." error executing Copy-SFApplicationPackage

Is your feature request related to a problem? Please describe.
Yes. When using Copy-SFApplicationPackage to copy a larger package, the cmdlet times out and cancels the copy. The result is only a partial copy of the package to the Image Store. So, the application can't be used. Example/repro:

Copy-SFApplicationPackage -ApplicationPackagePath -ApplicationPackagePathInImageStore
A task was canceled.

We are seeing this error for our package that is ~ 51MB. It's possible the issue occurs for smaller packages. Note that no stack error is returned, just the "A task was canceled." message. It seems the default time in this cmdlet is too small.

Describe the solution you'd like
Add a timeout parameter is added to Copy-SFApplicationPackage. Thus, we can increase the timeout to try to avoid this issue.

Describe alternatives you've considered
None.

Additional context
None.

No Idea what I need to provide as the ConfigurationApiVersion for Get-SfClusterConfiguration

Cluseter version: 7.1.458.9590

Get-SfClusterConfiguration has a mandatory parameter ConfigurationApiVersion
I have no idea what I should be putting in here, I have tried our current Config Version, Code Version, api version. Everything comes back with a NotSupportedException.

PS C:\Windows\System32> Get-SFClusterConfiguration -ConfigurationApiVersion "3.0"
Get-SFClusterConfiguration: System.Runtime.InteropServices.COMException (-2147017627)
NotSupportedException: 3.0 is not supported!

PS C:\Windows\System32> Get-SFClusterConfiguration -ConfigurationApiVersion "363"
Get-SFClusterConfiguration: System.Runtime.InteropServices.COMException (-2147017627)
NotSupportedException: 363 is not supported!

PS C:\Windows\System32> Get-SFClusterConfiguration -ConfigurationApiVersion $null
Get-SFClusterConfiguration: Cannot bind argument to parameter 'ConfigurationApiVersion' because it is null.
PS C:\Windows\System32> Get-SFClusterConfiguration -ConfigurationApiVersion ""
Get-SFClusterConfiguration: Cannot bind argument to parameter 'ConfigurationApiVersion' because it is an empty string.

The best docs that I can find on this are https://docs.microsoft.com/en-us/rest/api/servicefabric/sfclient-api-getclusterconfiguration

"The API version of the Standalone cluster json configuration."

Really not sure what this means...

Please could you either update the docs to give us a fighting chance of working out what this should be or just make this work like the old command Get-ServiceFabricClusterConfiguration where this value was not required at all...

Cheers.

Missing details in documentation on how to connect from PowerShell

Describe the bug

Maybe an alternative title could be - how to connect given that I have the Az-Context with permissions to manage the cluster?

I am trying to connect from an Azure Automation account in a similar fashion to Az.ServiceFabric, but have not been successful following the documentation. The Az.ServiceFabric command will only update services made with ARM templates, so I am trying my luck using this library.

Using Az.ServiceFabric
we can connect to Service fabric from Azure Automation accounts by setting the Az context and then running commands.

Connect-AzAccount `
    -ServicePrincipal `
    -Tenant $ServicePrincipalConnection.TenantId `
    -ApplicationId $ServicePrincipalConnection.ApplicationId `
    -CertificateThumbprint $ServicePrincipalConnection.CertificateThumbprint

Get-AzSubscription -SubscriptionName $SubscriptionName -TenantId $ServicePrincipalConnection.TenantId | Set-AzContext

I am trying to use this package from Azure Automation and connection following Connect-SFCluster, but struggling to figure out how to make it work in a similar fashion.

I have tried to connect using

Connect-SFCluster -ConnectionEndpoint $ServiceFabricConnectionEndpoint `
                  -AzureActiveDirectory `
                  -ServerCertThumbprint $ServicePrincipalConnection.CertificateThumbprint `
                  -ClientTimeout 90 

but it fails with

System.EntryPointNotFoundException: Unable to find an entry point named 'GetPerAdapterInfo' in DLL 'iphlpapi.dll'.
   at Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.Platform.WebUI.<AcquireAuthorizationAsync>d__12.MoveNext()
--- End of stack trace from previous location where exception was thrown ---

I have also tried supplying "the AAD Token" as mentioned in the documentation, but I am not sure which excact token this is, scope etc, so all my attempts have failed. Since I was already connected with az I was hoping to use Get-AzAccessToken and supply it directly as mentioned here.

For example, I have tried with

$securityToken = Get-AzAccessToken -TenantId  $ServicePrincipalConnection.TenantId
Connect-SFCluster -ConnectionEndpoint $ServiceFabricConnectionEndpoint `
                  -AzureActiveDirectory `
                  -ServerCertThumbprint $ServicePrincipalConnection.CertificateThumbprint `
                  -ClientTimeout 90 `
                  -SecurityToken $securityToken.Token

. The token I get back looks OK, but it gives

Microsoft.ServiceFabric.Client.Exceptions.InvalidCredentialsException: Authorization error, invalid client credentials.
   at Microsoft.ServiceFabric.Client.Http.ServiceFabricHttpClient.<SendAsyncHandleSecurityExceptions>d__32.MoveNext() in D:\a\1\s\src\Microsoft.ServiceFabric.Client.Http\ServiceFabricHttpClient.cs:line 477
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.ServiceFabric.Client.Http.ServiceFabricHttpClient.<SendAsyncHandleUnsuccessfulResponse>d__31.MoveNext() in D:\a\1\s\src\Microsoft.ServiceFabric.Client.Http\ServiceFabricHttpClient.cs:line 402
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.ServiceFabric.Client.Http.ServiceFabricHttpClient.<SendAsyncGetResponse>d__27`1.MoveNext() in D:\a\1\s\src\Microsoft.ServiceFabric.Client.Http\ServiceFabricHttpClient.cs:line 233
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.ServiceFabric.Powershell.Http.ConnectClusterCmdlet.ProcessRecordInternal() in D:\a\1\s\src\Microsoft.ServiceFabric.Powershell.Http\ConnectClusterCmdlet.cs:line 324
   at Microsoft.ServiceFabric.Powershell.Http.CommonCmdletBase.ProcessRecord() in D:\a\1\s\src\Microsoft.ServiceFabric.Powershell.Http\CommonCmdletBase.cs:line 97
Authorization error, invalid client credentials.

To Reproduce
Create an Azure Automation account with a Runbook and a Service Fabric cluster.
Try to connect with the Connect-SFCluster command.

Expected behavior
Expecting to connect to the cluster.

JsonReaderException raised from InfrastructureClient

Describe the bug
The following two InfrastructureClient APIs always fail with a Newtonsoft.Json.JsonReaderException when valid commands are passed in.

InfrastructureClient.InvokeInfrastructureQueryAsync()
InfrastructureClient.InvokeInfrastructureCommandAsync()

Microsoft.ServiceFabric.Common.Exceptions.ServiceFabricException: Failed to deserialize json response from server. ---> Newtonsoft.Json.JsonReaderException: Error reading string. Unexpected token: None.
   at Microsoft.ServiceFabric.Client.Http.JsonReaderExtensions.ReadValueAsString(JsonReader reader)
   at Microsoft.ServiceFabric.Client.Http.ServiceFabricHttpClient.<SendAsyncGetResponse>d__26`1.MoveNext()

To Reproduce

IServiceFabricClient client = ...
var infraServices = await client.Services.GetServiceInfoListAsync("System", "InfrastructureServiceType");
foreach (var svc in infraServices.Data)
{
    string result1 = await client.Infrastructure.InvokeInfrastructureQueryAsync(queryCommand, svc.Id);
    string result2 = await client.Infrastructure.InvokeInfrastructureCommandAsync(adminCommand, svc.Id);
}

Expected behavior
These commands are expected to work when valid commands are passed in.

Additional context

The InvokeInfrastructureCommandAsync and InvokeInfrastructureQueryAsync APIs only return strings, presumably to support returning different kinds of JSON results for the different commands that can be passed in. So the APIs should just pass thru the raw JSON response content string to the caller, instead of trying to do any kind of special parsing or deserialization like what is happening in JsonReaderExtensions.ReadValueAsString(JsonReader).

Copy-SFApplicationPackage returns "The operation was canceled." with no indication why or docs explaining the issue

Describe the bug
When calling Copy-SFApplicationPackage, the majority of the time, a message "The operation was canceled." is returned, with no other information.
Of 8 attempts calls, I've seen one succeed, so the command is correct.

To Reproduce
Generate a pkg folder 205 MB in size.
Connect to a secure SF Cluster using cert thumbprint identification with Connect-SFCluster
Run command:
Copy-SFApplicationPackage -ApplicationPackagePath "PathToPkgFolder" -ApplicationPackagePathInImageStore "AppType"

Expected behavior
The command is successful the majority of the time and a useful error is returned when it fails.

Other client implementations

Currently the client library is partially set up such that a non http version of the client could be implemented. For example there is a factory method that is not specific to http.
However that factory method is currently hard coded to use the http specific implementation.

Are there other implementations planned for the foreseeable future? If not this abstraction layer seem to only add complexity and not offer much in return

Respones from cmdlets do not get piped to PowerShell output correctly

Describe the bug
If a cmdlet returns an error response, this is written to the host window instead of being written to the output stream.
This means that the output cannot be assigned to variables or added to a pipeline.

To Reproduce

$result = Copy-SFApplicationPackage -ApplicationPackagePath $PackagePath `
        -ApplicationPackagePathInImageStore $ApplicationType

Expected behavior
The response of the Copy-SFApplicationPackage cmdlet is written to $result.

Actual behavior
The response of the Copy-SFApplicationPackage cmdlet is written to the PowerShell host window and $result is $null.

Additional context
This is a particular problem for the cmdlet mentioned above "Copy-SFApplicationPackage" as there appears to be no Get-SFApplicationPackage cmdlet to check if the value was written successfully. The image store could be queried directly as a workaround but this is a deficiency in the module.

Get-SFClusterUpgradeProgress : Failed to deserialize json response from server

Describe the bug
When calling Get-SFClusterUpgradeProgress against a Cluster in the "Ready" state, the error below is thrown.
Service Fabric version: 6.5.664.9590

Get-SFClusterUpgradeProgress : Failed to deserialize json response from server.
At line:1 char:1
+ Get-SFClusterUpgradeProgress
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : NotSpecified: (:) [Get-SFClusterUpgradeProgress], ServiceFabricException
+ FullyQualifiedErrorId : GetClusterUpgradeProgressErrorId,Microsoft.ServiceFabric.Powershell.Http.GetClusterUpgradeProgressCmdlet

To Reproduce
Connect to a secure cluster.
Run Get-SFClusterUpgradeProgress

Expected behavior
A result is returned to the caller.

Services.UpdateServiceAsync can't change instance count.

Describe the bug

await client.Services.UpdateServiceAsync("ServiceFabricApp1~Stateless1", new StatelessServiceUpdateDescription(instanceCount: 5, defaultMoveCost: Microsoft.ServiceFabric.Common.MoveCost.Zero));

after the API returned succeed but nothing changed for the service in cluster explorer.

Do the same operation in PowerShell, the InstanceCount would be changed.
Update-ServiceFabricService -Stateless fabric:/ServiceFabricApp1/Stateless1 -InstanceCount 5

To Reproduce
Steps or code snippet to reproduce the behavior.
Func<CancellationToken, Task> GetSecurityCredentials = (ct) =>
{
// get the X509Certificate2 either from Certificate store or from file.
var clientCert = new System.Security.Cryptography.X509Certificates.X509Certificate2(@"C:\Users\jchiou\jackysf320191031213903.pfx", "Password01!");
var remoteSecuritySettings = new RemoteX509SecuritySettings(new List { "8AB797576F2EF93574631A6BD7C5B381C86A60C4" });
return Task.FromResult(new X509SecuritySettings(clientCert, remoteSecuritySettings));
};

        // create client using ServiceFabricClientBuilder.UseX509Security
        var client = new ServiceFabricClientBuilder()
                        .UseEndpoints(new Uri(@"https://jackysf3.eastasia.cloudapp.azure.com:19080"))
                        .UseX509Security(GetSecurityCredentials)
                        .BuildAsync().GetAwaiter().GetResult();

// you can change serviceId and instanceCount
await client.Services.UpdateServiceAsync("ServiceFabricApp1~Stateless1", new StatelessServiceUpdateDescription(instanceCount: 5, defaultMoveCost: Microsoft.ServiceFabric.Common.MoveCost.Zero));

        var serviceDesc = await client.Services.GetServiceDescriptionAsync("ServiceFabricApp1~Stateless1");

Expected behavior
Instance Count is changed as we assigned.

Additional context
Add any other context about the problem here.

New-SFReplicaHealth always error out with "A required parameter is missing: ServiceKind"

Description

New-SFReplicaHealth and the equivalent C# client method ReportReplicaHealthAsync always exception out with message "A required parameter is missing: ServiceKind".

To Reproduce

New-SFReplicaHealth -PartitionId dc39bb20-fc29-4008-89bd-2d89dcfae2e3 -ReplicaId 131957984827086818 -ReplicaHealthReportServiceKind Stateless -SourceId Test -Property Hello -HealthState Warning
New-SFReplicaHealth : A required parameter is missing: ServiceKind.
At line:1 char:1
+ New-SFReplicaHealth -PartitionId dc39bb20-fc29-4008-89bd-2d89dcfae2e3 ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : NotSpecified: (:) [New-SFReplicaHealth], ServiceFabricException
+ FullyQualifiedErrorId : NewReplicaHealthErrorId,Microsoft.ServiceFabric.Powershell.Http.NewReplicaHealthCmdlet

Expected behavior

We expect this command to work and set the health state to Warning for that replica.

Additional context

I looked up on Service Fabric code and the REST API was actually expecting ServiceKind in query param instead of ReplicaHealthReportServiceKind so this seems like a bug on client library. My cluster version is 6.4.622.9590

Arithmetic operation resulted in an overflow

Describe the bug

With 2.0.0-preview1, when attempting to upload an application package using the image store, I get:

System.OverflowException: Arithmetic operation resulted in an overflow.
   at Microsoft.ServiceFabric.Client.Http.ImageStoreClient.<UploadChunkAsync>d__17.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.ServiceFabric.Common.Utilities.ConcurrentOperationsRunner`1.<RunOperationsSerially>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.ServiceFabric.Common.Utilities.ConcurrentOperationsRunner`1.<RunAll>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.ServiceFabric.Client.Http.ImageStoreClient.<UploadAllChunksAsync>d__16.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
   at Microsoft.ServiceFabric.Client.Http.ImageStoreClient.<UploadApplicationPackageAsync>d__9.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   at UserQuery.<Main>d__0.MoveNext() in C:\Users\Kent\AppData\Local\Temp\LINQPad5\_djbahaxc\query_mwrirh.cs:line 646

To Reproduce

Here's a LINQPad script:

async Task Main()
{
    var automationCertificate = new X509Certificate2(@"C:\Users\Kent\Repository\<<redacted>>\Azure.pfx");
    var clusterManagementEndpoint = "https://<<redacted>>cluster.northcentralus.cloudapp.azure.com:19080";
    var clusterManagementUri = new Uri(clusterManagementEndpoint);

    var fabricClient = await new ServiceFabricClientBuilder()
        .UseEndpoints(clusterManagementUri)
        .UseX509Security(
            _ =>
            {
                var remoteSecuritySettings = new RemoteX509SecuritySettings(new List<string> { "<<redacted>>" });
                var x509SecuritySettings = new X509SecuritySettings(automationCertificate, remoteSecuritySettings);
                return System.Threading.Tasks.Task.FromResult<SecuritySettings>(x509SecuritySettings);
            })
        .BuildAsync();

    "Waiting for cluster management endpoint to become available.".Dump();

    while (true)
    {
        try
        {
            var clusterHealth = await fabricClient.Cluster.GetClusterHealthAsync();

            if (clusterHealth.AggregatedHealthState == HealthState.Ok)
            {
                "Connected to cluster management endpoint.".Dump();
                break;
            }

            $"Cluster health is not OK. It is '{clusterHealth.AggregatedHealthState}' - waiting.".Dump();
        }
        catch (ServiceFabricRequestException)
        {
            "Unable to connect to Service Fabric management endpoint - waiting.".Dump();
        }

        await System.Threading.Tasks.Task.Delay(TimeSpan.FromSeconds(10));
    }
    
    var resourceNamePrefix = "<<redacted>>";
    var pkgDir = @"C:\Users\Kent\Repository\<<redacted>>\pkg\Release\";

    "Uploading package to image store.".Dump();
    try
    {
        await fabricClient
            .ImageStore
            .UploadApplicationPackageAsync(pkgDir, compressPackage: true, applicationPackagePathInImageStore: resourceNamePrefix);
    }
    catch (Exception ex)
    {
        // THIS IS TRIGGERING
        ex.ToString().Dump();
    }

    "Provisioning application type.".Dump();
    var applicationTypeDescription = new ProvisionApplicationTypeDescription(
        resourceNamePrefix,
        applicationPackageCleanupPolicy: ApplicationPackageCleanupPolicy.Automatic);
    await fabricClient
        .ApplicationTypes
        .ProvisionApplicationTypeAsync(applicationTypeDescription);

    "Creating application.".Dump();
    var applicationDescription = new ApplicationDescription(
        new ApplicationName("fabric:/" + resourceNamePrefix),
        resourceNamePrefix,
        "1.0.0");
    await fabricClient
        .Applications
        .CreateApplicationAsync(applicationDescription);

    $"Done".Dump();
}

I have tried both with and without compression enabled - the result is the same.

Expected behavior

The package should upload without error, or provide better information about why it is failing.

Additional context

I'm attempting to automate SF deployments. I've repro'd this on both Linux and Windows, though I may also have an additional problem on Linux to do with SSL (will file a separate issue if it comes to it).

I'd be happy to provide the package itself privately if that helps.

Move UploadApplicationPackageAsync to IApplicationTypeClient

Is there a particular reason UploadApplicationPackageAsync IApplicationTypeClient is in IApplicationClient and not IApplicationTypeClient? It feels more related to application types than application instances, but perhaps that's just my gut feeling

Wrong chunk calculation in UploadChunkAsync

Hi,

When trying to upload my application package files to the image store, I got the following exception:
System.OverflowException: Arithmetic operation resulted in an overflow

While looking at the code, I noticed a bug in UploadChunkAsync.
When calculating the chunk length, the calculation is as follows:

var length = chunkInfo.StartPosition - chunkInfo.EndPosition + 1;
var chunk = new byte[length];

This is a bug which results in negative length and therefore the new byte array results in an exception.
To reproduce, just upload any application package to the data store which has a file with size larger than UploadLimitSizeInBytes.

Thanks,
Dan Yaari

Unhelpful error when New-SFMeshResourceDeployment fails

Describe the bug

I'm trying to troubleshoot ASF Mesh project in VS. When powershell command is executed and something is wrong, the error message is:

2>C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\Sdks\Microsoft.SFApp.Sdk\build\Microsoft.VisualStudio.Azure.SFApp.Targets.targets(322,5): error : New-SFMeshResourceDeployment : Input string was not in a correct format.
2>C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\Sdks\Microsoft.SFApp.Sdk\build\Microsoft.VisualStudio.Azure.SFApp.Targets.targets(322,5): error : At line:1 char:157
2>C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\Sdks\Microsoft.SFApp.Sdk\build\Microsoft.VisualStudio.Azure.SFApp.Targets.targets(322,5): error : + ... -SFCluster; New-SFMeshResourceDeployment -ResourceDescriptionList 'D: ...
2>C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\Sdks\Microsoft.SFApp.Sdk\build\Microsoft.VisualStudio.Azure.SFApp.Targets.targets(322,5): error : + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2>C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\Sdks\Microsoft.SFApp.Sdk\build\Microsoft.VisualStudio.Azure.SFApp.Targets.targets(322,5): error : + CategoryInfo : NotSpecified: (:) [New-SFMeshResourceDeployment], FormatException
2>C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\Sdks\Microsoft.SFApp.Sdk\build\Microsoft.VisualStudio.Azure.SFApp.Targets.targets(322,5): error : + FullyQualifiedErrorId : DeployMeshResourcesErrorId,Microsoft.ServiceFabric.Powershell.Http.DeployMeshResourcesCmdlet
2>C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\Sdks\Microsoft.SFApp.Sdk\build\Microsoft.VisualStudio.Azure.SFApp.Targets.targets(322,5): error :
2>C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\Sdks\Microsoft.SFApp.Sdk\build\Microsoft.VisualStudio.Azure.SFApp.Targets.targets(322,5): error : An error occurred running New-SFMeshResourceDeployment.
2>C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\Sdks\Microsoft.SFApp.Sdk\build\Microsoft.VisualStudio.Azure.SFApp.Targets.targets(322,5): error : Exit Code: 1

To Reproduce

powershell.exe -NoProfile -ExecutionPolicy Bypass -Command "import-module 'C:\Program Files\Microsoft SDKs\Service Fabric\Tools\Mesh\Scripts\PSModule\Microsoft.ServiceFabric.Powershell.Http.psd1'; Connect-SFCluster; New-SFMeshResourceDeployment -ResourceDescriptionList 'D:\work\MyApp\src\App.AsfMesh\App Resources\app.yaml', 'D:\work\MyApp\src\App\Service Resources\service.yaml', 'D:\work\MyApp\src\App.AsfMesh\obj\SFApp\App.debug.yaml', 'D:\work\MyApp\src\App.AsfMesh\App Resources\gateway.yaml', 'D:\work\MyApp\src\App.AsfMesh\App Resources\network.yaml' -ParameterFileName 'D:\work\MyApp\src\App.AsfMesh\Environments\Local\parameters.yaml'"

Expected behavior

If something is wrong with my settings, I expect a helpful error message that explains what is going on.

Additional context
Add any other context about the problem here.

Get-SFImageStoreContent throws and does not honor -ErrorAction Ignore

Describe the bug
When calling Get-SFImageStoreContent, if a match is found it is returned to the caller.
If no match is found an exception is thrown, which is probably a bug in itself.
However, the exception is still thrown when -ErrorAction Ignore is passed to the cmdlet causing the calling script to exit.

To Reproduce
Create a script that connects to a cluster, then calls:
$result = Get-SFImageStoreContent -ContentPath "ContentNotThere" -ErrorAction Ignore
then continues processing in the script.

Expected behavior
The script continues executing.

Unable to use ImageStore Client in .NET API: throws with service not found

I have a .NET API that is connecting to service fabric, I can do all the following:
var content = await fabricClient.Cluster.GetImageStoreConnectionStringAsync();
var list = await fabricClient.ApplicationTypes.GetApplicationTypeInfoListAsync();
var applications = await fabricClient.Applications.GetApplicationInfoAsync("addc/QueryServiceWatchdogApp");
BUT If I try to do anything with the ImageStore API, it throws with service not found
var foldersize = await fabricClient.ImageStore.GetImageStoreRootFolderSizeAsync();
This goes for upgrading the application as well.

Change APIs to work with TimeSpan instead of seconds/milliseconds

Hi,

I was wondering whether it will be possible to change the APIs to work with TimeSpan and make the conversions inside the APIs, I believe it will be more inline with the Service Fabric SDK and will be more intuitive to use.
This can save possible mistakes with doing wrong conversions outside the API.

Thanks,
Dan

allow passing in a list of certificates

Is your feature request related to a problem? Please describe.
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
It should be possible to pass in a list of certificates to the http client

Describe the solution you'd like
A clear and concise description of what you want to happen.

Describe alternatives you've considered
A clear and concise description of any alternative solutions or features you've considered.

Additional context
Add any other context or screenshots about the feature request here.

ChaosClient.GetChaosEventsAsync does not return entries

Describe the bug
Calling ChaosClient.GetChaosEventsAsync() does not return the chaos entries of the cluster. Providing start and stop times did not work either. The resulting IPagedData has an empty ContinuationToken and the Data IEnumerableis null.

To Reproduce
private IServiceFabricClient client;
ServiceFabricClientBuilder builder = new ServiceFabricClientBuilder();
builder.UseEndpoints(clusterUrl);
(Authenticate the builder if necessary)
client = await builder.BuildAsync();
client.ChaosClient.StartChaosAsync(parameters);
Wait a bit for some chaos events to happen
PagedData report = await client.ChaosClient.GetChaosEventsAsync();

report.Data is null and report.ContinuationToken is empty.
Connecting to the cluster using powershell and calling Get-ServiceFabricChaosReport does return results so I know that the report should exist.

Expected behavior
Should receive the list of chaos event wrappers in Data and a continuationtoken if needed

Additional context
Using the latest version of the internal package:
SF.ClientLib.Internal" version="2.0.0-preview5" targetFramework="net461"

Add support for sfpkg generation

This is not high priority, as discussed. However, it would be great to have parity among the various client impls in this regard - deployment packaging and uploading. The file/folder structure used today here is correct. The only thing left to do is to add support for sfpkg file generation, where the code/data/config folder structure (zipped or not) + configuration files are housed in a single sfpkg file (which is also a zip file...).

Connect-SFCluster -AzureActiveDirectory fails with Could not load file or assembly Microsoft.IdentityModel.Clients.ActiveDirectory

Describe the bug
Assembly loading error when using Connect-SFCluster on Powershell Core:

Import-Module Microsoft.ServiceFabric.Powershell.Http

Connect-SFCluster -ConnectionEndpoint $sfEndpoint -AzureActiveDirectory -ServerCommonName $sfCommonName

Fails with:

Connect-SFCluster : Could not load file or assembly 'Microsoft.IdentityModel.Clients.ActiveDirectory, Version=3.19.8.16603, Culture=neutral, PublicKeyToken=31bf3856ad364e35'. Could not find or load a specific file. (Exception from HRESULT: 0x80131621)
At C:\src\scraps.local\test-sf-client.ps1:11 char:1
+ Connect-SFCluster -ConnectionEndpoint $sfEndpoint -AzureActiveDirecto ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : NotSpecified: (:) [Connect-SFCluster], FileLoadException
+ FullyQualifiedErrorId : ConnectClusterErrorId,Microsoft.ServiceFabric.Powershell.Http.ConnectClusterCmdlet

I'm pretty sure this isn't an environment-specific issue. I have uninstalled and reinstalled the Microsoft.ServiceFabric.Powershell.Http module.

Expected behavior
Successful connection and no exception.

ObjectDisposedException when uploading package using .NET Core on Linux

Describe the bug

When calling the UploadApplicationPackageAsync on Linux using .NET Core 2.1, I get:

Unhandled Exception: System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'SslStream'.
   at System.Net.Security.SslState.ThrowIfExceptional()
   at System.Net.Security.SslState.CheckThrow(Boolean authSuccessCheck, Boolean shutdownCheck)
   at System.Net.Security.SslState.CheckOldKeyDecryptedData(Memory`1 buffer)
   at System.Net.Security.SslState.HandleQueuedCallback(Object& queuedStateRequest)
   at System.Net.Security.SslState.FinishHandshakeRead(Int32 newState)
   at System.Net.Security.SslState.FinishHandshake(Exception e, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.RehandshakeCompleteCallback(IAsyncResult result)
   at System.Net.LazyAsyncResult.Complete(IntPtr userToken)
   at System.Net.LazyAsyncResult.ProtectedInvokeCallback(Object result, IntPtr userToken)
   at System.Net.AsyncProtocolRequest.CompleteUserWithError(Exception e)
   at System.Net.FixedSizeReader.ReadPacketAsync(Stream transport, AsyncProtocolRequest request)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location where exception was thrown ---
   at System.Threading.ThreadPoolWorkQueue.Dispatch()

However, this doesn't seem to reproduce 100% of the time.

To Reproduce

This is the relevant snippet of code (from a Cake build script):

var fabricClient = await new ServiceFabricClientBuilder()
    .UseEndpoints(clusterManagementUri)
    .UseX509Security(
        _ =>
        {
            var remoteSecuritySettings = new RemoteX509SecuritySettings(new List<string> { GenerateThumbprintFor(certificateBundle.X509Thumbprint) });
            var x509SecuritySettings = new X509SecuritySettings(automationCertificate, remoteSecuritySettings);
            return System.Threading.Tasks.Task.FromResult<SecuritySettings>(x509SecuritySettings);
        })
    .BuildAsync();

Information("Waiting for cluster management endpoint to become available.");

while (true)
{
    try
    {
        var clusterHealth = await fabricClient.Cluster.GetClusterHealthAsync();

        if (clusterHealth.AggregatedHealthState == HealthState.Ok)
        {
            Information("Connected to cluster management endpoint.");
            break;
        }

        Debug($"Cluster health is not OK. It is '{clusterHealth.AggregatedHealthState}' - waiting.");
    }
    catch (ServiceFabricRequestException)
    {
        Information("Unable to connect to Service Fabric management endpoint - waiting.");
    }

    await System.Threading.Tasks.Task.Delay(TimeSpan.FromSeconds(10));
}

Information("Uploading package to image store.");
// THIS IS WHERE THE EXCEPTION IS THROWN
await fabricClient
    .ImageStore
    .UploadApplicationPackageAsync(pkgDir, compressPackage: false, applicationPackagePathInImageStore: resourceNamePrefix);

Expected behavior

No exception should be thrown.

Additional context

I'm attempting to automate SF deployments, and in doing so have been running on both Linux (a Cake script running in a Docker container) and Windows (using LINQPad). I've only seen this particular issue on Linux, never on Windows. But like I said, it doesn't seem to always trigger.

I'd be happy to provide any other information that would help diagnose.

ImageStore operations for dev clusters (FileSystem)

All operations on the ImageStore give exceptions when using the client with a dev cluster. (also UploadApplicationPackageAsync)
Microsoft.ServiceFabric.Common.Exceptions.ServiceFabricException: FABRIC_E_SERVICE_DOES_NOT_EXIST. Service does not exist.

The reason is the lack of an ImageStoreService in a dev cluster. It uses the file system instead. The old fabric client api could handle this as you specified the ImageStoreConnectionString (filepath incase of a dev cluster).

Will there come support for the file system imagestore in this client aswell?

GetServiceInfoListAsync not working on a 6.2.274 cluster

GetServiceInfoListAsync fails on the newest version (6.2.274) of a cluster (not sure if it worked on older versions)

The reason it fails is because when parsing the serviceInfo, the response it reads the first property and expects it to be "ServiceKind" but the response it got is something like the following:

{"ContinuationToken":"", "Items":[{"Id":"devApp~SomeActorService", "ServiceKind":"Stateful","...},...]}

Incorrect string in SafetyCheckConverter

Hi,
With the latest version of service fabric (6.4.622.9590), I have seen that we have property value of "WaitForInBuildReplica" instead of "WaitForInbuildReplica" as appears in SafetyCheckConverter.
As the string comparison is case sensitive, I receive "Unknown Kind." thrown.
I have reproduced this with a local service fabric cluster.

Thanks,
Dan

Cannot Retrieving any data from eventStore (ex. GetNodesEventListAsync)

Describe the bug
Any request to retrieve eventStore data returns System.ArgumentNullException: 'Value cannot be null. (Parameter 'error')'

image

Seems to be an issue with the Deserialization of the event

To Reproduce
Make any request to eventStore. Not just limited to Node Requests
image

Expected behavior
In this case I am expected to receive a list of Node Events.

Additional context
Add any other context about the problem here.

Service Fabric Connect from Linux Client

I have deployed a service fabric cluster (not managed) using the certificate common names:

"properties": {
                "certificateCommonNames": {
                    "commonNames": [
                        {
                            "certificateCommonName": "[parameters('clusterCertificateCommonName')]",
                            "certificateIssuerThumbprint": ""
                        }
                    ],
                    "x509StoreName": "[parameters('certificateStoreValue')]"
                },
                "clientCertificateCommonNames": [
                    {
                        "isAdmin": true,
                        "certificateCommonName": "[parameters('clientCertificateCommonName')]"
                    }
                ],

Then, from Linux machine (ubuntu 20.04), I tried the following two options:

  1. Installing cert on the host (Running in Powershell Core):
Write-Host "Get Service Fabric certificate from KeyVault"
az keyvault certificate download --vault-name $KeyVaultName --name $CertificateName --file cert.pem --encoding PEM
Write-Host "Get certificate content from cert.pem"
$certContent = Get-Content -Path cert.pem
Write-Host "Save the content in local share folder as cert.crt"
$certContent | Add-Content -Path /usr/local/share/ca-certificates/cert.crt
Write-Host "Run updates on certificates to import the new certificate"
bash -c "update-ca-certificates"
  1. Create the store and use:
$StoreName = [System.Security.Cryptography.X509Certificates.StoreName]::My
$StoreLocation = [System.Security.Cryptography.X509Certificates.StoreLocation]::CurrentUser
$Store = [System.Security.Cryptography.X509Certificates.X509Store]::new($StoreName, $StoreLocation)
$Flag = [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable
$Certificate = [System.Security.Cryptography.X509Certificates.X509Certificate2]::new("./cert.pfx", "", $Flag)
            $Store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite)
$Store.Add($Certificate)
$Store.Close()

After each option, I tried to connect to the cluster:

Connect-SFCluster -ConnectionEndpoint $connectionEndpoint -X509Credential -StoreLocation 'CurrentUser' -StoreName 'My' -ServerCommonName $CertificateCommonName -FindType 'FindBySubjectName' -FindValue $CertificateCommonName -ClientTimeout 1800

but it always failed with the following error:

Microsoft.ServiceFabric.Client.Exceptions.ServiceFabricRequestException: Connection timed out (bapsa1f62fccluster.eastus.cloudapp.azure.com:19080)
                         ---> System.Net.Http.HttpRequestException: Connection timed out (bapsa1f62fccluster.eastus.cloudapp.azure.com:19080)
                         ---> System.Net.Sockets.SocketException (110): Connection timed out
                           at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.ThrowException(SocketError error, CancellationToken cancellationToken)
                           at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.System.Threading.Tasks.Sources.IValueTaskSource.GetResult(Int16 token)
                           at System.Net.Sockets.Socket.<ConnectAsync>g__WaitForConnectWithCancellation|277_0(AwaitableSocketAsyncEventArgs saea, ValueTask connectTask, CancellationToken cancellationToken)
                           at System.Net.Http.HttpConnectionPool.ConnectToTcpHostAsync(String host, Int32 port, HttpRequestMessage initialRequest, Boolean async, CancellationToken cancellationToken)
                           --- End of inner exception stack trace ---
                           at System.Net.Http.HttpConnectionPool.ConnectToTcpHostAsync(String host, Int32 port, HttpRequestMessage initialRequest, Boolean async, CancellationToken cancellationToken)
                           at System.Net.Http.HttpConnectionPool.ConnectAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
                           at System.Net.Http.HttpConnectionPool.CreateHttp11ConnectionAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
                           at System.Net.Http.HttpConnectionPool.AddHttp11ConnectionAsync(HttpRequestMessage request)
                           at System.Threading.Tasks.TaskCompletionSourceWithCancellation`1.WaitWithCancellationAsync(CancellationToken cancellationToken)
                           at System.Net.Http.HttpConnectionPool.GetHttp11ConnectionAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
                           at System.Net.Http.HttpConnectionPool.SendWithVersionDetectionAndRetryAsync(HttpRequestMessage request, Boolean async, Boolean doRequestAuth, CancellationToken cancellationToken)
                           at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
                           at System.Net.Http.HttpClient.<SendAsync>g__Core|83_0(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationTokenSource cts, Boolean disposeCts, CancellationTokenSource pendingRequestsCts, CancellationToken originalCancellationToken)
                           at Microsoft.ServiceFabric.Client.Http.ServiceFabricHttpClient.SendAsyncHandleSecurityExceptions(Func`1 requestFunc, String clientRequestId, CancellationToken cancellationToken)
                           --- End of inner exception stack trace ---
                           at Microsoft.ServiceFabric.Client.Http.ServiceFabricHttpClient.SendAsyncHandleSecurityExceptions(Func`1 requestFunc, String clientRequestId, CancellationToken cancellationToken)
                           at Microsoft.ServiceFabric.Client.Http.ServiceFabricHttpClient.SendAsyncHandleUnsuccessfulResponse(Func`1 requestFunc, Uri requestUri, String clientRequestId, CancellationToken cancellationToken)
                           at Microsoft.ServiceFabric.Client.Http.ServiceFabricHttpClient.SendAsyncGetResponse[T](Func`1 requestFunc, String relativeUri, Func`2 deserializeFunc, String requestId, CancellationToken cancellationToken)
                           at Microsoft.ServiceFabric.Powershell.Http.ConnectClusterCmdlet.ProcessRecordInternal()
                           at Microsoft.ServiceFabric.Powershell.Http.CommonCmdletBase.ProcessRecord()

Does anyone know about this issue? I can connect to the cluster from Windows machine.

Get ReplicaId from ReplicaInfo

Hi,

I am trying to go over all replicas in a specific partition and remove them.
However, to remove the replicas, I need the replicaId. This information is not available in ReplicaInfo which is the result of GetReplicaInfoListAsync (As far as I have seen, the ReplicaId is given in the result of the REST API, but it is not serialized into the ReplicaInfo.
Currently, if removing all replicas from a list is needed, it is needed to parse the Address property from ReplicaInfo to get the ReplicaId.
I think the ReplicaId should be added to the ReplicaInfo class to provide easy access (as several methods require the ReplicaId parameter). This behavior will be more inline with QueryManager.GetReplicaListAsync in the Service Fabric SDK, as each Replica contains the ID there.

Here is an example of working code with the Service Fabric SDK:

await (await fabricClient.QueryManager.GetReplicaListAsync(partitionid)).
                                            ForEachAsync(
                                                async replica => await fabricClient.ServiceManager.RemoveReplicaAsync(
                                                    replica.NodeName,
                                                    partitionid,
                                                    replica.Id,
                                                    true))

When trying to replicate the code using Microsoft.ServiceFabric.Client.Http:

await (await serviceFabricClient.
                                            Replicas.
                                            GetReplicaInfoListAsync(
                                                partitionId,
                                                cancellationToken: _cancellationToken)).
                                            Data.
                                            ForEachAsync(
                                                async replica => await serviceFabricClient.
                                                    Replicas.
                                                    RemoveReplicaAsync(
                                                    replica.NodeName,
                                                    partitionId,
                                                    /* No access to replica.Id, need to parse replica.Address */,
                                                    true))

Thanks for the help,
Dan Yaari

FabricException: Overall upgrade timeout must be greater than the combined health check wait and retry timeouts

Describe the bug
When running an SFClusterConfigurationUpgrade with the following settings it throws an error about the overall timeout not being high enough, but it seems there is no parameter to set this overall time out.

To Reproduce
Start-SFClusterConfigurationUpgrade -ClusterConfig (Get-Content $refreshFile | Out-String)
-MaxPercentUnhealthyApplications 25 -MaxPercentUnhealthyNodes 25
-MaxPercentDeltaUnhealthyNodes 25 -MaxPercentUpgradeDomainDeltaUnhealthyNodes 25
-HealthCheckWaitDurationInSeconds 5 -HealthCheckStableDurationInSeconds 5
-HealthCheckRetryTimeout 5 `
-UpgradeTimeoutInSeconds 500

Expected behavior
does an upgrade

Actual behavior
System.Runtime.InteropServices.COMException (-2147017627) FabricException: Overall upgrade timeout must be greater than the combined health check wait and retry timeouts. Requested values (overall timeout, wait, retry): (00.000, 00.000, 00.000)

GetServiceTypeInfoByName fails to parse response

The following code returns null

var client = ServiceFabricClientFactory.Create(clusterUri, settings);
return await client.ServiceTypes.GetServiceTypeInfoByNameAsync("MyApplication", "1.0.0.0", "MyServiceType");

ServiceTypeDescriptionConverter.GetFromJsonProperties throws JsonReader exception with the following message:

'Incorrect discriminator property name IsStateful, Expected discriminator property name is Kind.'

The JSON returned in the response is the following:

{
  "ServiceTypeDescription": {
    "IsStateful": true,
    "ServiceTypeName": "MyServiceType",
    "PlacementConstraints": "",
    "HasPersistedState": true,
    "Kind": "Stateful",
    "Extensions": [],
    "LoadMetrics": [],
    "ServicePlacementPolicies": []
  },
  "ServiceManifestVersion": "1.0.0.0",
  "ServiceManifestName": "MyServiceTypePkg",
  "IsServiceGroup": false
}

[Bug] GetPropertyInfoListAsync is using incorrect deserializer

Calling Get-SFSubNameInfoList does not work. After digging into the code I attempted to repro in powershell

Connect-SFCluster ...
$sfHttpClient = $ExecutionContext.SessionState.PSVariable.Get("SFHttpClusterConnection").Value
$sfHttpClient.Properties.GetSubNameInfoListAsync("<valid_prop_name>", $false, [Microsoft.ServiceFabric.Common.ContinuationToken]::Default, 15).GetAwaiter().GetResult()

Inspected the http trace via fiddler - the request was successfully going through. Finally noticed GetSubNameInfoListAsync is using PropertyInfoConverter.Deserialize for deserialization which is not correct. That serializer does not handle response from $/GetSubNames.

return this.httpClient.SendAsyncGetResponseAsPagedData(RequestFunc, url, PropertyInfoConverter.Deserialize, requestId, cancellationToken);

StartPartitionRestartAsync throws exception on ubuntu

I have a console app which restarts a servicefabric service . I am using Microsoft.ServiceFabric.Client.IServiceFabricClient to restart any service fabric service. This console app works fine when published as win-x64 to restart servicefabric services deployed on windows but the same application throws exception and does not restart service fabric application when published as linux-x64 on ubuntu VM to restart servicefabric services on ubuntu cluster.

To Reproduce
public async Task Test()
{
try
{
var service = $"{config.Tenant}/{config.ServiceName}";

            var clientTask = new Microsoft.ServiceFabric.Client.ServiceFabricClientBuilder()
                .UseEndpoints(new Uri($"https://{_config.ClusterDNS}:19080"))
                .UseX509Security((ct) =>
                {
                // get the X509Certificate2 either from Certificate store or from file.
                var clientCert = new X509Certificate2("cert.pfx", "");
                    var remoteSecuritySettings = new RemoteX509SecuritySettings(new List<string> { _config.ClusterCertificateThumbPrint });
                    return Task.FromResult<SecuritySettings>(new X509SecuritySettings(clientCert, remoteSecuritySettings));
                })
                .BuildAsync();

            var client = await clientTask;
            var partitionInfo = await client.Partitions.GetPartitionInfoListAsync(service);
            var partitionID = partitionInfo.Data.First().PartitionInformation.Id;
            Console.WriteLine($"partitionID:{partitionID}");

            var restartOperation = Guid.NewGuid();
            await client.Faults.StartPartitionRestartAsync(service, partitionID, restartOperation, Microsoft.ServiceFabric.Common.RestartPartitionMode.AllReplicasOrInstances);

        }
        catch (Microsoft.ServiceFabric.Common.Exceptions.ServiceFabricException ex)
        {
            Console.WriteLine("ErrorCode" + ex.ErrorCode);
            Console.WriteLine("IsTransient" + ex.IsTransient);
            Console.WriteLine("HelpLink" + ex.HelpLink);
            _logger.LogError(ex, "ServiceFabricException");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Test error");
        }

    }

Expected behavior
Service fabric service should restart

Additional context
This is exception
2022-06-03 06:14:44.0501|INFO|Program|Start of application
Service url: Galore/VectorStreams
partitionID:5dd33937-a166-4ab0-8f2b-acac463d69cf
2022-06-03 06:14:45.7945|DEBUG|TimescaleMigrationTool.TestClass|partitionID:5dd33937-a166-4ab0-8f2b-acac463d69cf
ErrorCodeUNKNOWN
IsTransientFalse
HelpLink
2022-06-03 06:14:45.8833|ERROR|TimescaleMigrationTool.TestClass|ServiceFabricException Microsoft.ServiceFabric.Common.Exceptions.ServiceFabricException: Null
at Microsoft.ServiceFabric.Client.Http.ServiceFabricHttpClient.SendAsyncHandleUnsuccessfulResponse(Func1 requestFunc, Uri requestUri, String clientRequestId, CancellationToken cancellati onToken) at Microsoft.ServiceFabric.Client.Http.ServiceFabricHttpClient.SendAsync(Func1 requestFunc, String relativeUri, String requestId, CancellationToken cancellationToken)

image

ReplicaInfo doesn't carry ReplicaId information

How to get ReplicaId?

I'm trying to remove replica using RemoveReplicaAsync() which expects ReplicaId as one of the parameter. I'm calling GetDeployedServiceReplicaInfoListAsync()/GetReplicaInfoAsync() to get more information on replica and the value returned i.e ReplicaInfo doesn't contain any information about ReplicaId.

Add compression parameter to UploadApplicationPackageAsync

According to the docs UploadApplicationPackageAsync will always compress the package as part of the upload, however, looking at the code it doesn seem like compression is actually performed as this method never seems to be called:

https://github.com/Microsoft/service-fabric-client-dotnet/blob/71655e0f90c0547f09876975d457957000f25155/src/Microsoft.ServiceFabric.Client.Http/ApplicationClient_.cs#L293

In any case, there should probably be a parameter for enabling compression or not.

Intermittent security exception when uploading application packages to SF cluster

Describe the bug
When using the ImageStore API (ImageStore.UploadApplicationPackageAsync) to upload application packages to SF cluster, the following exception happens intermittently after few files have been uploaded.

InnerException {System.IO.IOException: The write operation failed, see inner exception. ---> System.Net.Http.WinHttpException: A security error occurred
--- End of inner exception stack trace ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Net.Http.HttpContent.d__44.MoveNext()} System.Exception {System.IO.IOException}

To Reproduce
Create a ServiceFabricHttpClient instance and use the following API to upload the application package to the SF cluster.

ImageStore.UploadApplicationPackageAsync

After a few files are uploaded to the cluster, the security exception shown above is thrown.

Expected behavior
No exception should be thrown during the upload action

Additional context
Add any other context about the problem here.

IServiceFabricClient.Services.CreateService throws exception

IServiceFabricClient.Services.CreateService fails with below exception because of bug in IEquatable implementation for FabricName. PR #20 fixes this issue.

System.NullReferenceException: Object reference not set to an instance of an object.
at Microsoft.ServiceFabric.Common.FabricName.op_Inequality(FabricName name1, FabricName name2)

Move methods that operate on packages to public static classes

Currently there is a method to compress an application package, however it is internal to the library. For CI scenarios it would be useful to pre-compress packages before they're actually uploaded to a cluster.

Consider moving methods like this to a public (static?) class that can be used without connecting to a cluster.

Add tests for APIs

Repo needs tests for client APIs to avoid bugs and validation during check-in.

Add swagger code generation tool chain to this repo

As discussed in #12, A significant portion of the client code is created via code generation from swagger, however the scripts/tools that do this code generation is not in this repo.

Please consider adding them so that the community can contribute to them as well.

How are PowerShell help files generated for this repository?

I see that Microsoft.ServiceFabric.Powershell.Http-Help.xml is stored in the repository, and the build depends on this file's presence. Are you able to share how this file is generated? As far as I can tell, the build isn't responsible for it, and no generation tools are referenced by the repository.

Thank you for making this module available!

Add full type definition for manifest types

In the old Sdk there the various manifest types are fully defined in terms of properties so that they can be deserialized directly from the xml manifests on disk.

It would be useful to have those in this library to be able to easily set things like versions and properties programmatically as part of a CI pipeline without dealing with xml namespaces and all that.

For example, compare System.Fabric.Management.ServiceModel.ApplicationManifestType to Microsoft.ServiceFabric.Common.ApplicationTypeManifest

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.