FSAssetService.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815
  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. gz.Close();
  285. }
  286. File.Delete(files[i]);
  287. //File.Move(files[i], diskFile);
  288. }
  289. catch(System.IO.IOException e)
  290. {
  291. if (e.Message.StartsWith("Win32 IO returned ERROR_ALREADY_EXISTS"))
  292. File.Delete(files[i]);
  293. else
  294. throw;
  295. }
  296. }
  297. }
  298. int totalTicks = System.Environment.TickCount - tickCount;
  299. if (totalTicks > 0) // Wrap?
  300. {
  301. m_log.InfoFormat("[ASSET]: Write cycle complete, {0} files, {1} ticks, avg {2:F2}", files.Length, totalTicks, (double)totalTicks / (double)files.Length);
  302. }
  303. }
  304. Thread.Sleep(1000);
  305. }
  306. }
  307. string GetSHA256Hash(byte[] data)
  308. {
  309. byte[] hash = SHA256.ComputeHash(data);
  310. return BitConverter.ToString(hash).Replace("-", String.Empty);
  311. }
  312. public string HashToPath(string hash)
  313. {
  314. if (hash == null || hash.Length < 10)
  315. return "junkyard";
  316. if (m_useOsgridFormat)
  317. {
  318. /*
  319. * The code below is the OSGrid code.
  320. */
  321. return Path.Combine(hash.Substring(0, 3),
  322. Path.Combine(hash.Substring(3, 3)));
  323. }
  324. else
  325. {
  326. /*
  327. * The below is what core would normally use.
  328. * This is modified to work in OSGrid, as seen
  329. * above, because the SRAS data is structured
  330. * that way.
  331. */
  332. return Path.Combine(hash.Substring(0, 2),
  333. Path.Combine(hash.Substring(2, 2),
  334. Path.Combine(hash.Substring(4, 2),
  335. hash.Substring(6, 4))));
  336. }
  337. }
  338. private bool AssetExists(string hash)
  339. {
  340. string s = HashToFile(hash);
  341. string diskFile = Path.Combine(m_FSBase, s);
  342. if (File.Exists(diskFile + ".gz") || File.Exists(diskFile))
  343. return true;
  344. return false;
  345. }
  346. public virtual bool[] AssetsExist(string[] ids)
  347. {
  348. UUID[] uuid = Array.ConvertAll(ids, id => UUID.Parse(id));
  349. return m_DataConnector.AssetsExist(uuid);
  350. }
  351. public string HashToFile(string hash)
  352. {
  353. return Path.Combine(HashToPath(hash), hash);
  354. }
  355. public virtual AssetBase Get(string id)
  356. {
  357. string hash;
  358. return Get(id, out hash);
  359. }
  360. private AssetBase Get(string id, out string sha)
  361. {
  362. string hash = string.Empty;
  363. int startTime = System.Environment.TickCount;
  364. AssetMetadata metadata;
  365. lock (m_readLock)
  366. {
  367. metadata = m_DataConnector.Get(id, out hash);
  368. }
  369. sha = hash;
  370. if (metadata == null)
  371. {
  372. AssetBase asset = null;
  373. if (m_FallbackService != null)
  374. {
  375. asset = m_FallbackService.Get(id);
  376. if (asset != null)
  377. {
  378. asset.Metadata.ContentType =
  379. SLUtil.SLAssetTypeToContentType((int)asset.Type);
  380. sha = GetSHA256Hash(asset.Data);
  381. m_log.InfoFormat("[FSASSETS]: Added asset {0} from fallback to local store", id);
  382. Store(asset);
  383. }
  384. }
  385. if (asset == null && m_showStats)
  386. {
  387. // m_log.InfoFormat("[FSASSETS]: Asset {0} not found", id);
  388. m_missingAssets++;
  389. }
  390. return asset;
  391. }
  392. AssetBase newAsset = new AssetBase();
  393. newAsset.Metadata = metadata;
  394. try
  395. {
  396. newAsset.Data = GetFsData(hash);
  397. if (newAsset.Data.Length == 0)
  398. {
  399. AssetBase asset = null;
  400. if (m_FallbackService != null)
  401. {
  402. asset = m_FallbackService.Get(id);
  403. if (asset != null)
  404. {
  405. asset.Metadata.ContentType =
  406. SLUtil.SLAssetTypeToContentType((int)asset.Type);
  407. sha = GetSHA256Hash(asset.Data);
  408. m_log.InfoFormat("[FSASSETS]: Added asset {0} from fallback to local store", id);
  409. Store(asset);
  410. }
  411. }
  412. if (asset == null)
  413. {
  414. if (m_showStats)
  415. m_missingAssetsFS++;
  416. // m_log.InfoFormat("[FSASSETS]: Asset {0}, hash {1} not found in FS", id, hash);
  417. }
  418. else
  419. {
  420. // Deal with bug introduced in Oct. 20 (1eb3e6cc43e2a7b4053bc1185c7c88e22356c5e8)
  421. // Fix bad assets before sending them elsewhere
  422. if (asset.Type == (int)AssetType.Object && asset.Data != null)
  423. {
  424. string xml = ExternalRepresentationUtils.SanitizeXml(Utils.BytesToString(asset.Data));
  425. asset.Data = Utils.StringToBytes(xml);
  426. }
  427. return asset;
  428. }
  429. }
  430. if (m_showStats)
  431. {
  432. lock (m_statsLock)
  433. {
  434. m_readTicks += Environment.TickCount - startTime;
  435. m_readCount++;
  436. }
  437. }
  438. // Deal with bug introduced in Oct. 20 (1eb3e6cc43e2a7b4053bc1185c7c88e22356c5e8)
  439. // Fix bad assets before sending them elsewhere
  440. if (newAsset.Type == (int)AssetType.Object && newAsset.Data != null)
  441. {
  442. string xml = ExternalRepresentationUtils.SanitizeXml(Utils.BytesToString(newAsset.Data));
  443. newAsset.Data = Utils.StringToBytes(xml);
  444. }
  445. return newAsset;
  446. }
  447. catch (Exception exception)
  448. {
  449. m_log.Error(exception.ToString());
  450. Thread.Sleep(5000);
  451. Environment.Exit(1);
  452. return null;
  453. }
  454. }
  455. public virtual AssetMetadata GetMetadata(string id)
  456. {
  457. string hash;
  458. return m_DataConnector.Get(id, out hash);
  459. }
  460. public virtual byte[] GetData(string id)
  461. {
  462. string hash;
  463. if (m_DataConnector.Get(id, out hash) == null)
  464. return null;
  465. return GetFsData(hash);
  466. }
  467. public bool Get(string id, Object sender, AssetRetrieved handler)
  468. {
  469. AssetBase asset = Get(id);
  470. handler(id, sender, asset);
  471. return true;
  472. }
  473. public byte[] GetFsData(string hash)
  474. {
  475. string spoolFile = Path.Combine(m_SpoolDirectory, hash + ".asset");
  476. if (File.Exists(spoolFile))
  477. {
  478. try
  479. {
  480. byte[] content = File.ReadAllBytes(spoolFile);
  481. return content;
  482. }
  483. catch
  484. {
  485. }
  486. }
  487. string file = HashToFile(hash);
  488. string diskFile = Path.Combine(m_FSBase, file);
  489. if (File.Exists(diskFile + ".gz"))
  490. {
  491. try
  492. {
  493. using (GZipStream gz = new GZipStream(new FileStream(diskFile + ".gz", FileMode.Open, FileAccess.Read), CompressionMode.Decompress))
  494. {
  495. using (MemoryStream ms = new MemoryStream())
  496. {
  497. byte[] data = new byte[32768];
  498. int bytesRead;
  499. do
  500. {
  501. bytesRead = gz.Read(data, 0, 32768);
  502. if (bytesRead > 0)
  503. ms.Write(data, 0, bytesRead);
  504. } while (bytesRead > 0);
  505. return ms.ToArray();
  506. }
  507. }
  508. }
  509. catch (Exception)
  510. {
  511. return new Byte[0];
  512. }
  513. }
  514. else if (File.Exists(diskFile))
  515. {
  516. try
  517. {
  518. byte[] content = File.ReadAllBytes(diskFile);
  519. return content;
  520. }
  521. catch
  522. {
  523. }
  524. }
  525. return new Byte[0];
  526. }
  527. public virtual string Store(AssetBase asset)
  528. {
  529. return Store(asset, false);
  530. }
  531. private string Store(AssetBase asset, bool force)
  532. {
  533. int tickCount = Environment.TickCount;
  534. string hash = GetSHA256Hash(asset.Data);
  535. if (!AssetExists(hash))
  536. {
  537. string tempFile = Path.Combine(Path.Combine(m_SpoolDirectory, "spool"), hash + ".asset");
  538. string finalFile = Path.Combine(m_SpoolDirectory, hash + ".asset");
  539. if (!File.Exists(finalFile))
  540. {
  541. // Deal with bug introduced in Oct. 20 (1eb3e6cc43e2a7b4053bc1185c7c88e22356c5e8)
  542. // Fix bad assets before storing on this server
  543. if (asset.Type == (int)AssetType.Object && asset.Data != null)
  544. {
  545. string xml = ExternalRepresentationUtils.SanitizeXml(Utils.BytesToString(asset.Data));
  546. asset.Data = Utils.StringToBytes(xml);
  547. }
  548. FileStream fs = File.Create(tempFile);
  549. fs.Write(asset.Data, 0, asset.Data.Length);
  550. fs.Close();
  551. File.Move(tempFile, finalFile);
  552. }
  553. }
  554. if (asset.ID == string.Empty)
  555. {
  556. if (asset.FullID == UUID.Zero)
  557. {
  558. asset.FullID = UUID.Random();
  559. }
  560. asset.ID = asset.FullID.ToString();
  561. }
  562. else if (asset.FullID == UUID.Zero)
  563. {
  564. UUID uuid = UUID.Zero;
  565. if (UUID.TryParse(asset.ID, out uuid))
  566. {
  567. asset.FullID = uuid;
  568. }
  569. else
  570. {
  571. asset.FullID = UUID.Random();
  572. }
  573. }
  574. if (!m_DataConnector.Store(asset.Metadata, hash))
  575. {
  576. if (asset.Metadata.Type == -2)
  577. return asset.ID;
  578. return UUID.Zero.ToString();
  579. }
  580. else
  581. {
  582. return asset.ID;
  583. }
  584. }
  585. public bool UpdateContent(string id, byte[] data)
  586. {
  587. return false;
  588. // string oldhash;
  589. // AssetMetadata meta = m_DataConnector.Get(id, out oldhash);
  590. //
  591. // if (meta == null)
  592. // return false;
  593. //
  594. // AssetBase asset = new AssetBase();
  595. // asset.Metadata = meta;
  596. // asset.Data = data;
  597. //
  598. // Store(asset);
  599. //
  600. // return true;
  601. }
  602. public virtual bool Delete(string id)
  603. {
  604. m_DataConnector.Delete(id);
  605. return true;
  606. }
  607. private void HandleShowAssets(string module, string[] args)
  608. {
  609. int num = m_DataConnector.Count();
  610. MainConsole.Instance.Output(string.Format("Total asset count: {0}", num));
  611. }
  612. private void HandleShowDigest(string module, string[] args)
  613. {
  614. if (args.Length < 3)
  615. {
  616. MainConsole.Instance.Output("Syntax: show digest <ID>");
  617. return;
  618. }
  619. string hash;
  620. AssetBase asset = Get(args[2], out hash);
  621. if (asset == null || asset.Data.Length == 0)
  622. {
  623. MainConsole.Instance.Output("Asset not found");
  624. return;
  625. }
  626. int i;
  627. MainConsole.Instance.Output(String.Format("Name: {0}", asset.Name));
  628. MainConsole.Instance.Output(String.Format("Description: {0}", asset.Description));
  629. MainConsole.Instance.Output(String.Format("Type: {0}", asset.Type));
  630. MainConsole.Instance.Output(String.Format("Content-type: {0}", asset.Metadata.ContentType));
  631. MainConsole.Instance.Output(String.Format("Flags: {0}", asset.Metadata.Flags.ToString()));
  632. MainConsole.Instance.Output(String.Format("FS file: {0}", HashToFile(hash)));
  633. for (i = 0 ; i < 5 ; i++)
  634. {
  635. int off = i * 16;
  636. if (asset.Data.Length <= off)
  637. break;
  638. int len = 16;
  639. if (asset.Data.Length < off + len)
  640. len = asset.Data.Length - off;
  641. byte[] line = new byte[len];
  642. Array.Copy(asset.Data, off, line, 0, len);
  643. string text = BitConverter.ToString(line);
  644. MainConsole.Instance.Output(String.Format("{0:x4}: {1}", off, text));
  645. }
  646. }
  647. private void HandleDeleteAsset(string module, string[] args)
  648. {
  649. if (args.Length < 3)
  650. {
  651. MainConsole.Instance.Output("Syntax: delete asset <ID>");
  652. return;
  653. }
  654. AssetBase asset = Get(args[2]);
  655. if (asset == null || asset.Data.Length == 0)
  656. {
  657. MainConsole.Instance.Output("Asset not found");
  658. return;
  659. }
  660. m_DataConnector.Delete(args[2]);
  661. MainConsole.Instance.Output("Asset deleted");
  662. }
  663. private void HandleImportAssets(string module, string[] args)
  664. {
  665. bool force = false;
  666. if (args[0] == "force")
  667. {
  668. force = true;
  669. List<string> list = new List<string>(args);
  670. list.RemoveAt(0);
  671. args = list.ToArray();
  672. }
  673. if (args.Length < 3)
  674. {
  675. MainConsole.Instance.Output("Syntax: import <conn> <table> [<start> <count>]");
  676. }
  677. else
  678. {
  679. string conn = args[1];
  680. string table = args[2];
  681. int start = 0;
  682. int count = -1;
  683. if (args.Length > 3)
  684. {
  685. start = Convert.ToInt32(args[3]);
  686. }
  687. if (args.Length > 4)
  688. {
  689. count = Convert.ToInt32(args[4]);
  690. }
  691. m_DataConnector.Import(conn, table, start, count, force, new FSStoreDelegate(Store));
  692. }
  693. }
  694. public AssetBase GetCached(string id)
  695. {
  696. return Get(id);
  697. }
  698. }
  699. }