BotManager.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632
  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.Collections.Generic;
  29. using System.Linq;
  30. using System.Reflection;
  31. using System.Threading;
  32. using OpenMetaverse;
  33. using log4net;
  34. using log4net.Appender;
  35. using log4net.Core;
  36. using log4net.Repository;
  37. using Nini.Config;
  38. using OpenSim.Framework;
  39. using OpenSim.Framework.Console;
  40. using pCampBot.Interfaces;
  41. namespace pCampBot
  42. {
  43. /// <summary>
  44. /// Thread/Bot manager for the application
  45. /// </summary>
  46. public class BotManager
  47. {
  48. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  49. public const int DefaultLoginDelay = 5000;
  50. /// <summary>
  51. /// Is pCampbot in the process of connecting bots?
  52. /// </summary>
  53. public bool ConnectingBots { get; private set; }
  54. /// <summary>
  55. /// Is pCampbot in the process of disconnecting bots?
  56. /// </summary>
  57. public bool DisconnectingBots { get; private set; }
  58. /// <summary>
  59. /// Delay between logins of multiple bots.
  60. /// </summary>
  61. /// <remarks>TODO: This value needs to be configurable by a command line argument.</remarks>
  62. public int LoginDelay { get; set; }
  63. /// <summary>
  64. /// Command console
  65. /// </summary>
  66. protected CommandConsole m_console;
  67. /// <summary>
  68. /// Controls whether bots start out sending agent updates on connection.
  69. /// </summary>
  70. public bool InitBotSendAgentUpdates { get; set; }
  71. /// <summary>
  72. /// Controls whether bots request textures for the object information they receive
  73. /// </summary>
  74. public bool InitBotRequestObjectTextures { get; set; }
  75. /// <summary>
  76. /// Created bots, whether active or inactive.
  77. /// </summary>
  78. protected List<Bot> m_bots;
  79. /// <summary>
  80. /// Random number generator.
  81. /// </summary>
  82. public Random Rng { get; private set; }
  83. /// <summary>
  84. /// Track the assets we have and have not received so we don't endlessly repeat requests.
  85. /// </summary>
  86. public Dictionary<UUID, bool> AssetsReceived { get; private set; }
  87. /// <summary>
  88. /// The regions that we know about.
  89. /// </summary>
  90. public Dictionary<ulong, GridRegion> RegionsKnown { get; private set; }
  91. /// <summary>
  92. /// First name for bots
  93. /// </summary>
  94. private string m_firstName;
  95. /// <summary>
  96. /// Last name stem for bots
  97. /// </summary>
  98. private string m_lastNameStem;
  99. /// <summary>
  100. /// Password for bots
  101. /// </summary>
  102. private string m_password;
  103. /// <summary>
  104. /// Login URI for bots.
  105. /// </summary>
  106. private string m_loginUri;
  107. /// <summary>
  108. /// Start location for bots.
  109. /// </summary>
  110. private string m_startUri;
  111. /// <summary>
  112. /// Postfix bot number at which bot sequence starts.
  113. /// </summary>
  114. private int m_fromBotNumber;
  115. /// <summary>
  116. /// Wear setting for bots.
  117. /// </summary>
  118. private string m_wearSetting;
  119. /// <summary>
  120. /// Behaviour switches for bots.
  121. /// </summary>
  122. private HashSet<string> m_behaviourSwitches = new HashSet<string>();
  123. /// <summary>
  124. /// Constructor Creates MainConsole.Instance to take commands and provide the place to write data
  125. /// </summary>
  126. public BotManager()
  127. {
  128. InitBotSendAgentUpdates = true;
  129. InitBotRequestObjectTextures = true;
  130. LoginDelay = DefaultLoginDelay;
  131. Rng = new Random(Environment.TickCount);
  132. AssetsReceived = new Dictionary<UUID, bool>();
  133. RegionsKnown = new Dictionary<ulong, GridRegion>();
  134. m_console = CreateConsole();
  135. MainConsole.Instance = m_console;
  136. // Make log4net see the console
  137. //
  138. ILoggerRepository repository = LogManager.GetRepository();
  139. IAppender[] appenders = repository.GetAppenders();
  140. OpenSimAppender consoleAppender = null;
  141. foreach (IAppender appender in appenders)
  142. {
  143. if (appender.Name == "Console")
  144. {
  145. consoleAppender = (OpenSimAppender)appender;
  146. consoleAppender.Console = m_console;
  147. break;
  148. }
  149. }
  150. m_console.Commands.AddCommand(
  151. "bot", false, "shutdown", "shutdown", "Shutdown bots and exit", HandleShutdown);
  152. m_console.Commands.AddCommand(
  153. "bot", false, "quit", "quit", "Shutdown bots and exit", HandleShutdown);
  154. m_console.Commands.AddCommand(
  155. "bot", false, "connect", "connect [<n>]", "Connect bots",
  156. "If an <n> is given, then the first <n> disconnected bots by postfix number are connected.\n"
  157. + "If no <n> is given, then all currently disconnected bots are connected.",
  158. HandleConnect);
  159. m_console.Commands.AddCommand(
  160. "bot", false, "disconnect", "disconnect [<n>]", "Disconnect bots",
  161. "Disconnecting bots will interupt any bot connection process, including connection on startup.\n"
  162. + "If an <n> is given, then the last <n> connected bots by postfix number are disconnected.\n"
  163. + "If no <n> is given, then all currently connected bots are disconnected.",
  164. HandleDisconnect);
  165. m_console.Commands.AddCommand(
  166. "bot", false, "sit", "sit", "Sit all bots on the ground.",
  167. HandleSit);
  168. m_console.Commands.AddCommand(
  169. "bot", false, "stand", "stand", "Stand all bots.",
  170. HandleStand);
  171. m_console.Commands.AddCommand(
  172. "bot", false, "show regions", "show regions", "Show regions known to bots", HandleShowRegions);
  173. m_console.Commands.AddCommand(
  174. "bot", false, "show bots", "show bots", "Shows the status of all bots", HandleShowBotsStatus);
  175. m_console.Commands.AddCommand(
  176. "bot", false, "show bot", "show bot <first-name> <last-name>",
  177. "Shows the detailed status and settings of a particular bot.", HandleShowBotStatus);
  178. m_bots = new List<Bot>();
  179. }
  180. /// <summary>
  181. /// Startup number of bots specified in the starting arguments
  182. /// </summary>
  183. /// <param name="botcount">How many bots to start up</param>
  184. /// <param name="cs">The configuration for the bots to use</param>
  185. public void CreateBots(int botcount, IConfig startupConfig)
  186. {
  187. m_firstName = startupConfig.GetString("firstname");
  188. m_lastNameStem = startupConfig.GetString("lastname");
  189. m_password = startupConfig.GetString("password");
  190. m_loginUri = startupConfig.GetString("loginuri");
  191. m_fromBotNumber = startupConfig.GetInt("from", 0);
  192. m_wearSetting = startupConfig.GetString("wear", "no");
  193. m_startUri = ParseInputStartLocationToUri(startupConfig.GetString("start", "last"));
  194. Array.ForEach<string>(
  195. startupConfig.GetString("behaviours", "p").Split(new char[] { ',' }), b => m_behaviourSwitches.Add(b));
  196. for (int i = 0; i < botcount; i++)
  197. {
  198. lock (m_bots)
  199. {
  200. string lastName = string.Format("{0}_{1}", m_lastNameStem, i + m_fromBotNumber);
  201. // We must give each bot its own list of instantiated behaviours since they store state.
  202. List<IBehaviour> behaviours = new List<IBehaviour>();
  203. // Hard-coded for now
  204. if (m_behaviourSwitches.Contains("c"))
  205. behaviours.Add(new CrossBehaviour());
  206. if (m_behaviourSwitches.Contains("g"))
  207. behaviours.Add(new GrabbingBehaviour());
  208. if (m_behaviourSwitches.Contains("n"))
  209. behaviours.Add(new NoneBehaviour());
  210. if (m_behaviourSwitches.Contains("p"))
  211. behaviours.Add(new PhysicsBehaviour());
  212. if (m_behaviourSwitches.Contains("t"))
  213. behaviours.Add(new TeleportBehaviour());
  214. CreateBot(this, behaviours, m_firstName, lastName, m_password, m_loginUri, m_startUri, m_wearSetting);
  215. }
  216. }
  217. }
  218. public void ConnectBots(int botcount)
  219. {
  220. ConnectingBots = true;
  221. Thread connectBotThread = new Thread(o => ConnectBotsInternal(botcount));
  222. connectBotThread.Name = "Bots connection thread";
  223. connectBotThread.Start();
  224. }
  225. private void ConnectBotsInternal(int botcount)
  226. {
  227. MainConsole.Instance.OutputFormat(
  228. "[BOT MANAGER]: Starting {0} bots connecting to {1}, location {2}, named {3} {4}_<n>",
  229. botcount,
  230. m_loginUri,
  231. m_startUri,
  232. m_firstName,
  233. m_lastNameStem);
  234. MainConsole.Instance.OutputFormat("[BOT MANAGER]: Delay between logins is {0}ms", LoginDelay);
  235. MainConsole.Instance.OutputFormat("[BOT MANAGER]: BotsSendAgentUpdates is {0}", InitBotSendAgentUpdates);
  236. MainConsole.Instance.OutputFormat("[BOT MANAGER]: InitBotRequestObjectTextures is {0}", InitBotRequestObjectTextures);
  237. for (int i = 0; i < botcount; i++)
  238. {
  239. lock (m_bots)
  240. {
  241. if (DisconnectingBots)
  242. {
  243. MainConsole.Instance.Output(
  244. "[BOT MANAGER]: Aborting bot connection due to user-initiated disconnection");
  245. break;
  246. }
  247. m_bots[i].Connect();
  248. }
  249. // Stagger logins
  250. Thread.Sleep(LoginDelay);
  251. }
  252. ConnectingBots = false;
  253. }
  254. /// <summary>
  255. /// Parses the command line start location to a start string/uri that the login mechanism will recognize.
  256. /// </summary>
  257. /// <returns>
  258. /// The input start location to URI.
  259. /// </returns>
  260. /// <param name='startLocation'>
  261. /// Start location.
  262. /// </param>
  263. private string ParseInputStartLocationToUri(string startLocation)
  264. {
  265. if (startLocation == "home" || startLocation == "last")
  266. return startLocation;
  267. string regionName;
  268. // Just a region name or only one (!) extra component. Like a viewer, we will stick 128/128/0 on the end
  269. Vector3 startPos = new Vector3(128, 128, 0);
  270. string[] startLocationComponents = startLocation.Split('/');
  271. regionName = startLocationComponents[0];
  272. if (startLocationComponents.Length >= 2)
  273. {
  274. float.TryParse(startLocationComponents[1], out startPos.X);
  275. if (startLocationComponents.Length >= 3)
  276. {
  277. float.TryParse(startLocationComponents[2], out startPos.Y);
  278. if (startLocationComponents.Length >= 4)
  279. float.TryParse(startLocationComponents[3], out startPos.Z);
  280. }
  281. }
  282. return string.Format("uri:{0}&{1}&{2}&{3}", regionName, startPos.X, startPos.Y, startPos.Z);
  283. }
  284. /// <summary>
  285. /// This creates a bot but does not start it.
  286. /// </summary>
  287. /// <param name="bm"></param>
  288. /// <param name="behaviours">Behaviours for this bot to perform.</param>
  289. /// <param name="firstName">First name</param>
  290. /// <param name="lastName">Last name</param>
  291. /// <param name="password">Password</param>
  292. /// <param name="loginUri">Login URI</param>
  293. /// <param name="startLocation">Location to start the bot. Can be "last", "home" or a specific sim name.</param>
  294. /// <param name="wearSetting"></param>
  295. public void CreateBot(
  296. BotManager bm, List<IBehaviour> behaviours,
  297. string firstName, string lastName, string password, string loginUri, string startLocation, string wearSetting)
  298. {
  299. MainConsole.Instance.OutputFormat(
  300. "[BOT MANAGER]: Creating bot {0} {1}, behaviours are {2}",
  301. firstName, lastName, string.Join(",", behaviours.ConvertAll<string>(b => b.Name).ToArray()));
  302. Bot pb = new Bot(bm, behaviours, firstName, lastName, password, startLocation, loginUri);
  303. pb.wear = wearSetting;
  304. pb.Client.Settings.SEND_AGENT_UPDATES = InitBotSendAgentUpdates;
  305. pb.RequestObjectTextures = InitBotRequestObjectTextures;
  306. pb.OnConnected += handlebotEvent;
  307. pb.OnDisconnected += handlebotEvent;
  308. m_bots.Add(pb);
  309. }
  310. /// <summary>
  311. /// High level connnected/disconnected events so we can keep track of our threads by proxy
  312. /// </summary>
  313. /// <param name="callbot"></param>
  314. /// <param name="eventt"></param>
  315. private void handlebotEvent(Bot callbot, EventType eventt)
  316. {
  317. switch (eventt)
  318. {
  319. case EventType.CONNECTED:
  320. {
  321. m_log.Info("[" + callbot.FirstName + " " + callbot.LastName + "]: Connected");
  322. break;
  323. }
  324. case EventType.DISCONNECTED:
  325. {
  326. m_log.Info("[" + callbot.FirstName + " " + callbot.LastName + "]: Disconnected");
  327. break;
  328. }
  329. }
  330. }
  331. /// <summary>
  332. /// Standard CreateConsole routine
  333. /// </summary>
  334. /// <returns></returns>
  335. protected CommandConsole CreateConsole()
  336. {
  337. return new LocalConsole("pCampbot");
  338. }
  339. private void HandleConnect(string module, string[] cmd)
  340. {
  341. if (ConnectingBots)
  342. {
  343. MainConsole.Instance.Output("Still connecting bots. Please wait for previous process to complete.");
  344. return;
  345. }
  346. lock (m_bots)
  347. {
  348. int botsToConnect;
  349. int disconnectedBots = m_bots.Count(b => b.ConnectionState == ConnectionState.Disconnected);
  350. if (cmd.Length == 1)
  351. {
  352. botsToConnect = disconnectedBots;
  353. }
  354. else
  355. {
  356. if (!ConsoleUtil.TryParseConsoleNaturalInt(MainConsole.Instance, cmd[1], out botsToConnect))
  357. return;
  358. botsToConnect = Math.Min(botsToConnect, disconnectedBots);
  359. }
  360. MainConsole.Instance.OutputFormat("Connecting {0} bots", botsToConnect);
  361. ConnectBots(botsToConnect);
  362. }
  363. }
  364. private void HandleDisconnect(string module, string[] cmd)
  365. {
  366. lock (m_bots)
  367. {
  368. int botsToDisconnect;
  369. int connectedBots = m_bots.Count(b => b.ConnectionState == ConnectionState.Connected);
  370. if (cmd.Length == 1)
  371. {
  372. botsToDisconnect = connectedBots;
  373. }
  374. else
  375. {
  376. if (!ConsoleUtil.TryParseConsoleNaturalInt(MainConsole.Instance, cmd[1], out botsToDisconnect))
  377. return;
  378. botsToDisconnect = Math.Min(botsToDisconnect, connectedBots);
  379. }
  380. DisconnectingBots = true;
  381. MainConsole.Instance.OutputFormat("Disconnecting {0} bots", botsToDisconnect);
  382. int disconnectedBots = 0;
  383. for (int i = m_bots.Count - 1; i >= 0; i--)
  384. {
  385. if (disconnectedBots >= botsToDisconnect)
  386. break;
  387. Bot thisBot = m_bots[i];
  388. if (thisBot.ConnectionState == ConnectionState.Connected)
  389. {
  390. Util.FireAndForget(o => thisBot.Disconnect());
  391. disconnectedBots++;
  392. }
  393. }
  394. DisconnectingBots = false;
  395. }
  396. }
  397. private void HandleSit(string module, string[] cmd)
  398. {
  399. lock (m_bots)
  400. {
  401. m_bots.ForEach(b => b.SitOnGround());
  402. }
  403. }
  404. private void HandleStand(string module, string[] cmd)
  405. {
  406. lock (m_bots)
  407. {
  408. m_bots.ForEach(b => b.Stand());
  409. }
  410. }
  411. private void HandleShutdown(string module, string[] cmd)
  412. {
  413. lock (m_bots)
  414. {
  415. int connectedBots = m_bots.Count(b => b.ConnectionState == ConnectionState.Connected);
  416. if (connectedBots > 0)
  417. {
  418. MainConsole.Instance.OutputFormat("Please disconnect {0} connected bots first", connectedBots);
  419. return;
  420. }
  421. }
  422. MainConsole.Instance.Output("Shutting down");
  423. Environment.Exit(0);
  424. }
  425. private void HandleShowRegions(string module, string[] cmd)
  426. {
  427. string outputFormat = "{0,-30} {1, -20} {2, -5} {3, -5}";
  428. MainConsole.Instance.OutputFormat(outputFormat, "Name", "Handle", "X", "Y");
  429. lock (RegionsKnown)
  430. {
  431. foreach (GridRegion region in RegionsKnown.Values)
  432. {
  433. MainConsole.Instance.OutputFormat(
  434. outputFormat, region.Name, region.RegionHandle, region.X, region.Y);
  435. }
  436. }
  437. }
  438. private void HandleShowBotsStatus(string module, string[] cmd)
  439. {
  440. ConsoleDisplayTable cdt = new ConsoleDisplayTable();
  441. cdt.AddColumn("Name", 30);
  442. cdt.AddColumn("Region", 30);
  443. cdt.AddColumn("Status", 14);
  444. cdt.AddColumn("Connections", 11);
  445. Dictionary<ConnectionState, int> totals = new Dictionary<ConnectionState, int>();
  446. foreach (object o in Enum.GetValues(typeof(ConnectionState)))
  447. totals[(ConnectionState)o] = 0;
  448. lock (m_bots)
  449. {
  450. foreach (Bot pb in m_bots)
  451. {
  452. Simulator currentSim = pb.Client.Network.CurrentSim;
  453. totals[pb.ConnectionState]++;
  454. cdt.AddRow(
  455. pb.Name, currentSim != null ? currentSim.Name : "(none)", pb.ConnectionState, pb.SimulatorsCount);
  456. }
  457. }
  458. MainConsole.Instance.Output(cdt.ToString());
  459. ConsoleDisplayList cdl = new ConsoleDisplayList();
  460. foreach (KeyValuePair<ConnectionState, int> kvp in totals)
  461. cdl.AddRow(kvp.Key, kvp.Value);
  462. MainConsole.Instance.Output(cdl.ToString());
  463. }
  464. private void HandleShowBotStatus(string module, string[] cmd)
  465. {
  466. if (cmd.Length != 4)
  467. {
  468. MainConsole.Instance.Output("Usage: show bot <first-name> <last-name>");
  469. return;
  470. }
  471. string name = string.Format("{0} {1}", cmd[2], cmd[3]);
  472. Bot bot;
  473. lock (m_bots)
  474. bot = m_bots.Find(b => b.Name == name);
  475. if (bot == null)
  476. {
  477. MainConsole.Instance.Output("No bot found with name {0}", name);
  478. return;
  479. }
  480. ConsoleDisplayList cdl = new ConsoleDisplayList();
  481. cdl.AddRow("Name", bot.Name);
  482. cdl.AddRow("Status", bot.ConnectionState);
  483. Simulator currentSim = bot.Client.Network.CurrentSim;
  484. cdl.AddRow("Region", currentSim != null ? currentSim.Name : "(none)");
  485. List<Simulator> connectedSimulators = bot.Simulators;
  486. List<string> simulatorNames = connectedSimulators.ConvertAll<string>(cs => cs.Name);
  487. cdl.AddRow("Connections", string.Join(", ", simulatorNames));
  488. MainConsole.Instance.Output(cdl.ToString());
  489. MainConsole.Instance.Output("Settings");
  490. ConsoleDisplayList statusCdl = new ConsoleDisplayList();
  491. GridClient botClient = bot.Client;
  492. statusCdl.AddRow("SEND_AGENT_UPDATES", botClient.Settings.SEND_AGENT_UPDATES);
  493. MainConsole.Instance.Output(statusCdl.ToString());
  494. }
  495. internal void Grid_GridRegion(object o, GridRegionEventArgs args)
  496. {
  497. lock (RegionsKnown)
  498. {
  499. GridRegion newRegion = args.Region;
  500. if (RegionsKnown.ContainsKey(newRegion.RegionHandle))
  501. {
  502. return;
  503. }
  504. else
  505. {
  506. m_log.DebugFormat(
  507. "[BOT MANAGER]: Adding {0} {1} to known regions", newRegion.Name, newRegion.RegionHandle);
  508. RegionsKnown[newRegion.RegionHandle] = newRegion;
  509. }
  510. }
  511. }
  512. }
  513. }