HostingServicesManager.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net;
  5. using System.Net.NetworkInformation;
  6. using System.Net.Sockets;
  7. using UnityEditor.AddressableAssets.Build.DataBuilders;
  8. using UnityEditor.AddressableAssets.Settings;
  9. using UnityEngine;
  10. using UnityEngine.Serialization;
  11. // ReSharper disable DelegateSubtraction
  12. namespace UnityEditor.AddressableAssets.HostingServices
  13. {
  14. /// <summary>
  15. /// Manages the hosting services.
  16. /// </summary>
  17. [Serializable]
  18. public class HostingServicesManager : ISerializationCallbackReceiver
  19. {
  20. internal const string KPrivateIpAddressKey = "PrivateIpAddress";
  21. internal string GetPrivateIpAddressKey(int id = 0)
  22. {
  23. if (id == 0)
  24. return KPrivateIpAddressKey;
  25. return $"{KPrivateIpAddressKey}_{id}";
  26. }
  27. [Serializable]
  28. internal class HostingServiceInfo
  29. {
  30. [SerializeField]
  31. internal string classRef;
  32. [SerializeField]
  33. internal KeyDataStore dataStore;
  34. }
  35. [FormerlySerializedAs("m_hostingServiceInfos")]
  36. [SerializeField]
  37. List<HostingServiceInfo> m_HostingServiceInfos;
  38. [FormerlySerializedAs("m_settings")]
  39. [SerializeField]
  40. AddressableAssetSettings m_Settings;
  41. [FormerlySerializedAs("m_nextInstanceId")]
  42. [SerializeField]
  43. int m_NextInstanceId;
  44. [FormerlySerializedAs("m_registeredServiceTypeRefs")]
  45. [SerializeField]
  46. List<string> m_RegisteredServiceTypeRefs;
  47. readonly Type[] m_BuiltinServiceTypes =
  48. {
  49. typeof(HttpHostingService)
  50. };
  51. Dictionary<IHostingService, HostingServiceInfo> m_HostingServiceInfoMap;
  52. ILogger m_Logger;
  53. List<Type> m_RegisteredServiceTypes;
  54. internal bool exitingEditMode = false;
  55. /// <summary>
  56. /// Key/Value pairs valid for profile variable substitution
  57. /// </summary>
  58. public Dictionary<string, string> GlobalProfileVariables { get; private set; }
  59. internal static readonly string k_GlobalProfileVariablesCountKey = $"com.unity.addressables.{nameof(GlobalProfileVariables)}Count";
  60. internal static string GetSessionStateKey(int id) { return $"com.unity.addressables.{nameof(GlobalProfileVariables)}{id}"; }
  61. /// <summary>
  62. /// Direct logging output of all managed services
  63. /// </summary>
  64. public ILogger Logger
  65. {
  66. get { return m_Logger; }
  67. set
  68. {
  69. m_Logger = value ?? Debug.unityLogger;
  70. foreach (var svc in HostingServices)
  71. svc.Logger = m_Logger;
  72. }
  73. }
  74. /// <summary>
  75. /// Static method for use in starting up the HostingServicesManager in batch mode.
  76. /// </summary>
  77. /// <param name="settings"> </param>
  78. public static void BatchMode(AddressableAssetSettings settings)
  79. {
  80. if (settings == null)
  81. {
  82. Debug.LogError("Could not load Addressable Assets settings - aborting.");
  83. return;
  84. }
  85. var manager = settings.HostingServicesManager;
  86. if (manager == null)
  87. {
  88. Debug.LogError("Could not load HostingServicesManager - aborting.");
  89. return;
  90. }
  91. manager.StartAllServices();
  92. }
  93. /// <summary>
  94. /// Static method for use in starting up the HostingServicesManager in batch mode. This method
  95. /// without parameters will find and use the default <see cref="AddressableAssetSettings"/> object.
  96. /// </summary>
  97. public static void BatchMode()
  98. {
  99. BatchMode(AddressableAssetSettingsDefaultObject.Settings);
  100. }
  101. /// <summary>
  102. /// Indicates whether or not this HostingServiceManager is initialized
  103. /// </summary>
  104. public bool IsInitialized
  105. {
  106. get { return m_Settings != null; }
  107. }
  108. /// <summary>
  109. /// Return an enumerable list of all configured <see cref="IHostingService"/> objects
  110. /// </summary>
  111. public ICollection<IHostingService> HostingServices
  112. {
  113. get { return m_HostingServiceInfoMap.Keys; }
  114. }
  115. /// <summary>
  116. /// Get an array of all <see cref="IHostingService"/> types that have been used by the manager, or are known
  117. /// built-in types available for use.
  118. /// </summary>
  119. /// <returns></returns>
  120. public Type[] RegisteredServiceTypes
  121. {
  122. get
  123. {
  124. if (m_RegisteredServiceTypes.Count == 0)
  125. m_RegisteredServiceTypes.AddRange(m_BuiltinServiceTypes);
  126. return m_RegisteredServiceTypes.ToArray();
  127. }
  128. }
  129. /// <summary>
  130. /// The id value that will be assigned to the next <see cref="IHostingService"/> add to the manager.
  131. /// </summary>
  132. public int NextInstanceId
  133. {
  134. get { return m_NextInstanceId; }
  135. }
  136. /// <summary>
  137. /// Create a new <see cref="HostingServicesManager"/>
  138. /// </summary>
  139. public HostingServicesManager()
  140. {
  141. GlobalProfileVariables = new Dictionary<string, string>();
  142. m_HostingServiceInfos = new List<HostingServiceInfo>();
  143. m_HostingServiceInfoMap = new Dictionary<IHostingService, HostingServiceInfo>();
  144. m_RegisteredServiceTypes = new List<Type>();
  145. m_RegisteredServiceTypeRefs = new List<string>();
  146. m_Logger = Debug.unityLogger;
  147. }
  148. /// <summary>
  149. /// Initialize manager with the given <see cref="AddressableAssetSettings"/> object.
  150. /// </summary>
  151. /// <param name="settings"></param>
  152. public void Initialize(AddressableAssetSettings settings)
  153. {
  154. if (IsInitialized) return;
  155. m_Settings = settings;
  156. RefreshGlobalProfileVariables();
  157. }
  158. /// <summary>
  159. /// Calls <see cref="IHostingService.StopHostingService"/> on all managed <see cref="IHostingService"/> instances
  160. /// where <see cref="IHostingService.IsHostingServiceRunning"/> is true
  161. /// </summary>
  162. public void StopAllServices()
  163. {
  164. foreach (var svc in HostingServices)
  165. {
  166. try
  167. {
  168. if (svc.IsHostingServiceRunning)
  169. svc.StopHostingService();
  170. }
  171. catch (Exception e)
  172. {
  173. m_Logger.LogFormat(LogType.Error, e.Message);
  174. }
  175. }
  176. }
  177. /// <summary>
  178. /// Calls <see cref="IHostingService.StartHostingService"/> on all managed <see cref="IHostingService"/> instances
  179. /// where <see cref="IHostingService.IsHostingServiceRunning"/> is false
  180. /// </summary>
  181. public void StartAllServices()
  182. {
  183. foreach (var svc in HostingServices)
  184. {
  185. try
  186. {
  187. if (!svc.IsHostingServiceRunning)
  188. svc.StartHostingService();
  189. }
  190. catch (Exception e)
  191. {
  192. m_Logger.LogFormat(LogType.Error, e.Message);
  193. }
  194. }
  195. }
  196. /// <summary>
  197. /// Add a new hosting service instance of the given type. The <paramref name="serviceType"/> must implement the
  198. /// <see cref="IHostingService"/> interface, or an <see cref="ArgumentException"/> is thrown.
  199. /// </summary>
  200. /// <param name="serviceType">A <see cref="Type"/> object for the service. Must implement <see cref="IHostingService"/></param>
  201. /// <param name="name">A descriptive name for the new service instance.</param>
  202. /// <returns></returns>
  203. public IHostingService AddHostingService(Type serviceType, string name)
  204. {
  205. var svc = Activator.CreateInstance(serviceType) as IHostingService;
  206. if (svc == null)
  207. throw new ArgumentException("Provided type does not implement IHostingService", "serviceType");
  208. if (!m_RegisteredServiceTypes.Contains(serviceType))
  209. m_RegisteredServiceTypes.Add(serviceType);
  210. var info = new HostingServiceInfo
  211. {
  212. classRef = TypeToClassRef(serviceType),
  213. dataStore = new KeyDataStore()
  214. };
  215. svc.Logger = m_Logger;
  216. svc.DescriptiveName = name;
  217. svc.InstanceId = m_NextInstanceId;
  218. svc.HostingServiceContentRoots.AddRange(GetAllContentRoots());
  219. m_Settings.profileSettings.RegisterProfileStringEvaluationFunc(svc.EvaluateProfileString);
  220. m_HostingServiceInfoMap.Add(svc, info);
  221. m_Settings.SetDirty(AddressableAssetSettings.ModificationEvent.HostingServicesManagerModified, this, true, true);
  222. AddressableAssetUtility.OpenAssetIfUsingVCIntegration(m_Settings);
  223. m_NextInstanceId++;
  224. return svc;
  225. }
  226. /// <summary>
  227. /// Stops the given <see cref="IHostingService"/>, unregisters callbacks, and removes it from management. This
  228. /// function does nothing if the service is not being managed by this <see cref="HostingServicesManager"/>
  229. /// </summary>
  230. /// <param name="svc"></param>
  231. public void RemoveHostingService(IHostingService svc)
  232. {
  233. if (!m_HostingServiceInfoMap.ContainsKey(svc))
  234. return;
  235. svc.StopHostingService();
  236. m_Settings.profileSettings.UnregisterProfileStringEvaluationFunc(svc.EvaluateProfileString);
  237. m_HostingServiceInfoMap.Remove(svc);
  238. m_Settings.SetDirty(AddressableAssetSettings.ModificationEvent.HostingServicesManagerModified, this, true, true);
  239. AddressableAssetUtility.OpenAssetIfUsingVCIntegration(m_Settings);
  240. }
  241. /// <summary>
  242. /// Should be called by parent <see cref="ScriptableObject"/> instance OnEnable method
  243. /// </summary>
  244. public void OnEnable()
  245. {
  246. Debug.Assert(IsInitialized);
  247. m_Settings.OnModification -= OnSettingsModification;
  248. m_Settings.OnModification += OnSettingsModification;
  249. m_Settings.profileSettings.RegisterProfileStringEvaluationFunc(EvaluateGlobalProfileVariableKey);
  250. bool hasAnEnabledService = false;
  251. foreach (var svc in HostingServices)
  252. {
  253. svc.Logger = m_Logger;
  254. m_Settings.profileSettings.RegisterProfileStringEvaluationFunc(svc.EvaluateProfileString);
  255. var baseSvc = svc as BaseHostingService;
  256. baseSvc?.OnEnable();
  257. if (!hasAnEnabledService)
  258. hasAnEnabledService = svc.IsHostingServiceRunning || baseSvc != null && baseSvc.WasEnabled;
  259. }
  260. if (!exitingEditMode || exitingEditMode && hasAnEnabledService && IsUsingPackedPlayMode())
  261. RefreshGlobalProfileVariables();
  262. else
  263. LoadSessionStateKeys();
  264. }
  265. bool IsUsingPackedPlayMode()
  266. {
  267. return m_Settings.ActivePlayModeDataBuilder != null && m_Settings.ActivePlayModeDataBuilder.GetType() == typeof(BuildScriptPackedPlayMode);
  268. }
  269. /// <summary>
  270. /// Should be called by parent <see cref="ScriptableObject"/> instance OnDisable method
  271. /// </summary>
  272. public void OnDisable()
  273. {
  274. Debug.Assert(IsInitialized);
  275. // ReSharper disable once DelegateSubtraction
  276. m_Settings.OnModification -= OnSettingsModification;
  277. m_Settings.profileSettings.UnregisterProfileStringEvaluationFunc(EvaluateGlobalProfileVariableKey);
  278. foreach (var svc in HostingServices)
  279. {
  280. svc.Logger = null;
  281. m_Settings.profileSettings.UnregisterProfileStringEvaluationFunc(svc.EvaluateProfileString);
  282. (svc as BaseHostingService)?.OnDisable();
  283. }
  284. SaveSessionStateKeys();
  285. }
  286. internal void LoadSessionStateKeys()
  287. {
  288. int numKeys = SessionState.GetInt(k_GlobalProfileVariablesCountKey, 0);
  289. for (int i = 0; i < numKeys; i++)
  290. {
  291. string profileVar = SessionState.GetString(GetSessionStateKey(i), string.Empty);
  292. if (!string.IsNullOrEmpty(profileVar))
  293. GlobalProfileVariables.Add(GetPrivateIpAddressKey(i), profileVar);
  294. }
  295. }
  296. internal void SaveSessionStateKeys()
  297. {
  298. int prevNumKeys = SessionState.GetInt(k_GlobalProfileVariablesCountKey, 0);
  299. SessionState.SetInt(k_GlobalProfileVariablesCountKey, GlobalProfileVariables.Count);
  300. int profileVarIdx = 0;
  301. foreach (KeyValuePair<string, string> pair in GlobalProfileVariables)
  302. {
  303. SessionState.SetString(GetSessionStateKey(profileVarIdx), pair.Value);
  304. profileVarIdx++;
  305. }
  306. EraseSessionStateKeys(profileVarIdx, prevNumKeys);
  307. }
  308. internal static void EraseSessionStateKeys()
  309. {
  310. int numKeys = SessionState.GetInt(k_GlobalProfileVariablesCountKey, 0);
  311. EraseSessionStateKeys(0, numKeys);
  312. SessionState.EraseInt(k_GlobalProfileVariablesCountKey);
  313. }
  314. static void EraseSessionStateKeys(int min, int max)
  315. {
  316. for (int i = min; i < max; i++)
  317. {
  318. SessionState.EraseString(GetSessionStateKey(i));
  319. }
  320. }
  321. /// <summary> Ensure object is ready for serialization, and calls <see cref="IHostingService.OnBeforeSerialize"/> methods
  322. /// on all managed <see cref="IHostingService"/> instances
  323. /// </summary>
  324. public void OnBeforeSerialize()
  325. {
  326. // https://docs.unity3d.com/ScriptReference/EditorWindow.OnInspectorUpdate.html
  327. // Because the manager is a serialized field in the Addressables settings, this method is called
  328. // at 10 frames per second when the settings are opened in the inspector...
  329. // Be careful what you put in there...
  330. m_HostingServiceInfos.Clear();
  331. foreach (var svc in HostingServices)
  332. {
  333. var info = m_HostingServiceInfoMap[svc];
  334. m_HostingServiceInfos.Add(info);
  335. svc.OnBeforeSerialize(info.dataStore);
  336. }
  337. m_RegisteredServiceTypeRefs.Clear();
  338. foreach (var type in m_RegisteredServiceTypes)
  339. m_RegisteredServiceTypeRefs.Add(TypeToClassRef(type));
  340. }
  341. /// <summary> Ensure object is ready for serialization, and calls <see cref="IHostingService.OnBeforeSerialize"/> methods
  342. /// on all managed <see cref="IHostingService"/> instances
  343. /// </summary>
  344. public void OnAfterDeserialize()
  345. {
  346. m_HostingServiceInfoMap = new Dictionary<IHostingService, HostingServiceInfo>();
  347. foreach (var svcInfo in m_HostingServiceInfos)
  348. {
  349. IHostingService svc = CreateHostingServiceInstance(svcInfo.classRef);
  350. if (svc == null) continue;
  351. svc.OnAfterDeserialize(svcInfo.dataStore);
  352. m_HostingServiceInfoMap.Add(svc, svcInfo);
  353. }
  354. m_RegisteredServiceTypes = new List<Type>();
  355. foreach (var typeRef in m_RegisteredServiceTypeRefs)
  356. {
  357. var type = Type.GetType(typeRef, false);
  358. if (type == null) continue;
  359. m_RegisteredServiceTypes.Add(type);
  360. }
  361. }
  362. /// <summary>
  363. /// Refresh values in the global profile variables table.
  364. /// </summary>
  365. public void RefreshGlobalProfileVariables()
  366. {
  367. var vars = GlobalProfileVariables;
  368. vars.Clear();
  369. var ipAddressList = FilterValidIPAddresses(NetworkInterface.GetAllNetworkInterfaces()
  370. .Where(n => n.NetworkInterfaceType != NetworkInterfaceType.Loopback && n.OperationalStatus == OperationalStatus.Up)
  371. .SelectMany(n => n.GetIPProperties().UnicastAddresses)
  372. .Where(a => a.Address.AddressFamily == AddressFamily.InterNetwork)
  373. .Select(a => a.Address).ToList());
  374. if (ipAddressList.Count > 0)
  375. {
  376. vars.Add(KPrivateIpAddressKey, ipAddressList[0].ToString());
  377. if (ipAddressList.Count > 1)
  378. {
  379. for (var i = 1; i < ipAddressList.Count; i++)
  380. vars.Add(KPrivateIpAddressKey + "_" + i, ipAddressList[i].ToString());
  381. }
  382. }
  383. }
  384. // Internal for unit tests
  385. internal string EvaluateGlobalProfileVariableKey(string key)
  386. {
  387. string retVal;
  388. GlobalProfileVariables.TryGetValue(key, out retVal);
  389. return retVal;
  390. }
  391. void OnSettingsModification(AddressableAssetSettings s, AddressableAssetSettings.ModificationEvent evt, object obj)
  392. {
  393. switch (evt)
  394. {
  395. case AddressableAssetSettings.ModificationEvent.GroupAdded:
  396. case AddressableAssetSettings.ModificationEvent.GroupRemoved:
  397. case AddressableAssetSettings.ModificationEvent.GroupSchemaAdded:
  398. case AddressableAssetSettings.ModificationEvent.GroupSchemaRemoved:
  399. case AddressableAssetSettings.ModificationEvent.GroupSchemaModified:
  400. case AddressableAssetSettings.ModificationEvent.ActiveProfileSet:
  401. case AddressableAssetSettings.ModificationEvent.BuildSettingsChanged:
  402. case AddressableAssetSettings.ModificationEvent.ProfileModified:
  403. var profileRemoteBuildPath = m_Settings.profileSettings.GetValueByName(m_Settings.activeProfileId, AddressableAssetSettings.kRemoteBuildPath);
  404. if (profileRemoteBuildPath != null && (profileRemoteBuildPath.Contains('[') || !CurrentContentRootsContain(profileRemoteBuildPath)))
  405. ConfigureAllHostingServices();
  406. break;
  407. case AddressableAssetSettings.ModificationEvent.BatchModification:
  408. ConfigureAllHostingServices();
  409. break;
  410. }
  411. }
  412. bool CurrentContentRootsContain(string root)
  413. {
  414. foreach (var svc in HostingServices)
  415. {
  416. if (!svc.HostingServiceContentRoots.Contains(root))
  417. return false;
  418. }
  419. return true;
  420. }
  421. void ConfigureAllHostingServices()
  422. {
  423. var contentRoots = GetAllContentRoots();
  424. foreach (var svc in HostingServices)
  425. {
  426. svc.HostingServiceContentRoots.Clear();
  427. svc.HostingServiceContentRoots.AddRange(contentRoots);
  428. }
  429. }
  430. string[] GetAllContentRoots()
  431. {
  432. Debug.Assert(IsInitialized);
  433. var contentRoots = new List<string>();
  434. foreach (var group in m_Settings.groups)
  435. {
  436. if (group != null)
  437. {
  438. foreach (var schema in group.Schemas)
  439. {
  440. var configProvider = schema as IHostingServiceConfigurationProvider;
  441. if (configProvider != null)
  442. {
  443. var groupRoot = configProvider.HostingServicesContentRoot;
  444. if (groupRoot != null && !contentRoots.Contains(groupRoot))
  445. contentRoots.Add(groupRoot);
  446. }
  447. }
  448. }
  449. }
  450. return contentRoots.ToArray();
  451. }
  452. IHostingService CreateHostingServiceInstance(string classRef)
  453. {
  454. try
  455. {
  456. var objType = Type.GetType(classRef, true);
  457. var svc = (IHostingService)Activator.CreateInstance(objType);
  458. return svc;
  459. }
  460. catch (Exception e)
  461. {
  462. m_Logger.LogFormat(LogType.Error, "Could not create IHostingService from class ref '{0}'", classRef);
  463. m_Logger.LogFormat(LogType.Error, e.Message);
  464. }
  465. return null;
  466. }
  467. static string TypeToClassRef(Type t)
  468. {
  469. return string.Format("{0}, {1}", t.FullName, t.Assembly.GetName().Name);
  470. }
  471. // For unit tests
  472. internal AddressableAssetSettings Settings
  473. {
  474. get { return m_Settings; }
  475. }
  476. private List<IPAddress> FilterValidIPAddresses(List<IPAddress> ipAddresses)
  477. {
  478. List<IPAddress> validIpList = new List<IPAddress>();
  479. foreach (IPAddress address in ipAddresses)
  480. {
  481. var sender = new System.Net.NetworkInformation.Ping();
  482. var reply = sender.Send(address.ToString(), 5000);
  483. if (reply.Status == IPStatus.Success)
  484. {
  485. validIpList.Add(address);
  486. }
  487. }
  488. return validIpList;
  489. }
  490. }
  491. }