public OperationsServiceImpl(
     IMemoryStoreClientManager <IMemoryStoreClient> memoryStoreClientManager,
     PlayerAuthServiceClient playerAuthServiceClient)
 {
     _memoryStoreClientManager = memoryStoreClientManager;
     _playerAuthServiceClient  = playerAuthServiceClient;
 }
Exemplo n.º 2
0
        public static void Main(string[] args)
        {
            // See https://support.microsoft.com/en-gb/help/821268/contention-poor-performance-and-deadlocks-when-you-make-calls-to-web-s
            // Experimentation shows we need the ThreadPool to always spin up threads for good performance under load
            ThreadPool.GetMaxThreads(out var workerThreads, out var ioThreads);
            ThreadPool.SetMinThreads(workerThreads, ioThreads);

            Parser.Default.ParseArguments <PartyServerCommandLineArgs>(args)
            .WithParsed(parsedArgs =>
            {
                parsedArgs.Validate();

                var spatialRefreshToken = Secrets.GetEnvSecret(SpatialRefreshTokenEnvironmentVariable);

                PartyDataModel.Defaults.MinMembers = (uint)parsedArgs.DefaultMinMembers;
                PartyDataModel.Defaults.MaxMembers = (uint)parsedArgs.DefaultMaxMembers;

                Log.Logger = new LoggerConfiguration()
                             .WriteTo.Console(new RenderedCompactJsonFormatter())
                             .Enrich.FromLogContext()
                             .CreateLogger();

                using (var server = GrpcBaseServer.Build(parsedArgs))
                    using (var memoryStoreManager = new RedisClientManager(parsedArgs.RedisConnectionString))
                    {
                        Log.Information($"Successfully connected to Redis at {parsedArgs.RedisConnectionString}");
                        server.AddInterceptor(new PlayerIdentityTokenValidatingInterceptor(
                                                  PlayerAuthServiceClient.Create(credentials: new PlatformRefreshTokenCredential(spatialRefreshToken)),
                                                  memoryStoreManager.GetRawClient(Database.CACHE)
                                                  ))
                        .AddInterceptor(new ExceptionMappingInterceptor(new Dictionary <Type, StatusCode>
                        {
                            { typeof(EntryNotFoundException), StatusCode.NotFound },
                            { typeof(EntryAlreadyExistsException), StatusCode.AlreadyExists },
                            { typeof(TransactionAbortedException), StatusCode.Unavailable }
                        }));
                        server.AddService(
                            PartyService.BindService(new PartyServiceImpl(memoryStoreManager)));
                        server.AddService(
                            InviteService.BindService(new InviteServiceImpl(memoryStoreManager)));
                        var serverTask = Task.Run(() => server.Start());
                        var signalTask = Task.Run(() => UnixSignal.WaitAny(new[] { new UnixSignal(Signum.SIGINT), new UnixSignal(Signum.SIGTERM) }));
                        Task.WaitAny(serverTask, signalTask);

                        if (signalTask.IsCompleted)
                        {
                            Log.Information($"Received UNIX signal {signalTask.Result}");
                            Log.Information("Server shutting down...");
                            server.Shutdown();
                            serverTask.Wait();
                            Log.Information("Server stopped cleanly");
                        }
                        else
                        {
                            /* The server task has completed; we can just exit. */
                            Log.Information("The Party server has stopped itself or encountered an unhandled exception.");
                        }
                    }
            });
        }
Exemplo n.º 3
0
 public static PlayerAuthServiceClient CreatePlayerAuthClient(Options.Common options)
 {
     return(string.IsNullOrEmpty(options.Environment)
         ? PlayerAuthServiceClient.Create()
         : PlayerAuthServiceClient.Create(GetEndpoint(options.Environment),
                                          GetTokenCredential(options.Environment)));
 }
        public void OneTimeSetUp()
        {
            _projectName = Environment.GetEnvironmentVariable("SPATIAL_PROJECT");
            if (string.IsNullOrEmpty(_projectName))
            {
                Assert.Fail("Project name is missing from environment.");
            }

            var refreshToken = Environment.GetEnvironmentVariable("SPATIAL_REFRESH_TOKEN");

            if (string.IsNullOrEmpty(refreshToken))
            {
                Assert.Fail("Refresh token is missing from environment.");
            }
            _authServiceClient = PlayerAuthServiceClient.Create(
                credentials: new PlatformRefreshTokenCredential(refreshToken));
            _leaderPit     = CreatePlayerIdentityTokenForPlayer(LeaderPlayerId);
            _partyClient   = new PartyService.PartyServiceClient(new Channel(PartyTarget, ChannelCredentials.Insecure));
            _inviteClient  = new InviteService.InviteServiceClient(new Channel(PartyTarget, ChannelCredentials.Insecure));
            _gatewayClient =
                new GatewayService.GatewayServiceClient(new Channel(GatewayTarget, ChannelCredentials.Insecure));
            _leaderMetadata = new Metadata {
                { PitRequestHeaderName, _leaderPit }
            };
        }
Exemplo n.º 5
0
        public static void Main(string[] args)
        {
            // See https://support.microsoft.com/en-gb/help/821268/contention-poor-performance-and-deadlocks-when-you-make-calls-to-web-s
            // Experimentation shows we need the ThreadPool to always spin up threads for good performance under load
            ThreadPool.GetMaxThreads(out var workerThreads, out var ioThreads);
            ThreadPool.SetMinThreads(workerThreads, ioThreads);

            Parser.Default.ParseArguments <SteamAuthArguments>(args)
            .WithParsed(parsedArgs =>
            {
                Log.Logger = new LoggerConfiguration()
                             .WriteTo.Console(new RenderedCompactJsonFormatter())
                             .Enrich.FromLogContext()
                             .CreateLogger();

                var steamDeveloperKey = Secrets.GetEnvSecret(SteamSymmetricKey).Trim();


                var server = GrpcBaseServer.Build(parsedArgs);
                server.AddService
                (
                    AuthService.BindService
                    (
                        new SteamAuthImpl
                        (
                            parsedArgs.ProjectName,
                            PlayerAuthServiceClient.Create
                            (
                                endpoint: new PlatformApiEndpoint(/*host*/ "steamauth.api.com", /*pot*/ 443, /*insecure*/ true),
                                credentials: null, //new PlatformRefreshTokenCredential()
                                settings: null
                            ),
                            analytics: null
                        )
                    )
                );

                var serverTask = Task.Run(() => server.Start());
                var signalTask = Task.Run(() => UnixSignal.WaitAny(new[] { new UnixSignal(Signum.SIGINT), new UnixSignal(Signum.SIGTERM) }));
                Log.Information("Steam authentication server started up");
                Task.WaitAny(serverTask, signalTask);

                if (signalTask.IsCompleted)
                {
                    Log.Information($"Received UNIX signal {signalTask.Result}");
                    Log.Information("Server shutting down...");
                    server.Shutdown();
                    serverTask.Wait();
                    Log.Information("Server stopped cleanly");
                }
                else
                {
                    /* The server task has completed; we can just exit. */
                    Log.Information("The PlayFab authentication server has stopped itself or encountered an unhandled exception.");
                }

                Environment.Exit(0);
            });
        }
Exemplo n.º 6
0
        public static void Main(string[] args)
        {
            // See https://support.microsoft.com/en-gb/help/821268/contention-poor-performance-and-deadlocks-when-you-make-calls-to-web-s
            // Experimentation shows we need the ThreadPool to always spin up threads for good performance under load
            ThreadPool.GetMaxThreads(out var workerThreads, out var ioThreads);
            ThreadPool.SetMinThreads(workerThreads, ioThreads);

            Parser.Default.ParseArguments <PlayFabAuthArguments>(args)
            .WithParsed(parsedArgs =>
            {
                Log.Logger = new LoggerConfiguration()
                             .WriteTo.Console(new RenderedCompactJsonFormatter())
                             .Enrich.FromLogContext()
                             .CreateLogger();
                //spatial service account token i set up and entered into kubernets
                var spatialRefreshToken = Secrets.GetEnvSecret(SpatialRefreshTokenEnvironmentVariable).Trim();
                var playfabDeveloperKey = Secrets.GetEnvSecret(PlayFabSecretKeyEnvironmentVariable).Trim();

                PlayFabSettings.DeveloperSecretKey = playfabDeveloperKey;
                PlayFabSettings.TitleId            = parsedArgs.PlayFabTitleId;

                IAnalyticsSender analyticsSender = new AnalyticsSenderBuilder("playfab_auth")
                                                   .WithCommandLineArgs(parsedArgs)
                                                   .With(new LogExceptionStrategy(Log.Logger))
                                                   .Build();


                var server = GrpcBaseServer.Build(parsedArgs);
                server.AddService(AuthService.BindService(
                                      new PlayFabAuthImpl(
                                          parsedArgs.SpatialProject,
                                          PlayerAuthServiceClient.Create(
                                              /*endpoint: new PlatformApiEndpoint("playerauth.api.improbable.io", 443),*/
                                              credentials: new PlatformRefreshTokenCredential(spatialRefreshToken)),
                                          analyticsSender)
                                      ));

                var serverTask = Task.Run(() => server.Start());
                var signalTask = Task.Run(() => UnixSignal.WaitAny(new[] { new UnixSignal(Signum.SIGINT), new UnixSignal(Signum.SIGTERM) }));
                Log.Information("PlayFab authentication server started up");
                Task.WaitAny(serverTask, signalTask);

                if (signalTask.IsCompleted)
                {
                    Log.Information($"Received UNIX signal {signalTask.Result}");
                    Log.Information("Server shutting down...");
                    server.Shutdown();
                    serverTask.Wait();
                    Log.Information("Server stopped cleanly");
                }
                else
                {
                    /* The server task has completed; we can just exit. */
                    Log.Information("The PlayFab authentication server has stopped itself or encountered an unhandled exception.");
                }

                Environment.Exit(0);
            });
        }
Exemplo n.º 7
0
 public GatewayServiceImpl(
     IMemoryStoreClientManager <IMemoryStoreClient> memoryStoreClientManager,
     PlayerAuthServiceClient playerAuthServiceClient, IAnalyticsSender analytics = null)
 {
     _memoryStoreClientManager = memoryStoreClientManager;
     _playerAuthServiceClient  = playerAuthServiceClient;
     _analytics = (analytics ?? new NullAnalyticsSender()).WithEventClass("match");
 }
Exemplo n.º 8
0
        static void Main(string[] args)
        {
            Log.Logger = new LoggerConfiguration()
                         .WriteTo.Console(new RenderedCompactJsonFormatter())
                         .Enrich.FromLogContext()
                         .CreateLogger();

            // See https://support.microsoft.com/en-gb/help/821268/contention-poor-performance-and-deadlocks-when-you-make-calls-to-web-s
            // Experimentation shows we need the ThreadPool to always spin up threads for good performance under load
            ThreadPool.GetMaxThreads(out var workerThreads, out var ioThreads);
            ThreadPool.SetMinThreads(workerThreads, ioThreads);

            Parser.Default.ParseArguments <GatewayArgs>(args)
            .WithParsed(parsedArgs =>
            {
                var spatialRefreshToken = Secrets.GetEnvSecret(SpatialRefreshTokenEnvironmentVariable);

                var memoryStoreClientManager =
                    new RedisClientManager(parsedArgs.RedisConnectionString);

                var playerAuthClient =
                    PlayerAuthServiceClient.Create(
                        credentials: new PlatformRefreshTokenCredential(spatialRefreshToken));

                IAnalyticsSender analyticsSender = new AnalyticsSenderBuilder("gateway_gateway")
                                                   .WithCommandLineArgs(parsedArgs)
                                                   .With(new LogExceptionStrategy(Log.Logger))
                                                   .Build();

                var server = GrpcBaseServer.Build(parsedArgs);
                server.AddInterceptor(new PlayerIdentityTokenValidatingInterceptor(
                                          playerAuthClient,
                                          memoryStoreClientManager.GetRawClient(Database.CACHE)));
                server.AddService(
                    GatewayService.BindService(new GatewayServiceImpl(memoryStoreClientManager, playerAuthClient, analyticsSender)));

                var serverTask = Task.Run(() => server.Start());
                var signalTask = Task.Run(() => UnixSignal.WaitAny(new[] { new UnixSignal(Signum.SIGINT), new UnixSignal(Signum.SIGTERM) }));
                Task.WaitAny(serverTask, signalTask);

                if (signalTask.IsCompleted)
                {
                    Log.Information($"Received UNIX signal {signalTask.Result}");
                    Log.Information("Server shutting down...");
                    server.Shutdown();
                    serverTask.Wait();
                    Log.Information("Server stopped cleanly");
                }
                else
                {
                    /* The server task has completed; we can just exit. */
                    Log.Information("The Gateway server has stopped itself or encountered an unhandled exception.");
                }
            });
        }
Exemplo n.º 9
0
        public SpatialOSPlatformService()
        {
            var spatialOSServiceAccountToken = Environment.GetEnvironmentVariable("SPATIALOS_TOKEN");

            DeploymentTagFilter = Environment.GetEnvironmentVariable("DEPLOYMENT_TAG");

            var credentialsWithProvidedToken = new PlatformRefreshTokenCredential(spatialOSServiceAccountToken);

            deploymentServiceClient = DeploymentServiceClient.Create(credentials: credentialsWithProvidedToken);
            playerAuthServiceClient = PlayerAuthServiceClient.Create(credentials: credentialsWithProvidedToken);
        }
Exemplo n.º 10
0
        public static async Task <string> CreateDevAuthTokenAsync(ProjectConfig config, CancellationToken cancellation = default)
        {
            var authClient = PlayerAuthServiceClient.Create(credentials: GetCredentials());

            var token = await authClient.CreateDevelopmentAuthenticationTokenAsync(new CreateDevelopmentAuthenticationTokenRequest
            {
                Description = config.ProjectName,
                Lifetime    = Duration.FromTimeSpan(TimeSpan.FromMinutes(30)),
                ProjectName = config.ProjectName
            }, CallSettings.FromCancellationToken(cancellation));

            return(token.TokenSecret);
        }
Exemplo n.º 11
0
 public async Task <object> CreatePlayerIdentityToken(dynamic data)
 {
     return(await Task.Run(() => {
         PlatformRefreshTokenCredential CredentialWithProvidedToken = new PlatformRefreshTokenCredential(data._RefreshToken);
         PlayerAuthServiceClient _playerAuthServiceClient = PlayerAuthServiceClient.Create(credentials: CredentialWithProvidedToken);
         var playerIdentityTokenResponse = _playerAuthServiceClient.CreatePlayerIdentityToken(
             new CreatePlayerIdentityTokenRequest
         {
             Provider = data._Provider,
             PlayerIdentifier = data._PlayerIdentifier,
             ProjectName = data._ProjectName
         });
         return playerIdentityTokenResponse.PlayerIdentityToken;
     }));
 }
Exemplo n.º 12
0
        private static string ModifySimulatedPlayerLaunchJson(Options.CreateSimulated options)
        {
            var playerAuthServiceClient = PlayerAuthServiceClient.Create();

            // Create development authentication token used by the simulated players.
            var dat = playerAuthServiceClient.CreateDevelopmentAuthenticationToken(
                new CreateDevelopmentAuthenticationTokenRequest
            {
                Description = "DAT for sim worker deployment.",
                Lifetime    = Duration.FromTimeSpan(TimeSpan.FromDays(7)),
                ProjectName = options.ProjectName
            });

            // Add worker flags to sim deployment JSON.
            var devAuthTokenIdFlag = new JObject
            {
                { "name", $"{options.FlagPrefix}_simulated_players_dev_auth_token_id" },
                { "value", dat.TokenSecret }
            };

            var targetDeploymentFlag = new JObject
            {
                { "name", $"{options.FlagPrefix}_simulated_players_target_deployment" },
                { "value", options.TargetDeployment }
            };

            var launchConfigRaw = File.ReadAllText(options.LaunchJsonPath);

            // Dynamically traverse the JSON object. The '.' operator on the dynamic object corresponds to indexing
            // into the JSON fields. The alternative would be to write a model of the configuration file.
            dynamic launchConfig = JObject.Parse(launchConfigRaw);

            for (var i = 0; i < launchConfig.workers.Count; ++i)
            {
                if (launchConfig.workers[i].worker_type == options.SimulatedCoordinatorWorkerType)
                {
                    if (launchConfig.workers[i].flags == null)
                    {
                        launchConfig.workers[i].Add(new JProperty("flags"));
                    }

                    launchConfig.workers[i].flags.Add(devAuthTokenIdFlag);
                    launchConfig.workers[i].flags.Add(targetDeploymentFlag);
                }
            }

            return(launchConfig.ToString());
        }
Exemplo n.º 13
0
 public async Task <object> CreateLoginToken(dynamic data)
 {
     return(await Task.Run(() => {
         PlatformRefreshTokenCredential CredentialWithProvidedToken = new PlatformRefreshTokenCredential(data._RefreshToken);
         PlayerAuthServiceClient _playerAuthServiceClient = PlayerAuthServiceClient.Create(credentials: CredentialWithProvidedToken);
         var createLoginTokenResponse = _playerAuthServiceClient.CreateLoginToken(
             new CreateLoginTokenRequest
         {
             PlayerIdentityToken = data._PlayerIdentityToken,
             DeploymentId = data._DeploymentID,
             LifetimeDuration = Duration.FromTimeSpan(TimeSpan.FromSeconds(data._Duration)),
             WorkerType = data._ScenarioWorkerType
         });
         return createLoginTokenResponse.LoginToken;
     }));
 }
Exemplo n.º 14
0
        public void OneTimeSetUp()
        {
            _projectName = Environment.GetEnvironmentVariable("SPATIAL_PROJECT");
            if (string.IsNullOrEmpty(_projectName))
            {
                Assert.Fail("Project name is missing from environment.");
            }

            var refreshToken = Environment.GetEnvironmentVariable("SPATIAL_REFRESH_TOKEN");

            if (string.IsNullOrEmpty(refreshToken))
            {
                Assert.Fail("Refresh token is missing from environment.");
            }
            _authServiceClient =
                PlayerAuthServiceClient.Create(credentials: new PlatformRefreshTokenCredential(refreshToken));
            var channel = new Channel(PartyServerTarget, ChannelCredentials.Insecure);

            _partyClient  = new PartyService.PartyServiceClient(channel);
            _inviteClient = new InviteService.InviteServiceClient(channel);
        }
Exemplo n.º 15
0
        public void OneTimeSetUp()
        {
            ThreadPool.GetMaxThreads(out var workerThreads, out var ioThreads);
            ThreadPool.SetMinThreads(workerThreads, ioThreads);

            _projectName = Environment.GetEnvironmentVariable("SPATIAL_PROJECT");
            if (string.IsNullOrEmpty(_projectName))
            {
                Assert.Fail("Project name is missing from environment.");
            }

            var refreshToken = Environment.GetEnvironmentVariable("SPATIAL_REFRESH_TOKEN");

            if (string.IsNullOrEmpty(refreshToken))
            {
                Assert.Fail("Refresh token is missing from environment.");
            }

            // Create multiple clients in order to connect to every instance behind the load balancer and spread load.
            _partyClients       = new List <PartyService.PartyServiceClient>(Clients);
            _inviteClients      = new List <InviteService.InviteServiceClient>(Clients);
            _authServiceClients = new List <PlayerAuthServiceClient>(Clients);
            _operationsClients  = new List <OperationsClient>(Clients);
            _gatewayClients     = new List <GatewayService.GatewayServiceClient>(Clients);

            for (var i = 0; i < Clients; i++)
            {
                _authServiceClients.Add(PlayerAuthServiceClient.Create(
                                            credentials: new PlatformRefreshTokenCredential(refreshToken)
                                            ));
                _partyClients.Add(
                    new PartyService.PartyServiceClient(new Channel(PartyTarget, ChannelCredentials.Insecure)));
                _inviteClients.Add(
                    new InviteService.InviteServiceClient(new Channel(PartyTarget, ChannelCredentials.Insecure)));
                _gatewayClients.Add(
                    new GatewayService.GatewayServiceClient(new Channel(GatewayTarget, ChannelCredentials.Insecure)));
                _operationsClients.Add(
                    OperationsClient.Create(new Channel(GatewayTarget, ChannelCredentials.Insecure)));
            }
        }
Exemplo n.º 16
0
        private static Operation <Deployment, CreateDeploymentMetadata> CreateSimPlayerDeploymentAsync(DeploymentServiceClient deploymentServiceClient,
                                                                                                       string projectName, string assemblyName, string mainDeploymentName, string simDeploymentName, string simDeploymentJsonPath, string regionCode, int simNumPlayers)
        {
            var playerAuthServiceClient = PlayerAuthServiceClient.Create();

            // Create development authentication token used by the simulated players.
            var dat = playerAuthServiceClient.CreateDevelopmentAuthenticationToken(
                new CreateDevelopmentAuthenticationTokenRequest
            {
                Description = "DAT for simulated player deployment.",
                Lifetime    = Duration.FromTimeSpan(new TimeSpan(7, 0, 0, 0)),
                ProjectName = projectName
            });

            // Add worker flags to sim deployment JSON.
            var devAuthTokenFlag = new JObject();

            devAuthTokenFlag.Add("name", "simulated_players_dev_auth_token");
            devAuthTokenFlag.Add("value", dat.TokenSecret);

            var targetDeploymentFlag = new JObject();

            targetDeploymentFlag.Add("name", "simulated_players_target_deployment");
            targetDeploymentFlag.Add("value", mainDeploymentName);

            var numSimulatedPlayersFlag = new JObject();

            numSimulatedPlayersFlag.Add("name", "total_num_simulated_players");
            numSimulatedPlayersFlag.Add("value", $"{simNumPlayers}");

            var     simWorkerConfigJson = File.ReadAllText(simDeploymentJsonPath);
            dynamic simWorkerConfig     = JObject.Parse(simWorkerConfigJson);

            for (var i = 0; i < simWorkerConfig.workers.Count; ++i)
            {
                if (simWorkerConfig.workers[i].worker_type == CoordinatorWorkerName)
                {
                    simWorkerConfig.workers[i].flags.Add(devAuthTokenFlag);
                    simWorkerConfig.workers[i].flags.Add(targetDeploymentFlag);
                    simWorkerConfig.workers[i].flags.Add(numSimulatedPlayersFlag);
                }
            }

            // Specify the number of managed coordinator workers to start by editing
            // the load balancing options in the launch config. It creates a rectangular
            // launch config of N cols X 1 row, N being the number of coordinators
            // to create.
            // This assumes the launch config contains a rectangular load balancing
            // layer configuration already for the coordinator worker.
            var lbLayerConfigurations = simWorkerConfig.load_balancing.layer_configurations;

            for (var i = 0; i < lbLayerConfigurations.Count; ++i)
            {
                if (lbLayerConfigurations[i].layer == CoordinatorWorkerName)
                {
                    var rectangleGrid = lbLayerConfigurations[i].rectangle_grid;
                    rectangleGrid.cols = simNumPlayers;
                    rectangleGrid.rows = 1;
                }
            }

            simWorkerConfigJson = simWorkerConfig.ToString();

            // Create simulated player deployment.
            var simDeploymentConfig = new Deployment
            {
                AssemblyId   = assemblyName,
                LaunchConfig = new LaunchConfig
                {
                    ConfigJson = simWorkerConfigJson
                },
                Name        = simDeploymentName,
                ProjectName = projectName,
                RegionCode  = regionCode
                              // No snapshot included for the simulated player deployment
            };

            simDeploymentConfig.Tag.Add(DEPLOYMENT_LAUNCHED_BY_LAUNCHER_TAG);
            simDeploymentConfig.Tag.Add(SIM_PLAYER_DEPLOYMENT_TAG);

            Console.WriteLine(
                $"Creating the simulated player deployment {simDeploymentName} in project {projectName} with {simNumPlayers} simulated players. Link: https://console.improbable.io/projects/{projectName}/deployments/{simDeploymentName}/overview");

            var simDeploymentCreateOp = deploymentServiceClient.CreateDeployment(new CreateDeploymentRequest
            {
                Deployment = simDeploymentConfig
            });

            return(simDeploymentCreateOp);
        }
Exemplo n.º 17
0
        private static Operation <Deployment, CreateDeploymentMetadata> CreateSimPlayerDeploymentAsync(DeploymentServiceClient deploymentServiceClient,
                                                                                                       string projectName, string assemblyName, string runtimeVersion, string mainDeploymentName, string simDeploymentName,
                                                                                                       string simDeploymentJsonPath, string simDeploymentSnapshotPath, string regionCode, string clusterCode, int numSimPlayers, bool useChinaPlatform)
        {
            var snapshotServiceClient = SnapshotServiceClient.Create(GetApiEndpoint(useChinaPlatform), GetPlatformRefreshTokenCredential(useChinaPlatform));

            // Upload snapshots.
            var simDeploymentSnapshotId = UploadSnapshot(snapshotServiceClient, simDeploymentSnapshotPath, projectName,
                                                         simDeploymentName, useChinaPlatform);

            if (simDeploymentSnapshotId.Length == 0)
            {
                throw new Exception("Error while uploading sim player snapshot.");
            }

            var playerAuthServiceClient = PlayerAuthServiceClient.Create(GetApiEndpoint(useChinaPlatform), GetPlatformRefreshTokenCredential(useChinaPlatform));

            // Create development authentication token used by the simulated players.
            var dat = playerAuthServiceClient.CreateDevelopmentAuthenticationToken(
                new CreateDevelopmentAuthenticationTokenRequest
            {
                Description = "DAT for simulated player deployment.",
                Lifetime    = Duration.FromTimeSpan(new TimeSpan(7, 0, 0, 0)),
                ProjectName = projectName
            });

            // Add worker flags to sim deployment JSON.
            var devAuthTokenFlag = new JObject();

            devAuthTokenFlag.Add("name", "simulated_players_dev_auth_token");
            devAuthTokenFlag.Add("value", dat.TokenSecret);

            var targetDeploymentFlag = new JObject();

            targetDeploymentFlag.Add("name", "simulated_players_target_deployment");
            targetDeploymentFlag.Add("value", mainDeploymentName);

            var numSimulatedPlayersFlag = new JObject();

            numSimulatedPlayersFlag.Add("name", "total_num_simulated_players");
            numSimulatedPlayersFlag.Add("value", $"{numSimPlayers}");

            var     simDeploymentConfigJson = File.ReadAllText(simDeploymentJsonPath);
            dynamic simDeploymentConfig     = JObject.Parse(simDeploymentConfigJson);

            if (simDeploymentJsonPath.EndsWith(".pb.json"))
            {
                for (var i = 0; i < simDeploymentConfig.worker_flagz.Count; ++i)
                {
                    if (simDeploymentConfig.worker_flagz[i].worker_type == CoordinatorWorkerName)
                    {
                        simDeploymentConfig.worker_flagz[i].flagz.Add(devAuthTokenFlag);
                        simDeploymentConfig.worker_flagz[i].flagz.Add(targetDeploymentFlag);
                        simDeploymentConfig.worker_flagz[i].flagz.Add(numSimulatedPlayersFlag);
                        break;
                    }
                }

                for (var i = 0; i < simDeploymentConfig.flagz.Count; ++i)
                {
                    if (simDeploymentConfig.flagz[i].name == "loadbalancer_v2_config_json")
                    {
                        string  layerConfigJson       = simDeploymentConfig.flagz[i].value;
                        dynamic loadBalanceConfig     = JObject.Parse(layerConfigJson);
                        var     lbLayerConfigurations = loadBalanceConfig.layerConfigurations;
                        for (var j = 0; j < lbLayerConfigurations.Count; ++j)
                        {
                            if (lbLayerConfigurations[j].layer == CoordinatorWorkerName)
                            {
                                var rectangleGrid = lbLayerConfigurations[j].rectangleGrid;
                                rectangleGrid.cols = numSimPlayers;
                                rectangleGrid.rows = 1;
                                break;
                            }
                        }
                        simDeploymentConfig.flagz[i].value = Newtonsoft.Json.JsonConvert.SerializeObject(loadBalanceConfig);
                        break;
                    }
                }
            }
            else // regular non pb.json
            {
                for (var i = 0; i < simDeploymentConfig.workers.Count; ++i)
                {
                    if (simDeploymentConfig.workers[i].worker_type == CoordinatorWorkerName)
                    {
                        simDeploymentConfig.workers[i].flags.Add(devAuthTokenFlag);
                        simDeploymentConfig.workers[i].flags.Add(targetDeploymentFlag);
                        simDeploymentConfig.workers[i].flags.Add(numSimulatedPlayersFlag);
                    }
                }

                // Specify the number of managed coordinator workers to start by editing
                // the load balancing options in the launch config. It creates a rectangular
                // launch config of N cols X 1 row, N being the number of coordinators
                // to create.
                // This assumes the launch config contains a rectangular load balancing
                // layer configuration already for the coordinator worker.
                var lbLayerConfigurations = simDeploymentConfig.load_balancing.layer_configurations;
                for (var i = 0; i < lbLayerConfigurations.Count; ++i)
                {
                    if (lbLayerConfigurations[i].layer == CoordinatorWorkerName)
                    {
                        var rectangleGrid = lbLayerConfigurations[i].rectangle_grid;
                        rectangleGrid.cols = numSimPlayers;
                        rectangleGrid.rows = 1;
                    }
                }
            }

            // Create simulated player deployment.
            var simDeployment = new Deployment
            {
                AssemblyId   = assemblyName,
                LaunchConfig = new LaunchConfig
                {
                    ConfigJson = simDeploymentConfig.ToString()
                },
                Name               = simDeploymentName,
                ProjectName        = projectName,
                RuntimeVersion     = runtimeVersion,
                StartingSnapshotId = simDeploymentSnapshotId,
            };

            if (!String.IsNullOrEmpty(clusterCode))
            {
                simDeployment.ClusterCode = clusterCode;
            }
            else
            {
                simDeployment.RegionCode = regionCode;
            }

            simDeployment.Tag.Add(DEPLOYMENT_LAUNCHED_BY_LAUNCHER_TAG);
            simDeployment.Tag.Add(SIM_PLAYER_DEPLOYMENT_TAG);

            Console.WriteLine(
                $"Creating the simulated player deployment {simDeploymentName} in project {projectName} with {numSimPlayers} simulated players. Link: https://{GetConsoleHost(useChinaPlatform)}/projects/{projectName}/deployments/{simDeploymentName}/overview");

            var simDeploymentCreateOp = deploymentServiceClient.CreateDeployment(new CreateDeploymentRequest
            {
                Deployment = simDeployment
            });

            return(simDeploymentCreateOp);
        }
 public PlayFabAuthImpl(string project, PlayerAuthServiceClient authServiceClient)
 {
     _project           = project;
     _authServiceClient = authServiceClient;
 }
Exemplo n.º 19
0
 // This service is instantiated by Program.cs (base server)
 public SteamAuthImpl(string project, PlayerAuthServiceClient authServiceClient, IAnalyticsSender analytics = null)
 {
     _authServiceClient = authServiceClient;
     _analytics         = (analytics ?? new NullAnalyticsSender()).WithEventClass("authentication");
 }
Exemplo n.º 20
0
        private static int CreateDeployment(string[] args)
        {
            bool launchSimPlayerDeployment = args.Length == 9;

            var projectName                    = args[1];
            var assemblyName                   = args[2];
            var mainDeploymentName             = args[3];
            var mainDeploymentJson             = args[4];
            var mainDeploymentSnapshotFilePath = args[5];
            var deploymentRegionCode           = args[6];

            var simDeploymentName = string.Empty;
            var simDeploymentJson = string.Empty;

            if (launchSimPlayerDeployment)
            {
                simDeploymentName = args[7];
                simDeploymentJson = args[8];
            }

            // Create service clients.
            var playerAuthServiceClient = PlayerAuthServiceClient.Create();
            var snapshotServiceClient   = SnapshotServiceClient.Create();
            var deploymentServiceClient = DeploymentServiceClient.Create();

            try
            {
                // Upload snapshots.
                var mainSnapshotId = UploadSnapshot(snapshotServiceClient, mainDeploymentSnapshotFilePath, projectName,
                                                    mainDeploymentName);

                if (mainSnapshotId.Length == 0)
                {
                    return(1);
                }

                // Create main deployment.
                var mainDeploymentConfig = new Deployment
                {
                    AssemblyId   = assemblyName,
                    LaunchConfig = new LaunchConfig
                    {
                        ConfigJson = File.ReadAllText(mainDeploymentJson)
                    },
                    Name               = mainDeploymentName,
                    ProjectName        = projectName,
                    StartingSnapshotId = mainSnapshotId,
                    RegionCode         = deploymentRegionCode
                };

                if (launchSimPlayerDeployment)
                {
                    // This tag needs to be added to allow simulated clients to connect using login
                    // tokens generated with anonymous auth.
                    mainDeploymentConfig.Tag.Add("dev_login");
                }

                Console.WriteLine(
                    $"Creating the main deployment {mainDeploymentName} in project {projectName} with snapshot ID {mainSnapshotId}.");

                var mainDeploymentCreateOp = deploymentServiceClient.CreateDeployment(new CreateDeploymentRequest
                {
                    Deployment = mainDeploymentConfig
                }).PollUntilCompleted();

                Console.WriteLine("Successfully created the main deployment.");

                if (launchSimPlayerDeployment)
                {
                    // Create development authentication token used by the simulated players.
                    var dat = playerAuthServiceClient.CreateDevelopmentAuthenticationToken(
                        new CreateDevelopmentAuthenticationTokenRequest
                    {
                        Description = "DAT for sim worker deployment.",
                        Lifetime    = Duration.FromTimeSpan(new TimeSpan(7, 0, 0, 0)),
                        ProjectName = projectName
                    });

                    // Add worker flags to sim deployment JSON.
                    var devAuthTokenIdFlag = new JObject();
                    devAuthTokenIdFlag.Add("name", "fps_simulated_players_dev_auth_token_id");
                    devAuthTokenIdFlag.Add("value", dat.DevelopmentAuthenticationToken.Id);

                    var targetDeploymentFlag = new JObject();
                    targetDeploymentFlag.Add("name", "fps_simulated_players_target_deployment");
                    targetDeploymentFlag.Add("value", mainDeploymentName);

                    var     simWorkerConfigJson = File.ReadAllText(simDeploymentJson);
                    dynamic simWorkerConfig     = JObject.Parse(simWorkerConfigJson);

                    for (var i = 0; i < simWorkerConfig.workers.Count; ++i)
                    {
                        if (simWorkerConfig.workers[i].worker_type == "SimulatedPlayerCoordinator")
                        {
                            simWorkerConfig.workers[i].flags.Add(devAuthTokenIdFlag);
                            simWorkerConfig.workers[i].flags.Add(targetDeploymentFlag);
                        }
                    }

                    simWorkerConfigJson = simWorkerConfig.ToString();

                    // Create simulated player deployment.
                    var simDeploymentConfig = new Deployment
                    {
                        AssemblyId   = assemblyName,
                        LaunchConfig = new LaunchConfig
                        {
                            ConfigJson = simWorkerConfigJson
                        },
                        Name        = simDeploymentName,
                        ProjectName = projectName,
                        RegionCode  = deploymentRegionCode
                    };

                    simDeploymentConfig.Tag.Add("simulated_clients");

                    Console.WriteLine($"Creating the simulated player deployment {simDeploymentName} in project {projectName}.");

                    var simDeploymentCreateOp = deploymentServiceClient.CreateDeployment(new CreateDeploymentRequest
                    {
                        Deployment = simDeploymentConfig
                    }).PollUntilCompleted();

                    Console.WriteLine("Successfully created the simulated player deployment.");
                }
            }
            catch (Grpc.Core.RpcException e)
            {
                if (e.Status.StatusCode == Grpc.Core.StatusCode.NotFound)
                {
                    Console.WriteLine(
                        $"Unable to launch the deployment(s). This is likely because the project '{projectName}' or assembly '{assemblyName}' doesn't exist.");
                }
                else
                {
                    throw;
                }
            }

            return(0);
        }
 public PlayerIdentityTokenValidatingInterceptor(PlayerAuthServiceClient authClient, IDatabase cacheClient)
 {
     _authClient  = authClient;
     _cacheClient = cacheClient;
 }
 public PlayerIdentityTokenValidatingInterceptor(PlayerAuthServiceClient authClient)
 {
     _authClient = authClient;
 }
        public static void Init(string token)
        {
            var credentials = new PlatformRefreshTokenCredential(token);

            PlayerAuthServiceClient = PlayerAuthServiceClient.Create(credentials: credentials);
        }