/// <summary>
        ///     This assumes you already have the local API service ("spatiald") running at the specified port.
        ///     For more information about how to start the local API service, visit the accompanying documentation on
        ///     https://docs.improbable.io/reference/latest//platform-sdk/local-api.
        ///     This starts a local deployment using the blank SpatialOS project included in this repository.
        /// </summary>
        private static void Setup()
        {
            Console.WriteLine("Setting up for the scenario");
            Console.WriteLine($"Assuming the local API service is running at localhost:{SpatialDPort}");
            Console.WriteLine("Starting a local deployment");
            var launchConfig = File.ReadAllText(LaunchConfigFilePath);

            _localDeployment = LocalDeploymentServiceClient.CreateDeployment(new CreateDeploymentRequest
            {
                Deployment = new Deployment
                {
                    ProjectName  = ProjectName,
                    Name         = DeploymentName,
                    LaunchConfig = new LaunchConfig
                    {
                        ConfigJson = launchConfig
                    }
                }
            }).PollUntilCompleted().GetResultOrNull();

            if (_localDeployment.Status == Deployment.Types.Status.Error)
            {
                throw new Exception(
                          "Failed to create the local eployment; please make sure to build the project by running `spatial build` in the project directory");
            }
        }
Exemple #2
0
        public async Task <object> CloneDeployment(dynamic data)
        {
            return(await Task.Run(() => {
                PlatformRefreshTokenCredential CredentialWithProvidedToken = new PlatformRefreshTokenCredential(data._RefreshToken);
                DeploymentServiceClient _deploymentServiceClient = DeploymentServiceClient.Create(credentials: CredentialWithProvidedToken);
                var suitableDeployment = _deploymentServiceClient.ListDeployments(new ListDeploymentsRequest
                {
                    ProjectName = data._ProjectName
                }).First(d => d.Id.Contains(data._DeploymentID));

                var newDeployment = suitableDeployment.Clone();
                newDeployment.StartingSnapshotId = data._SnapshotID;
                newDeployment.Tag.Clear();
                newDeployment = _deploymentServiceClient.CreateDeployment(new CreateDeploymentRequest {
                    Deployment = newDeployment
                })
                                .PollUntilCompleted()
                                .GetResultOrNull();
                newDeployment.Tag.Add(data._ScenarioDeploymentTag);
                _deploymentServiceClient.UpdateDeployment(new UpdateDeploymentRequest {
                    Deployment = newDeployment
                });
                return newDeployment.Id;
            }));
        }
        public static Google.LongRunning.Operation <Deployment, CreateDeploymentMetadata> CreateDeployment(DeploymentTemplate template)
        {
            var request = new CreateDeploymentRequest
            {
                Deployment = template.ToDeployment()
            };

            return(ExceptionHandler.HandleGrpcCall(() => deploymentServiceClient.CreateDeployment(request)));
        }
Exemple #4
0
        private static Operation <Deployment, CreateDeploymentMetadata> CreateMainDeploymentAsync(DeploymentServiceClient deploymentServiceClient,
                                                                                                  bool launchSimPlayerDeployment, string projectName, string assemblyName, string runtimeVersion, string mainDeploymentName, string mainDeploymentJsonPath, string mainDeploymentSnapshotPath, string regionCode, string clusterCode, string deploymentTags)
        {
            var snapshotServiceClient = SnapshotServiceClient.Create(GetApiEndpoint(regionCode), GetPlatformRefreshTokenCredential(regionCode));

            // Upload snapshots.
            var mainSnapshotId = UploadSnapshot(snapshotServiceClient, mainDeploymentSnapshotPath, projectName,
                                                mainDeploymentName, regionCode);

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

            // Create main deployment.
            var mainDeploymentConfig = new Deployment
            {
                AssemblyId   = assemblyName,
                LaunchConfig = new LaunchConfig
                {
                    ConfigJson = File.ReadAllText(mainDeploymentJsonPath)
                },
                Name               = mainDeploymentName,
                ProjectName        = projectName,
                StartingSnapshotId = mainSnapshotId,
                RegionCode         = regionCode,
                ClusterCode        = clusterCode,
                RuntimeVersion     = runtimeVersion
            };

            mainDeploymentConfig.Tag.Add(DEPLOYMENT_LAUNCHED_BY_LAUNCHER_TAG);
            foreach (String tag in deploymentTags.Split(' '))
            {
                if (tag.Length > 0)
                {
                    mainDeploymentConfig.Tag.Add(tag);
                }
            }

            if (launchSimPlayerDeployment)
            {
                // This tag needs to be added to allow simulated players 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}. Link: https://console.improbable.io/projects/{projectName}/deployments/{mainDeploymentName}/overview");

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

            return(mainDeploymentCreateOp);
        }
Exemple #5
0
 /// <summary>
 ///     This creates a cloud deployment using a launch configuration file with a capacity limit of 2.
 /// </summary>
 protected override void Setup()
 {
     Console.WriteLine("Setting up for the scenario");
     Console.WriteLine($"Preparing a live deployment with capacity: 2, name: {DeploymentName}");
     _deploymentServiceClient.CreateDeployment(new CreateDeploymentRequest
     {
         ProjectName    = ProjectName,
         DeploymentName = DeploymentName,
         LaunchConfig   = new LaunchConfig
         {
             ConfigJson = File.ReadAllText(LaunchConfigFilePath)
         },
         AssemblyName = AssemblyId
     })
     .PollUntilCompleted();
 }
Exemple #6
0
        protected override void Setup()
        {
            Console.WriteLine($"Starting a deployment with name: {DeploymentName}");
            var launchConfig = File.ReadAllText(LaunchConfigFilePath);

            _deployment = _deploymentServiceClient.CreateDeployment(new CreateDeploymentRequest
            {
                ProjectName    = ProjectName,
                DeploymentName = DeploymentName,
                LaunchConfig   = new LaunchConfig
                {
                    ConfigJson = launchConfig
                },
                AssemblyName = AssemblyId,
                Tags         = { ScenarioDeploymentTag }
            }).PollUntilCompleted().GetResultOrNull();
        }
Exemple #7
0
 public async Task <object> CreateDeployment(dynamic data)
 {
     return(await Task.Run(() => {
         PlatformRefreshTokenCredential CredentialWithProvidedToken = new PlatformRefreshTokenCredential(data._RefreshToken);
         DeploymentServiceClient _deploymentServiceClient = DeploymentServiceClient.Create(credentials: CredentialWithProvidedToken);
         var newDeployment = _deploymentServiceClient.CreateDeployment(new CreateDeploymentRequest
         {
             Deployment = new Deployment
             {
                 ProjectName = data._ProjectName,
                 Name = data._DeploymentName,
                 LaunchConfig = new LaunchConfig
                 {
                     ConfigJson = data._Config
                 },
                 AssemblyId = data._AssemblyID,
                 Tag = { data._ScenarioDeploymentTag }
             }
         }).PollUntilCompleted().GetResultOrNull();
         return newDeployment.Id;
     }));
 }
Exemple #8
0
        private static void CreateDeployment(string id)
        {
            var projectName    = Test.Project.Prefix + id;
            var deploymentName = Test.Deployment.Prefix + id;
            var launchConfig   = File.ReadAllText(Test.Project.LaunchConfigFile);

            var operation = DeploymentService.CreateDeployment(new CreateDeploymentRequest
            {
                Deployment = new Deployment
                {
                    Id           = id,
                    ProjectName  = projectName,
                    Name         = deploymentName,
                    LaunchConfig = new LaunchConfig
                    {
                        ConfigJson = launchConfig
                    },
                }
            });

            operation.PollUntilCompleted().GetResultOrNull();
        }
Exemple #9
0
        /// <summary>
        ///     This contains the implementation of the "Game maintenance" scenario.
        ///     1. Get the currently running cloud deployment that needs taking down for maintenance.
        ///     2. Lock down the deployment by removing the `live` tag and setting the worker flag.
        ///     3. Take a snapshot of the deployment.
        ///     4. Stop the deployment.
        ///     5. Start a new cloud deployment based on the old deployment, but with clean tags.
        ///     6. Mark the new cloud deployment live by adding the `live` tag.
        /// </summary>
        /// <param name="args"></param>
        private static void Main(string[] args)
        {
            Setup();

            Console.WriteLine("Finding the current running deployment");
            var currentLiveDeployment = DeploymentServiceClient.GetRunningDeploymentByName(new GetRunningDeploymentByNameRequest
            {
                ProjectName    = ProjectName,
                DeploymentName = DeploymentName,
            });

            Console.WriteLine("Putting the deployment to maintenance mode");
            currentLiveDeployment.Deployment.Tags.Remove("my_live_tag");
            var setTagsRequest = new SetDeploymentTagsRequest
            {
                DeploymentId = currentLiveDeployment.Deployment.Id,
                Tags         = { currentLiveDeployment.Deployment.Tags },
            };

            DeploymentServiceClient.SetDeploymentTags(setTagsRequest);


            Console.WriteLine("Taking a cloud snapshot");
            var latestSnapshot = SnapshotServiceClient.TakeSnapshot(new TakeSnapshotRequest
            {
                Snapshot = new Snapshot
                {
                    ProjectName    = currentLiveDeployment.Deployment.ProjectName,
                    DeploymentName = currentLiveDeployment.Deployment.DeploymentName
                }
            }).PollUntilCompleted()
                                 .GetResultOrNull();

            Console.WriteLine("Stopping the deployment");
            DeploymentServiceClient.DeleteDeployment(new DeleteDeploymentRequest
            {
                Id = currentLiveDeployment.Deployment.Id,
            }).PollUntilCompleted();

            Console.WriteLine("Starting a new deployment with empty tags");
            var newDeployment = DeploymentServiceClient.CreateDeployment(new CreateDeploymentRequest
            {
                DeploymentName     = currentLiveDeployment.Deployment.DeploymentName,
                ProjectName        = currentLiveDeployment.Deployment.ProjectName,
                StartingSnapshotId = latestSnapshot.Id,
                LaunchConfig       = currentLiveDeployment.Deployment.LaunchConfig,
                AssemblyName       = currentLiveDeployment.Deployment.AssemblyName,
            })
                                .PollUntilCompleted()
                                .GetResultOrNull();

            Console.WriteLine("Putting the new deployment to live");
            var setLiveTagsRequest = new SetDeploymentTagsRequest
            {
                DeploymentId = newDeployment.Id,
            };

            setTagsRequest.Tags.Add("my_live_tag");
            DeploymentServiceClient.SetDeploymentTags(setLiveTagsRequest);

            Cleanup(newDeployment);
        }
        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);
        }
Exemple #11
0
        /// <summary>
        ///     This contains the implementation of the "Game maintenance" scenario.
        ///     1. Get the currently running cloud deployment that needs taking down for maintenance.
        ///     2. Lock down the deployment by removing the `live` tag and setting the worker flag.
        ///     3. Take a snapshot of the deployment.
        ///     4. Stop the deployment.
        ///     5. Start a new cloud deployment based on the old deployment, but with clean tags.
        ///     6. Mark the new cloud deployment live by adding the `live` tag.
        /// </summary>
        /// <param name="args"></param>
        private static void Main(string[] args)
        {
            Setup();

            Console.WriteLine("Finding a current running deployment with live tag");
            var currentLiveDeployment = DeploymentServiceClient
                                        .ListDeployments(new ListDeploymentsRequest
            {
                ProjectName    = ProjectName,
                DeploymentName = DeploymentName
            })
                                        .First(d => d.Status == Deployment.Types.Status.Running && d.Tag.Contains("my_live_tag"));

            Console.WriteLine("Putting the deployment to maintenance mode");
            currentLiveDeployment.Tag.Remove("my_live_tag");
            currentLiveDeployment.WorkerFlags.Add(new WorkerFlag
            {
                Key        = "maintenance",
                Value      = "true",
                WorkerType = "unity"
            });
            DeploymentServiceClient.UpdateDeployment(new UpdateDeploymentRequest {
                Deployment = currentLiveDeployment
            });

            Console.WriteLine("Taking a cloud snapshot");
            var latestSnapshot = SnapshotServiceClient.TakeSnapshot(new TakeSnapshotRequest
            {
                Snapshot = new Snapshot
                {
                    ProjectName    = currentLiveDeployment.ProjectName,
                    DeploymentName = currentLiveDeployment.Name
                }
            }).PollUntilCompleted()
                                 .GetResultOrNull();

            Console.WriteLine("Stopping the deployment");
            DeploymentServiceClient.StopDeployment(new StopDeploymentRequest
            {
                Id          = currentLiveDeployment.Id,
                ProjectName = currentLiveDeployment.ProjectName
            });

            Console.WriteLine("Starting a new deployment with empty tags");
            var newDeployment = currentLiveDeployment.Clone();

            newDeployment.StartingSnapshotId = latestSnapshot.Id;
            newDeployment.Tag.Clear();
            newDeployment = DeploymentServiceClient
                            .CreateDeployment(new CreateDeploymentRequest {
                Deployment = newDeployment
            })
                            .PollUntilCompleted()
                            .GetResultOrNull();

            Console.WriteLine("Putting the new deployment to live");
            newDeployment.Tag.Add("my_live_tag");
            DeploymentServiceClient.UpdateDeployment(new UpdateDeploymentRequest {
                Deployment = newDeployment
            });

            Cleanup(newDeployment);
        }
        /// <summary>
        ///     This contains the implementation of the "Replicate local state to cloud" scenario.
        ///     1. Take a snapshot of a local deployment.
        ///     2. Download the local snapshot to a temporary address.
        ///     3. Upload the local snapshot to the cloud through in three steps:
        ///     3a. Allocate space for the snapshot.
        ///     3b. Upload the local snapshot to the allocated space.
        ///     3c. Confirm uploading has completed to mark the snapshot as available.
        ///     4. Start a new cloud deployment using the newly uploaded snapshot.
        ///
        ///     In order for this script to start the local deployment correctly, please build the local project by running "spatial build" in the project directory.
        /// </summary>
        /// <param name="args"></param>
        private static void Main(string[] args)
        {
            Setup();

            Console.WriteLine("Taking a local snapshot");
            var localSnapshot = LocalSnapshotServiceClient.TakeSnapshot(new TakeSnapshotRequest
            {
                Snapshot = new Snapshot
                {
                    ProjectName    = ProjectName,
                    DeploymentName = DeploymentName
                }
            })
                                .PollUntilCompleted()
                                .GetResultOrNull();

            Console.WriteLine("Downloading the local snapshot");
            var snapshotFile = Path.GetTempPath() + Guid.NewGuid();

            using (var client = new WebClient())
            {
                client.DownloadFile(localSnapshot.DownloadUrl, snapshotFile);
            }

            Console.WriteLine("Uploading the local snapshot to cloud");
            Console.WriteLine("Acquiring a URL to upload");
            localSnapshot.ProjectName    = ProjectName;
            localSnapshot.DeploymentName = DeploymentName;
            var uploadSnapshotResponse =
                CloudSnapshotServiceClient.UploadSnapshot(new UploadSnapshotRequest {
                Snapshot = localSnapshot
            });

            Console.WriteLine("Uploading to the acquired URL");
            var newSnapshot = uploadSnapshotResponse.Snapshot;
            var httpRequest = WebRequest.Create(uploadSnapshotResponse.UploadUrl) as HttpWebRequest;

            httpRequest.Method        = "PUT";
            httpRequest.ContentLength = newSnapshot.Size;
            httpRequest.Headers.Set("Content-MD5", newSnapshot.Checksum);
            using (var dataStream = httpRequest.GetRequestStream())
            {
                var bytesToSend = File.ReadAllBytes(snapshotFile);
                dataStream.Write(bytesToSend, 0, bytesToSend.Length);
            }

            httpRequest.GetResponse();

            Console.WriteLine("Confirming that uploading is finished");
            CloudSnapshotServiceClient.ConfirmUpload(new ConfirmUploadRequest
            {
                DeploymentName = newSnapshot.DeploymentName,
                Id             = newSnapshot.Id,
                ProjectName    = newSnapshot.ProjectName
            });

            Console.WriteLine("Starting a new cloud deployment with the new snapshot");
            _cloudDeployment = new Deployment
            {
                ProjectName  = ProjectName,
                Name         = DeploymentName,
                LaunchConfig = new LaunchConfig
                {
                    ConfigJson = File.ReadAllText(LaunchConfigFilePath)
                },
                AssemblyId         = AssemblyId,
                StartingSnapshotId = newSnapshot.Id
            };
            _cloudDeployment = CloudDeploymentServiceClient.CreateDeployment(new CreateDeploymentRequest
            {
                Deployment = _cloudDeployment
            }).PollUntilCompleted().GetResultOrNull();

            Cleanup();
        }
Exemple #13
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);
        }
Exemple #14
0
        private void StartDeployment(string newDeploymentName)
        {
            Log.Logger.Information("Starting new deployment named {dplName}", newDeploymentName);
            string snapshotId;

            try
            {
                snapshotId = CreateSnapshotId(newDeploymentName);
            }
            catch (RpcException e)
            {
                if (e.StatusCode == StatusCode.ResourceExhausted)
                {
                    Log.Logger.Warning("Resource exhausted creating snapshot: {err}", e.Message);
                    return;
                }

                throw e;
            }
            var launchConfig = GetLaunchConfig();

            var deployment = new Deployment
            {
                Name               = newDeploymentName,
                ProjectName        = spatialProject,
                Description        = "Launched by Deployment Pool",
                AssemblyId         = assemblyName,
                LaunchConfig       = launchConfig,
                StartingSnapshotId = snapshotId,
            };

            deployment.Tag.Add(DeploymentPool.StartingTag);
            deployment.Tag.Add(matchType);

            var createDeploymentRequest = new CreateDeploymentRequest
            {
                Deployment = deployment
            };

            try
            {
                var startTime = DateTime.Now;
                Reporter.ReportDeploymentCreationRequest(matchType);
                var createOp = deploymentServiceClient.CreateDeployment(createDeploymentRequest);
                Task.Run(() =>
                {
                    var completed = createOp.PollUntilCompleted();
                    Reporter.ReportDeploymentCreationDuration(matchType, (DateTime.Now - startTime).TotalSeconds);
                    if (completed.IsCompleted)
                    {
                        Log.Logger.Information("Deployment {dplName} started succesfully", completed.Result.Name);
                    }
                    else if (completed.IsFaulted)
                    {
                        Log.Logger.Error("Failed to start deployment {DplName}. Operation {opName}. Error {err}", createDeploymentRequest.Deployment.Name, completed.Name, completed.Exception.Message);
                    }
                    else
                    {
                        Log.Logger.Error("Internal error starting deployment {dplName}. Operation {opName}. Error {err}", completed.Result.Name, completed.Name, completed.Exception.Message);
                    }
                });
            }
            catch (RpcException e)
            {
                Reporter.ReportDeploymentCreationFailure(matchType);
                Log.Logger.Error("Failed to start deployment creation. Error: {err}", e.Message);
            }
        }