repo_name
stringlengths 1
52
| repo_creator
stringclasses 6
values | programming_language
stringclasses 4
values | code
stringlengths 0
9.68M
| num_lines
int64 1
234k
|
---|---|---|---|---|
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System.Globalization;
namespace AmazonGameLift.Editor
{
internal static class SettingsFormatter
{
public static int? ParseInt(string value)
{
bool success = int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int result);
return success ? result : default(int?);
}
public static string FormatInt(int value)
{
return value.ToString(CultureInfo.InvariantCulture);
}
}
}
| 22 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using AmazonGameLiftPlugin.Core.SettingsManagement.Models;
using UnityEditor;
namespace AmazonGameLift.Editor
{
internal class BootstrapSetting : Setting
{
private readonly CoreApi _coreApi;
private readonly CredentialsSetting _credentialsSetting;
public BootstrapSetting(CoreApi coreApi, CredentialsSetting credentialsSetting)
: base(Strings.LabelSettingsBootstrapTitle, Strings.LabelSettingsBootstrapButton,
Strings.TooltipSettingsBootstrap, Strings.LabelSettingsBootstrapWarning)
{
_coreApi = coreApi ?? throw new ArgumentNullException(nameof(coreApi));
_credentialsSetting = credentialsSetting ?? throw new ArgumentNullException(nameof(credentialsSetting));
IsPrimaryActionEnabled = false;
}
internal override void RunPrimaryAction()
{
EditorWindow.GetWindow<BootstrapWindow>();
}
internal override void Refresh()
{
base.Refresh();
IsPrimaryActionEnabled = _credentialsSetting.IsConfigured;
}
protected override bool RefreshIsConfigured()
{
GetSettingResponse bucketNameResponse = _coreApi.GetSetting(SettingsKeys.CurrentBucketName);
string currentBucketName = bucketNameResponse.Success ? bucketNameResponse.Value : null;
GetSettingResponse currentRegionResponse = _coreApi.GetSetting(SettingsKeys.CurrentRegion);
string currentRegion = currentRegionResponse.Success ? currentRegionResponse.Value : null;
return !string.IsNullOrEmpty(currentBucketName) && _coreApi.IsValidRegion(currentRegion);
}
}
}
| 46 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using AmazonGameLiftPlugin.Core.CredentialManagement.Models;
using AmazonGameLiftPlugin.Core.SettingsManagement.Models;
using UnityEditor;
namespace AmazonGameLift.Editor
{
/// <summary>
/// Ensures that the AWS profile and region are set up. Primary action is to open the setup window.
/// </summary>
internal class CredentialsSetting : Setting
{
private readonly CoreApi _coreApi;
public CredentialsSetting(CoreApi coreApi)
: base(Strings.LabelSettingsAwsCredentialsTitle, Strings.LabelSettingsAwsCredentialsSetUpButton, Strings.TooltipSettingsAwsCredentials) =>
_coreApi = coreApi ?? throw new ArgumentNullException(nameof(coreApi));
internal override void RunPrimaryAction()
{
EditorWindow.GetWindow<AwsCredentialsWindow>();
}
protected override bool RefreshIsConfigured()
{
PrimaryActionMessage = Strings.LabelSettingsAwsCredentialsSetUpButton;
GetSettingResponse profileResponse = _coreApi.GetSetting(SettingsKeys.CurrentProfileName);
if (!profileResponse.Success)
{
return false;
}
RetriveAwsCredentialsResponse credentialsResponse = _coreApi.RetrieveAwsCredentials(profileResponse.Value);
if (!credentialsResponse.Success)
{
return false;
}
GetSettingResponse currentRegionResponse = _coreApi.GetSetting(SettingsKeys.CurrentRegion);
if (!currentRegionResponse.Success || !_coreApi.IsValidRegion(currentRegionResponse.Value))
{
return false;
}
PrimaryActionMessage = Strings.LabelAwsCredentialsUpdateButton;
return true;
}
}
}
| 56 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using UnityEditor;
namespace AmazonGameLift.Editor
{
/// <summary>
/// Ensures that Unity project .NET settings are set up. Primary action is to set the required project settings.
/// </summary>
internal class DotNetSetting : Setting
{
public DotNetSetting()
: base(Strings.LabelSettingsDotNetTitle, Strings.LabelSettingsDotNetButton, Strings.TooltipSettingsDotNet)
{
}
internal override void RunPrimaryAction()
{
PlayerSettings.SetApiCompatibilityLevel(BuildTargetGroup.Standalone,
ApiCompatibilityLevel.NET_4_6);
PlayerSettings.SetApiCompatibilityLevel(BuildTargetGroup.Android,
ApiCompatibilityLevel.NET_4_6);
}
protected override bool RefreshIsConfigured()
{
return IsApiCompatibilityLevel4X();
}
public static bool IsApiCompatibilityLevel4X()
{
ApiCompatibilityLevel apiLevel = PlayerSettings.GetApiCompatibilityLevel(BuildTargetGroup.Standalone);
return apiLevel == ApiCompatibilityLevel.NET_4_6;
}
}
}
| 38 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using AmazonGameLiftPlugin.Core.SettingsManagement.Models;
using UnityEditor;
using UnityEngine;
namespace AmazonGameLift.Editor
{
/// <summary>
/// Shows the settings window once; started by Unity.
/// </summary>
internal sealed class FirstTimeSettingsLauncher
{
private const string NonEmptyValue = "1";
[InitializeOnLoadMethod]
private static void Run()
{
if (Application.isBatchMode)
{
return;
}
GetSettingResponse response = CoreApi.SharedInstance.GetSetting(SettingsKeys.WasSettingsWindowShown);
if (!response.Success)
{
EditorMenu.ShowPluginSettings();
}
}
internal static void SetSetting()
{
CoreApi.SharedInstance.PutSetting(SettingsKeys.WasSettingsWindowShown, NonEmptyValue);
}
}
}
| 39 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using AmazonGameLiftPlugin.Core.SettingsManagement.Models;
using UnityEngine;
namespace AmazonGameLift.Editor
{
/// <summary>
/// Ensures that GameLift Local is available. Primary action is to open a web browser with the download page.
/// </summary>
internal class GameLiftLocalSetting : Setting
{
private readonly CoreApi _coreApi;
public GameLiftLocalSetting(CoreApi coreApi)
: base(Strings.LabelSettingsLocalTestingTitle, Strings.LabelSettingsLocalTestingButton, Strings.TooltipSettingsLocalTesting) =>
_coreApi = coreApi ?? throw new System.ArgumentNullException(nameof(coreApi));
internal override void RunPrimaryAction()
{
Application.OpenURL(Urls.AwsGameLiftLocal);
}
protected override bool RefreshIsConfigured()
{
GetSettingResponse response = _coreApi.GetSetting(SettingsKeys.GameLiftLocalPath);
return response.Success && _coreApi.FileExists(response.Value);
}
internal virtual void SetPath(string path)
{
_coreApi.PutSetting(SettingsKeys.GameLiftLocalPath, path);
RefreshIsConfigured();
}
}
}
| 38 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using UnityEditor;
using UnityEngine;
namespace AmazonGameLift.Editor
{
internal class GameLiftSettingPanel : SettingPanel
{
private readonly GameLiftLocalSetting _setting;
private readonly string _startPath;
private readonly string _labelSetPath;
private readonly string _titleSetPathDialog;
public GameLiftSettingPanel(GameLiftLocalSetting setting, TextProvider textProvider)
: base(setting, textProvider)
{
_setting = setting ?? throw new ArgumentNullException(nameof(setting));
_startPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
_labelSetPath = textProvider.Get(Strings.LabelSettingsLocalTestingSetPathButton);
_titleSetPathDialog = textProvider.Get(Strings.TitleLocalTestingGameLiftPathDialog);
}
public override void DrawAction()
{
EditorGUILayout.BeginHorizontal();
{
base.DrawAction();
if (GUILayout.Button(_labelSetPath))
{
string path = EditorUtility.OpenFilePanel(_titleSetPathDialog, _startPath, "jar");
_setting.SetPath(path);
}
}
EditorGUILayout.EndHorizontal();
}
}
}
| 42 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using UnityEngine;
namespace AmazonGameLift.Editor
{
/// <summary>
/// Ensures that Java runtime is available. Primary action is to open a web browser with the download page.
/// </summary>
internal class JavaSetting : Setting
{
private readonly CoreApi _coreApi;
public JavaSetting(CoreApi coreApi)
: base(Strings.LabelSettingsJavaTitle, Strings.LabelSettingsJavaButton, Strings.TooltipSettingsJava) =>
_coreApi = coreApi ?? throw new System.ArgumentNullException(nameof(coreApi));
internal override void RunPrimaryAction()
{
Application.OpenURL(Urls.JavaDownload);
}
protected override bool RefreshIsConfigured()
{
return _coreApi.CheckInstalledJavaVersion();
}
}
}
| 30 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
namespace AmazonGameLift.Editor
{
internal abstract class Setting
{
public string Title { get; }
public string PrimaryActionMessage { get; protected set; }
public string PrimaryActionDisabledTooltip { get; }
public string Tooltip { get; }
public virtual bool IsConfigured { get; private set; }
public virtual bool IsPrimaryActionEnabled { get; protected set; } = true;
protected Setting(string title, string primaryActionMessage, string tooltip, string primaryActionDisabledTooltip = null)
{
Title = title;
PrimaryActionMessage = primaryActionMessage;
Tooltip = tooltip;
PrimaryActionDisabledTooltip = primaryActionDisabledTooltip;
}
/// <summary>
/// Run any action needed by clicking the primary setting button.
/// </summary>
internal abstract void RunPrimaryAction();
internal virtual void Refresh()
{
IsConfigured = RefreshIsConfigured();
}
protected abstract bool RefreshIsConfigured();
}
}
| 41 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using UnityEditor;
using UnityEngine;
namespace AmazonGameLift.Editor
{
internal class SettingPanel
{
private readonly Setting _setting;
private readonly string _labelSettingsConfigured;
private readonly string _labelSettingsNotConfigured;
private readonly string _settingTitle;
private readonly string _settingTooltip;
private readonly string _primaryActionDisabledTooltip;
private GUIStyle _hintStyle;
protected TextProvider TextProvider { get; }
public SettingPanel(Setting setting, TextProvider textProvider)
{
_setting = setting ?? throw new ArgumentNullException(nameof(setting));
TextProvider = textProvider ?? throw new ArgumentNullException(nameof(textProvider));
_labelSettingsConfigured = textProvider.Get(Strings.LabelSettingsConfigured);
_labelSettingsNotConfigured = textProvider.Get(Strings.LabelSettingsNotConfigured);
_settingTitle = textProvider.Get(setting.Title);
_settingTooltip = textProvider.Get(setting.Tooltip);
_primaryActionDisabledTooltip = _setting.PrimaryActionDisabledTooltip != null
? TextProvider.Get(_setting.PrimaryActionDisabledTooltip)
: null;
}
public void Draw()
{
if (_hintStyle == null)
{
_hintStyle = ResourceUtility.GetInfoLabelStyle();
}
EditorGUILayout.BeginVertical();
{
EditorGUILayout.BeginHorizontal();
{
GUILayout.Label(_settingTitle, style: EditorStyles.largeLabel);
GUILayout.FlexibleSpace();
DrawConfiguredStatus();
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
{
GUILayout.Space(5f);
GUILayout.Label(_settingTooltip, _hintStyle);
}
EditorGUILayout.EndHorizontal();
GUILayout.Space(7f);
DrawAction();
}
EditorGUILayout.EndVertical();
}
public virtual void DrawAction()
{
bool disabled = !_setting.IsPrimaryActionEnabled;
using (new EditorGUI.DisabledScope(disabled))
{
string label = TextProvider.Get(_setting.PrimaryActionMessage);
string tooltip = disabled ? _primaryActionDisabledTooltip : null;
if (GUILayout.Button(new GUIContent(label, tooltip)))
{
_setting.RunPrimaryAction();
}
}
}
private void DrawConfiguredStatus()
{
if (_setting.IsConfigured)
{
GUILayout.Label(_labelSettingsConfigured, ResourceUtility.GetConfiguredStyle());
}
else
{
GUILayout.Label(_labelSettingsNotConfigured, ResourceUtility.GetNotConfiguredStyle());
}
GUILayout.Space(3f);
}
}
}
| 96 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using System.Collections.Generic;
namespace AmazonGameLift.Editor
{
internal sealed class Settings
{
public static Settings SharedInstance { get; } = new Settings();
public BootstrapSetting BootstrapSetting { get; }
public CredentialsSetting CredentialsSetting { get; }
public DotNetSetting DotNetSetting { get; } = new DotNetSetting();
public GameLiftLocalSetting GameLiftLocalSetting { get; }
public JavaSetting JavaSetting { get; }
public IEnumerable<Setting> AllSettings { get; }
public event Action AnySettingChanged;
/// <summary>
/// Only for testing.
/// </summary>
internal Settings(BootstrapSetting bootstrapSetting, CredentialsSetting credentialsSetting,
GameLiftLocalSetting gameLiftLocalSetting, JavaSetting javaSetting)
{
BootstrapSetting = bootstrapSetting ?? throw new ArgumentNullException(nameof(bootstrapSetting));
CredentialsSetting = credentialsSetting ?? throw new System.ArgumentNullException(nameof(credentialsSetting));
GameLiftLocalSetting = gameLiftLocalSetting ?? throw new System.ArgumentNullException(nameof(gameLiftLocalSetting));
JavaSetting = javaSetting ?? throw new System.ArgumentNullException(nameof(javaSetting));
}
private Settings()
{
CoreApi coreApi = CoreApi.SharedInstance;
CredentialsSetting = new CredentialsSetting(coreApi);
BootstrapSetting = new BootstrapSetting(coreApi, CredentialsSetting);
GameLiftLocalSetting = new GameLiftLocalSetting(coreApi);
JavaSetting = new JavaSetting(coreApi);
AllSettings = new List<Setting>
{
CredentialsSetting,
BootstrapSetting,
DotNetSetting,
GameLiftLocalSetting,
JavaSetting
};
}
public void Refresh()
{
bool isAnySettingChanged = false;
foreach (Setting setting in AllSettings)
{
bool wasConfigured = setting.IsConfigured;
setting.Refresh();
if (setting.IsConfigured != wasConfigured)
{
isAnySettingChanged = true;
}
}
if (isAnySettingChanged)
{
AnySettingChanged?.Invoke();
}
}
}
}
| 78 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System.Threading.Tasks;
using UnityEditor;
using UnityEngine;
namespace AmazonGameLift.Editor
{
/// <summary>
/// Runs the periodic settings checks; started by Unity.
/// </summary>
internal sealed class SettingsChecker
{
private const int CheckPeriodMs = 3000;
[InitializeOnLoadMethod]
private static async void StartPeriodicChecks()
{
if (Application.isBatchMode)
{
return;
}
Settings settings = Settings.SharedInstance;
while (true)
{
if (SettingsWindow.IsOpen)
{
settings.Refresh();
}
await Task.Delay(CheckPeriodMs);
}
}
}
}
| 39 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using System.Linq;
using UnityEngine;
namespace AmazonGameLift.Editor
{
[Serializable]
internal sealed class SettingsState
{
public const int TabSdk = 0;
public const int TabTest = 1;
public const int TabDeploy = 2;
public const int TabHelp = 3;
private Status _status;
private TextProvider _textProvider;
private Settings _settings;
public IReadStatus Status => _status;
[field:SerializeField]
public int ActiveTab { get; set; }
public bool CanDeploy =>
_settings.CredentialsSetting.IsConfigured
&& _settings.BootstrapSetting.IsConfigured;
public bool CanRunLocalTest => _settings.GameLiftLocalSetting.IsConfigured
&& _settings.JavaSetting.IsConfigured;
public SettingsState(Settings settings, TextProvider textProvider)
{
Restore(settings, textProvider);
}
public void Restore(Settings settings, TextProvider textProvider)
{
if (settings is null)
{
throw new ArgumentNullException(nameof(settings));
}
if (textProvider is null)
{
throw new ArgumentNullException(nameof(textProvider));
}
_textProvider = textProvider;
_settings = settings;
_status = new Status();
}
public void Refresh()
{
bool allConfigured = _settings.AllSettings.All(setting => setting.IsConfigured);
if (allConfigured == _status.IsDisplayed)
{
return;
}
_status.IsDisplayed = allConfigured;
if (allConfigured)
{
_status.SetMessage(_textProvider.Get(Strings.LabelSettingsAllConfigured), UnityEditor.MessageType.Info);
}
}
}
}
| 74 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using UnityEditor;
using UnityEngine;
namespace AmazonGameLift.Editor
{
internal class SettingsWindow : EditorWindow
{
private const float SettingsWindowMinWidth = 320;
private const float SettingsWindowMinHeight = 500;
private const float GameLiftLogoHeight = 35;
private const float SettingsPanelTopMargin = 15f;
private const float TopMarginPixels = 7f;
private const float LeftMarginPixels = 17f;
private const float RightMarginPixels = 13f;
private const float SpaceBetweenSettingsPixels = 15f;
private Settings _settings;
private StatusLabel _statusLabel;
private SettingPanel _dotNetPanel;
private GameLiftSettingPanel _glLocalPanel;
private SettingPanel _javaPanel;
private SettingPanel _credentialsPanel;
private SettingPanel _bootstrapPanel;
private ControlDrawer _controlDrawer;
private ImageLoader _imageLoader;
private TextProvider _textProvider;
[SerializeField]
private Texture2D _gameLiftLogo;
private SettingsState _settingsState;
private string _labelSdkTab;
private string _labelOpenForums;
private string _labelOpenAwsHelp;
private string _labelReportSecurity;
private string _labelPingSdk;
private string _labelReportBugs;
private string _labelOpenDeployment;
private string _labelOpenLocalTest;
private string _labelHelpTab;
private string _labelTestTab;
private string _labelDeployTab;
private string _labelOpenSdkIntegrationDoc;
private string _labelOpenSdkApiDoc;
public static bool IsOpen { get; private set; }
private void SetUp()
{
_imageLoader = new ImageLoader();
_textProvider = TextProviderFactory.Create();
_labelSdkTab = _textProvider.Get(Strings.LabelSettingsSdkTab);
_labelDeployTab = _textProvider.Get(Strings.LabelSettingsDeployTab);
_labelTestTab = _textProvider.Get(Strings.LabelSettingsTestTab);
_labelHelpTab = _textProvider.Get(Strings.LabelSettingsHelpTab);
_labelOpenForums = _textProvider.Get(Strings.LabelSettingsOpenForums);
_labelOpenAwsHelp = _textProvider.Get(Strings.LabelSettingsOpenAwsHelp);
_labelReportSecurity = _textProvider.Get(Strings.LabelSettingsReportSecurity);
_labelReportBugs = _textProvider.Get(Strings.LabelSettingsReportBugs);
_labelOpenDeployment = _textProvider.Get(Strings.LabelSettingsOpenDeployment);
_labelOpenLocalTest = _textProvider.Get(Strings.LabelSettingsOpenLocalTest);
_labelPingSdk = _textProvider.Get(Strings.LabelSettingsPingSdk);
_labelOpenSdkIntegrationDoc = _textProvider.Get(Strings.LabelOpenSdkIntegrationDoc);
_labelOpenSdkApiDoc = _textProvider.Get(Strings.LabelOpenSdkApiDoc);
titleContent = new GUIContent(_textProvider.Get(Strings.TitleSettings));
minSize = new Vector2(SettingsWindowMinWidth, SettingsWindowMinHeight);
_statusLabel = new StatusLabel();
_controlDrawer = ControlDrawerFactory.Create();
_settings = Settings.SharedInstance;
_dotNetPanel = new SettingPanel(_settings.DotNetSetting, _textProvider);
_glLocalPanel = new GameLiftSettingPanel(_settings.GameLiftLocalSetting, _textProvider);
_javaPanel = new SettingPanel(_settings.JavaSetting, _textProvider);
_credentialsPanel = new SettingPanel(_settings.CredentialsSetting, _textProvider);
_bootstrapPanel = new SettingPanel(_settings.BootstrapSetting, _textProvider);
if (_settingsState == null)
{
_settingsState = new SettingsState(_settings, _textProvider);
}
else
{
_settingsState.Restore(_settings, _textProvider);
}
_settings.AnySettingChanged += Repaint;
_settings.Refresh();
}
private void OnEnable()
{
SetUp();
IsOpen = true;
}
private void OnDisable()
{
IsOpen = false;
if (_settings != null)
{
_settings.AnySettingChanged -= Repaint;
}
FirstTimeSettingsLauncher.SetSetting();
}
private void OnGUI()
{
// HACK: During InitializeOnLoadMethod in FirstTimeSettingsLauncher.cs, Resource.Load() cannot find
// the image at "Images/Dark/GameLiftLogo", though subsequent attempts load the image successfully.
// This is suspected to be due to a race condition between InitializeOnLoadMethod and readiness
// of the Editor Resources.
if (_gameLiftLogo == null)
{
_gameLiftLogo = _imageLoader.LoadImage(AssetNames.GameLiftLogo);
}
// Displays the GameLift Logo
GUILayout.Space(TopMarginPixels);
if (_gameLiftLogo)
{
GUILayout.Space(TopMarginPixels);
using (new EditorGUILayout.HorizontalScope())
{
GUILayout.Space(LeftMarginPixels);
float logoHeight = GameLiftLogoHeight;
float logoWidth = GameLiftLogoHeight / _gameLiftLogo.height * _gameLiftLogo.width;
Rect logoRect = GUILayoutUtility.GetRect(logoWidth, logoHeight, style: GUI.skin.box);
GUI.DrawTexture(logoRect, _gameLiftLogo, ScaleMode.ScaleToFit);
GUILayout.Space(RightMarginPixels);
}
}
// Displays the Settings UI top nav
GUILayout.Space(TopMarginPixels);
using (new EditorGUILayout.HorizontalScope(EditorStyles.toolbar))
{
GUILayout.Space(LeftMarginPixels);
DrawTabHeader(_labelSdkTab, SettingsState.TabSdk);
DrawTabHeader(_labelTestTab, SettingsState.TabTest);
DrawTabHeader(_labelDeployTab, SettingsState.TabDeploy);
GUILayout.FlexibleSpace();
DrawTabHeader(_labelHelpTab, SettingsState.TabHelp);
GUILayout.Space(RightMarginPixels);
}
// Displays the current active panel, e.g. SDK / Testing / Deployment / Help
GUILayout.Space(SettingsPanelTopMargin);
DrawActiveTab();
_settingsState.Refresh();
}
private void DrawTabHeader(string label, int tabId, float width = 70f)
{
GUIStyle style = _settingsState.ActiveTab == tabId ? ResourceUtility.GetTabActiveStyle() : ResourceUtility.GetTabNormalStyle();
if (GUILayout.Button(label, style, GUILayout.MaxWidth(width)))
{
_settingsState.ActiveTab = tabId;
}
}
private void DrawActiveTab()
{
using (new EditorGUILayout.HorizontalScope())
{
GUILayout.Space(LeftMarginPixels - 5f);
using (new EditorGUILayout.VerticalScope())
{
switch (_settingsState.ActiveTab)
{
case SettingsState.TabSdk:
DrawSdkTab();
break;
case SettingsState.TabTest:
DrawTestTab();
break;
case SettingsState.TabDeploy:
DrawDeployTab();
break;
case SettingsState.TabHelp:
DrawHelpTab();
break;
default:
break;
}
}
GUILayout.Space(RightMarginPixels);
}
}
private void DrawHelpTab()
{
if (GUILayout.Button(_labelOpenAwsHelp))
{
EditorMenu.OpenAwsDocumentation();
}
GUILayout.Space(TopMarginPixels);
if (GUILayout.Button(_labelOpenForums))
{
EditorMenu.OpenForums();
}
GUILayout.Space(TopMarginPixels);
if (GUILayout.Button(_labelReportBugs))
{
EditorMenu.ReportBugs();
}
GUILayout.Space(TopMarginPixels);
if (GUILayout.Button(_labelReportSecurity))
{
EditorMenu.ReportSecurity();
}
}
private void DrawDeployTab()
{
_credentialsPanel.Draw();
GUILayout.Space(SpaceBetweenSettingsPixels);
_bootstrapPanel.Draw();
_controlDrawer.DrawSeparator();
using (new EditorGUI.DisabledGroupScope(!_settingsState.CanDeploy))
{
if (GUILayout.Button(_labelOpenDeployment))
{
EditorMenu.ShowDeployment();
}
}
if (_settingsState.CanDeploy)
{
using (new EditorGUILayout.HorizontalScope())
{
GUILayout.Space(5F);
_statusLabel.Draw(_textProvider.Get(Strings.SettingsUIDeployNextStepLabel), MessageType.Info);
}
}
}
private void DrawTestTab()
{
_glLocalPanel.Draw();
GUILayout.Space(SpaceBetweenSettingsPixels);
_javaPanel.Draw();
_controlDrawer.DrawSeparator();
using (new EditorGUI.DisabledGroupScope(!_settingsState.CanRunLocalTest))
{
if (GUILayout.Button(_labelOpenLocalTest))
{
EditorMenu.ShowLocalTesting();
}
}
if (_settingsState.CanRunLocalTest)
{
using (new EditorGUILayout.HorizontalScope())
{
GUILayout.Space(5F);
_statusLabel.Draw(_textProvider.Get(Strings.SettingsUITestNextStepLabel), MessageType.Info);
}
}
}
private void DrawSdkTab()
{
_dotNetPanel.Draw();
_controlDrawer.DrawSeparator();
if (GUILayout.Button(_labelPingSdk))
{
EditorMenu.PingSdk();
}
GUILayout.Space(TopMarginPixels);
if (GUILayout.Button(_labelOpenSdkIntegrationDoc))
{
EditorMenu.OpenGameLiftServerCSharpSdkIntegrationDoc();
}
GUILayout.Space(TopMarginPixels);
if (GUILayout.Button(_labelOpenSdkApiDoc))
{
EditorMenu.OpenGameLiftServerCSharpSdkApiDoc();
}
GUILayout.Space(TopMarginPixels);
if (DotNetSetting.IsApiCompatibilityLevel4X())
{
using (new EditorGUILayout.HorizontalScope())
{
GUILayout.Space(5F);
_statusLabel.Draw(_textProvider.Get(Strings.SettingsUISdkNextStepLabel), MessageType.Info);
}
}
}
}
}
| 316 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System.Threading.Tasks;
using AmazonGameLift.Editor;
using AmazonGameLiftPlugin.Core.DeploymentManagement.Models;
using AmazonGameLiftPlugin.Core.Shared;
using JetBrains.Annotations;
namespace AmazonGameLift.AuthOnly
{
[UsedImplicitly]
public sealed class Deployer : DeployerBase
{
public override string DisplayName => "Auth Only";
public override string Description =>
"This CloudFormation template sets up a minimal game backend service with only 1 functionality -- player authentication. "
+ "Lambda handler to start a game and view game connection information are stubbed to always return 501 error (Unimplemented).";
public override string HelpUrl => "https://docs.aws.amazon.com/gamelift/latest/developerguide/unity-plug-in-scenario.html";
public override string ScenarioFolder => "scenario1_auth_only";
public override bool HasGameServer => false;
public override int PreferredUiOrder => 1;
protected override Task<DeploymentResponse> Deploy(DeploymentRequest request)
{
ExecuteChangeSetResponse executeResponse = GameLiftCoreApi.ExecuteChangeSet(
request.Profile, request.Region, request.StackName, request.ChangeSetName);
if (!executeResponse.Success)
{
return Task.FromResult(Response.Fail(new DeploymentResponse(executeResponse)));
}
return Task.FromResult(Response.Ok(new DeploymentResponse()));
}
}
}
| 43 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System.Threading.Tasks;
using AmazonGameLift.Editor;
using AmazonGameLiftPlugin.Core.DeploymentManagement.Models;
using AmazonGameLiftPlugin.Core.Shared;
using JetBrains.Annotations;
namespace AmazonGameLift.SingleFleet
{
[UsedImplicitly]
public sealed class Deployer : DeployerBase
{
public override string DisplayName => "Single-Region Fleet";
public override string Description =>
"This CloudFormation template sets up a game backend service with a single Amazon GameLift fleet. "
+ "After player authenticates and start a game via POST /start_game, a lambda handler searches for an existing viable game session with open player slot on the fleet, and if not found, creates a new game session. "
+ "The game client is then expected to poll POST /get_game_connection to receive a viable game session.";
public override string HelpUrl => "https://docs.aws.amazon.com/gamelift/latest/developerguide/unity-plug-in-scenario.html";
public override string ScenarioFolder => "scenario2_single_fleet";
public override bool HasGameServer => true;
public override int PreferredUiOrder => 2;
protected override Task<DeploymentResponse> Deploy(DeploymentRequest request)
{
string zipPath = GameLiftCoreApi.GetUniqueTempFilePath();
GameLiftCoreApi.Zip(request.BuildFolderPath, zipPath);
UploadServerBuildResponse uploadBuildResponse = GameLiftCoreApi.UploadServerBuild(
request.Profile, request.Region, request.BucketName, request.BuildS3Key, zipPath);
if (GameLiftCoreApi.FileExists(zipPath))
{
GameLiftCoreApi.FileDelete(zipPath);
}
if (!uploadBuildResponse.Success)
{
return Task.FromResult(Response.Fail(new DeploymentResponse(uploadBuildResponse)));
}
ExecuteChangeSetResponse executeResponse = GameLiftCoreApi.ExecuteChangeSet(
request.Profile, request.Region, request.StackName, request.ChangeSetName);
if (!executeResponse.Success)
{
return Task.FromResult(Response.Fail(new DeploymentResponse(executeResponse)));
}
return Task.FromResult(Response.Ok(new DeploymentResponse()));
}
}
}
| 60 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System.Threading.Tasks;
using AmazonGameLift.Editor;
using AmazonGameLiftPlugin.Core.DeploymentManagement.Models;
using AmazonGameLiftPlugin.Core.Shared;
using JetBrains.Annotations;
namespace AmazonGameLift.MrfQueue
{
[UsedImplicitly]
public sealed class Deployer : DeployerBase
{
public override string DisplayName => "Multi-Region Fleets with Queue and Custom Matchmaker";
public override string Description =>
"This CloudFormation template sets up a scenario where Amazon GameLift queues are used in conjunction with a custom matchmaker. "
+ "For simplicity sake, this custom matchmaker form matches by taking the oldest players in the waiting pool and not considering any other factors such as skills or latency. "
+ "Once the group of players to form matches is identified, a lambda function calls GameLift:StartGameSessionPlacement to start a queue placement.";
public override string HelpUrl => "https://docs.aws.amazon.com/gamelift/latest/developerguide/unity-plug-in-scenario.html";
public override string ScenarioFolder => "scenario3_mrf_queue";
public override bool HasGameServer => true;
public override int PreferredUiOrder => 3;
protected override Task<DeploymentResponse> Deploy(DeploymentRequest request)
{
string zipPath = GameLiftCoreApi.GetUniqueTempFilePath();
GameLiftCoreApi.Zip(request.BuildFolderPath, zipPath);
UploadServerBuildResponse uploadBuildResponse = GameLiftCoreApi.UploadServerBuild(
request.Profile, request.Region, request.BucketName, request.BuildS3Key, zipPath);
if (GameLiftCoreApi.FileExists(zipPath))
{
GameLiftCoreApi.FileDelete(zipPath);
}
if (!uploadBuildResponse.Success)
{
return Task.FromResult(Response.Fail(new DeploymentResponse(uploadBuildResponse)));
}
ExecuteChangeSetResponse executeResponse = GameLiftCoreApi.ExecuteChangeSet(
request.Profile, request.Region, request.StackName, request.ChangeSetName);
if (!executeResponse.Success)
{
return Task.FromResult(Response.Fail(new DeploymentResponse(executeResponse)));
}
return Task.FromResult(Response.Ok(new DeploymentResponse()));
}
}
}
| 60 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System.Threading.Tasks;
using AmazonGameLift.Editor;
using AmazonGameLiftPlugin.Core.DeploymentManagement.Models;
using AmazonGameLiftPlugin.Core.Shared;
using JetBrains.Annotations;
namespace AmazonGameLift.SpotFleets
{
[UsedImplicitly]
public sealed class Deployer : DeployerBase
{
public override string DisplayName => "SPOT Fleets with Queue and Custom Matchmaker";
public override string Description =>
"This CloudFormation template sets up the exact same scenario as 'Multi-Region Fleets', except that 3 fleets are created instead of 1, with 2 of the fleets being SPOT fleets containing nuanced instance types. "
+ "This is to demonstrate the best practices in using GameLift queues to keep availability high and cost low.";
public override string HelpUrl => "https://docs.aws.amazon.com/gamelift/latest/developerguide/unity-plug-in-scenario.html";
public override string ScenarioFolder => "scenario4_spot_fleets";
public override bool HasGameServer => true;
public override int PreferredUiOrder => 4;
protected override Task<DeploymentResponse> Deploy(DeploymentRequest request)
{
string zipPath = GameLiftCoreApi.GetUniqueTempFilePath();
GameLiftCoreApi.Zip(request.BuildFolderPath, zipPath);
UploadServerBuildResponse uploadBuildResponse = GameLiftCoreApi.UploadServerBuild(
request.Profile, request.Region, request.BucketName, request.BuildS3Key, zipPath);
if (GameLiftCoreApi.FileExists(zipPath))
{
GameLiftCoreApi.FileDelete(zipPath);
}
if (!uploadBuildResponse.Success)
{
return Task.FromResult(Response.Fail(new DeploymentResponse(uploadBuildResponse)));
}
ExecuteChangeSetResponse executeResponse = GameLiftCoreApi.ExecuteChangeSet(
request.Profile, request.Region, request.StackName, request.ChangeSetName);
if (!executeResponse.Success)
{
return Task.FromResult(Response.Fail(new DeploymentResponse(executeResponse)));
}
return Task.FromResult(Response.Ok(new DeploymentResponse()));
}
}
}
| 59 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System.Threading.Tasks;
using AmazonGameLift.Editor;
using AmazonGameLiftPlugin.Core.DeploymentManagement.Models;
using AmazonGameLiftPlugin.Core.Shared;
using JetBrains.Annotations;
namespace AmazonGameLift.FlexMatch
{
[UsedImplicitly]
public sealed class Deployer : DeployerBase
{
public override string DisplayName => "FlexMatch";
public override string Description =>
"This CloudFormation template sets up a scenario to use FlexMatch -- a managed matchmaking service provided by GameLift. "
+ "The template demonstrates best practices in acquiring the matchmaking ticket status, "
+ "by listening to FlexMatch events in conjunction with a low frequency poller to ensure incomplete tickets are periodically pinged and therefore are not discarded by GameLift.";
public override string HelpUrl => "https://docs.aws.amazon.com/gamelift/latest/developerguide/unity-plug-in-scenario.html";
public override string ScenarioFolder => "scenario5_flexmatch";
public override bool HasGameServer => true;
public override int PreferredUiOrder => 5;
protected override Task<DeploymentResponse> Deploy(DeploymentRequest request)
{
string zipPath = GameLiftCoreApi.GetUniqueTempFilePath();
GameLiftCoreApi.Zip(request.BuildFolderPath, zipPath);
UploadServerBuildResponse uploadBuildResponse = GameLiftCoreApi.UploadServerBuild(
request.Profile, request.Region, request.BucketName, request.BuildS3Key, zipPath);
if (GameLiftCoreApi.FileExists(zipPath))
{
GameLiftCoreApi.FileDelete(zipPath);
}
if (!uploadBuildResponse.Success)
{
return Task.FromResult(Response.Fail(new DeploymentResponse(uploadBuildResponse)));
}
ExecuteChangeSetResponse executeResponse = GameLiftCoreApi.ExecuteChangeSet(
request.Profile, request.Region, request.StackName, request.ChangeSetName);
if (!executeResponse.Success)
{
return Task.FromResult(Response.Fail(new DeploymentResponse(executeResponse)));
}
return Task.FromResult(Response.Ok(new DeploymentResponse()));
}
}
}
| 60 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
[assembly: System.Reflection.AssemblyCompany("Amazon Web Services")]
[assembly: System.Reflection.AssemblyTitle("GameLift Plugin Editor")]
[assembly: System.Reflection.AssemblyCopyright("Copyright 2021.")]
| 9 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using UnityEngine;
namespace AmazonGameLift.Runtime
{
[CreateAssetMenu(fileName = "GameLiftClientSettings", menuName = "GameLift/Client Settings")]
public sealed class GameLiftClientSettings : ScriptableObject
{
public string AwsRegion;
public string UserPoolClientId;
public string ApiGatewayUrl;
public string LocalUrl = "http://localhost";
public ushort LocalPort = 8080;
public bool IsLocalTest;
public GameLiftConfiguration GetConfiguration()
{
string endpoint = IsLocalTest
? $"{LocalUrl}:{LocalPort}"
: ApiGatewayUrl;
string awsRegion = IsLocalTest ? "eu-west-1" : AwsRegion;
return new GameLiftConfiguration
{
ApiGatewayEndpoint = endpoint,
AwsRegion = awsRegion,
UserPoolClientId = UserPoolClientId,
};
}
}
}
| 33 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
namespace AmazonGameLift.Runtime
{
[System.Serializable]
public struct GameLiftConfiguration
{
public string AwsRegion;
public string UserPoolClientId;
public string ApiGatewayEndpoint;
}
}
| 14 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
#if !UNITY_SERVER
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AmazonGameLiftPlugin.Core.ApiGatewayManagement;
using AmazonGameLiftPlugin.Core.ApiGatewayManagement.Models;
using AmazonGameLiftPlugin.Core.Latency;
using AmazonGameLiftPlugin.Core.Latency.Models;
using AmazonGameLiftPlugin.Core.Shared;
using AmazonGameLiftPlugin.Core.UserIdentityManagement;
using AmazonGameLiftPlugin.Core.UserIdentityManagement.Models;
namespace AmazonGameLift.Runtime
{
public class GameLiftCoreApi
{
private readonly GameLiftConfiguration _configuration;
private readonly bool _isLocalMode;
public GameLiftCoreApi(GameLiftConfiguration configuration)
{
_configuration = configuration;
_userIdentity = new UserIdentity(new AmazonCognitoIdentityWrapper(configuration.AwsRegion));
_apiGateway = new ApiGateway(_userIdentity, new JwtTokenExpirationCheck(), new HttpClientWrapper());
if (_configuration.ApiGatewayEndpoint.StartsWith("https://localhost"))
{
throw new ArgumentException("Invalid configuration: https is not supported by GameLift Local.", nameof(configuration));
}
if (_configuration.ApiGatewayEndpoint.StartsWith("http://localhost"))
{
var gameLiftClientWrapper = new AmazonGameLiftClientWrapper(_configuration.ApiGatewayEndpoint);
_localGame = new LocalGameAdapter(gameLiftClientWrapper);
_isLocalMode = true;
}
}
#region User Accounts
private readonly IUserIdentity _userIdentity;
public virtual SignUpResponse SignUp(string email, string password)
{
if (_isLocalMode)
{
return Response.Ok(new SignUpResponse());
}
var request = new SignUpRequest()
{
ClientId = _configuration.UserPoolClientId,
Username = email,
Password = password,
};
return _userIdentity.SignUp(request);
}
public virtual ConfirmSignUpResponse ConfirmSignUp(string email, string confirmationCode)
{
if (_isLocalMode)
{
return Response.Ok(new ConfirmSignUpResponse());
}
var request = new ConfirmSignUpRequest()
{
ClientId = _configuration.UserPoolClientId,
Username = email,
ConfirmationCode = confirmationCode,
};
return _userIdentity.ConfirmSignUp(request);
}
public virtual SignInResponse SignIn(string email, string password)
{
if (_isLocalMode)
{
return Response.Ok(new SignInResponse()
{
AccessToken = string.Empty,
IdToken = string.Empty,
RefreshToken = string.Empty,
});
}
var request = new SignInRequest()
{
ClientId = _configuration.UserPoolClientId,
Username = email,
Password = password,
};
return _userIdentity.SignIn(request);
}
public virtual SignOutResponse SignOut(string accessToken)
{
if (_isLocalMode)
{
return Response.Ok(new SignOutResponse());
}
var request = new SignOutRequest()
{
AccessToken = accessToken,
};
return _userIdentity.SignOut(request);
}
#endregion
#region Matchmaking
private readonly ApiGateway _apiGateway;
private readonly LatencyService _latencyService = new LatencyService(new PingWrapper());
private readonly LocalGameAdapter _localGame;
public virtual string[] ListAvailableRegions()
{
return AwsRegionMapper.AvailableRegions().ToArray();
}
public virtual Task<GetLatenciesResponse> GetLatencies(string[] regions)
{
var request = new GetLatenciesRequest()
{
Regions = regions
};
return _latencyService.GetLatencies(request);
}
public virtual Task<GetGameConnectionResponse> GetGameConnection(string idToken, string refreshToken)
{
var request = new GetGameConnectionRequest()
{
ClientId = _configuration.UserPoolClientId,
ApiGatewayEndpoint = _configuration.ApiGatewayEndpoint,
IdToken = idToken,
RefreshToken = refreshToken,
};
if (_localGame != null)
{
return _localGame.GetGameConnection(request);
}
return _apiGateway.GetGameConnection(request);
}
public virtual Task<StartGameResponse> StartGame(string idToken, string refreshToken, Dictionary<string, long> latencies)
{
var request = new StartGameRequest()
{
ClientId = _configuration.UserPoolClientId,
ApiGatewayEndpoint = _configuration.ApiGatewayEndpoint,
IdToken = idToken,
RefreshToken = refreshToken,
RegionLatencies = latencies
};
if (_localGame != null)
{
return _localGame.StartGame(request);
}
return _apiGateway.StartGame(request);
}
#endregion
}
}
#endif
| 179 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using Amazon.SecurityToken;
using Amazon.SecurityToken.Model;
using AmazonGameLiftPlugin.Core.AccountManagement.Models;
using AmazonGameLiftPlugin.Core.Shared;
using AmazonGameLiftPlugin.Core.Shared.Logging;
namespace AmazonGameLiftPlugin.Core.AccountManagement
{
public class AccountManager : IAccountManager
{
private readonly IAmazonSecurityTokenServiceClientWrapper _tokenServiceClient;
public AccountManager(IAmazonSecurityTokenServiceClientWrapper tokenServiceClient)
{
_tokenServiceClient = tokenServiceClient;
}
public RetrieveAccountIdByCredentialsResponse RetrieveAccountIdByCredentials(RetrieveAccountIdByCredentialsRequest request)
{
if (string.IsNullOrEmpty(request.AccessKey) || string.IsNullOrEmpty(request.SecretKey))
{
return Response.Fail(new RetrieveAccountIdByCredentialsResponse
{
ErrorCode = ErrorCode.InvalidParameters
});
}
try
{
GetCallerIdentityResponse callerIdentityResponse = _tokenServiceClient
.GetCallerIdentity(request.AccessKey, request.SecretKey);
if (callerIdentityResponse.HttpStatusCode == System.Net.HttpStatusCode.OK)
{
return Response.Ok(new RetrieveAccountIdByCredentialsResponse
{
AccountId = callerIdentityResponse.Account
});
}
else
{
return Response.Fail(new RetrieveAccountIdByCredentialsResponse
{
ErrorCode = ErrorCode.AwsError,
ErrorMessage = $"HTTP Status Code {callerIdentityResponse.HttpStatusCode}"
});
}
}
catch (AmazonSecurityTokenServiceException ex)
{
Logger.LogError(ex, ex.Message);
return Response.Fail(new RetrieveAccountIdByCredentialsResponse
{
ErrorCode = ErrorCode.AwsError,
ErrorMessage = ex.Message
});
}
}
}
}
| 65 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using Amazon.Runtime;
using Amazon.SecurityToken;
using Amazon.SecurityToken.Model;
namespace AmazonGameLiftPlugin.Core.AccountManagement
{
public class AmazonSecurityTokenServiceClientWrapper : IAmazonSecurityTokenServiceClientWrapper
{
public GetCallerIdentityResponse GetCallerIdentity(string accessKey, string secretKey)
{
var basicAWSCredentials = new BasicAWSCredentials(accessKey, secretKey);
var stsClient = new AmazonSecurityTokenServiceClient(basicAWSCredentials);
GetCallerIdentityResponse callerIdentityResponse = stsClient.GetCallerIdentity(
new GetCallerIdentityRequest());
return callerIdentityResponse;
}
}
}
| 23 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using AmazonGameLiftPlugin.Core.AccountManagement.Models;
namespace AmazonGameLiftPlugin.Core.AccountManagement
{
public interface IAccountManager
{
RetrieveAccountIdByCredentialsResponse RetrieveAccountIdByCredentials(RetrieveAccountIdByCredentialsRequest request);
}
}
| 13 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using Amazon.SecurityToken.Model;
namespace AmazonGameLiftPlugin.Core.AccountManagement
{
public interface IAmazonSecurityTokenServiceClientWrapper
{
GetCallerIdentityResponse GetCallerIdentity(string accessKey, string secretKey);
}
}
| 13 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using AmazonGameLiftPlugin.Core.Shared;
namespace AmazonGameLiftPlugin.Core.AccountManagement.Models
{
public class RetrieveAccountIdByCredentialsRequest
{
public string AccessKey { get; set; }
public string SecretKey { get; set; }
}
public class RetrieveAccountIdByCredentialsResponse : Response
{
public string AccountId { get; set; }
}
}
| 20 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System.Threading;
using System.Threading.Tasks;
using Amazon.GameLift;
using Amazon.GameLift.Model;
namespace AmazonGameLiftPlugin.Core.ApiGatewayManagement
{
public class AmazonGameLiftClientWrapper : IAmazonGameLiftClientWrapper
{
private readonly IAmazonGameLift _amazonGameLiftClient;
private static readonly string s_dummyAwsAccessKey = "1";
private static readonly string s_dummyAwsSecretKey = "1";
internal AmazonGameLiftClientWrapper(IAmazonGameLift amazonGameLiftClient)
{
_amazonGameLiftClient = amazonGameLiftClient;
}
public AmazonGameLiftClientWrapper(string localEndpoint)
{
_amazonGameLiftClient = Create(localEndpoint);
}
public async Task<CreateGameSessionResponse> CreateGameSessionAsync(
CreateGameSessionRequest request,
CancellationToken cancellationToken = default
)
{
return await _amazonGameLiftClient.CreateGameSessionAsync(request);
}
public async Task<CreatePlayerSessionResponse> CreatePlayerSession(CreatePlayerSessionRequest request)
{
return await _amazonGameLiftClient.CreatePlayerSessionAsync(request);
}
public async Task<SearchGameSessionsResponse> SearchGameSessions(SearchGameSessionsRequest request)
{
return await _amazonGameLiftClient.SearchGameSessionsAsync(request);
}
public static IAmazonGameLift Create(string localEndpoint)
{
return new AmazonGameLiftClient(s_dummyAwsAccessKey, s_dummyAwsSecretKey, new AmazonGameLiftConfig
{
ServiceURL = localEndpoint
});
}
public async Task<DescribeGameSessionsResponse> DescribeGameSessions(DescribeGameSessionsRequest request)
{
return await _amazonGameLiftClient.DescribeGameSessionsAsync(request);
}
}
}
| 59 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using System.Net;
using System.Threading.Tasks;
using AmazonGameLiftPlugin.Core.ApiGatewayManagement.Models;
using AmazonGameLiftPlugin.Core.Shared;
using AmazonGameLiftPlugin.Core.Shared.Logging;
using AmazonGameLiftPlugin.Core.UserIdentityManagement;
using Newtonsoft.Json;
namespace AmazonGameLiftPlugin.Core.ApiGatewayManagement
{
public class ApiGateway : IGameServerAdapter
{
private readonly IUserIdentity _userIdentity;
private readonly IJwtTokenExpirationCheck _jwtTokenExpirationCheck;
private readonly IHttpClientWrapper _httpWrapper;
public ApiGateway(
IUserIdentity userIdentity,
IJwtTokenExpirationCheck jwtTokenExpirationCheck,
IHttpClientWrapper httpWrapper
)
{
_userIdentity = userIdentity;
_jwtTokenExpirationCheck = jwtTokenExpirationCheck;
_httpWrapper = httpWrapper;
}
private bool IsValid(ApiGatewayRequest request)
{
if (request == null
|| string.IsNullOrWhiteSpace(request.ApiGatewayEndpoint)
|| string.IsNullOrWhiteSpace(request.ClientId)
|| string.IsNullOrWhiteSpace(request.IdToken)
|| string.IsNullOrWhiteSpace(request.RefreshToken))
{
return false;
}
return true;
}
public async Task<StartGameResponse> StartGame(StartGameRequest request)
{
try
{
string latenciesJson = null;
if (request.RegionLatencies != null)
{
string regionToLatencyMappingJson =
JsonConvert.SerializeObject(request.RegionLatencies);
latenciesJson =
string.Format("{{\"regionToLatencyMapping\":{0}}}", regionToLatencyMappingJson);
}
if (!IsValid(request))
{
return Response.Fail(new StartGameResponse
{
ErrorCode = ErrorCode.InvalidParameters
});
}
(bool success, string errorCode, string token) =
_jwtTokenExpirationCheck.RefreshTokenIfExpired(request, _userIdentity);
if (!success)
{
return Response.Fail(new StartGameResponse
{
ErrorCode = errorCode
});
}
(HttpStatusCode statusCode, string body) response = await _httpWrapper.Post(
request.ApiGatewayEndpoint,
token,
"start_game",
latenciesJson
);
if (response.statusCode == HttpStatusCode.Conflict)
{
return Response.Fail(new StartGameResponse
{
ErrorCode = ErrorCode.ConflictError,
ErrorMessage = FormatRequestError(response)
});
}
if (response.statusCode != HttpStatusCode.Accepted)
{
return Response.Fail(new StartGameResponse
{
ErrorCode = ErrorCode.ApiGatewayRequestError,
ErrorMessage = FormatRequestError(response)
});
}
return Response.Ok(new StartGameResponse
{
IdToken = token
});
}
catch (Exception ex)
{
Logger.LogError(ex, ex.Message);
return Response.Fail(new StartGameResponse
{
ErrorCode = ErrorCode.UnknownError,
ErrorMessage = ex.Message
});
}
}
public async Task<GetGameConnectionResponse> GetGameConnection(GetGameConnectionRequest request)
{
try
{
if (!IsValid(request))
{
return Response.Fail(new GetGameConnectionResponse
{
ErrorCode = ErrorCode.InvalidParameters
});
}
(bool success, string errorCode, string token) =
_jwtTokenExpirationCheck.RefreshTokenIfExpired(request, _userIdentity);
if (!success)
{
return Response.Fail(new GetGameConnectionResponse
{
ErrorCode = errorCode
});
}
(HttpStatusCode statusCode, string body) response = await _httpWrapper.Post(
request.ApiGatewayEndpoint,
token,
"get_game_connection"
);
if (response.statusCode == HttpStatusCode.OK)
{
GetGameConnectionResult result = JsonConvert.DeserializeObject<GetGameConnectionResult>
(response.body);
return Response.Ok(new GetGameConnectionResponse
{
Ready = true,
IpAddress = result.IpAddress,
DnsName = result.DnsName,
Port = result.Port,
PlayerSessionId = result.PlayerSessionId,
IdToken = token
});
}
if (response.statusCode == HttpStatusCode.NoContent)
{
return Response.Ok(new GetGameConnectionResponse { IdToken = token });
}
return Response.Fail(new GetGameConnectionResponse
{
ErrorCode = ErrorCode.ApiGatewayRequestError,
ErrorMessage = FormatRequestError(response)
});
}
catch (Exception ex)
{
Logger.LogError(ex, ex.Message);
return Response.Fail(new GetGameConnectionResponse
{
ErrorCode = ErrorCode.UnknownError,
ErrorMessage = ex.Message
});
}
}
private static string FormatRequestError((HttpStatusCode statusCode, string body) response) =>
string.Format("Request failed with status {0}. Request body {1}.", (int)response.statusCode, response.body);
}
}
| 194 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
namespace AmazonGameLiftPlugin.Core.ApiGatewayManagement
{
public sealed class HttpClientWrapper : IHttpClientWrapper
{
private static readonly HttpClient s_httpClient = new HttpClient();
public async Task<(HttpStatusCode statusCode, string body)> Post(
string endpoint,
string token,
string path,
string body = null)
{
s_httpClient.BaseAddress = new Uri(endpoint);
var request = new HttpRequestMessage(HttpMethod.Post, path);
request.Headers.TryAddWithoutValidation("auth", token);
if (!string.IsNullOrWhiteSpace(body))
{
request.Content = new StringContent(body);
}
HttpResponseMessage response = await s_httpClient.SendAsync(request);
string responseBody = await response.Content?.ReadAsStringAsync();
return (response.StatusCode, responseBody);
}
}
}
| 36 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System.Threading;
using System.Threading.Tasks;
using Amazon.GameLift.Model;
namespace AmazonGameLiftPlugin.Core.ApiGatewayManagement
{
public interface IAmazonGameLiftClientWrapper
{
Task<CreateGameSessionResponse> CreateGameSessionAsync(
CreateGameSessionRequest request,
CancellationToken cancellationToken = default
);
Task<CreatePlayerSessionResponse> CreatePlayerSession(CreatePlayerSessionRequest request);
Task<SearchGameSessionsResponse> SearchGameSessions(SearchGameSessionsRequest request);
Task<DescribeGameSessionsResponse> DescribeGameSessions(DescribeGameSessionsRequest request);
}
}
| 24 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System.Threading.Tasks;
using AmazonGameLiftPlugin.Core.ApiGatewayManagement.Models;
namespace AmazonGameLiftPlugin.Core.ApiGatewayManagement
{
public interface IGameServerAdapter
{
Task<GetGameConnectionResponse> GetGameConnection(GetGameConnectionRequest request);
Task<StartGameResponse> StartGame(StartGameRequest request);
}
}
| 16 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System.Net;
using System.Threading.Tasks;
namespace AmazonGameLiftPlugin.Core.ApiGatewayManagement
{
public interface IHttpClientWrapper
{
Task<(HttpStatusCode statusCode, string body)> Post(string endpoint, string token, string path, string body = null);
}
}
| 14 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using AmazonGameLiftPlugin.Core.ApiGatewayManagement.Models;
using AmazonGameLiftPlugin.Core.UserIdentityManagement;
namespace AmazonGameLiftPlugin.Core.ApiGatewayManagement
{
public interface IJwtTokenExpirationCheck
{
(bool success, string errorCode, string token) RefreshTokenIfExpired(
ApiGatewayRequest request, IUserIdentity userIdentity);
}
}
| 15 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using AmazonGameLiftPlugin.Core.ApiGatewayManagement.Models;
using AmazonGameLiftPlugin.Core.Shared;
using AmazonGameLiftPlugin.Core.UserIdentityManagement;
namespace AmazonGameLiftPlugin.Core.ApiGatewayManagement
{
public class JwtTokenExpirationCheck : IJwtTokenExpirationCheck
{
public (bool success, string errorCode, string token) RefreshTokenIfExpired(
ApiGatewayRequest request, IUserIdentity userIdentity)
{
var jwtTokenHandler = new JwtSecurityTokenHandler();
bool isValid = jwtTokenHandler.CanReadToken(request.IdToken);
if (!isValid)
{
return (false, ErrorCode.InvalidIdToken, request.IdToken);
}
JwtSecurityToken token = jwtTokenHandler.ReadJwtToken(request.IdToken);
Claim expDate = token.Claims.First(x => x.Type == "exp");
long expDateInSeconds = long.Parse(expDate.Value);
var tokenExpirationDate = DateTimeOffset.FromUnixTimeSeconds(expDateInSeconds);
if (DateTime.UtcNow > tokenExpirationDate)
{
UserIdentityManagement.Models.RefreshTokenResponse refreshTokenResponse =
userIdentity.RefreshToken(new UserIdentityManagement.Models.RefreshTokenRequest
{
ClientId = request.ClientId,
RefreshToken = request.RefreshToken
});
return (true, string.Empty, refreshTokenResponse.IdToken);
}
else
{
return (true, string.Empty, request.IdToken);
}
}
}
}
| 52 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using System.Linq;
using System.Threading.Tasks;
using AmazonGameLiftPlugin.Core.ApiGatewayManagement.Models;
using AmazonGameLiftPlugin.Core.Shared;
using AmazonGameLiftPlugin.Core.Shared.Logging;
namespace AmazonGameLiftPlugin.Core.ApiGatewayManagement
{
public class LocalGameAdapter : IGameServerAdapter
{
private readonly IAmazonGameLiftClientWrapper _amazonGameLiftClientWrapper;
private readonly string _fleetId = "fleet-123";
private readonly string _playerIdPrefix = "playerId-";
public LocalGameAdapter(IAmazonGameLiftClientWrapper amazonGameLiftClientWrapper)
{
_amazonGameLiftClientWrapper = amazonGameLiftClientWrapper;
}
public async Task<GetGameConnectionResponse> GetGameConnection(GetGameConnectionRequest request)
{
try
{
Amazon.GameLift.Model.DescribeGameSessionsResponse describeGameSessionsResponse = await _amazonGameLiftClientWrapper.DescribeGameSessions(new Amazon.GameLift.Model.DescribeGameSessionsRequest
{
FleetId = _fleetId,
});
if (describeGameSessionsResponse.GameSessions.Any())
{
Amazon.GameLift.Model.GameSession oldestGameSession = describeGameSessionsResponse.GameSessions.First();
Amazon.GameLift.Model.CreatePlayerSessionResponse createPlayerSessionResponse = await _amazonGameLiftClientWrapper.CreatePlayerSession(new Amazon.GameLift.Model.CreatePlayerSessionRequest
{
GameSessionId = oldestGameSession.GameSessionId,
PlayerId = _playerIdPrefix + Guid.NewGuid().ToString()
});
Amazon.GameLift.Model.PlayerSession playerSession = createPlayerSessionResponse.PlayerSession;
var response = new GetGameConnectionResponse
{
IpAddress = playerSession.IpAddress,
DnsName = playerSession.DnsName,
Port = playerSession.Port.ToString(),
PlayerSessionId = playerSession.PlayerSessionId,
Ready = true
};
return Response.Ok(response);
}
return Response.Fail(new GetGameConnectionResponse
{
ErrorCode = ErrorCode.NoGameSessionWasFound
});
}
catch (Exception ex)
{
Logger.LogError(ex, ex.Message);
return Response.Fail(new GetGameConnectionResponse
{
ErrorCode = ErrorCode.UnknownError,
ErrorMessage = ex.Message
});
}
}
public async Task<StartGameResponse> StartGame(StartGameRequest request)
{
try
{
Amazon.GameLift.Model.DescribeGameSessionsResponse describeGameSessionsResponse = await _amazonGameLiftClientWrapper.DescribeGameSessions(new Amazon.GameLift.Model.DescribeGameSessionsRequest
{
FleetId = _fleetId,
});
if (!describeGameSessionsResponse.GameSessions.Any())
{
Amazon.GameLift.Model.CreateGameSessionResponse createGameSessionResponse = await _amazonGameLiftClientWrapper.CreateGameSessionAsync(new Amazon.GameLift.Model.CreateGameSessionRequest
{
MaximumPlayerSessionCount = 4,
FleetId = _fleetId
});
}
return Response.Ok(new StartGameResponse());
}
catch (Exception ex)
{
Logger.LogError(ex, ex.Message);
return Response.Fail(new StartGameResponse
{
ErrorCode = ErrorCode.UnknownError,
ErrorMessage = ex.Message
});
}
}
}
}
| 106 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
namespace AmazonGameLiftPlugin.Core.ApiGatewayManagement.Models
{
public class ApiGatewayRequest
{
public string ApiGatewayEndpoint { get; set; }
public string ClientId { get; set; }
public string RefreshToken { get; set; }
public string IdToken { get; set; }
}
}
| 14 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using AmazonGameLiftPlugin.Core.Shared;
namespace AmazonGameLiftPlugin.Core.ApiGatewayManagement.Models
{
public class GetGameConnectionRequest : ApiGatewayRequest
{
}
public class GetGameConnectionResponse : Response
{
public string IdToken { get; set; }
public string IpAddress { get; set; }
public string DnsName { get; set; }
public string Port { get; set; }
public string PlayerSessionId { get; set; }
public bool Ready { get; set; }
}
}
| 23 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
namespace AmazonGameLiftPlugin.Core.ApiGatewayManagement.Models
{
public class GetGameConnectionResult
{
public string IpAddress { get; set; }
public string Port { get; set; }
public string DnsName { get; set; }
public string PlayerSessionId { get; set; }
}
}
| 14 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System.Collections.Generic;
using AmazonGameLiftPlugin.Core.Shared;
namespace AmazonGameLiftPlugin.Core.ApiGatewayManagement.Models
{
public class StartGameRequest : ApiGatewayRequest
{
public Dictionary<string, long> RegionLatencies { get; set; }
}
public class StartGameResponse : Response
{
public string IdToken { get; set; }
}
}
| 19 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using Amazon.S3;
using Amazon.S3.Model;
using AmazonGameLiftPlugin.Core.BucketManagement.Models;
using AmazonGameLiftPlugin.Core.Shared;
using AmazonGameLiftPlugin.Core.Shared.Logging;
using AmazonGameLiftPlugin.Core.Shared.S3Bucket;
using Serilog;
namespace AmazonGameLiftPlugin.Core.BucketManagement
{
public class BucketStore : IBucketStore
{
/// <summary>
/// Regex pattern matches with rule defined in the page https://docs.aws.amazon.com/AmazonS3/latest/userguide/bucketnamingrules.html
/// Described here https://stackoverflow.com/questions/50480924/regex-for-s3-bucket-name/50484916
/// </summary>
private static readonly string s_s3BucketNamePattern = @"(?=^.{3,63}$)(?!^(\d+\.)+\d+$)(^(([a-z0-9]|[a-z0-9][a-z0-9\-]*[a-z0-9])\.)*([a-z0-9]|[a-z0-9][a-z0-9\-]*[a-z0-9])$)";
private readonly IAmazonS3Wrapper _amazonS3Wrapper;
public BucketStore(IAmazonS3Wrapper amazonS3Wrapper)
{
_amazonS3Wrapper = amazonS3Wrapper;
}
public CreateBucketResponse CreateBucket(CreateBucketRequest request)
{
ValidationResult validationResult = Validate(request);
if (!validationResult.IsValid)
{
return Response.Fail(new CreateBucketResponse
{
ErrorCode = validationResult.ErrorCode
});
}
try
{
// Create bootstrap bucket
PutBucketResponse putBucketResponse = _amazonS3Wrapper.PutBucket(new PutBucketRequest
{
BucketName = request.BucketName,
BucketRegionName = request.Region,
});
if (putBucketResponse.HttpStatusCode != HttpStatusCode.OK)
{
return Response.Fail(new CreateBucketResponse()
{
ErrorCode = ErrorCode.AwsError,
ErrorMessage = $"HTTP Status Code {putBucketResponse.HttpStatusCode}"
});
}
// TODO (#17): Allow users to toggle audit-logging, versioning and encryption on bootstrap bucket
// Enable bootstrap bucket versioning
PutBucketVersioningResponse putBucketVersioningRequest = _amazonS3Wrapper.PutBucketVersioning(new PutBucketVersioningRequest
{
BucketName = request.BucketName,
VersioningConfig = new S3BucketVersioningConfig
{
Status = VersionStatus.Enabled
}
});
if (putBucketVersioningRequest.HttpStatusCode != HttpStatusCode.OK)
{
return Response.Fail(new CreateBucketResponse()
{
ErrorCode = ErrorCode.AwsError,
ErrorMessage = $"HTTP Status Code {putBucketVersioningRequest.HttpStatusCode}"
});
}
// Enable bootstrap bucket server-side encryption
PutBucketEncryptionResponse putBucketEncryptionRequest = _amazonS3Wrapper.PutBucketEncryption(new PutBucketEncryptionRequest
{
BucketName = request.BucketName,
ServerSideEncryptionConfiguration = new ServerSideEncryptionConfiguration
{
ServerSideEncryptionRules = new List<ServerSideEncryptionRule>
{
new ServerSideEncryptionRule
{
ServerSideEncryptionByDefault = new ServerSideEncryptionByDefault
{
ServerSideEncryptionAlgorithm = ServerSideEncryptionMethod.AES256
}
}
}
}
});
if (putBucketEncryptionRequest.HttpStatusCode != HttpStatusCode.OK)
{
return Response.Fail(new CreateBucketResponse()
{
ErrorCode = ErrorCode.AwsError,
ErrorMessage = $"HTTP Status Code {putBucketEncryptionRequest.HttpStatusCode}"
});
}
// Create logging bucket for the bootstrap bucket
string loggingBucketName = request.BucketName + "-log";
PutBucketResponse putLoggingBucketResponse = _amazonS3Wrapper.PutBucket(new PutBucketRequest
{
BucketName = loggingBucketName,
BucketRegionName = request.Region,
});
if (putLoggingBucketResponse.HttpStatusCode != HttpStatusCode.OK)
{
return Response.Fail(new CreateBucketResponse()
{
ErrorCode = ErrorCode.AwsError,
ErrorMessage = $"HTTP Status Code {putLoggingBucketResponse.HttpStatusCode}"
});
}
// Getting Existing ACL of the logging bucket
GetACLResponse getACLResponse = _amazonS3Wrapper.GetACL(new GetACLRequest
{
BucketName = loggingBucketName
});
if (getACLResponse.HttpStatusCode != HttpStatusCode.OK)
{
return Response.Fail(new CreateBucketResponse()
{
ErrorCode = ErrorCode.AwsError,
ErrorMessage = $"HTTP Status Code {getACLResponse.HttpStatusCode}"
});
}
S3AccessControlList s3AccessControlList = getACLResponse.AccessControlList;
s3AccessControlList.AddGrant(new S3Grantee { URI = "http://acs.amazonaws.com/groups/s3/LogDelivery" }, S3Permission.WRITE);
s3AccessControlList.AddGrant(new S3Grantee { URI = "http://acs.amazonaws.com/groups/s3/LogDelivery" }, S3Permission.READ_ACP);
// Grant logging access to the logging bucket
PutACLResponse putACLResponse = _amazonS3Wrapper.PutACL(new PutACLRequest
{
BucketName = loggingBucketName,
AccessControlList = s3AccessControlList
});
if (putACLResponse.HttpStatusCode != HttpStatusCode.OK)
{
return Response.Fail(new CreateBucketResponse()
{
ErrorCode = ErrorCode.AwsError,
ErrorMessage = $"HTTP Status Code {putACLResponse.HttpStatusCode}"
});
}
// Enable access logging on the bootstrap bucket using the newly created logging bucket
PutBucketLoggingResponse putBucketLoggingRequest = _amazonS3Wrapper.PutBucketLogging(new PutBucketLoggingRequest
{
BucketName = request.BucketName,
LoggingConfig = new S3BucketLoggingConfig
{
TargetBucketName = loggingBucketName,
TargetPrefix = "GameLiftBootstrap",
}
});
if (putBucketLoggingRequest.HttpStatusCode != HttpStatusCode.OK)
{
return Response.Fail(new CreateBucketResponse()
{
ErrorCode = ErrorCode.AwsError,
ErrorMessage = $"HTTP Status Code {putBucketLoggingRequest.HttpStatusCode}"
});
}
return Response.Ok(new CreateBucketResponse());
}
catch (Exception ex)
{
Logger.LogError(ex, ex.Message);
return HandleAwsException(ex, () => new CreateBucketResponse());
}
}
private ValidationResult Validate(CreateBucketRequest request)
{
if (!AwsRegionMapper.IsValidRegion(request.Region))
{
return ValidationResult.Invalid(ErrorCode.InvalidRegion);
}
bool bucketAlreadyExists = _amazonS3Wrapper.DoesBucketExist(request.BucketName);
if (bucketAlreadyExists)
{
return ValidationResult.Invalid(ErrorCode.BucketNameAlreadyExists);
}
if (!Regex.Match(request.BucketName, s_s3BucketNamePattern).Success)
{
return ValidationResult.Invalid(ErrorCode.BucketNameIsWrong);
}
return ValidationResult.Valid();
}
public Models.PutLifecycleConfigurationResponse PutLifecycleConfiguration(Models.PutLifecycleConfigurationRequest request)
{
if (!Enum.IsDefined(typeof(BucketPolicy), request.BucketPolicy) || request.BucketPolicy == BucketPolicy.None)
{
return Response.Fail(new Models.PutLifecycleConfigurationResponse()
{
ErrorCode = ErrorCode.InvalidBucketPolicy
});
}
GetLifecycleConfigurationResponse lifecycleResponse =
_amazonS3Wrapper.GetLifecycleConfiguration(request.BucketName);
LifecycleConfiguration lifecycleConfiguration = lifecycleResponse.Configuration;
if (lifecycleResponse.HttpStatusCode == HttpStatusCode.NotFound)
{
lifecycleConfiguration = new LifecycleConfiguration
{
Rules = new List<LifecycleRule>()
};
}
lifecycleConfiguration.Rules.Add(new LifecycleRule
{
Id = $"GameLiftBootstrapBucketRule_{Guid.NewGuid()}",
Filter = new LifecycleFilter(),
Expiration = new LifecycleRuleExpiration
{
Days = (int)request.BucketPolicy
},
Status = new LifecycleRuleStatus("Enabled")
});
try
{
Amazon.S3.Model.PutLifecycleConfigurationResponse putLifecycleConfigurationResponse =
_amazonS3Wrapper.PutLifecycleConfiguration(new Amazon.S3.Model.PutLifecycleConfigurationRequest
{
BucketName = request.BucketName,
Configuration = lifecycleConfiguration
});
if (putLifecycleConfigurationResponse.HttpStatusCode == HttpStatusCode.OK)
{
return Response.Ok(new Models.PutLifecycleConfigurationResponse());
}
else
{
return Response.Fail(new Models.PutLifecycleConfigurationResponse()
{
ErrorCode = ErrorCode.AwsError,
ErrorMessage = $"HTTP Status Code {putLifecycleConfigurationResponse.HttpStatusCode}"
});
}
}
catch (Exception ex)
{
Logger.LogError(ex, ex.Message);
return HandleAwsException(ex, () => new Models.PutLifecycleConfigurationResponse());
}
}
public GetBucketsResponse GetBuckets(GetBucketsRequest request)
{
try
{
ListBucketsResponse response = _amazonS3Wrapper.ListBuckets();
if (response.HttpStatusCode == HttpStatusCode.OK)
{
var buckets = new List<string>();
if (!string.IsNullOrEmpty(request.Region))
{
foreach (string bucketName in response.Buckets.Select(bucket => bucket.BucketName))
{
GetBucketLocationResponse locationResponse = _amazonS3Wrapper.GetBucketLocation(new GetBucketLocationRequest
{
BucketName = bucketName
});
if (locationResponse.HttpStatusCode == HttpStatusCode.OK && ToBucketRegion(locationResponse) == request.Region)
{
buckets.Add(bucketName);
}
}
}
else
{
buckets = response.Buckets.Select(bucket => bucket.BucketName).ToList();
}
return Response.Ok(new GetBucketsResponse()
{
Buckets = buckets
});
}
else
{
return Response.Fail(new GetBucketsResponse()
{
ErrorCode = ErrorCode.AwsError,
ErrorMessage = $"HTTP Status Code {response.HttpStatusCode}"
});
}
}
catch (Exception ex)
{
Logger.LogError(ex, ex.Message);
return HandleAwsException(ex, () => new GetBucketsResponse());
}
}
private string ToBucketRegion(GetBucketLocationResponse getBucketLocationResponse)
{
string locationValue = getBucketLocationResponse.Location.Value;
// See: https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/S3/TS3Region.html
switch (locationValue)
{
case "":
return "us-east-1";
case "EU":
return "eu-west-1";
default:
return locationValue;
}
}
public GetAvailableRegionsResponse GetAvailableRegions(GetAvailableRegionsRequest request)
{
return Response.Ok(new GetAvailableRegionsResponse
{
Regions = AwsRegionMapper.AvailableRegions()
});
}
public GetBucketPoliciesResponse GetBucketPolicies(GetBucketPoliciesRequest request)
{
return Response.Ok(new GetBucketPoliciesResponse
{
Policies = (IEnumerable<BucketPolicy>)Enum.GetValues(typeof(BucketPolicy))
});
}
private T HandleAwsException<T>(Exception ex, Func<T> responseObject) where T : Response
{
T response = responseObject();
if (ex is AmazonS3Exception exception)
{
response.ErrorCode = ErrorCode.AwsError;
response.ErrorMessage = exception.Message;
}
else if (ex is WebException
|| ex is ArgumentNullException)
{
response.ErrorCode = ErrorCode.AwsError;
response.ErrorMessage = ex.Message;
}
else
{
throw ex;
}
return Response.Fail(response);
}
}
}
| 387 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using AmazonGameLiftPlugin.Core.BucketManagement.Models;
namespace AmazonGameLiftPlugin.Core.BucketManagement
{
public interface IBucketStore
{
CreateBucketResponse CreateBucket(CreateBucketRequest request);
PutLifecycleConfigurationResponse PutLifecycleConfiguration(PutLifecycleConfigurationRequest request);
GetBucketsResponse GetBuckets(GetBucketsRequest request);
GetAvailableRegionsResponse GetAvailableRegions(GetAvailableRegionsRequest request);
GetBucketPoliciesResponse GetBucketPolicies(GetBucketPoliciesRequest request);
}
}
| 21 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
namespace AmazonGameLiftPlugin.Core.BucketManagement.Models
{
public enum BucketPolicy
{
None,
SevenDaysLifecycle = 7,
ThirtyDaysLifecycle = 30
}
}
| 13 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using AmazonGameLiftPlugin.Core.Shared;
namespace AmazonGameLiftPlugin.Core.BucketManagement.Models
{
public class CreateBucketRequest
{
public string BucketName { get; set; }
public string Region { get; set; }
}
public class CreateBucketResponse : Response
{
}
}
| 19 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System.Collections.Generic;
using AmazonGameLiftPlugin.Core.Shared;
namespace AmazonGameLiftPlugin.Core.BucketManagement.Models
{
public class GetAvailableRegionsRequest
{
}
public class GetAvailableRegionsResponse : Response
{
public IEnumerable<string> Regions { get; set; }
}
}
| 18 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System.Collections.Generic;
using AmazonGameLiftPlugin.Core.Shared;
namespace AmazonGameLiftPlugin.Core.BucketManagement.Models
{
public class GetBucketPoliciesRequest
{
}
public class GetBucketPoliciesResponse : Response
{
public IEnumerable<BucketPolicy> Policies { get; set; }
}
}
| 18 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System.Collections.Generic;
using AmazonGameLiftPlugin.Core.Shared;
namespace AmazonGameLiftPlugin.Core.BucketManagement.Models
{
public class GetBucketsRequest
{
public string Region { get; set; }
}
public class GetBucketsResponse : Response
{
public IEnumerable<string> Buckets { get; set; }
}
}
| 19 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using AmazonGameLiftPlugin.Core.Shared;
using AmazonGameLiftPlugin.Core.Shared.S3Bucket;
namespace AmazonGameLiftPlugin.Core.BucketManagement.Models
{
public class PutLifecycleConfigurationRequest
{
public string BucketName { get; set; }
public BucketPolicy BucketPolicy { get; set; }
}
public class PutLifecycleConfigurationResponse : Response
{
}
}
| 20 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using Amazon.Runtime;
using Amazon.Runtime.CredentialManagement;
using AmazonGameLiftPlugin.Core.CredentialManagement.Models;
using AmazonGameLiftPlugin.Core.Shared;
using AmazonGameLiftPlugin.Core.Shared.FileSystem;
using AmazonGameLiftPlugin.Core.Shared.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
namespace AmazonGameLiftPlugin.Core.CredentialManagement
{
public class CredentialsStore : ICredentialsStore
{
private readonly SharedCredentialsFile _sharedFile;
private readonly CredentialProfileStoreChain _credentialProfileStoreChain;
private readonly IFileWrapper _file;
public CredentialsStore(IFileWrapper fileWrapper, string filePath = default)
{
_file = fileWrapper ?? throw new ArgumentNullException(nameof(fileWrapper));
_sharedFile = string.IsNullOrEmpty(filePath) ? new SharedCredentialsFile() : new SharedCredentialsFile(filePath);
_credentialProfileStoreChain = string.IsNullOrEmpty(filePath) ? new CredentialProfileStoreChain() : new CredentialProfileStoreChain(filePath);
}
public SaveAwsCredentialsResponse SaveAwsCredentials(SaveAwsCredentialsRequest request)
{
try
{
var options = new CredentialProfileOptions
{
AccessKey = request.AccessKey,
SecretKey = request.SecretKey
};
if (_credentialProfileStoreChain.TryGetAWSCredentials(request.ProfileName, out AWSCredentials awsCredentials))
{
return Response.Fail(new SaveAwsCredentialsResponse()
{
ErrorCode = ErrorCode.ProfileAlreadyExists
});
}
var profile = new CredentialProfile(request.ProfileName, options);
_sharedFile.RegisterProfile(profile);
FixEndOfFile();
return Response.Ok(new SaveAwsCredentialsResponse());
}
catch (Exception ex)
{
Logger.LogError(ex, ex.Message);
return Response.Fail(new SaveAwsCredentialsResponse()
{
ErrorMessage = ex.Message
});
}
}
public RetriveAwsCredentialsResponse RetriveAwsCredentials(RetriveAwsCredentialsRequest request)
{
if (_credentialProfileStoreChain.TryGetAWSCredentials(request.ProfileName, out AWSCredentials awsCredentials))
{
ImmutableCredentials credentials = awsCredentials.GetCredentials();
return Response.Ok(new RetriveAwsCredentialsResponse()
{
AccessKey = credentials.AccessKey,
SecretKey = credentials.SecretKey
});
}
return Response.Fail(new RetriveAwsCredentialsResponse()
{
ErrorCode = ErrorCode.NoProfileFound
});
}
public UpdateAwsCredentialsResponse UpdateAwsCredentials(UpdateAwsCredentialsRequest request)
{
try
{
if (_sharedFile.TryGetProfile(request.ProfileName, out CredentialProfile profile))
{
profile.Options.AccessKey = request.AccessKey;
profile.Options.SecretKey = request.SecretKey;
_sharedFile.RegisterProfile(profile);
FixEndOfFile();
return Response.Ok(new UpdateAwsCredentialsResponse());
}
return Response.Fail(new UpdateAwsCredentialsResponse()
{
ErrorCode = ErrorCode.NoProfileFound
});
}
catch (Exception ex)
{
Logger.LogError(ex, ex.Message);
return Response.Fail(new UpdateAwsCredentialsResponse()
{
ErrorMessage = ex.Message
});
}
}
public GetProfilesResponse GetProfiles(GetProfilesRequest request)
{
IEnumerable<string> profiles = _credentialProfileStoreChain.ListProfiles().Select(x => x.Name);
return Response.Ok(new GetProfilesResponse()
{
Profiles = profiles
});
}
private void FixEndOfFile()
{
string filePath = _sharedFile.FilePath;
string text = _file.ReadAllText(filePath);
text += Environment.NewLine;
_file.WriteAllText(filePath, text);
}
}
}
| 134 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using AmazonGameLiftPlugin.Core.CredentialManagement.Models;
namespace AmazonGameLiftPlugin.Core.CredentialManagement
{
public interface ICredentialsStore
{
SaveAwsCredentialsResponse SaveAwsCredentials(SaveAwsCredentialsRequest request);
RetriveAwsCredentialsResponse RetriveAwsCredentials(RetriveAwsCredentialsRequest request);
UpdateAwsCredentialsResponse UpdateAwsCredentials(UpdateAwsCredentialsRequest request);
GetProfilesResponse GetProfiles(GetProfilesRequest request);
}
}
| 19 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System.Collections.Generic;
using AmazonGameLiftPlugin.Core.Shared;
namespace AmazonGameLiftPlugin.Core.CredentialManagement.Models
{
public class GetProfilesRequest
{
}
public class GetProfilesResponse : Response
{
public IEnumerable<string> Profiles { get; set; }
}
}
| 18 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using AmazonGameLiftPlugin.Core.Shared;
namespace AmazonGameLiftPlugin.Core.CredentialManagement.Models
{
public class RetriveAwsCredentialsRequest
{
public string ProfileName { get; set; }
}
public class RetriveAwsCredentialsResponse : Response
{
public string AccessKey { get; set; }
public string SecretKey { get; set; }
}
}
| 20 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using AmazonGameLiftPlugin.Core.Shared;
namespace AmazonGameLiftPlugin.Core.CredentialManagement.Models
{
public class SaveAwsCredentialsRequest
{
public string ProfileName { get; set; }
public string AccessKey { get; set; }
public string SecretKey { get; set; }
}
public class SaveAwsCredentialsResponse : Response
{
}
}
| 21 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using AmazonGameLiftPlugin.Core.Shared;
namespace AmazonGameLiftPlugin.Core.CredentialManagement.Models
{
public class UpdateAwsCredentialsRequest
{
public string ProfileName { get; set; }
public string AccessKey { get; set; }
public string SecretKey { get; set; }
}
public class UpdateAwsCredentialsResponse : Response
{
}
}
| 21 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using Amazon.CloudFormation;
using Amazon.CloudFormation.Model;
using AmazonGameLiftPlugin.Core.Shared;
namespace AmazonGameLiftPlugin.Core.DeploymentManagement
{
public class AmazonCloudFormationWrapper : IAmazonCloudFormationWrapper
{
private readonly IAmazonCloudFormation _amazonCloudFormation;
public AmazonCloudFormationWrapper(string accessKey, string secretKey, string region)
{
_amazonCloudFormation = new AmazonCloudFormationClient(
accessKey,
secretKey,
AwsRegionMapper.GetRegionEndpoint(region)
);
}
public CreateChangeSetResponse CreateChangeSet(CreateChangeSetRequest request)
{
return _amazonCloudFormation.CreateChangeSet(request);
}
public DescribeChangeSetResponse DescribeChangeSet(DescribeChangeSetRequest request)
{
return _amazonCloudFormation.DescribeChangeSet(request);
}
public DescribeStacksResponse DescribeStacks(DescribeStacksRequest request)
{
return _amazonCloudFormation.DescribeStacks(request);
}
public ValidateTemplateResponse ValidateTemplate(ValidateTemplateRequest request)
{
return _amazonCloudFormation.ValidateTemplate(request);
}
public ExecuteChangeSetResponse ExecuteChangeSet(ExecuteChangeSetRequest request)
{
return _amazonCloudFormation.ExecuteChangeSet(request);
}
public CancelUpdateStackResponse CancelDeployment(CancelUpdateStackRequest request)
{
return _amazonCloudFormation.CancelUpdateStack(request);
}
public DeleteChangeSetResponse DeleteChangeSet(DeleteChangeSetRequest request)
{
return _amazonCloudFormation.DeleteChangeSet(request);
}
public DeleteStackResponse DeleteStack(DeleteStackRequest request)
{
return _amazonCloudFormation.DeleteStack(request);
}
}
}
| 64 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using System.Linq;
namespace AmazonGameLiftPlugin.Core.DeploymentManagement
{
public sealed class DeploymentFormatter
{
public string GetServerGamePath(string gameFilePathInBuild)
{
if (gameFilePathInBuild is null)
{
throw new ArgumentNullException(nameof(gameFilePathInBuild));
}
return $"C:\\game\\{gameFilePathInBuild}";
}
public string GetBuildS3Key()
{
string timeStamp = DateTime.Now.Ticks.ToString();
return $"GameLift_Build_{timeStamp}.zip";
}
public string GetStackName(string gameName)
{
if (gameName is null)
{
throw new ArgumentNullException(nameof(gameName));
}
return $"GameLiftPluginForUnity-{gameName}";
}
public string GetChangeSetName() => $"changeset-{Guid.NewGuid()}";
public string GetCloudFormationFileKey(string fileName)
{
if (fileName is null)
{
throw new ArgumentNullException(nameof(fileName));
}
string timeStamp = DateTime.Now.Ticks.ToString();
string[] parts = fileName.Split('.');
string name = parts.First();
string extension = parts.Last();
return $"CloudFormation/{name}_{timeStamp}.{extension}";
}
public string GetS3Url(string bucketName, string region, string fileName)
{
if (bucketName is null)
{
throw new ArgumentNullException(nameof(bucketName));
}
if (region is null)
{
throw new ArgumentNullException(nameof(region));
}
if (fileName is null)
{
throw new ArgumentNullException(nameof(fileName));
}
return $"https://{bucketName}.s3.{region}.amazonaws.com/{fileName}";
}
public string GetLambdaS3Key(string gameName)
{
if (gameName is null)
{
throw new ArgumentNullException(nameof(gameName));
}
return $"functions/gamelift/GameLift_{gameName}_{DateTime.Now.Ticks}.zip";
}
}
}
| 84 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Amazon.CloudFormation;
using Amazon.CloudFormation.Model;
using Amazon.S3;
using Amazon.S3.Model;
using AmazonGameLiftPlugin.Core.DeploymentManagement.Models;
using AmazonGameLiftPlugin.Core.Shared;
using AmazonGameLiftPlugin.Core.Shared.FileSystem;
using AmazonGameLiftPlugin.Core.Shared.FileZip;
using AmazonGameLiftPlugin.Core.Shared.Logging;
using AmazonGameLiftPlugin.Core.Shared.S3Bucket;
using Newtonsoft.Json;
using CreateChangeSetRequest = AmazonGameLiftPlugin.Core.DeploymentManagement.Models.CreateChangeSetRequest;
using CreateChangeSetResponse = AmazonGameLiftPlugin.Core.DeploymentManagement.Models.CreateChangeSetResponse;
using ExecuteChangeSetRequest = AmazonGameLiftPlugin.Core.DeploymentManagement.Models.ExecuteChangeSetRequest;
using ExecuteChangeSetResponse = AmazonGameLiftPlugin.Core.DeploymentManagement.Models.ExecuteChangeSetResponse;
namespace AmazonGameLiftPlugin.Core.DeploymentManagement
{
public class DeploymentManager : IDeploymentManager
{
private static readonly string s_gameNameParameter = "GameNameParameter";
private static readonly string s_lambdaZipS3KeyParameter = "LambdaZipS3KeyParameter";
private static readonly string s_lambdaZipS3BucketParameter = "LambdaZipS3BucketParameter";
private static readonly string s_buildS3BucketParameter = "BuildS3BucketParameter";
private static readonly string s_buildS3KeyParameter = "BuildS3KeyParameter";
private static readonly DeploymentFormatter s_formatter = new DeploymentFormatter();
private readonly IAmazonCloudFormationWrapper _amazonCloudFormation;
private readonly IAmazonS3Wrapper _amazonS3Wrapper;
private readonly IFileWrapper _fileWrapper;
private readonly IFileZip _fileZip;
public DeploymentManager(
IAmazonCloudFormationWrapper amazonCloudFormation,
IAmazonS3Wrapper amazonS3Wrapper,
IFileWrapper fileWrapper,
IFileZip fileZip)
{
_amazonCloudFormation = amazonCloudFormation;
_amazonS3Wrapper = amazonS3Wrapper;
_fileWrapper = fileWrapper;
_fileZip = fileZip;
}
private (bool success, string errorMessage, List<Parameter> parameters) DeserializeParameters(string parametersFilePath)
{
try
{
List<Parameter> result = JsonConvert.DeserializeObject<List<Parameter>>(_fileWrapper.ReadAllText(
parametersFilePath
));
return (true, string.Empty, result);
}
catch (JsonException ex)
{
return (false, ex.Message, null);
}
}
private void InjectBuildParameters(
List<Parameter> parameters,
string buildS3Bucket,
string buildS3Key)
{
if (string.IsNullOrEmpty(buildS3Bucket) || string.IsNullOrEmpty(buildS3Key))
{
return;
}
parameters.Add(new Parameter
{
ParameterKey = s_buildS3BucketParameter,
ParameterValue = buildS3Bucket
});
parameters.Add(new Parameter
{
ParameterKey = s_buildS3KeyParameter,
ParameterValue = buildS3Key
});
}
public ValidateCfnTemplateResponse ValidateCfnTemplate(ValidateCfnTemplateRequest request)
{
if (!_fileWrapper.FileExists(request.TemplateFilePath))
{
return Response.Fail(new ValidateCfnTemplateResponse
{
ErrorCode = ErrorCode.TemplateFileNotFound
});
}
try
{
ValidateTemplateResponse validateTemplateResponse = _amazonCloudFormation.ValidateTemplate(new ValidateTemplateRequest
{
TemplateBody = _fileWrapper.ReadAllText(request.TemplateFilePath),
});
return Response.Ok(new ValidateCfnTemplateResponse());
}
catch (AmazonCloudFormationException ex)
{
Logger.LogError(ex, ex.Message);
return Response.Fail(new ValidateCfnTemplateResponse
{
ErrorCode = ErrorCode.InvalidCfnTemplate,
ErrorMessage = ex.Message
});
}
}
public DescribeStackResponse DescribeStack(DescribeStackRequest request)
{
try
{
DescribeStacksResponse describeStacksResponse = _amazonCloudFormation.DescribeStacks(new DescribeStacksRequest()
{
StackName = request.StackName
});
if (!describeStacksResponse.Stacks.Any())
{
return Response.Fail(new DescribeStackResponse()
{
ErrorCode = ErrorCode.StackDoesNotExist
});
}
Stack stack = describeStacksResponse.Stacks[0];
string gameName = stack.Parameters.Find(target => target.ParameterKey == s_gameNameParameter)?.ParameterValue;
var response = new DescribeStackResponse
{
StackId = stack.StackId,
LastUpdatedTime = stack.LastUpdatedTime,
StackStatus = stack.StackStatus,
GameName = gameName
};
if (request.OutputKeys != null)
{
var outputs =
stack.Outputs.Where(x => request.OutputKeys.Contains(x.OutputKey))
.ToDictionary(key => key.OutputKey, value => value.OutputValue);
response.Outputs = outputs;
}
return Response.Ok(response);
}
catch (AmazonCloudFormationException ex)
{
Logger.LogError(ex, ex.Message);
return Response.Fail(new DescribeStackResponse()
{
ErrorCode = ErrorCode.StackDoesNotExist,
ErrorMessage = ex.Message
});
}
}
public CreateChangeSetResponse CreateChangeSet(CreateChangeSetRequest request)
{
try
{
if (!_fileWrapper.FileExists(request.ParametersFilePath))
{
return Response.Fail(new CreateChangeSetResponse
{
ErrorCode = ErrorCode.ParametersFileNotFound
});
}
(bool success, string errorMessage, List<Parameter> parameters) deserializedParameters
= DeserializeParameters(request.ParametersFilePath);
if (!deserializedParameters.success)
{
return Response.Fail(new CreateChangeSetResponse
{
ErrorCode = ErrorCode.InvalidParameters,
ErrorMessage = deserializedParameters.errorMessage
});
}
bool exists = _amazonS3Wrapper.DoesBucketExist(request.BootstrapBucketName);
if (!exists)
{
return Response.Fail(new CreateChangeSetResponse
{
ErrorCode = ErrorCode.BucketDoesNotExist
});
}
string fileName = Path.GetFileName(request.TemplateFilePath);
string key = s_formatter.GetCloudFormationFileKey(fileName);
(bool success, string fileUrl, _)
= UploadFile(request.BootstrapBucketName, request.TemplateFilePath, key);
if (!success)
{
return Response.Fail(new CreateChangeSetResponse
{
ErrorCode = ErrorCode.AwsError
});
}
InjectLambdaParameters(
deserializedParameters.parameters,
request.BootstrapBucketName,
request.GameName,
request.LambdaSourcePath
);
InjectBuildParameters(
deserializedParameters.parameters,
request.BootstrapBucketName,
request.BuildS3Key
);
StackExistsResponse stackExistsResponse = StackExists(new StackExistsRequest
{
StackName = request.StackName
});
if (!stackExistsResponse.Success)
{
return Response.Fail(new CreateChangeSetResponse
{
ErrorCode = stackExistsResponse.ErrorCode
});
}
ChangeSetType changeSetType =
stackExistsResponse.Exists ? ChangeSetType.UPDATE : ChangeSetType.CREATE;
string changeSetName = s_formatter.GetChangeSetName();
Amazon.CloudFormation.Model.CreateChangeSetResponse createChangeSetResponse =
_amazonCloudFormation.CreateChangeSet(new Amazon.CloudFormation.Model.CreateChangeSetRequest()
{
ChangeSetName = changeSetName,
StackName = request.StackName,
Parameters = deserializedParameters.parameters,
TemplateURL = fileUrl,
Capabilities = new List<string> { "CAPABILITY_NAMED_IAM" },
ChangeSetType = changeSetType
});
return Response.Ok(new CreateChangeSetResponse
{
CreatedChangeSetName = changeSetName
});
}
catch (AlreadyExistsException ex)
{
Logger.LogError(ex, ex.Message);
return Response.Fail(new CreateChangeSetResponse
{
ErrorCode = ErrorCode.ResourceWithTheNameRequestetAlreadyExists,
ErrorMessage = ex.Message
});
}
catch (InsufficientCapabilitiesException ex)
{
Logger.LogError(ex, ex.Message);
return Response.Fail(new CreateChangeSetResponse
{
ErrorCode = ErrorCode.InsufficientCapabilities,
ErrorMessage = ex.Message
});
}
catch (LimitExceededException ex)
{
Logger.LogError(ex, ex.Message);
return Response.Fail(new CreateChangeSetResponse
{
ErrorCode = ErrorCode.LimitExceeded,
ErrorMessage = ex.Message
});
}
catch (AmazonCloudFormationException ex)
{
Logger.LogError(ex, ex.Message);
return Response.Fail(new CreateChangeSetResponse
{
ErrorCode = ErrorCode.AwsError,
ErrorMessage = ex.Message
});
}
catch (AmazonS3Exception ex)
{
Logger.LogError(ex, ex.Message);
return Response.Fail(new CreateChangeSetResponse
{
ErrorCode = ErrorCode.AwsError,
ErrorMessage = ex.Message
});
}
catch (Exception ex)
{
Logger.LogError(ex, ex.Message);
return Response.Fail(new CreateChangeSetResponse
{
ErrorCode = ErrorCode.UnknownError,
ErrorMessage = ex.Message
});
}
}
public Models.DescribeChangeSetResponse DescribeChangeSet(Models.DescribeChangeSetRequest request)
{
try
{
Amazon.CloudFormation.Model.DescribeChangeSetResponse describeChangeSetResponse =
_amazonCloudFormation.DescribeChangeSet(new Amazon.CloudFormation.Model.DescribeChangeSetRequest
{
ChangeSetName = request.ChangeSetName,
StackName = request.StackName
});
var response = new Models.DescribeChangeSetResponse
{
StackId = describeChangeSetResponse.StackId,
ChangeSetId = describeChangeSetResponse.ChangeSetId,
ExecutionStatus = describeChangeSetResponse.ExecutionStatus?.Value
};
if (describeChangeSetResponse.Changes != null)
{
response.Changes = describeChangeSetResponse
.Changes
.Select(x => new Models.Change
{
Action = x.ResourceChange?.Action?.Value,
LogicalId = x.ResourceChange?.LogicalResourceId,
Module = x.ResourceChange?.ModuleInfo?.LogicalIdHierarchy,
PhysicalId = x.ResourceChange?.PhysicalResourceId,
Replacement = x.ResourceChange?.Replacement?.Value,
ResourceType = x.ResourceChange?.ResourceType,
}).ToList();
}
return Response.Ok(response);
}
catch (ChangeSetNotFoundException ex)
{
Logger.LogError(ex, ex.Message);
return Response.Fail(new Models.DescribeChangeSetResponse
{
ErrorCode = ErrorCode.ChangeSetNotFound,
ErrorMessage = ex.Message
});
}
catch (AmazonCloudFormationException ex)
{
Logger.LogError(ex, ex.Message);
return Response.Fail(new Models.DescribeChangeSetResponse
{
ErrorCode = ErrorCode.AwsError,
ErrorMessage = ex.Message
});
}
}
public ExecuteChangeSetResponse ExecuteChangeSet(ExecuteChangeSetRequest request)
{
try
{
Amazon.CloudFormation.Model.ExecuteChangeSetResponse executeChangeSetResponse =
_amazonCloudFormation.ExecuteChangeSet(new Amazon.CloudFormation.Model.ExecuteChangeSetRequest
{
StackName = request.StackName,
ChangeSetName = request.ChangeSetName
});
return Response.Ok(new ExecuteChangeSetResponse());
}
catch (TokenAlreadyExistsException ex)
{
Logger.LogError(ex, ex.Message);
return Response.Fail(new ExecuteChangeSetResponse
{
ErrorCode = ErrorCode.TokenAlreadyExists,
ErrorMessage = ex.Message
});
}
catch (InvalidChangeSetStatusException ex)
{
Logger.LogError(ex, ex.Message);
return Response.Fail(new ExecuteChangeSetResponse
{
ErrorCode = ErrorCode.InvalidChangeSetStatus,
ErrorMessage = ex.Message
});
}
catch (InsufficientCapabilitiesException ex)
{
Logger.LogError(ex, ex.Message);
return Response.Fail(new ExecuteChangeSetResponse
{
ErrorCode = ErrorCode.InsufficientCapabilities,
ErrorMessage = ex.Message
});
}
catch (ChangeSetNotFoundException ex)
{
Logger.LogError(ex, ex.Message);
return Response.Fail(new ExecuteChangeSetResponse
{
ErrorCode = ErrorCode.ChangeSetNotFound,
ErrorMessage = ex.Message
});
}
catch (AmazonCloudFormationException ex)
{
Logger.LogError(ex, ex.Message);
return Response.Fail(new ExecuteChangeSetResponse
{
ErrorCode = ErrorCode.AwsError,
ErrorMessage = ex.Message
});
}
}
public StackExistsResponse StackExists(StackExistsRequest request)
{
if (string.IsNullOrEmpty(request.StackName))
{
return Response.Fail(new StackExistsResponse
{
ErrorCode = ErrorCode.InvalidParameters
});
}
return Response.Ok(new StackExistsResponse
{
Exists = DescribeStack(new DescribeStackRequest
{
StackName = request.StackName
}).Success
});
}
public UploadServerBuildResponse UploadServerBuild(UploadServerBuildRequest request)
{
if (string.IsNullOrEmpty(request.BucketName) || string.IsNullOrEmpty(request.BuildS3Key) || string.IsNullOrEmpty(request.FilePath))
{
return Response.Fail(new UploadServerBuildResponse
{
ErrorCode = ErrorCode.InvalidParameters
});
}
if (!_fileWrapper.FileExists(request.FilePath))
{
return Response.Fail(new UploadServerBuildResponse
{
ErrorCode = ErrorCode.FileNotFound
});
}
(bool success, string fileUrl, string uploadErrorMessage) uploadResult = UploadFile(request.BucketName, request.FilePath, request.BuildS3Key);
if (uploadResult.success)
{
return Response.Ok(new UploadServerBuildResponse());
}
return Response.Fail(new UploadServerBuildResponse
{
ErrorMessage = uploadResult.uploadErrorMessage
});
}
public CancelDeploymentResponse CancelDeployment(CancelDeploymentRequest request)
{
if (string.IsNullOrEmpty(request.StackName))
{
return Response.Fail(new CancelDeploymentResponse()
{
ErrorCode = ErrorCode.InvalidParameters
});
}
try
{
_amazonCloudFormation.CancelDeployment(new CancelUpdateStackRequest
{
StackName = request.StackName,
ClientRequestToken = request.ClientRequestToken ?? Guid.NewGuid().ToString()
});
return Response.Ok(new CancelDeploymentResponse());
}
catch (TokenAlreadyExistsException ex)
{
Logger.LogError(ex, ex.Message);
return Response.Fail(new CancelDeploymentResponse
{
ErrorCode = ErrorCode.TokenAlreadyExists,
ErrorMessage = ex.ErrorCode
});
}
catch (AmazonCloudFormationException ex)
{
Logger.LogError(ex, ex.Message);
return Response.Fail(new CancelDeploymentResponse
{
ErrorCode = ErrorCode.AwsError,
ErrorMessage = ex.ErrorCode
});
}
catch (Exception ex)
{
Logger.LogError(ex, ex.Message);
return Response.Fail(new CancelDeploymentResponse
{
ErrorCode = ErrorCode.UnknownError,
ErrorMessage = ex.Message
});
}
}
public Models.DeleteChangeSetResponse DeleteChangeSet(Models.DeleteChangeSetRequest request)
{
if (string.IsNullOrEmpty(request.ChangeSetName) || string.IsNullOrEmpty(request.StackName))
{
return Response.Fail(new Models.DeleteChangeSetResponse()
{
ErrorCode = ErrorCode.InvalidParameters
});
}
try
{
_amazonCloudFormation.DeleteChangeSet(new Amazon.CloudFormation.Model.DeleteChangeSetRequest
{
ChangeSetName = request.ChangeSetName,
StackName = request.StackName
});
return Response.Ok(new Models.DeleteChangeSetResponse());
}
catch (InvalidChangeSetStatusException ex)
{
Logger.LogError(ex, ex.Message);
return Response.Fail(new Models.DeleteChangeSetResponse()
{
ErrorCode = ErrorCode.InvalidChangeSetStatus,
ErrorMessage = ex.ErrorCode
});
}
catch (AmazonCloudFormationException ex)
{
Logger.LogError(ex, ex.Message);
return Response.Fail(new Models.DeleteChangeSetResponse()
{
ErrorCode = ErrorCode.AwsError,
ErrorMessage = ex.ErrorCode
});
}
}
public Models.DeleteStackResponse DeleteStack(Models.DeleteStackRequest request)
{
if (string.IsNullOrEmpty(request.StackName))
{
return Response.Fail(new Models.DeleteStackResponse()
{
ErrorCode = ErrorCode.InvalidParameters
});
}
try
{
_amazonCloudFormation.DeleteStack(new Amazon.CloudFormation.Model.DeleteStackRequest
{
StackName = request.StackName
});
return Response.Ok(new Models.DeleteStackResponse());
}
catch (TokenAlreadyExistsException ex)
{
Logger.LogError(ex, ex.Message);
return Response.Fail(new Models.DeleteStackResponse()
{
ErrorCode = ErrorCode.TokenAlreadyExists,
ErrorMessage = ex.ErrorCode
});
}
catch (AmazonCloudFormationException ex)
{
Logger.LogError(ex, ex.Message);
return Response.Fail(new Models.DeleteStackResponse()
{
ErrorCode = ErrorCode.AwsError,
ErrorMessage = ex.ErrorCode
});
}
}
private (bool success, string fileUrl, string uploadErrorMessage) UploadFile(string bucketName, string filePath, string key)
{
try
{
var putObjectRequest = new PutObjectRequest
{
BucketName = bucketName,
FilePath = filePath,
Key = key
};
PutObjectResponse putObjectResponse = _amazonS3Wrapper.PutObject(putObjectRequest);
string region = _amazonS3Wrapper.GetRegionEndpoint();
string s3Url = s_formatter.GetS3Url(bucketName, region, key);
return (true, s3Url, string.Empty);
}
catch (AmazonS3Exception ex)
{
return (false, string.Empty, ex.ErrorCode);
}
}
private void InjectLambdaParameters(
List<Parameter> parameters,
string bootstrapBucketName,
string gameName,
string lambdaSourcePath
)
{
if (string.IsNullOrEmpty(lambdaSourcePath))
{
return;
}
string s3LambdaKey = UploadLambda(
bootstrapBucketName,
gameName,
lambdaSourcePath
);
parameters.Add(new Parameter
{
ParameterKey = s_lambdaZipS3BucketParameter,
ParameterValue = bootstrapBucketName
});
parameters.Add(new Parameter
{
ParameterKey = s_lambdaZipS3KeyParameter,
ParameterValue = s3LambdaKey
});
}
private string UploadLambda(
string bootstrapBucketName,
string gameName,
string lambdaSourcePath)
{
string zipFilePath = _fileWrapper.GetUniqueTempFilePath();
_fileZip.Zip(lambdaSourcePath, zipFilePath);
string lambdaS3Key = s_formatter.GetLambdaS3Key(gameName);
var putObjectRequest = new PutObjectRequest
{
BucketName = bootstrapBucketName,
FilePath = zipFilePath,
Key = lambdaS3Key
};
PutObjectResponse putObjectResponse =
_amazonS3Wrapper.PutObject(putObjectRequest);
if (_fileWrapper.FileExists(zipFilePath))
{
_fileWrapper.Delete(zipFilePath);
}
return lambdaS3Key;
}
}
}
| 722 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using Amazon.CloudFormation.Model;
namespace AmazonGameLiftPlugin.Core.DeploymentManagement
{
public interface IAmazonCloudFormationWrapper
{
ValidateTemplateResponse ValidateTemplate(ValidateTemplateRequest request);
DescribeStacksResponse DescribeStacks(DescribeStacksRequest request);
CreateChangeSetResponse CreateChangeSet(CreateChangeSetRequest request);
DescribeChangeSetResponse DescribeChangeSet(DescribeChangeSetRequest request);
ExecuteChangeSetResponse ExecuteChangeSet(ExecuteChangeSetRequest request);
CancelUpdateStackResponse CancelDeployment(CancelUpdateStackRequest request);
DeleteChangeSetResponse DeleteChangeSet(DeleteChangeSetRequest request);
DeleteStackResponse DeleteStack(DeleteStackRequest request);
}
}
| 27 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using AmazonGameLiftPlugin.Core.DeploymentManagement.Models;
namespace AmazonGameLiftPlugin.Core.DeploymentManagement
{
public interface IDeploymentManager
{
DescribeStackResponse DescribeStack(DescribeStackRequest request);
ValidateCfnTemplateResponse ValidateCfnTemplate(ValidateCfnTemplateRequest request);
CreateChangeSetResponse CreateChangeSet(CreateChangeSetRequest request);
DescribeChangeSetResponse DescribeChangeSet(DescribeChangeSetRequest request);
StackExistsResponse StackExists(StackExistsRequest request);
ExecuteChangeSetResponse ExecuteChangeSet(ExecuteChangeSetRequest request);
UploadServerBuildResponse UploadServerBuild(UploadServerBuildRequest request);
CancelDeploymentResponse CancelDeployment(CancelDeploymentRequest request);
DeleteChangeSetResponse DeleteChangeSet(DeleteChangeSetRequest request);
DeleteStackResponse DeleteStack(DeleteStackRequest request);
}
}
| 31 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using AmazonGameLiftPlugin.Core.Shared;
namespace AmazonGameLiftPlugin.Core.DeploymentManagement.Models
{
public class CancelDeploymentRequest
{
public string StackName { get; set; }
public string ClientRequestToken { get; set; }
}
public class CancelDeploymentResponse : Response
{
}
}
| 19 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using AmazonGameLiftPlugin.Core.Shared;
namespace AmazonGameLiftPlugin.Core.DeploymentManagement.Models
{
public class CreateChangeSetRequest
{
public string StackName { get; set; }
public string TemplateFilePath { get; set; }
public string ParametersFilePath { get; set; }
public string BootstrapBucketName { get; set; }
public string LambdaSourcePath { get; set; }
public string GameName { get; set; }
public string BuildS3Key { get; set; }
}
public class CreateChangeSetResponse : Response
{
public string CreatedChangeSetName { get; set; }
}
}
| 30 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using AmazonGameLiftPlugin.Core.Shared;
namespace AmazonGameLiftPlugin.Core.DeploymentManagement.Models
{
public class DeleteChangeSetRequest
{
public string StackName { get; set; }
public string ChangeSetName { get; set; }
}
public class DeleteChangeSetResponse : Response
{
}
}
| 19 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using AmazonGameLiftPlugin.Core.Shared;
namespace AmazonGameLiftPlugin.Core.DeploymentManagement.Models
{
public class DeleteStackRequest
{
public string StackName { get; set; }
}
public class DeleteStackResponse : Response
{
}
}
| 18 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System.Collections.Generic;
using AmazonGameLiftPlugin.Core.Shared;
namespace AmazonGameLiftPlugin.Core.DeploymentManagement.Models
{
public class DescribeChangeSetRequest
{
public string StackName { get; set; }
public string ChangeSetName { get; set; }
}
public class DescribeChangeSetResponse : Response
{
public string StackId { get; set; }
public string ChangeSetId { get; set; }
public string ExecutionStatus { get; set; }
public IEnumerable<Change> Changes { get; set; }
}
public class Change
{
public string Action { get; set; }
public string LogicalId { get; set; }
public string PhysicalId { get; set; }
public string ResourceType { get; set; }
public string Replacement { get; set; }
public string Module { get; set; }
}
}
| 38 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using System.Collections;
using System.Collections.Generic;
using AmazonGameLiftPlugin.Core.Shared;
namespace AmazonGameLiftPlugin.Core.DeploymentManagement.Models
{
public class DescribeStackRequest
{
public string StackName { get; set; }
public IEnumerable<string> OutputKeys { get; set; }
}
public class DescribeStackResponse : Response
{
public string StackStatus { get; set; }
public Dictionary<string, string> Outputs { get; set; }
public string StackId { get; set; }
public DateTime LastUpdatedTime { get; set; }
public string GameName { get; set; }
}
}
| 27 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using AmazonGameLiftPlugin.Core.Shared;
namespace AmazonGameLiftPlugin.Core.DeploymentManagement.Models
{
public class ExecuteChangeSetRequest
{
public string StackName { get; set; }
public string ChangeSetName { get; set; }
}
public class ExecuteChangeSetResponse : Response
{
}
}
| 20 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using AmazonGameLiftPlugin.Core.Shared;
namespace AmazonGameLiftPlugin.Core.DeploymentManagement.Models
{
public class StackExistsRequest
{
public string StackName { get; set; }
}
public class StackExistsResponse : Response
{
public bool Exists { get; set; }
}
}
| 18 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using AmazonGameLiftPlugin.Core.Shared;
namespace AmazonGameLiftPlugin.Core.DeploymentManagement.Models
{
public class UploadServerBuildRequest
{
public string BucketName { get; set; }
public string BuildS3Key { get; set; }
public string FilePath { get; set; }
}
public class UploadServerBuildResponse : Response
{
}
}
| 21 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using AmazonGameLiftPlugin.Core.Shared;
namespace AmazonGameLiftPlugin.Core.DeploymentManagement.Models
{
public class ValidateCfnTemplateRequest
{
public string TemplateFilePath { get; set; }
}
public class ValidateCfnTemplateResponse : Response
{
}
}
| 17 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text.RegularExpressions;
using AmazonGameLiftPlugin.Core.GameLiftLocalTesting.Models;
using AmazonGameLiftPlugin.Core.Shared;
using AmazonGameLiftPlugin.Core.Shared.Logging;
using AmazonGameLiftPlugin.Core.Shared.ProcessManagement;
namespace AmazonGameLiftPlugin.Core.GameLiftLocalTesting
{
public class GameLiftProcess : IGameLiftProcess
{
private readonly IProcessWrapper _processWrapper;
public GameLiftProcess(IProcessWrapper processWrapper)
{
_processWrapper = processWrapper;
}
// This method starts GameLift Local
public StartResponse Start(StartRequest request)
{
try
{
if (request == null || string.IsNullOrWhiteSpace(request.GameLiftLocalFilePath))
{
return Response.Fail(new StartResponse
{
ErrorCode = ErrorCode.InvalidParameters
});
}
string arg = FormatCommand(request);
int processId;
if (request.LocalOperatingSystem == LocalOperatingSystem.MAC_OS)
{
// Starts a bash process to run an Apple script, which activates a new Terminal App window,
// and runs the GameLift local jar.
string activateTerminalScript = $"tell application \\\"Terminal\\\" to activate";
string setGameLiftLocalFilePath = $"set GameLiftLocalFilePathEnvVar to \\\"{request.GameLiftLocalFilePath}\\\"";
string runGameLiftLocalJarScript = $"\\\"java -jar \\\" & quoted form of GameLiftLocalFilePathEnvVar & \\\" -p {request.Port.ToString()}\\\"";
string runGameLiftLocal = $"tell application \\\"Terminal\\\" to do script {runGameLiftLocalJarScript}";
string osaScript = $"osascript -e \'{activateTerminalScript}\' -e \'{setGameLiftLocalFilePath}\' -e \'{runGameLiftLocal}\'";
string bashCommand = $" -c \"{osaScript}\"";
ProcessStartInfo processStartInfo = new ProcessStartInfo
{
UseShellExecute = false,
RedirectStandardOutput = true,
FileName = "/bin/bash",
CreateNoWindow = false,
Arguments = bashCommand,
WorkingDirectory = Path.GetDirectoryName(request.GameLiftLocalFilePath)
};
processId = ExecuteMacOsTerminalCommand(processStartInfo);
}
else
{
ProcessStartInfo processStartInfo = new ProcessStartInfo
{
UseShellExecute = true,
FileName = "java",
Arguments = arg,
WorkingDirectory = Path.GetDirectoryName(request.GameLiftLocalFilePath)
};
processId = _processWrapper.Start(processStartInfo);
}
return Response.Ok(new StartResponse
{
ProcessId = processId
});
}
catch (Exception ex)
{
Logger.LogError(ex, ex.Message);
return Response.Fail(new StartResponse
{
ErrorCode = ErrorCode.UnknownError,
ErrorMessage = ex.Message
});
}
}
private void CloseTerminalWindow(int windowId)
{
// Starts a bash process to run an Apple script, which tells Terminal App to close a specified window
string closeWindowScript = $"tell application \\\"Terminal\\\" to close window id {windowId}";
string osaScript = $"osascript -e \'{closeWindowScript}\'";
string bashCommand = $" -c \"{osaScript}\"";
var processStartInfo = new ProcessStartInfo
{
UseShellExecute = false,
RedirectStandardOutput = true,
FileName = "/bin/bash",
CreateNoWindow = false,
Arguments = bashCommand
};
_processWrapper.Start(processStartInfo);
}
private int ExecuteMacOsTerminalCommand(ProcessStartInfo processStartInfo)
{
(int bashId, string output) = _processWrapper.GetProcessIdAndStandardOutput(processStartInfo);
// When running script in Mac OS Terminal App via oascript, Terminal returns the window id as a response,
// e.g. "tab 1 of window id 62198". This will be used as the id when we terminate the window.
var match = Regex.Match(output, "window id (\\d+)");
if (match.Success)
{
// Return the Terminal app window id
return Int32.Parse(match.Groups[1].Value);
}
else
{
// Pass back the /bin/bash execution process id as an identifier instead
return bashId;
}
}
private string FormatCommand(StartRequest request)
{
var arguments = new List<string>();
arguments.Add("-jar");
arguments.Add(EscapeArgument(request.GameLiftLocalFilePath));
arguments.Add("-p");
arguments.Add(EscapeArgument(request.Port.ToString()));
return string.Join(" ", arguments);
}
private string EscapeArgument(string argument)
{
return "\"" + Regex.Replace(argument, @"(\\+)$", @"$1$1") + "\"";
}
public StopResponse Stop(StopRequest request)
{
try
{
if (request.LocalOperatingSystem == LocalOperatingSystem.MAC_OS) {
CloseTerminalWindow(request.ProcessId);
} else {
_processWrapper.Kill(request.ProcessId);
}
return Response.Ok(new StopResponse());
}
catch (Exception ex)
{
Logger.LogError(ex, ex.Message);
return Response.Fail(new StopResponse
{
ErrorCode = ErrorCode.UnknownError,
ErrorMessage = ex.Message
});
}
}
public RunLocalServerResponse RunLocalServer(RunLocalServerRequest request)
{
try
{
if (request == null || string.IsNullOrWhiteSpace(request.FilePath) || string.IsNullOrWhiteSpace(request.ApplicationProductName))
{
return Response.Fail(new RunLocalServerResponse
{
ErrorCode = ErrorCode.InvalidParameters
});
}
int processId;
if (request.LocalOperatingSystem == LocalOperatingSystem.MAC_OS)
{
// Starts a bash process to run an Apple script, which activates a new Terminal App window,
// and runs the game server executable in the Unity compiled .app file
string activateTerminalScript = $"tell application \\\"Terminal\\\" to activate";
string setGameServerFilePath = $"set GameServerFilePathEnvVar to \\\"{request.FilePath}/Contents/MacOS/{request.ApplicationProductName}\\\"";
string runGameServerScript = $"GameServerFilePathEnvVar";
string runGameServer = $"tell application \\\"Terminal\\\" to do script {runGameServerScript}";
string osaScript = $"osascript -e \'{activateTerminalScript}\' -e \'{setGameServerFilePath}\' -e \'{runGameServer}\'";
string bashCommand = $" -c \"{osaScript}\"";
ProcessStartInfo processStartInfo = new ProcessStartInfo
{
UseShellExecute = false,
RedirectStandardOutput = true,
FileName = "/bin/bash",
CreateNoWindow = false,
Arguments = bashCommand
};
processId = ExecuteMacOsTerminalCommand(processStartInfo);
}
else
{
ProcessStartInfo processStartInfo = new ProcessStartInfo
{
UseShellExecute = request.ShowWindow,
FileName = request.FilePath
};
processId = _processWrapper.Start(processStartInfo);
}
return Response.Ok(new RunLocalServerResponse
{
ProcessId = processId
});
}
catch (Exception ex)
{
Logger.LogError(ex, ex.Message);
return Response.Fail(new RunLocalServerResponse
{
ErrorCode = ErrorCode.UnknownError,
ErrorMessage = ex.Message
});
}
}
}
}
| 238 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using AmazonGameLiftPlugin.Core.GameLiftLocalTesting.Models;
namespace AmazonGameLiftPlugin.Core.GameLiftLocalTesting
{
public interface IGameLiftProcess
{
StartResponse Start(StartRequest request);
StopResponse Stop(StopRequest request);
RunLocalServerResponse RunLocalServer(RunLocalServerRequest request);
}
}
| 17 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using AmazonGameLiftPlugin.Core.Shared;
namespace AmazonGameLiftPlugin.Core.GameLiftLocalTesting.Models
{
public enum LocalOperatingSystem
{
WINDOWS,
MAC_OS,
UNSUPPORTED
}
}
| 15 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using AmazonGameLiftPlugin.Core.Shared;
namespace AmazonGameLiftPlugin.Core.GameLiftLocalTesting.Models
{
public class RunLocalServerRequest
{
public string FilePath { get; set; }
public bool ShowWindow { get; set; }
public string ApplicationProductName { get; set; }
public LocalOperatingSystem LocalOperatingSystem { get; set; }
}
public class RunLocalServerResponse : Response
{
public int ProcessId { get; set; }
}
}
| 21 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using AmazonGameLiftPlugin.Core.Shared;
namespace AmazonGameLiftPlugin.Core.GameLiftLocalTesting.Models
{
public class StartRequest
{
public string GameLiftLocalFilePath { get; set; }
public int Port { get; set; }
public LocalOperatingSystem LocalOperatingSystem { get; set; }
}
public class StartResponse : Response
{
public int ProcessId { get; set; }
}
}
| 22 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using AmazonGameLiftPlugin.Core.Shared;
namespace AmazonGameLiftPlugin.Core.GameLiftLocalTesting.Models
{
public class StopRequest
{
public int ProcessId { get; set; }
public LocalOperatingSystem LocalOperatingSystem { get; set; }
}
public class StopResponse : Response
{
}
}
| 20 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using AmazonGameLiftPlugin.Core.JavaCheck.Models;
namespace AmazonGameLiftPlugin.Core.JavaCheck
{
public interface IInstalledJavaVersionProvider
{
/// <summary>
/// Checks whether expected major version of java is installed or not.
/// Expected Version number is standard java version number like
/// described on the <see href="https://www.oracle.com/java/technologies/javase/versioning-naming.html">page</see>
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
CheckInstalledJavaVersionResponse CheckInstalledJavaVersion(CheckInstalledJavaVersionRequest request);
}
}
| 20 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using System.Diagnostics;
using System.Text.RegularExpressions;
using AmazonGameLiftPlugin.Core.JavaCheck.Models;
using AmazonGameLiftPlugin.Core.Shared;
using AmazonGameLiftPlugin.Core.Shared.Logging;
using AmazonGameLiftPlugin.Core.Shared.ProcessManagement;
namespace AmazonGameLiftPlugin.Core.JavaCheck
{
public class InstalledJavaVersionProvider : IInstalledJavaVersionProvider
{
private readonly IProcessWrapper _process;
public InstalledJavaVersionProvider(IProcessWrapper process)
{
_process = process;
}
private CheckInstalledJavaVersionResponse CreateCheckInstalledJavaVersionResponse(bool installed) {
return Response.Ok(new CheckInstalledJavaVersionResponse
{
IsInstalled = installed
});
}
public CheckInstalledJavaVersionResponse CheckInstalledJavaVersion(CheckInstalledJavaVersionRequest request)
{
var processStartInfo = new ProcessStartInfo();
processStartInfo.FileName = "java";
processStartInfo.Arguments = " -version";
processStartInfo.RedirectStandardError = true;
processStartInfo.UseShellExecute = false;
processStartInfo.CreateNoWindow = true;
string processOutput = null;
try
{
processOutput = _process.GetProcessOutput(processStartInfo);
}
catch (Exception ex)
{
Logger.LogError(ex, ex.Message);
return CreateCheckInstalledJavaVersionResponse(false);
}
if (processOutput == null) {
return CreateCheckInstalledJavaVersionResponse(false);
}
// Expected output format:
// (java|openjdk) version "<majorVersion>.<minorVersion>.<build>"
// ex: java version "1.8.0_291"
// openjdk version "1.8.0_322"
// openjdk version "19"
// majorVersion and minorVersion are integers. build can be anything
var outputPattern = new Regex("(?:openjdk|java) version \"(?<majorVersion>\\d+)(?:\\.(?<minorVersion>\\d+)(?:\\.[^\"]+))?\"");
Match outputMatch = outputPattern.Match(processOutput);
if (!outputMatch.Success) {
return CreateCheckInstalledJavaVersionResponse(false);
}
// if majorVersion is 1, we use minorVersion as the majorVersion, since java version had the format 1.?? until java 8
var majorVersion = outputMatch.Groups["majorVersion"].ToString();
var minorVersion = outputMatch.Groups["minorVersion"].ToString();
var actualMajorVersion = majorVersion.Equals("1") && !String.IsNullOrEmpty(minorVersion) ? minorVersion : majorVersion;
int.TryParse(actualMajorVersion, out int majorVersionAsNumber);
bool isInstalled = majorVersionAsNumber >= request.ExpectedMinimumJavaMajorVersion;
return CreateCheckInstalledJavaVersionResponse(isInstalled);
}
}
}
| 80 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using AmazonGameLiftPlugin.Core.Shared;
namespace AmazonGameLiftPlugin.Core.JavaCheck.Models
{
public class CheckInstalledJavaVersionRequest
{
public int ExpectedMinimumJavaMajorVersion { get; set; }
}
public class CheckInstalledJavaVersionResponse : Response
{
public bool IsInstalled { get; set; }
}
}
| 18 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System.Threading.Tasks;
using AmazonGameLiftPlugin.Core.Latency.Models;
namespace AmazonGameLiftPlugin.Core.LatencyMeasurement
{
public interface ILatencyService
{
Task<GetLatenciesResponse> GetLatencies(GetLatenciesRequest request);
}
}
| 14 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System.Net.NetworkInformation;
using System.Threading.Tasks;
using AmazonGameLiftPlugin.Core.Latency.Models;
namespace AmazonGameLiftPlugin.Core.Latency
{
public interface IPingWrapper
{
Task<PingResult> SendPingAsync(string hostNameOrAddress);
}
}
| 15 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Threading.Tasks;
using AmazonGameLiftPlugin.Core.Latency.Models;
using AmazonGameLiftPlugin.Core.LatencyMeasurement;
using AmazonGameLiftPlugin.Core.Shared;
using AmazonGameLiftPlugin.Core.Shared.Logging;
namespace AmazonGameLiftPlugin.Core.Latency
{
public class LatencyService : ILatencyService
{
private readonly IPingWrapper _pingWrapper;
private readonly int _pingCount;
private const int DefaultPingCount = 5;
public LatencyService(IPingWrapper pingWrapper, int pingCount = DefaultPingCount)
{
_pingWrapper = pingWrapper;
_pingCount = pingCount <= 0 ? DefaultPingCount : pingCount;
}
public async Task<GetLatenciesResponse> GetLatencies(GetLatenciesRequest request)
{
try
{
if (request == null || request.Regions == null || !request.Regions.Any())
{
return Response.Fail(new GetLatenciesResponse
{
ErrorCode = ErrorCode.InvalidParameters
});
}
var regionLatencyMap = new Dictionary<string, long>();
var regionLatencyCalculationTasks = new List<Task>();
foreach (string region in request.Regions)
{
regionLatencyCalculationTasks.Add(
CalculateLatencyForRegion(regionLatencyMap, region)
);
}
await Task.WhenAll(regionLatencyCalculationTasks);
return Response.Ok(new GetLatenciesResponse
{
RegionLatencies = regionLatencyMap
});
}
catch (Exception ex)
{
Logger.LogError(ex, ex.Message);
return Response.Fail(new GetLatenciesResponse
{
ErrorCode = ErrorCode.UnknownError,
ErrorMessage = ex.Message
});
}
}
private string GetEc2EndpointFromRegion(string region) => $"ec2.{region}.amazonaws.com";
private async Task CalculateLatencyForRegion(
Dictionary<string, long> regionLatencyMap,
string region)
{
try
{
string address = GetEc2EndpointFromRegion(region);
List<Task<PingResult>> pingTasks = PingAddress(address, _pingCount);
PingResult[] pingResults = await Task.WhenAll(pingTasks.ToArray());
long averagePingInMs = pingResults.Sum(x => x.RoundtripTime) / _pingCount;
regionLatencyMap.Add(region, averagePingInMs);
}
catch (PingException ex)
{
Logger.LogError(ex, ex.Message);
}
catch (SocketException ex)
{
Logger.LogError(ex, ex.Message);
}
}
private List<Task<PingResult>> PingAddress(string address, int pingCount)
{
var pingReplyTasks = new List<Task<PingResult>>();
for (int counter = 0; counter < pingCount; counter++)
{
pingReplyTasks.Add(_pingWrapper.SendPingAsync(address));
}
return pingReplyTasks;
}
}
}
| 112 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System.Net.NetworkInformation;
using System.Threading.Tasks;
using AmazonGameLiftPlugin.Core.Latency.Models;
namespace AmazonGameLiftPlugin.Core.Latency
{
public class PingWrapper : IPingWrapper
{
public async Task<PingResult> SendPingAsync(string hostNameOrAddress)
{
using (var pinger = new Ping())
{
PingReply pingReply = await pinger.SendPingAsync(hostNameOrAddress);
return new PingResult
{
RoundtripTime = pingReply.RoundtripTime
};
}
}
}
}
| 26 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System.Collections.Generic;
using AmazonGameLiftPlugin.Core.Shared;
namespace AmazonGameLiftPlugin.Core.Latency.Models
{
public class GetLatenciesRequest
{
public IEnumerable<string> Regions { get; set; }
}
public class GetLatenciesResponse : Response
{
public Dictionary<string, long> RegionLatencies { get; set; }
}
}
| 19 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
namespace AmazonGameLiftPlugin.Core.Latency.Models
{
public class PingResult
{
public long RoundtripTime { get; set; }
}
}
| 11 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using AmazonGameLiftPlugin.Core.SettingsManagement.Models;
namespace AmazonGameLiftPlugin.Core.SettingsManagement
{
public interface ISettingsStore
{
PutSettingResponse PutSetting(PutSettingRequest request);
GetSettingResponse GetSetting(GetSettingRequest request);
ClearSettingResponse ClearSetting(ClearSettingRequest request);
}
}
| 17 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using System.IO;
using System.Linq;
using AmazonGameLiftPlugin.Core.SettingsManagement.Models;
using AmazonGameLiftPlugin.Core.Shared;
using AmazonGameLiftPlugin.Core.Shared.FileSystem;
using AmazonGameLiftPlugin.Core.Shared.SettingsStore;
using YamlDotNet.RepresentationModel;
namespace AmazonGameLiftPlugin.Core.SettingsManagement
{
public class SettingsStore : ISettingsStore
{
private readonly string _settingsFilePath;
private readonly IFileWrapper _fileWrapper;
private readonly IStreamWrapper _yamlStreamWrapper;
public SettingsStore(IFileWrapper fileWrapper, IStreamWrapper yamlStreamWrapper = default, string settingsFilePath = default)
{
_fileWrapper = fileWrapper;
_yamlStreamWrapper = yamlStreamWrapper ?? new YamlStreamWrapper();
_settingsFilePath = settingsFilePath ?? $"{Directory.GetCurrentDirectory()}/settings.yaml";
}
public PutSettingResponse PutSetting(PutSettingRequest request)
{
if (string.IsNullOrEmpty(request.Key) || string.IsNullOrEmpty(request.Value))
{
return Response.Fail(new PutSettingResponse()
{
ErrorCode = ErrorCode.InvalidParameters
});
}
if (!_fileWrapper.FileExists(_settingsFilePath))
{
InitSettingsFile();
}
var input = new StringReader(_fileWrapper.ReadAllText(_settingsFilePath));
_yamlStreamWrapper.Load(input);
YamlMappingNode rootMappingNode = (_yamlStreamWrapper.GetDocuments().Count > 0) ? (YamlMappingNode)_yamlStreamWrapper.GetDocuments()[0].RootNode : default;
if (rootMappingNode == null)
{
return Response.Fail(new PutSettingResponse()
{
ErrorCode = ErrorCode.InvalidSettingsFile
});
}
if (rootMappingNode.Children.ContainsKey(request.Key))
{
rootMappingNode.Children.Remove(request.Key);
}
rootMappingNode.Add(request.Key, request.Value);
using (TextWriter writer = _fileWrapper.CreateText(_settingsFilePath))
{
_yamlStreamWrapper.Save(writer, false);
}
return Response.Ok(new PutSettingResponse());
}
public GetSettingResponse GetSetting(GetSettingRequest request)
{
if (string.IsNullOrEmpty(request.Key))
{
return Response.Fail(new GetSettingResponse
{
ErrorCode = ErrorCode.InvalidParameters
});
}
if (_fileWrapper.FileExists(_settingsFilePath))
{
var input = new StringReader(_fileWrapper.ReadAllText(_settingsFilePath));
_yamlStreamWrapper.Load(input);
YamlMappingNode rootMappingNode = (_yamlStreamWrapper.GetDocuments().Count > 0) ? (YamlMappingNode)_yamlStreamWrapper.GetDocuments()[0].RootNode : default;
if (rootMappingNode == null)
{
return Response.Fail(new GetSettingResponse()
{
ErrorCode = ErrorCode.InvalidSettingsFile
});
}
return rootMappingNode.Children.ContainsKey(request.Key)
? Response.Ok(new GetSettingResponse()
{
Value = rootMappingNode.Children.First(x => x.Key.ToString() == request.Key).Value.ToString()
})
: Response.Fail(new GetSettingResponse()
{
ErrorCode = ErrorCode.NoSettingsKeyFound
});
}
return Response.Fail(new GetSettingResponse
{
ErrorCode = ErrorCode.NoSettingsFileFound
});
}
public ClearSettingResponse ClearSetting(ClearSettingRequest request)
{
if (string.IsNullOrEmpty(request.Key))
{
return Response.Fail(new ClearSettingResponse()
{
ErrorCode = ErrorCode.InvalidParameters
});
}
if (!_fileWrapper.FileExists(_settingsFilePath))
{
return Response.Fail(new ClearSettingResponse
{
ErrorCode = ErrorCode.NoSettingsFileFound
});
}
var input = new StringReader(_fileWrapper.ReadAllText(_settingsFilePath));
_yamlStreamWrapper.Load(input);
YamlMappingNode rootMappingNode = (_yamlStreamWrapper.GetDocuments().Count > 0) ? (YamlMappingNode)_yamlStreamWrapper.GetDocuments()[0].RootNode : default;
if (rootMappingNode == null)
{
return Response.Fail(new ClearSettingResponse()
{
ErrorCode = ErrorCode.InvalidSettingsFile
});
}
if (rootMappingNode.Children.ContainsKey(request.Key))
{
rootMappingNode.Children.Remove(request.Key);
using (TextWriter writer = _fileWrapper.CreateText(_settingsFilePath))
{
_yamlStreamWrapper.Save(writer, false);
}
}
return Response.Ok(new ClearSettingResponse());
}
private void InitSettingsFile()
{
var input = new StringReader($"---{Environment.NewLine}version: 1{Environment.NewLine}...");
_yamlStreamWrapper.Load(input);
using (TextWriter writer = _fileWrapper.CreateText(_settingsFilePath))
{
_yamlStreamWrapper.Save(writer, false);
}
}
}
}
| 173 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using AmazonGameLiftPlugin.Core.Shared;
namespace AmazonGameLiftPlugin.Core.SettingsManagement.Models
{
public class ClearSettingRequest
{
public string Key { get; set; }
}
public class ClearSettingResponse : Response
{
}
}
| 17 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using AmazonGameLiftPlugin.Core.Shared;
namespace AmazonGameLiftPlugin.Core.SettingsManagement.Models
{
public class GetSettingRequest
{
public string Key { get; set; }
}
public class GetSettingResponse : Response
{
public string Value { get; set; }
}
}
| 18 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using AmazonGameLiftPlugin.Core.Shared;
namespace AmazonGameLiftPlugin.Core.SettingsManagement.Models
{
public class PutSettingRequest
{
public string Key { get; set; }
public string Value { get; set; }
}
public class PutSettingResponse : Response
{
}
}
| 19 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using System.Collections.Generic;
using Amazon;
namespace AmazonGameLiftPlugin.Core.Shared
{
public static class AwsRegionMapper
{
private static readonly Dictionary<string, RegionEndpoint> s_regions = new Dictionary<string, RegionEndpoint>
{
{
"us-east-2",
RegionEndpoint.USEast2
},
{
"us-east-1",
RegionEndpoint.USEast1
},
{
"us-west-1",
RegionEndpoint.USWest1
},
{
"us-west-2",
RegionEndpoint.USWest2
},
{
"ap-south-1",
RegionEndpoint.APSouth1
},
{
"ap-northeast-2",
RegionEndpoint.APNortheast2
},
{
"ap-southeast-1",
RegionEndpoint.APSoutheast1
},
{
"ap-southeast-2",
RegionEndpoint.APSoutheast2
},
{
"ap-northeast-1",
RegionEndpoint.APNortheast1
},
{
"ca-central-1",
RegionEndpoint.CACentral1
},
{
"cn-north-1",
RegionEndpoint.CNNorth1
},
{
"eu-central-1",
RegionEndpoint.EUCentral1
},
{
"eu-west-1",
RegionEndpoint.EUWest1
},
{
"eu-west-2",
RegionEndpoint.EUWest2
},
{
"sa-east-1",
RegionEndpoint.SAEast1
},
{
"cn-northwest-1",
RegionEndpoint.CNNorthWest1
}
};
internal static RegionEndpoint GetRegionEndpoint(string region)
{
if (IsValidRegion(region))
{
return s_regions[region];
}
throw new Exception(ErrorCode.InvalidRegion);
}
public static bool IsValidRegion(string region)
{
return !string.IsNullOrEmpty(region) && s_regions.ContainsKey(region);
}
public static IEnumerable<string> AvailableRegions()
{
return s_regions.Keys;
}
}
}
| 101 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using Serilog;
namespace AmazonGameLiftPlugin.Core.Shared
{
public class Bootstrapper
{
public static void Initialize()
{
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Error()
.WriteTo.File("logs/amazon-gamelift-plugin-logs.txt", rollingInterval: RollingInterval.Day)
.CreateLogger();
}
}
}
| 19 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
namespace AmazonGameLiftPlugin.Core.Shared
{
public sealed class ErrorCode
{
public static readonly string NoProfileFound = "NOPROFILEFOUND";
public static readonly string ProfileAlreadyExists = "PROFILEALREADYEXISTS";
public static readonly string BucketNameCanNotBeEmpty = "BUCKETNAMECANNOTBEEMPTY";
public static readonly string BucketNameAlreadyExists = "BUCKETNAMEALREADYEXISTS";
public static readonly string BucketNameIsWrong = "BUCKETNAMEISWRONG";
public static readonly string InvalidRegion = "INVALIDREGION";
public static readonly string NoSettingsKeyFound = "NOSETTINGSKEYFOUND";
public static readonly string NoSettingsFileFound = "NOSETTINGSFILEFOUND";
public static readonly string InvalidParameters = "INVALIDPARAMETERS";
public static readonly string InvalidSettingsFile = "INVALIDSETTINGSFILE";
public static readonly string InvalidBucketPolicy = "INVALIDBUCKETPOLICY";
public static readonly string AwsError = "AWSERROR";
public static readonly string InvalidCfnTemplate = "INVALIDCFNTEMPLATE";
public static readonly string StackDoesNotExist = "STACKDOESNOTEXIST";
public static readonly string ParametersFileNotFound = "PARAMETERSFILENOTFOUND";
public static readonly string TemplateFileNotFound = "TEMPLATEFILENOTFOUND";
public static readonly string StackDoesNotHaveChanges = "STACKDOESNOTHAVECHANGES";
public static readonly string BucketDoesNotExist = "BUCKETDOESNOTEXIST";
public static readonly string ChangeSetNotFound = "CHANGESETNOTFOUND";
public static readonly string ChangeSetAlreadyExists = "CHANGESETALREADYEXISTS";
public static readonly string InvalidParametersFile = "INVALIDPARAMETERSFILE";
public static readonly string UnknownError = "UNKNOWNERROR";
public static readonly string FileNotFound = "FILENOTFOUND";
public static readonly string UserNotConfirmed = "USERNOTCONFIRMED";
public static readonly string InvalidIdToken = "INVALIDIDTOKEN";
public static readonly string ApiGatewayRequestError = "APIGATEWAYREQUESTERROR";
public static readonly string ConflictError = "CONFLICTERROR";
public static readonly string NoGameSessionWasFound = "NOGAMESESSIONWASFOUND";
public static readonly string ResourceWithTheNameRequestetAlreadyExists = "RESOURCEWITHTHENAMEREQUESTETALREADYEXISTS";
public static readonly string InsufficientCapabilities = "INSUFFICIENTCAPABILITIES";
public static readonly string LimitExceeded = "LIMITEXCEEDED";
public static readonly string InvalidChangeSetStatus = "INVALIDCHANGESETSTATUS";
public static readonly string TokenAlreadyExists = "TOKENALREADTEXISTS";
}
}
| 75 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
namespace AmazonGameLiftPlugin.Core.Shared
{
/// <summary>
/// Response Base Class
/// </summary>
public class Response
{
public bool Success { get; private set; }
public string ErrorCode { get; set; }
public string ErrorMessage { get; set; }
public static T Ok<T>(T response) where T : Response
{
response.Success = true;
response.ErrorCode = default;
response.ErrorMessage = default;
return response;
}
public static T Fail<T>(T response) where T : Response
{
response.Success = false;
return response;
}
}
}
| 32 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
namespace AmazonGameLiftPlugin.Core.Shared
{
public class ValidationResult
{
public bool IsValid { get; private set; }
public string ErrorCode { get; private set; }
public static ValidationResult Valid()
=> new ValidationResult { IsValid = true };
public static ValidationResult Invalid(string errorCode)
=> new ValidationResult { IsValid = false, ErrorCode = errorCode };
}
}
| 17 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using System.IO;
namespace AmazonGameLiftPlugin.Core.Shared.FileSystem
{
public class FileWrapper : IFileWrapper
{
public bool FileExists(string path) => File.Exists(path);
public string ReadAllText(string path) => File.ReadAllText(path);
public void WriteAllText(string path, string text) => File.WriteAllText(path, text);
public StreamWriter CreateText(string path) => File.CreateText(path);
public void Delete(string path) => File.Delete(path);
public bool DirectoryExists(string path) => Directory.Exists(path);
public void CreateDirectory(string directoryPath)
=> Directory.CreateDirectory(directoryPath);
public string GetUniqueTempFilePath() => Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
}
}
| 29 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System.IO;
namespace AmazonGameLiftPlugin.Core.Shared.FileSystem
{
public interface IFileWrapper
{
bool FileExists(string path);
string ReadAllText(string path);
void WriteAllText(string path, string text);
StreamWriter CreateText(string path);
void Delete(string path);
bool DirectoryExists(string path);
void CreateDirectory(string directoryPath);
string GetUniqueTempFilePath();
}
}
| 27 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System.IO;
using System.IO.Compression;
namespace AmazonGameLiftPlugin.Core.Shared.FileZip
{
public class FileZip : IFileZip
{
public void Zip(string sourcePathDirectory, string zipFilePath)
{
if (File.Exists(zipFilePath))
{
File.Delete(zipFilePath);
}
ZipFile.CreateFromDirectory(sourcePathDirectory, zipFilePath);
}
}
}
| 22 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
namespace AmazonGameLiftPlugin.Core.Shared.FileZip
{
public interface IFileZip
{
void Zip(string sourcePathDirectory, string zipFilePath);
}
}
| 11 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using Serilog;
namespace AmazonGameLiftPlugin.Core.Shared.Logging
{
public class Logger
{
public static void LogError(Exception ex, string message)
{
Log.Error(ex, message);
}
}
}
| 17 |
Subsets and Splits