FSAssetService.cs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSimulator Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. using System;
  28. using System.Diagnostics;
  29. using System.Collections.Generic;
  30. using System.IO;
  31. using System.IO.Compression;
  32. using System.Text;
  33. using System.Threading;
  34. using System.Reflection;
  35. using OpenSim.Data;
  36. using OpenSim.Framework;
  37. using OpenSim.Framework.Serialization.External;
  38. using OpenSim.Framework.Console;
  39. using OpenSim.Server.Base;
  40. using OpenSim.Services.Base;
  41. using OpenSim.Services.Interfaces;
  42. using Nini.Config;
  43. using log4net;
  44. using OpenMetaverse;
  45. using System.Security.Cryptography;
  46. namespace OpenSim.Services.FSAssetService
  47. {
  48. public class FSAssetConnector : ServiceBase, IAssetService
  49. {
  50. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  51. static System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
  52. static SHA256CryptoServiceProvider SHA256 = new SHA256CryptoServiceProvider();
  53. static byte[] ToCString(string s)
  54. {
  55. byte[] ret = enc.GetBytes(s);
  56. Array.Resize(ref ret, ret.Length + 1);
  57. ret[ret.Length - 1] = 0;
  58. return ret;
  59. }
  60. protected IAssetLoader m_AssetLoader = null;
  61. protected IFSAssetDataPlugin m_DataConnector = null;
  62. protected IAssetService m_FallbackService;
  63. protected Thread m_WriterThread;
  64. protected Thread m_StatsThread;
  65. protected string m_SpoolDirectory;
  66. protected object m_readLock = new object();
  67. protected object m_statsLock = new object();
  68. protected int m_readCount = 0;
  69. protected int m_readTicks = 0;
  70. protected int m_missingAssets = 0;
  71. protected int m_missingAssetsFS = 0;
  72. protected string m_FSBase;
  73. protected bool m_useOsgridFormat = false;
  74. protected bool m_showStats = true;
  75. private static bool m_Initialized;
  76. private bool m_MainInstance;
  77. public FSAssetConnector(IConfigSource config)
  78. : this(config, "AssetService")
  79. {
  80. }
  81. public FSAssetConnector(IConfigSource config, string configName) : base(config)
  82. {
  83. if (!m_Initialized)
  84. {
  85. m_Initialized = true;
  86. m_MainInstance = true;
  87. MainConsole.Instance.Commands.AddCommand("fs", false,
  88. "show assets", "show assets", "Show asset stats",
  89. HandleShowAssets);
  90. MainConsole.Instance.Commands.AddCommand("fs", false,
  91. "show digest", "show digest <ID>", "Show asset digest",
  92. HandleShowDigest);
  93. MainConsole.Instance.Commands.AddCommand("fs", false,
  94. "delete asset", "delete asset <ID>",
  95. "Delete asset from database",
  96. HandleDeleteAsset);
  97. MainConsole.Instance.Commands.AddCommand("fs", false,
  98. "import", "import <conn> <table> [<start> <count>]",
  99. "Import legacy assets",
  100. HandleImportAssets);
  101. MainConsole.Instance.Commands.AddCommand("fs", false,
  102. "force import", "force import <conn> <table> [<start> <count>]",
  103. "Import legacy assets, overwriting current content",
  104. HandleImportAssets);
  105. }
  106. IConfig assetConfig = config.Configs[configName];
  107. if (assetConfig == null)
  108. throw new Exception("No AssetService configuration");
  109. // Get Database Connector from Asset Config (If present)
  110. string dllName = assetConfig.GetString("StorageProvider", string.Empty);
  111. string connectionString = assetConfig.GetString("ConnectionString", string.Empty);
  112. string realm = assetConfig.GetString("Realm", "fsassets");
  113. int SkipAccessTimeDays = assetConfig.GetInt("DaysBetweenAccessTimeUpdates", 0);
  114. // If not found above, fallback to Database defaults
  115. IConfig dbConfig = config.Configs["DatabaseService"];
  116. if (dbConfig != null)
  117. {
  118. if (dllName == String.Empty)
  119. dllName = dbConfig.GetString("StorageProvider", String.Empty);
  120. if (connectionString == String.Empty)
  121. connectionString = dbConfig.GetString("ConnectionString", String.Empty);
  122. }
  123. // No databse connection found in either config
  124. if (dllName.Equals(String.Empty))
  125. throw new Exception("No StorageProvider configured");
  126. if (connectionString.Equals(String.Empty))
  127. throw new Exception("Missing database connection string");
  128. // Create Storage Provider
  129. m_DataConnector = LoadPlugin<IFSAssetDataPlugin>(dllName);
  130. if (m_DataConnector == null)
  131. throw new Exception(string.Format("Could not find a storage interface in the module {0}", dllName));
  132. // Initialize DB And perform any migrations required
  133. m_DataConnector.Initialise(connectionString, realm, SkipAccessTimeDays);
  134. // Setup Fallback Service
  135. string str = assetConfig.GetString("FallbackService", string.Empty);
  136. if (str != string.Empty)
  137. {
  138. object[] args = new object[] { config };
  139. m_FallbackService = LoadPlugin<IAssetService>(str, args);
  140. if (m_FallbackService != null)
  141. {
  142. m_log.Info("[FSASSETS]: Fallback service loaded");
  143. }
  144. else
  145. {
  146. m_log.Error("[FSASSETS]: Failed to load fallback service");
  147. }
  148. }
  149. // Setup directory structure including temp directory
  150. m_SpoolDirectory = assetConfig.GetString("SpoolDirectory", "/tmp");
  151. string spoolTmp = Path.Combine(m_SpoolDirectory, "spool");
  152. Directory.CreateDirectory(spoolTmp);
  153. m_FSBase = assetConfig.GetString("BaseDirectory", String.Empty);
  154. if (m_FSBase == String.Empty)
  155. {
  156. m_log.ErrorFormat("[FSASSETS]: BaseDirectory not specified");
  157. throw new Exception("Configuration error");
  158. }
  159. m_useOsgridFormat = assetConfig.GetBoolean("UseOsgridFormat", m_useOsgridFormat);
  160. // Default is to show stats to retain original behaviour
  161. m_showStats = assetConfig.GetBoolean("ShowConsoleStats", m_showStats);
  162. if (m_MainInstance)
  163. {
  164. string loader = assetConfig.GetString("DefaultAssetLoader", string.Empty);
  165. if (loader != string.Empty)
  166. {
  167. m_AssetLoader = LoadPlugin<IAssetLoader>(loader);
  168. string loaderArgs = assetConfig.GetString("AssetLoaderArgs", string.Empty);
  169. m_log.InfoFormat("[FSASSETS]: Loading default asset set from {0}", loaderArgs);
  170. m_AssetLoader.ForEachDefaultXmlAsset(loaderArgs,
  171. delegate(AssetBase a)
  172. {
  173. Store(a, false);
  174. });
  175. }
  176. m_WriterThread = new Thread(Writer);
  177. m_WriterThread.Start();
  178. if (m_showStats)
  179. {
  180. m_StatsThread = new Thread(Stats);
  181. m_StatsThread.Start();
  182. }
  183. }
  184. m_log.Info("[FSASSETS]: FS asset service enabled");
  185. }
  186. private void Stats()
  187. {
  188. while (true)
  189. {
  190. Thread.Sleep(60000);
  191. lock (m_statsLock)
  192. {
  193. if (m_readCount > 0)
  194. {
  195. double avg = (double)m_readTicks / (double)m_readCount;
  196. // if (avg > 10000)
  197. // Environment.Exit(0);
  198. m_log.InfoFormat("[FSASSETS]: Read stats: {0} files, {1} ticks, avg {2:F2}, missing {3}, FS {4}", m_readCount, m_readTicks, (double)m_readTicks / (double)m_readCount, m_missingAssets, m_missingAssetsFS);
  199. }
  200. m_readCount = 0;
  201. m_readTicks = 0;
  202. m_missingAssets = 0;
  203. m_missingAssetsFS = 0;
  204. }
  205. }
  206. }
  207. private void Writer()
  208. {
  209. m_log.Info("[ASSET]: Writer started");
  210. while (true)
  211. {
  212. string[] files = Directory.GetFiles(m_SpoolDirectory);
  213. if (files.Length > 0)
  214. {
  215. int tickCount = Environment.TickCount;
  216. for (int i = 0 ; i < files.Length ; i++)
  217. {
  218. string hash = Path.GetFileNameWithoutExtension(files[i]);
  219. string s = HashToFile(hash);
  220. string diskFile = Path.Combine(m_FSBase, s);
  221. bool pathOk = false;
  222. // The cure for chicken bones!
  223. while(true)
  224. {
  225. try
  226. {
  227. // Try to make the directory we need for this file
  228. Directory.CreateDirectory(Path.GetDirectoryName(diskFile));
  229. pathOk = true;
  230. break;
  231. }
  232. catch (System.IO.IOException)
  233. {
  234. // Creating the directory failed. This can't happen unless
  235. // a part of the path already exists as a file. Sadly the
  236. // SRAS data contains such files.
  237. string d = Path.GetDirectoryName(diskFile);
  238. // Test each path component in turn. If we can successfully
  239. // make a directory, the level below must be the chicken bone.
  240. while (d.Length > 0)
  241. {
  242. Console.WriteLine(d);
  243. try
  244. {
  245. Directory.CreateDirectory(Path.GetDirectoryName(d));
  246. }
  247. catch (System.IO.IOException)
  248. {
  249. d = Path.GetDirectoryName(d);
  250. // We failed making the directory and need to
  251. // go up a bit more
  252. continue;
  253. }
  254. // We succeeded in making the directory and (d) is
  255. // the chicken bone
  256. break;
  257. }
  258. // Is the chicken alive?
  259. if (d.Length > 0)
  260. {
  261. Console.WriteLine(d);
  262. FileAttributes attr = File.GetAttributes(d);
  263. if ((attr & FileAttributes.Directory) == 0)
  264. {
  265. // The chicken bone should be resolved.
  266. // Return to writing the file.
  267. File.Delete(d);
  268. continue;
  269. }
  270. }
  271. }
  272. // Could not resolve, skipping
  273. m_log.ErrorFormat("[ASSET]: Could not resolve path creation error for {0}", diskFile);
  274. break;
  275. }
  276. if (pathOk)
  277. {
  278. try
  279. {
  280. byte[] data = File.ReadAllBytes(files[i]);
  281. using (GZipStream gz = new GZipStream(new FileStream(diskFile + ".gz", FileMode.Create), CompressionMode.Compress))
  282. {
  283. gz.Write(data, 0, data.Length);
  284. }
  285. File.Delete(files[i]);
  286. //File.Move(files[i], diskFile);
  287. }
  288. catch(System.IO.IOException e)
  289. {
  290. if (e.Message.StartsWith("Win32 IO returned ERROR_ALREADY_EXISTS"))
  291. File.Delete(files[i]);
  292. else
  293. throw;
  294. }
  295. }
  296. }
  297. int totalTicks = System.Environment.TickCount - tickCount;
  298. if (totalTicks > 0) // Wrap?
  299. {
  300. m_log.InfoFormat("[ASSET]: Write cycle complete, {0} files, {1} ticks, avg {2:F2}", files.Length, totalTicks, (double)totalTicks / (double)files.Length);
  301. }
  302. }
  303. Thread.Sleep(1000);
  304. }
  305. }
  306. string GetSHA256Hash(byte[] data)
  307. {
  308. byte[] hash = SHA256.ComputeHash(data);
  309. return BitConverter.ToString(hash).Replace("-", String.Empty);
  310. }
  311. public string HashToPath(string hash)
  312. {
  313. if (hash == null || hash.Length < 10)
  314. return "junkyard";
  315. if (m_useOsgridFormat)
  316. {
  317. /*
  318. * The code below is the OSGrid code.
  319. */
  320. return Path.Combine(hash.Substring(0, 3),
  321. Path.Combine(hash.Substring(3, 3)));
  322. }
  323. else
  324. {
  325. /*
  326. * The below is what core would normally use.
  327. * This is modified to work in OSGrid, as seen
  328. * above, because the SRAS data is structured
  329. * that way.
  330. */
  331. return Path.Combine(hash.Substring(0, 2),
  332. Path.Combine(hash.Substring(2, 2),
  333. Path.Combine(hash.Substring(4, 2),
  334. hash.Substring(6, 4))));
  335. }
  336. }
  337. private bool AssetExists(string hash)
  338. {
  339. string s = HashToFile(hash);
  340. string diskFile = Path.Combine(m_FSBase, s);
  341. if (File.Exists(diskFile + ".gz") || File.Exists(diskFile))
  342. return true;
  343. return false;
  344. }
  345. public virtual bool[] AssetsExist(string[] ids)
  346. {
  347. UUID[] uuid = Array.ConvertAll(ids, id => UUID.Parse(id));
  348. return m_DataConnector.AssetsExist(uuid);
  349. }
  350. public string HashToFile(string hash)
  351. {
  352. return Path.Combine(HashToPath(hash), hash);
  353. }
  354. public virtual AssetBase Get(string id)
  355. {
  356. string hash;
  357. return Get(id, out hash);
  358. }
  359. private AssetBase Get(string id, out string sha)
  360. {
  361. string hash = string.Empty;
  362. int startTime = System.Environment.TickCount;
  363. AssetMetadata metadata;
  364. lock (m_readLock)
  365. {
  366. metadata = m_DataConnector.Get(id, out hash);
  367. }
  368. sha = hash;
  369. if (metadata == null)
  370. {
  371. AssetBase asset = null;
  372. if (m_FallbackService != null)
  373. {
  374. asset = m_FallbackService.Get(id);
  375. if (asset != null)
  376. {
  377. asset.Metadata.ContentType =
  378. SLUtil.SLAssetTypeToContentType((int)asset.Type);
  379. sha = GetSHA256Hash(asset.Data);
  380. m_log.InfoFormat("[FSASSETS]: Added asset {0} from fallback to local store", id);
  381. Store(asset);
  382. }
  383. }
  384. if (asset == null && m_showStats)
  385. {
  386. // m_log.InfoFormat("[FSASSETS]: Asset {0} not found", id);
  387. m_missingAssets++;
  388. }
  389. return asset;
  390. }
  391. AssetBase newAsset = new AssetBase();
  392. newAsset.Metadata = metadata;
  393. try
  394. {
  395. newAsset.Data = GetFsData(hash);
  396. if (newAsset.Data.Length == 0)
  397. {
  398. AssetBase asset = null;
  399. if (m_FallbackService != null)
  400. {
  401. asset = m_FallbackService.Get(id);
  402. if (asset != null)
  403. {
  404. asset.Metadata.ContentType =
  405. SLUtil.SLAssetTypeToContentType((int)asset.Type);
  406. sha = GetSHA256Hash(asset.Data);
  407. m_log.InfoFormat("[FSASSETS]: Added asset {0} from fallback to local store", id);
  408. Store(asset);
  409. }
  410. }
  411. if (asset == null)
  412. {
  413. if (m_showStats)
  414. m_missingAssetsFS++;
  415. // m_log.InfoFormat("[FSASSETS]: Asset {0}, hash {1} not found in FS", id, hash);
  416. }
  417. else
  418. {
  419. // Deal with bug introduced in Oct. 20 (1eb3e6cc43e2a7b4053bc1185c7c88e22356c5e8)
  420. // Fix bad assets before sending them elsewhere
  421. if (asset.Type == (int)AssetType.Object && asset.Data != null)
  422. {
  423. string xml = ExternalRepresentationUtils.SanitizeXml(Utils.BytesToString(asset.Data));
  424. asset.Data = Utils.StringToBytes(xml);
  425. }
  426. return asset;
  427. }
  428. }
  429. if (m_showStats)
  430. {
  431. lock (m_statsLock)
  432. {
  433. m_readTicks += Environment.TickCount - startTime;
  434. m_readCount++;
  435. }
  436. }
  437. // Deal with bug introduced in Oct. 20 (1eb3e6cc43e2a7b4053bc1185c7c88e22356c5e8)
  438. // Fix bad assets before sending them elsewhere
  439. if (newAsset.Type == (int)AssetType.Object && newAsset.Data != null)
  440. {
  441. string xml = ExternalRepresentationUtils.SanitizeXml(Utils.BytesToString(newAsset.Data));
  442. newAsset.Data = Utils.StringToBytes(xml);
  443. }
  444. return newAsset;
  445. }
  446. catch (Exception exception)
  447. {
  448. m_log.Error(exception.ToString());
  449. Thread.Sleep(5000);
  450. Environment.Exit(1);
  451. return null;
  452. }
  453. }
  454. public virtual AssetMetadata GetMetadata(string id)
  455. {
  456. string hash;
  457. return m_DataConnector.Get(id, out hash);
  458. }
  459. public virtual byte[] GetData(string id)
  460. {
  461. string hash;
  462. if (m_DataConnector.Get(id, out hash) == null)
  463. return null;
  464. return GetFsData(hash);
  465. }
  466. public bool Get(string id, Object sender, AssetRetrieved handler)
  467. {
  468. AssetBase asset = Get(id);
  469. handler(id, sender, asset);
  470. return true;
  471. }
  472. public byte[] GetFsData(string hash)
  473. {
  474. string spoolFile = Path.Combine(m_SpoolDirectory, hash + ".asset");
  475. if (File.Exists(spoolFile))
  476. {
  477. try
  478. {
  479. byte[] content = File.ReadAllBytes(spoolFile);
  480. return content;
  481. }
  482. catch
  483. {
  484. }
  485. }
  486. string file = HashToFile(hash);
  487. string diskFile = Path.Combine(m_FSBase, file);
  488. if (File.Exists(diskFile + ".gz"))
  489. {
  490. try
  491. {
  492. using (GZipStream gz = new GZipStream(new FileStream(diskFile + ".gz", FileMode.Open, FileAccess.Read), CompressionMode.Decompress))
  493. {
  494. using (MemoryStream ms = new MemoryStream())
  495. {
  496. byte[] data = new byte[32768];
  497. int bytesRead;
  498. do
  499. {
  500. bytesRead = gz.Read(data, 0, 32768);
  501. if (bytesRead > 0)
  502. ms.Write(data, 0, bytesRead);
  503. } while (bytesRead > 0);
  504. return ms.ToArray();
  505. }
  506. }
  507. }
  508. catch (Exception)
  509. {
  510. return new Byte[0];
  511. }
  512. }
  513. else if (File.Exists(diskFile))
  514. {
  515. try
  516. {
  517. byte[] content = File.ReadAllBytes(diskFile);
  518. return content;
  519. }
  520. catch
  521. {
  522. }
  523. }
  524. return new Byte[0];
  525. }
  526. public virtual string Store(AssetBase asset)
  527. {
  528. return Store(asset, false);
  529. }
  530. private string Store(AssetBase asset, bool force)
  531. {
  532. int tickCount = Environment.TickCount;
  533. string hash = GetSHA256Hash(asset.Data);
  534. if (asset.Name.Length > AssetBase.MAX_ASSET_NAME)
  535. {
  536. string assetName = asset.Name.Substring(0, AssetBase.MAX_ASSET_NAME);
  537. m_log.WarnFormat(
  538. "[FSASSETS]: Name '{0}' for asset {1} truncated from {2} to {3} characters on add",
  539. asset.Name, asset.ID, asset.Name.Length, assetName.Length);
  540. asset.Name = assetName;
  541. }
  542. if (asset.Description.Length > AssetBase.MAX_ASSET_DESC)
  543. {
  544. string assetDescription = asset.Description.Substring(0, AssetBase.MAX_ASSET_DESC);
  545. m_log.WarnFormat(
  546. "[FSASSETS]: Description '{0}' for asset {1} truncated from {2} to {3} characters on add",
  547. asset.Description, asset.ID, asset.Description.Length, assetDescription.Length);
  548. asset.Description = assetDescription;
  549. }
  550. if (!AssetExists(hash))
  551. {
  552. string tempFile = Path.Combine(Path.Combine(m_SpoolDirectory, "spool"), hash + ".asset");
  553. string finalFile = Path.Combine(m_SpoolDirectory, hash + ".asset");
  554. if (!File.Exists(finalFile))
  555. {
  556. // Deal with bug introduced in Oct. 20 (1eb3e6cc43e2a7b4053bc1185c7c88e22356c5e8)
  557. // Fix bad assets before storing on this server
  558. if (asset.Type == (int)AssetType.Object && asset.Data != null)
  559. {
  560. string xml = ExternalRepresentationUtils.SanitizeXml(Utils.BytesToString(asset.Data));
  561. asset.Data = Utils.StringToBytes(xml);
  562. }
  563. FileStream fs = File.Create(tempFile);
  564. fs.Write(asset.Data, 0, asset.Data.Length);
  565. fs.Close();
  566. File.Move(tempFile, finalFile);
  567. }
  568. }
  569. if (asset.ID == string.Empty)
  570. {
  571. if (asset.FullID == UUID.Zero)
  572. {
  573. asset.FullID = UUID.Random();
  574. }
  575. asset.ID = asset.FullID.ToString();
  576. }
  577. else if (asset.FullID == UUID.Zero)
  578. {
  579. UUID uuid = UUID.Zero;
  580. if (UUID.TryParse(asset.ID, out uuid))
  581. {
  582. asset.FullID = uuid;
  583. }
  584. else
  585. {
  586. asset.FullID = UUID.Random();
  587. }
  588. }
  589. if (!m_DataConnector.Store(asset.Metadata, hash))
  590. {
  591. if (asset.Metadata.Type == -2)
  592. return asset.ID;
  593. return UUID.Zero.ToString();
  594. }
  595. else
  596. {
  597. return asset.ID;
  598. }
  599. }
  600. public bool UpdateContent(string id, byte[] data)
  601. {
  602. return false;
  603. // string oldhash;
  604. // AssetMetadata meta = m_DataConnector.Get(id, out oldhash);
  605. //
  606. // if (meta == null)
  607. // return false;
  608. //
  609. // AssetBase asset = new AssetBase();
  610. // asset.Metadata = meta;
  611. // asset.Data = data;
  612. //
  613. // Store(asset);
  614. //
  615. // return true;
  616. }
  617. public virtual bool Delete(string id)
  618. {
  619. m_DataConnector.Delete(id);
  620. return true;
  621. }
  622. private void HandleShowAssets(string module, string[] args)
  623. {
  624. int num = m_DataConnector.Count();
  625. MainConsole.Instance.Output(string.Format("Total asset count: {0}", num));
  626. }
  627. private void HandleShowDigest(string module, string[] args)
  628. {
  629. if (args.Length < 3)
  630. {
  631. MainConsole.Instance.Output("Syntax: show digest <ID>");
  632. return;
  633. }
  634. string hash;
  635. AssetBase asset = Get(args[2], out hash);
  636. if (asset == null || asset.Data.Length == 0)
  637. {
  638. MainConsole.Instance.Output("Asset not found");
  639. return;
  640. }
  641. int i;
  642. MainConsole.Instance.Output(String.Format("Name: {0}", asset.Name));
  643. MainConsole.Instance.Output(String.Format("Description: {0}", asset.Description));
  644. MainConsole.Instance.Output(String.Format("Type: {0}", asset.Type));
  645. MainConsole.Instance.Output(String.Format("Content-type: {0}", asset.Metadata.ContentType));
  646. MainConsole.Instance.Output(String.Format("Flags: {0}", asset.Metadata.Flags.ToString()));
  647. MainConsole.Instance.Output(String.Format("FS file: {0}", HashToFile(hash)));
  648. for (i = 0 ; i < 5 ; i++)
  649. {
  650. int off = i * 16;
  651. if (asset.Data.Length <= off)
  652. break;
  653. int len = 16;
  654. if (asset.Data.Length < off + len)
  655. len = asset.Data.Length - off;
  656. byte[] line = new byte[len];
  657. Array.Copy(asset.Data, off, line, 0, len);
  658. string text = BitConverter.ToString(line);
  659. MainConsole.Instance.Output(String.Format("{0:x4}: {1}", off, text));
  660. }
  661. }
  662. private void HandleDeleteAsset(string module, string[] args)
  663. {
  664. if (args.Length < 3)
  665. {
  666. MainConsole.Instance.Output("Syntax: delete asset <ID>");
  667. return;
  668. }
  669. AssetBase asset = Get(args[2]);
  670. if (asset == null || asset.Data.Length == 0)
  671. {
  672. MainConsole.Instance.Output("Asset not found");
  673. return;
  674. }
  675. m_DataConnector.Delete(args[2]);
  676. MainConsole.Instance.Output("Asset deleted");
  677. }
  678. private void HandleImportAssets(string module, string[] args)
  679. {
  680. bool force = false;
  681. if (args[0] == "force")
  682. {
  683. force = true;
  684. List<string> list = new List<string>(args);
  685. list.RemoveAt(0);
  686. args = list.ToArray();
  687. }
  688. if (args.Length < 3)
  689. {
  690. MainConsole.Instance.Output("Syntax: import <conn> <table> [<start> <count>]");
  691. }
  692. else
  693. {
  694. string conn = args[1];
  695. string table = args[2];
  696. int start = 0;
  697. int count = -1;
  698. if (args.Length > 3)
  699. {
  700. start = Convert.ToInt32(args[3]);
  701. }
  702. if (args.Length > 4)
  703. {
  704. count = Convert.ToInt32(args[4]);
  705. }
  706. m_DataConnector.Import(conn, table, start, count, force, new FSStoreDelegate(Store));
  707. }
  708. }
  709. public AssetBase GetCached(string id)
  710. {
  711. return Get(id);
  712. }
  713. }
  714. }