public static async Task <bool> DeployServiceFabricSolution(this IServiceFabricClient Client, ServiceFabricSolution apps, bool symlinkProvision, ILogger Logger = null)
        {
            var cluster  = FabricSerializers.ClusterManifestFromString((await Client.Cluster.GetClusterManifestAsync()).Manifest);
            var appTypes = await Client.ApplicationTypes.GetApplicationTypeInfoListAsync();

            apps.Validate();
            var appsToUpload = apps.Applications.Where(a => !appTypes.Data.Any(ap => ap.Name == a.Manifest.ApplicationTypeName && ap.Version == a.Manifest.ApplicationTypeVersion)).ToList();

            if (appsToUpload.Any())
            {
                var imageStore = cluster.FabricSettings.First(s => s.Name == "Management").Parameter.First(s => s.Name == "ImageStoreConnectionString").Value;
                Logger?.LogVerbose($"Using image store {imageStore}");
                var imageStorePath = new Uri(imageStore).LocalPath;

                // if (symlinkProvision && Directory.Exists(imageStorePath))
                // await Task.WhenAll(appsToUpload.Select(i => UploadAppToLocalPath(imageStore, imageStorePath, i)).ToList());
                // else
                await Task.WhenAll(appsToUpload.Select(i => Client.UploadApp(imageStore, i)).ToList());

                Logger?.LogInfo($"Apps uploaded");
            }

            foreach (var app in apps.Applications)
            {
                await Client.DeployServiceFabricApp(app);
            }
            return(true);
        }
        public static async Task DeployServiceFabricApp(this IServiceFabricClient Client, ServiceFabricApplicationSpec app, ILogger Logger = null)
        {
            var serverAppVersions = await Client.Applications.GetApplicationInfoListAsync();

            var deployed = serverAppVersions.Data.FirstOrDefault(sa => sa.Name == "fabric:/" + app.Name);

            if (deployed != null)
            {
                if (deployed.TypeVersion == app.Version)
                {
                    Logger?.LogInfo($"{app.Name} version {app.Version} is already deployed");
                    return;
                }

                var upgradeDescription = new ApplicationUpgradeDescription("fabric:/" + app.Name, app.Version, UpgradeKind.Rolling, app.Parameters, UpgradeMode.Monitored, 15);
                Logger?.LogInfo($"Upgrading app {upgradeDescription.Name} to version {upgradeDescription.TargetApplicationTypeVersion}");
                await Client.Applications.StartApplicationUpgradeAsync(app.Name, upgradeDescription);
            }
            else
            {
                var appDescription = new ApplicationDescription("fabric:/" + app.Name, app.Manifest.ApplicationTypeName, app.Manifest.ApplicationTypeVersion, app.Parameters);

                Logger?.LogInfo($"Creating app {appDescription.Name} with type {appDescription.TypeName} version {appDescription.TypeVersion}");
                Logger?.LogVerbose($"With parameters");
                if (appDescription.Parameters != null)
                {
                    foreach (var parameter in appDescription.Parameters.Keys)
                    {
                        Logger?.LogVerbose($"{parameter} =  {appDescription.Parameters[(string)parameter]}");
                    }
                }

                await Client.Applications.CreateApplicationAsync(appDescription);
            }
        }
예제 #3
0
        static int Main(string[] args)
        {
            var parsedArguments = new ToolArguments();

            if (!CommandLineUtility.ParseCommandLineArguments(args, parsedArguments))
            {
                Console.Out.Write(CommandLineUtility.CommandLineArgumentsUsage(typeof(ToolArguments)));
                return(-1);
            }

            clusterUrl               = parsedArguments.clusterUrl;
            certLocation             = parsedArguments.certLocation;
            serverCertThumbprint     = parsedArguments.serverCertThumbprint;
            applicationName          = parsedArguments.appName;
            applicationFileLocation  = parsedArguments.applicationFileLocation;
            applicationFileLocation2 = parsedArguments.applicationFileLocation2;

            var settings = new ClientSettings(GetSecurityCredentials);
            IServiceFabricClient sfClient = ServiceFabricClientFactory.Create(new Uri(clusterConnectionUrl), settings);

            //check if the application exists first
            var applicationInfo = sfClient.ApplicationResources.GetApplicationResourceAsync(applicationName).GetAwaiter().GetResult();

            if (applicationInfo == null)
            {
                Console.Out.Write("Application does not exist");
                return(-1);
            }

            upgrade(sfClient);

            return(0);
        }
예제 #4
0
        private static async Task DeleteExistingApplicationAsync(IServiceFabricClient fabricClient, string appId)
        {
            var existingApplicationInfo = await fabricClient.Applications.GetApplicationInfoAsync(appId);

            if (existingApplicationInfo != null)
            {
                await fabricClient.Applications.DeleteApplicationAsync(existingApplicationInfo.Id);
            }
        }
예제 #5
0
        public static void WaitUntilReady(IServiceFabricClient serviceFabricClient)
        {
            var status = serviceFabricClient.ApplicationResources.GetApplicationResourceAsync(applicationName).GetAwaiter().GetResult().Status;

            while (status != ApplicationResourceStatus.Ready)
            {
                Console.WriteLine(status);
                System.Threading.Thread.Sleep(2000);
                status = serviceFabricClient.ApplicationResources.GetApplicationResourceAsync(applicationName).GetAwaiter().GetResult().Status;
            }
        }
예제 #6
0
        private void SetClusterConnection(IServiceFabricClient clusterConnection)
        {
            var oldClusterConnection = this.SessionState.PSVariable.GetValue(Constants.ClusterConnectionVariableName, null) as IServiceFabricClient;

            if (oldClusterConnection != null)
            {
                this.WriteWarning(Resource.Info_ClusterConnectionAlreadyExisted);
            }

            this.SessionState.PSVariable.Set(Constants.ClusterConnectionVariableName, clusterConnection);
        }
예제 #7
0
        private static async Task RemoveApplicationTypeAsync(IServiceFabricClient fabricClient, string appTypeName)
        {
            var applicationTypes = await fabricClient.ApplicationTypes
                                   .GetApplicationTypeInfoListByNameAsync(appTypeName);

            foreach (var applicationType in applicationTypes.Data)
            {
                var descriptionInfo = new UnprovisionApplicationTypeDescriptionInfo(applicationType.Version, false);
                await fabricClient.ApplicationTypes
                .UnprovisionApplicationTypeAsync(applicationType.Name, descriptionInfo);
            }
        }
        /// <summary>
        /// Instantiate correct implementation of IServiceFabricClient depending on the cluster endpoints uri scheme.
        /// </summary>
        /// <param name="clusterEndpoints">Uris for Service Cluster management endpoint.</param>
        /// <param name="clientSettings">Client settings for connecting to cluster. Default value is null which means connecting to unsecured cluster.</param>
        /// <returns>Instance of correct implementation of IServiceFabricClient depending on the cluster endpoint uri scheme.</returns>
        public static IServiceFabricClient Create(IList <Uri> clusterEndpoints, ClientSettings clientSettings = null)
        {
            IServiceFabricClient serviceFabricClient = null;

            if (clusterEndpoints == null)
            {
                // TODO: Create Tcp FabricClient by default in this case when Tcp Fabric CLient implementation is available.
                throw new ArgumentNullException(nameof(clusterEndpoints));
            }

            if (clusterEndpoints.Count == 0)
            {
                throw new ArgumentException(SR.ErrorClusterEndpointNotProvided, nameof(clusterEndpoints));
            }

            if (clusterEndpoints.Any(url => url == null))
            {
                throw new ArgumentException(SR.ErrorUrlCannotBeNull, nameof(clusterEndpoints));
            }

            // all endpoints must have same Uri.UriScheme
            var scheme = clusterEndpoints[0].Scheme;

            if (clusterEndpoints.Any(url => !string.Equals(url.Scheme, scheme, StringComparison.OrdinalIgnoreCase)))
            {
                throw new ArgumentException(SR.ErrorUrlSchemeMismatch);
            }

            if (scheme.Equals(Uri.UriSchemeHttp, StringComparison.OrdinalIgnoreCase) ||
                scheme.Equals(Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase))
            {
                // Since this factory is used to create IServiceFabricClient based on the endpoints scheme, its generic
                // should use reflection to create ServiceFabricHttpClient.
                object[] args =
                {
                    clusterEndpoints,
                    clientSettings,
                    null, //// null for optional innerHandler param
                };

                var type = Type.GetType(ServiceFabricHttpClientTypeName);
                var obj  = Activator.CreateInstance(type, args);

                serviceFabricClient = (IServiceFabricClient)obj;
            }

            return(serviceFabricClient);
        }
        private static async Task UploadApp(this IServiceFabricClient Client, string imageStore, ServiceFabricApplicationSpec app)
        {
            var name = app.Manifest.ApplicationTypeName + "." + app.Manifest.ApplicationTypeVersion;
            await Client.ImageStore.UploadApplicationPackageAsync(Path.GetFullPath(app.PackagePath), true, name);

            await Client.ApplicationTypes.ProvisionApplicationTypeAsync(new ProvisionApplicationTypeDescription(name), 240);

            if (imageStore == "fabric:ImageStore")
            {
                await Client.ImageStore.DeleteImageStoreContentAsync(name);
            }
            //else
            //{
            //	Directory.Delete(Path.Combine(new Uri(imageStore).LocalPath, name), true);
            //}
        }
예제 #10
0
        public static void upgrade(IServiceFabricClient serviceFabricClient)
        {
            var allUniqiue = getAllBackendReplicaIds();

            Console.WriteLine("Are all replica IDs unique: " + allUniqiue.ToString());

            Console.WriteLine("Upgrading the application");
            FlipFlopUpgrade(serviceFabricClient);
            System.Threading.Thread.Sleep(30000);

            WaitUntilReady(serviceFabricClient);
            Console.WriteLine("Upgrade is finished");

            allUniqiue = getAllBackendReplicaIds();
            Console.WriteLine("Are all replica IDs unique: " + allUniqiue.ToString());
        }
        private static async Task UploadAppToLocalPath(this IServiceFabricClient Client, string imageStore, string imageStorep, ServiceFabricApplicationSpec app)
        {
            var name = app.Manifest.ApplicationTypeName + "." + app.Manifest.ApplicationTypeVersion;

            try
            {
                Symlink.CreateSymbolicLink(Path.Combine(imageStorep, name), app.PackagePath, SymbolicLink.Directory);
                await Client.ApplicationTypes.ProvisionApplicationTypeAsync(new ProvisionApplicationTypeDescription(name), 240, CancellationToken.None);

                Symlink.DeleteIfExists(Path.Combine(imageStorep, name));
            }
            catch (FileNotFoundException)
            {
                Symlink.DeleteIfExists(Path.Combine(imageStorep, name));
                await Client.UploadApp(imageStore, app);
            }
        }
예제 #12
0
        public static void FlipFlopUpgrade(IServiceFabricClient serviceFabricClient)
        {
            string currentVersion = GetCurrentVersionOfTemplate();

            Console.WriteLine("Current version in resource template is :" + currentVersion);

            string template = currentVersion == "1" ? applicationFileLocation2 : applicationFileLocation;

            Console.WriteLine("Upgrading to template : " + template);
            try
            {
                serviceFabricClient.ApplicationResources.CreateApplicationResourceAsync(template, applicationResourceName: applicationName).GetAwaiter().GetResult();
            }
            catch (Exception e)
            {
                Console.WriteLine("{0} Exception caught.", e);
            }
        }
예제 #13
0
 public void InitializeSfClientConnection(string sfClusterUri)
 {
     serviceFabricClient = new ServiceFabricClientBuilder()
                           .UseEndpoints(new Uri(sfClusterUri))
                           .BuildAsync().Result;
 }
        public static async Task <bool> CreateDiffPackage(this IServiceFabricClient Client, string packagePath, ILogger Logger = null)
        {
            var localAppManifest = FabricSerializers.AppManifestFromFile(Path.Combine(packagePath, "ApplicationManifest.xml"));
            var appTypes         = await Client.ApplicationTypes.GetApplicationTypeInfoListAsync();

            var appManifestTasks = appTypes.Data.Where(type => type.Name == localAppManifest.ApplicationTypeName).Select(type => Client.ApplicationTypes.GetApplicationManifestAsync(type.Name, type.Version));
            await Task.WhenAll(appManifestTasks);

            var    serverAppManifests = appManifestTasks.Select(task => FabricSerializers.AppManifestFromString(task.Result.Manifest)).ToList();
            string pkgPAth            = null;

            if (serverAppManifests.Any(serverAppManifest => serverAppManifest.ApplicationTypeVersion == localAppManifest.ApplicationTypeVersion))
            {
                Logger?.LogInfo($"Application {localAppManifest.ApplicationTypeName} {localAppManifest.ApplicationTypeVersion} is already provisioned");
                return(false);
            }

            foreach (var serverAppManifest in serverAppManifests)
            {
                foreach (var serviceImport in serverAppManifest.ServiceManifestImport)
                {
                    var localService = localAppManifest.ServiceManifestImport.FirstOrDefault(s => s.ServiceManifestRef.ServiceManifestName == serviceImport.ServiceManifestRef.ServiceManifestName);
                    if (localService != null && localService.ServiceManifestRef.ServiceManifestVersion == serviceImport.ServiceManifestRef.ServiceManifestVersion)
                    {
                        Logger?.LogInfo($"Service {localAppManifest.ApplicationTypeName}.{localService.ServiceManifestRef.ServiceManifestName} {localService.ServiceManifestRef.ServiceManifestVersion} is already provisioned");
                        foreach (var dir in Directory.GetDirectories(Path.Combine(packagePath, serviceImport.ServiceManifestRef.ServiceManifestName)))
                        {
                            Symlink.DeleteIfExists(dir);
                        }
                    }
                    else
                    {
                        var serverServiceManifest    = FabricSerializers.ServiceManifestFromString((await Client.ServiceTypes.GetServiceManifestAsync(serverAppManifest.ApplicationTypeName, serverAppManifest.ApplicationTypeVersion, serviceImport.ServiceManifestRef.ServiceManifestName)).Manifest);
                        var localServiceManifestPath = Path.Combine(packagePath, serviceImport.ServiceManifestRef.ServiceManifestName, "ServiceManifest.xml");
                        if (!File.Exists(localServiceManifestPath))
                        {
                            continue;
                        }
                        var localServiceManifest = FabricSerializers.ServiceManifestFromFile(localServiceManifestPath);

                        // Logger?.LogInfo($"{serverAppManifest.ApplicationTypeName}.{localService.ServiceManifestRef.ServiceManifestName} {localService.ServiceManifestRef.ServiceManifestVersion} not found on server, checking packages");
                        if (serverServiceManifest.CodePackage != null && localServiceManifest.CodePackage != null)
                        {
                            foreach (var package in serverServiceManifest.CodePackage.Where(sp => localServiceManifest.CodePackage.Any(lp => lp.Name == sp.Name && lp.Version == sp.Version)))
                            {
                                pkgPAth = Path.Combine(packagePath, localService.ServiceManifestRef.ServiceManifestName, package.Name);
                                if (Directory.Exists(pkgPAth))
                                {
                                    Logger?.LogInfo($"Deleting {localAppManifest.ApplicationTypeName}.{localService.ServiceManifestRef.ServiceManifestName}.{package.Name} {package.Version}");
                                    Symlink.DeleteIfExists(pkgPAth);
                                }
                            }
                        }

                        if (serverServiceManifest.ConfigPackage != null && localServiceManifest.ConfigPackage != null)
                        {
                            foreach (var package in serverServiceManifest.ConfigPackage.Where(sp => localServiceManifest.ConfigPackage.Any(lp => lp.Name == sp.Name && lp.Version == sp.Version)))
                            {
                                pkgPAth = Path.Combine(packagePath, localService.ServiceManifestRef.ServiceManifestName, package.Name);
                                if (Directory.Exists(pkgPAth))
                                {
                                    Logger?.LogInfo($"Deleting {localAppManifest.ApplicationTypeName}.{localService.ServiceManifestRef.ServiceManifestName}.{package.Name} {package.Version}");
                                    Symlink.DeleteIfExists(pkgPAth);
                                }
                            }
                        }

                        if (serverServiceManifest.DataPackage != null && localServiceManifest.DataPackage != null)
                        {
                            foreach (var package in serverServiceManifest.DataPackage.Where(sp => localServiceManifest.DataPackage.Any(lp => lp.Name == sp.Name && lp.Version == sp.Version)))
                            {
                                pkgPAth = Path.Combine(packagePath, localService.ServiceManifestRef.ServiceManifestName, package.Name);
                                if (Directory.Exists(pkgPAth))
                                {
                                    Logger?.LogInfo($"Deleting {localAppManifest.ApplicationTypeName}.{localService.ServiceManifestRef.ServiceManifestName}.{package.Name} {package.Version}");
                                    Symlink.DeleteIfExists(pkgPAth);
                                }
                            }
                        }
                    }
                }
            }

            return(true);
        }
예제 #15
0
파일: SfContext.cs 프로젝트: lulzzz/SfBot
 public SfContext(ITurnContext context) : base(context)
 {
     Client = ServiceFabricClientFactory.Create(new Uri("http://localhost:19080"));
 }
 public ServiceFabricApplicationHealthController()
 {
     this.serviceFabricClient = new ServiceFabricClientBuilder()
                                .UseEndpoints(new Uri(sfClusterUri))
                                .BuildAsync().Result;
 }
 public DeploymentCommandFactory(IServiceFabricClient fabricClient, ILogger logger)
 {
     _fabricClient = fabricClient;
     _logger       = logger;
 }