FSAssetService.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798
  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. private static bool m_Initialized;
  75. private bool m_MainInstance;
  76. public FSAssetConnector(IConfigSource config)
  77. : this(config, "AssetService")
  78. {
  79. }
  80. public FSAssetConnector(IConfigSource config, string configName) : base(config)
  81. {
  82. if (!m_Initialized)
  83. {
  84. m_Initialized = true;
  85. m_MainInstance = true;
  86. MainConsole.Instance.Commands.AddCommand("fs", false,
  87. "show assets", "show assets", "Show asset stats",
  88. HandleShowAssets);
  89. MainConsole.Instance.Commands.AddCommand("fs", false,
  90. "show digest", "show digest <ID>", "Show asset digest",
  91. HandleShowDigest);
  92. MainConsole.Instance.Commands.AddCommand("fs", false,
  93. "delete asset", "delete asset <ID>",
  94. "Delete asset from database",
  95. HandleDeleteAsset);
  96. MainConsole.Instance.Commands.AddCommand("fs", false,
  97. "import", "import <conn> <table> [<start> <count>]",
  98. "Import legacy assets",
  99. HandleImportAssets);
  100. MainConsole.Instance.Commands.AddCommand("fs", false,
  101. "force import", "force import <conn> <table> [<start> <count>]",
  102. "Import legacy assets, overwriting current content",
  103. HandleImportAssets);
  104. }
  105. IConfig assetConfig = config.Configs[configName];
  106. if (assetConfig == null)
  107. throw new Exception("No AssetService configuration");
  108. // Get Database Connector from Asset Config (If present)
  109. string dllName = assetConfig.GetString("StorageProvider", string.Empty);
  110. string connectionString = assetConfig.GetString("ConnectionString", string.Empty);
  111. string realm = assetConfig.GetString("Realm", "fsassets");
  112. int SkipAccessTimeDays = assetConfig.GetInt("DaysBetweenAccessTimeUpdates", 0);
  113. // If not found above, fallback to Database defaults
  114. IConfig dbConfig = config.Configs["DatabaseService"];
  115. if (dbConfig != null)
  116. {
  117. if (dllName == String.Empty)
  118. dllName = dbConfig.GetString("StorageProvider", String.Empty);
  119. if (connectionString == String.Empty)
  120. connectionString = dbConfig.GetString("ConnectionString", String.Empty);
  121. }
  122. // No databse connection found in either config
  123. if (dllName.Equals(String.Empty))
  124. throw new Exception("No StorageProvider configured");
  125. if (connectionString.Equals(String.Empty))
  126. throw new Exception("Missing database connection string");
  127. // Create Storage Provider
  128. m_DataConnector = LoadPlugin<IFSAssetDataPlugin>(dllName);
  129. if (m_DataConnector == null)
  130. throw new Exception(string.Format("Could not find a storage interface in the module {0}", dllName));
  131. // Initialize DB And perform any migrations required
  132. m_DataConnector.Initialise(connectionString, realm, SkipAccessTimeDays);
  133. // Setup Fallback Service
  134. string str = assetConfig.GetString("FallbackService", string.Empty);
  135. if (str != string.Empty)
  136. {
  137. object[] args = new object[] { config };
  138. m_FallbackService = LoadPlugin<IAssetService>(str, args);
  139. if (m_FallbackService != null)
  140. {
  141. m_log.Info("[FSASSETS]: Fallback service loaded");
  142. }
  143. else
  144. {
  145. m_log.Error("[FSASSETS]: Failed to load fallback service");
  146. }
  147. }
  148. // Setup directory structure including temp directory
  149. m_SpoolDirectory = assetConfig.GetString("SpoolDirectory", "/tmp");
  150. string spoolTmp = Path.Combine(m_SpoolDirectory, "spool");
  151. Directory.CreateDirectory(spoolTmp);
  152. m_FSBase = assetConfig.GetString("BaseDirectory", String.Empty);
  153. if (m_FSBase == String.Empty)
  154. {
  155. m_log.ErrorFormat("[FSASSETS]: BaseDirectory not specified");
  156. throw new Exception("Configuration error");
  157. }
  158. m_useOsgridFormat = assetConfig.GetBoolean("UseOsgridFormat", m_useOsgridFormat);
  159. if (m_MainInstance)
  160. {
  161. string loader = assetConfig.GetString("DefaultAssetLoader", string.Empty);
  162. if (loader != string.Empty)
  163. {
  164. m_AssetLoader = LoadPlugin<IAssetLoader>(loader);
  165. string loaderArgs = assetConfig.GetString("AssetLoaderArgs", string.Empty);
  166. m_log.InfoFormat("[FSASSETS]: Loading default asset set from {0}", loaderArgs);
  167. m_AssetLoader.ForEachDefaultXmlAsset(loaderArgs,
  168. delegate(AssetBase a)
  169. {
  170. Store(a, false);
  171. });
  172. }
  173. m_WriterThread = new Thread(Writer);
  174. m_WriterThread.Start();
  175. m_StatsThread = new Thread(Stats);
  176. m_StatsThread.Start();
  177. }
  178. m_log.Info("[FSASSETS]: FS asset service enabled");
  179. }
  180. private void Stats()
  181. {
  182. while (true)
  183. {
  184. Thread.Sleep(60000);
  185. lock (m_statsLock)
  186. {
  187. if (m_readCount > 0)
  188. {
  189. double avg = (double)m_readTicks / (double)m_readCount;
  190. // if (avg > 10000)
  191. // Environment.Exit(0);
  192. 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);
  193. }
  194. m_readCount = 0;
  195. m_readTicks = 0;
  196. m_missingAssets = 0;
  197. m_missingAssetsFS = 0;
  198. }
  199. }
  200. }
  201. private void Writer()
  202. {
  203. m_log.Info("[ASSET]: Writer started");
  204. while (true)
  205. {
  206. string[] files = Directory.GetFiles(m_SpoolDirectory);
  207. if (files.Length > 0)
  208. {
  209. int tickCount = Environment.TickCount;
  210. for (int i = 0 ; i < files.Length ; i++)
  211. {
  212. string hash = Path.GetFileNameWithoutExtension(files[i]);
  213. string s = HashToFile(hash);
  214. string diskFile = Path.Combine(m_FSBase, s);
  215. bool pathOk = false;
  216. // The cure for chicken bones!
  217. while(true)
  218. {
  219. try
  220. {
  221. // Try to make the directory we need for this file
  222. Directory.CreateDirectory(Path.GetDirectoryName(diskFile));
  223. pathOk = true;
  224. break;
  225. }
  226. catch (System.IO.IOException)
  227. {
  228. // Creating the directory failed. This can't happen unless
  229. // a part of the path already exists as a file. Sadly the
  230. // SRAS data contains such files.
  231. string d = Path.GetDirectoryName(diskFile);
  232. // Test each path component in turn. If we can successfully
  233. // make a directory, the level below must be the chicken bone.
  234. while (d.Length > 0)
  235. {
  236. Console.WriteLine(d);
  237. try
  238. {
  239. Directory.CreateDirectory(Path.GetDirectoryName(d));
  240. }
  241. catch (System.IO.IOException)
  242. {
  243. d = Path.GetDirectoryName(d);
  244. // We failed making the directory and need to
  245. // go up a bit more
  246. continue;
  247. }
  248. // We succeeded in making the directory and (d) is
  249. // the chicken bone
  250. break;
  251. }
  252. // Is the chicken alive?
  253. if (d.Length > 0)
  254. {
  255. Console.WriteLine(d);
  256. FileAttributes attr = File.GetAttributes(d);
  257. if ((attr & FileAttributes.Directory) == 0)
  258. {
  259. // The chicken bone should be resolved.
  260. // Return to writing the file.
  261. File.Delete(d);
  262. continue;
  263. }
  264. }
  265. }
  266. // Could not resolve, skipping
  267. m_log.ErrorFormat("[ASSET]: Could not resolve path creation error for {0}", diskFile);
  268. break;
  269. }
  270. if (pathOk)
  271. {
  272. try
  273. {
  274. byte[] data = File.ReadAllBytes(files[i]);
  275. using (GZipStream gz = new GZipStream(new FileStream(diskFile + ".gz", FileMode.Create), CompressionMode.Compress))
  276. {
  277. gz.Write(data, 0, data.Length);
  278. gz.Close();
  279. }
  280. File.Delete(files[i]);
  281. //File.Move(files[i], diskFile);
  282. }
  283. catch(System.IO.IOException e)
  284. {
  285. if (e.Message.StartsWith("Win32 IO returned ERROR_ALREADY_EXISTS"))
  286. File.Delete(files[i]);
  287. else
  288. throw;
  289. }
  290. }
  291. }
  292. int totalTicks = System.Environment.TickCount - tickCount;
  293. if (totalTicks > 0) // Wrap?
  294. {
  295. m_log.InfoFormat("[ASSET]: Write cycle complete, {0} files, {1} ticks, avg {2:F2}", files.Length, totalTicks, (double)totalTicks / (double)files.Length);
  296. }
  297. }
  298. Thread.Sleep(1000);
  299. }
  300. }
  301. string GetSHA256Hash(byte[] data)
  302. {
  303. byte[] hash = SHA256.ComputeHash(data);
  304. return BitConverter.ToString(hash).Replace("-", String.Empty);
  305. }
  306. public string HashToPath(string hash)
  307. {
  308. if (hash == null || hash.Length < 10)
  309. return "junkyard";
  310. if (m_useOsgridFormat)
  311. {
  312. /*
  313. * The code below is the OSGrid code.
  314. */
  315. return Path.Combine(hash.Substring(0, 3),
  316. Path.Combine(hash.Substring(3, 3)));
  317. }
  318. else
  319. {
  320. /*
  321. * The below is what core would normally use.
  322. * This is modified to work in OSGrid, as seen
  323. * above, because the SRAS data is structured
  324. * that way.
  325. */
  326. return Path.Combine(hash.Substring(0, 2),
  327. Path.Combine(hash.Substring(2, 2),
  328. Path.Combine(hash.Substring(4, 2),
  329. hash.Substring(6, 4))));
  330. }
  331. }
  332. private bool AssetExists(string hash)
  333. {
  334. string s = HashToFile(hash);
  335. string diskFile = Path.Combine(m_FSBase, s);
  336. if (File.Exists(diskFile + ".gz") || File.Exists(diskFile))
  337. return true;
  338. return false;
  339. }
  340. public virtual bool[] AssetsExist(string[] ids)
  341. {
  342. UUID[] uuid = Array.ConvertAll(ids, id => UUID.Parse(id));
  343. return m_DataConnector.AssetsExist(uuid);
  344. }
  345. public string HashToFile(string hash)
  346. {
  347. return Path.Combine(HashToPath(hash), hash);
  348. }
  349. public virtual AssetBase Get(string id)
  350. {
  351. string hash;
  352. return Get(id, out hash);
  353. }
  354. private AssetBase Get(string id, out string sha)
  355. {
  356. string hash = string.Empty;
  357. int startTime = System.Environment.TickCount;
  358. AssetMetadata metadata;
  359. lock (m_readLock)
  360. {
  361. metadata = m_DataConnector.Get(id, out hash);
  362. }
  363. sha = hash;
  364. if (metadata == null)
  365. {
  366. AssetBase asset = null;
  367. if (m_FallbackService != null)
  368. {
  369. asset = m_FallbackService.Get(id);
  370. if (asset != null)
  371. {
  372. asset.Metadata.ContentType =
  373. SLUtil.SLAssetTypeToContentType((int)asset.Type);
  374. sha = GetSHA256Hash(asset.Data);
  375. m_log.InfoFormat("[FSASSETS]: Added asset {0} from fallback to local store", id);
  376. Store(asset);
  377. }
  378. }
  379. if (asset == null)
  380. {
  381. // m_log.InfoFormat("[FSASSETS]: Asset {0} not found", id);
  382. m_missingAssets++;
  383. }
  384. return asset;
  385. }
  386. AssetBase newAsset = new AssetBase();
  387. newAsset.Metadata = metadata;
  388. try
  389. {
  390. newAsset.Data = GetFsData(hash);
  391. if (newAsset.Data.Length == 0)
  392. {
  393. AssetBase asset = null;
  394. if (m_FallbackService != null)
  395. {
  396. asset = m_FallbackService.Get(id);
  397. if (asset != null)
  398. {
  399. asset.Metadata.ContentType =
  400. SLUtil.SLAssetTypeToContentType((int)asset.Type);
  401. sha = GetSHA256Hash(asset.Data);
  402. m_log.InfoFormat("[FSASSETS]: Added asset {0} from fallback to local store", id);
  403. Store(asset);
  404. }
  405. }
  406. if (asset == null)
  407. m_missingAssetsFS++;
  408. // m_log.InfoFormat("[FSASSETS]: Asset {0}, hash {1} not found in FS", id, hash);
  409. else
  410. {
  411. // Deal with bug introduced in Oct. 20 (1eb3e6cc43e2a7b4053bc1185c7c88e22356c5e8)
  412. // Fix bad assets before sending them elsewhere
  413. if (asset.Type == (int)AssetType.Object && asset.Data != null)
  414. {
  415. string xml = ExternalRepresentationUtils.SanitizeXml(Utils.BytesToString(asset.Data));
  416. asset.Data = Utils.StringToBytes(xml);
  417. }
  418. return asset;
  419. }
  420. }
  421. lock (m_statsLock)
  422. {
  423. m_readTicks += Environment.TickCount - startTime;
  424. m_readCount++;
  425. }
  426. // Deal with bug introduced in Oct. 20 (1eb3e6cc43e2a7b4053bc1185c7c88e22356c5e8)
  427. // Fix bad assets before sending them elsewhere
  428. if (newAsset.Type == (int)AssetType.Object && newAsset.Data != null)
  429. {
  430. string xml = ExternalRepresentationUtils.SanitizeXml(Utils.BytesToString(newAsset.Data));
  431. newAsset.Data = Utils.StringToBytes(xml);
  432. }
  433. return newAsset;
  434. }
  435. catch (Exception exception)
  436. {
  437. m_log.Error(exception.ToString());
  438. Thread.Sleep(5000);
  439. Environment.Exit(1);
  440. return null;
  441. }
  442. }
  443. public virtual AssetMetadata GetMetadata(string id)
  444. {
  445. string hash;
  446. return m_DataConnector.Get(id, out hash);
  447. }
  448. public virtual byte[] GetData(string id)
  449. {
  450. string hash;
  451. if (m_DataConnector.Get(id, out hash) == null)
  452. return null;
  453. return GetFsData(hash);
  454. }
  455. public bool Get(string id, Object sender, AssetRetrieved handler)
  456. {
  457. AssetBase asset = Get(id);
  458. handler(id, sender, asset);
  459. return true;
  460. }
  461. public byte[] GetFsData(string hash)
  462. {
  463. string spoolFile = Path.Combine(m_SpoolDirectory, hash + ".asset");
  464. if (File.Exists(spoolFile))
  465. {
  466. try
  467. {
  468. byte[] content = File.ReadAllBytes(spoolFile);
  469. return content;
  470. }
  471. catch
  472. {
  473. }
  474. }
  475. string file = HashToFile(hash);
  476. string diskFile = Path.Combine(m_FSBase, file);
  477. if (File.Exists(diskFile + ".gz"))
  478. {
  479. try
  480. {
  481. using (GZipStream gz = new GZipStream(new FileStream(diskFile + ".gz", FileMode.Open, FileAccess.Read), CompressionMode.Decompress))
  482. {
  483. using (MemoryStream ms = new MemoryStream())
  484. {
  485. byte[] data = new byte[32768];
  486. int bytesRead;
  487. do
  488. {
  489. bytesRead = gz.Read(data, 0, 32768);
  490. if (bytesRead > 0)
  491. ms.Write(data, 0, bytesRead);
  492. } while (bytesRead > 0);
  493. return ms.ToArray();
  494. }
  495. }
  496. }
  497. catch (Exception)
  498. {
  499. return new Byte[0];
  500. }
  501. }
  502. else if (File.Exists(diskFile))
  503. {
  504. try
  505. {
  506. byte[] content = File.ReadAllBytes(diskFile);
  507. return content;
  508. }
  509. catch
  510. {
  511. }
  512. }
  513. return new Byte[0];
  514. }
  515. public virtual string Store(AssetBase asset)
  516. {
  517. return Store(asset, false);
  518. }
  519. private string Store(AssetBase asset, bool force)
  520. {
  521. int tickCount = Environment.TickCount;
  522. string hash = GetSHA256Hash(asset.Data);
  523. if (!AssetExists(hash))
  524. {
  525. string tempFile = Path.Combine(Path.Combine(m_SpoolDirectory, "spool"), hash + ".asset");
  526. string finalFile = Path.Combine(m_SpoolDirectory, hash + ".asset");
  527. if (!File.Exists(finalFile))
  528. {
  529. // Deal with bug introduced in Oct. 20 (1eb3e6cc43e2a7b4053bc1185c7c88e22356c5e8)
  530. // Fix bad assets before storing on this server
  531. if (asset.Type == (int)AssetType.Object && asset.Data != null)
  532. {
  533. string xml = ExternalRepresentationUtils.SanitizeXml(Utils.BytesToString(asset.Data));
  534. asset.Data = Utils.StringToBytes(xml);
  535. }
  536. FileStream fs = File.Create(tempFile);
  537. fs.Write(asset.Data, 0, asset.Data.Length);
  538. fs.Close();
  539. File.Move(tempFile, finalFile);
  540. }
  541. }
  542. if (asset.ID == string.Empty)
  543. {
  544. if (asset.FullID == UUID.Zero)
  545. {
  546. asset.FullID = UUID.Random();
  547. }
  548. asset.ID = asset.FullID.ToString();
  549. }
  550. else if (asset.FullID == UUID.Zero)
  551. {
  552. UUID uuid = UUID.Zero;
  553. if (UUID.TryParse(asset.ID, out uuid))
  554. {
  555. asset.FullID = uuid;
  556. }
  557. else
  558. {
  559. asset.FullID = UUID.Random();
  560. }
  561. }
  562. if (!m_DataConnector.Store(asset.Metadata, hash))
  563. {
  564. return UUID.Zero.ToString();
  565. }
  566. else
  567. {
  568. return asset.ID;
  569. }
  570. }
  571. public bool UpdateContent(string id, byte[] data)
  572. {
  573. return false;
  574. // string oldhash;
  575. // AssetMetadata meta = m_DataConnector.Get(id, out oldhash);
  576. //
  577. // if (meta == null)
  578. // return false;
  579. //
  580. // AssetBase asset = new AssetBase();
  581. // asset.Metadata = meta;
  582. // asset.Data = data;
  583. //
  584. // Store(asset);
  585. //
  586. // return true;
  587. }
  588. public virtual bool Delete(string id)
  589. {
  590. m_DataConnector.Delete(id);
  591. return true;
  592. }
  593. private void HandleShowAssets(string module, string[] args)
  594. {
  595. int num = m_DataConnector.Count();
  596. MainConsole.Instance.Output(string.Format("Total asset count: {0}", num));
  597. }
  598. private void HandleShowDigest(string module, string[] args)
  599. {
  600. if (args.Length < 3)
  601. {
  602. MainConsole.Instance.Output("Syntax: show digest <ID>");
  603. return;
  604. }
  605. string hash;
  606. AssetBase asset = Get(args[2], out hash);
  607. if (asset == null || asset.Data.Length == 0)
  608. {
  609. MainConsole.Instance.Output("Asset not found");
  610. return;
  611. }
  612. int i;
  613. MainConsole.Instance.Output(String.Format("Name: {0}", asset.Name));
  614. MainConsole.Instance.Output(String.Format("Description: {0}", asset.Description));
  615. MainConsole.Instance.Output(String.Format("Type: {0}", asset.Type));
  616. MainConsole.Instance.Output(String.Format("Content-type: {0}", asset.Metadata.ContentType));
  617. MainConsole.Instance.Output(String.Format("Flags: {0}", asset.Metadata.Flags.ToString()));
  618. MainConsole.Instance.Output(String.Format("FS file: {0}", HashToFile(hash)));
  619. for (i = 0 ; i < 5 ; i++)
  620. {
  621. int off = i * 16;
  622. if (asset.Data.Length <= off)
  623. break;
  624. int len = 16;
  625. if (asset.Data.Length < off + len)
  626. len = asset.Data.Length - off;
  627. byte[] line = new byte[len];
  628. Array.Copy(asset.Data, off, line, 0, len);
  629. string text = BitConverter.ToString(line);
  630. MainConsole.Instance.Output(String.Format("{0:x4}: {1}", off, text));
  631. }
  632. }
  633. private void HandleDeleteAsset(string module, string[] args)
  634. {
  635. if (args.Length < 3)
  636. {
  637. MainConsole.Instance.Output("Syntax: delete asset <ID>");
  638. return;
  639. }
  640. AssetBase asset = Get(args[2]);
  641. if (asset == null || asset.Data.Length == 0)
  642. {
  643. MainConsole.Instance.Output("Asset not found");
  644. return;
  645. }
  646. m_DataConnector.Delete(args[2]);
  647. MainConsole.Instance.Output("Asset deleted");
  648. }
  649. private void HandleImportAssets(string module, string[] args)
  650. {
  651. bool force = false;
  652. if (args[0] == "force")
  653. {
  654. force = true;
  655. List<string> list = new List<string>(args);
  656. list.RemoveAt(0);
  657. args = list.ToArray();
  658. }
  659. if (args.Length < 3)
  660. {
  661. MainConsole.Instance.Output("Syntax: import <conn> <table> [<start> <count>]");
  662. }
  663. else
  664. {
  665. string conn = args[1];
  666. string table = args[2];
  667. int start = 0;
  668. int count = -1;
  669. if (args.Length > 3)
  670. {
  671. start = Convert.ToInt32(args[3]);
  672. }
  673. if (args.Length > 4)
  674. {
  675. count = Convert.ToInt32(args[4]);
  676. }
  677. m_DataConnector.Import(conn, table, start, count, force, new FSStoreDelegate(Store));
  678. }
  679. }
  680. public AssetBase GetCached(string id)
  681. {
  682. return Get(id);
  683. }
  684. }
  685. }