BotManager.cs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848
  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_defaultBehaviourSwitches = 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. "Bots", false, "shutdown", "shutdown", "Shutdown bots and exit", HandleShutdown);
  152. m_console.Commands.AddCommand(
  153. "Bots", false, "quit", "quit", "Shutdown bots and exit", HandleShutdown);
  154. m_console.Commands.AddCommand(
  155. "Bots", 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. "Bots", 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. "Bots", false, "add behaviour", "add behaviour <abbreviated-name> [<bot-number>]",
  167. "Add a behaviour to a bot",
  168. "If no bot number is specified then behaviour is added to all bots.\n"
  169. + "Can be performed on connected or disconnected bots.",
  170. HandleAddBehaviour);
  171. m_console.Commands.AddCommand(
  172. "Bots", false, "remove behaviour", "remove behaviour <abbreviated-name> [<bot-number>]",
  173. "Remove a behaviour from a bot",
  174. "If no bot number is specified then behaviour is added to all bots.\n"
  175. + "Can be performed on connected or disconnected bots.",
  176. HandleRemoveBehaviour);
  177. m_console.Commands.AddCommand(
  178. "Bots", false, "sit", "sit", "Sit all bots on the ground.",
  179. HandleSit);
  180. m_console.Commands.AddCommand(
  181. "Bots", false, "stand", "stand", "Stand all bots.",
  182. HandleStand);
  183. m_console.Commands.AddCommand(
  184. "Bots", false, "set bots", "set bots <key> <value>", "Set a setting for all bots.", HandleSetBots);
  185. m_console.Commands.AddCommand(
  186. "Bots", false, "show regions", "show regions", "Show regions known to bots", HandleShowRegions);
  187. m_console.Commands.AddCommand(
  188. "Bots", false, "show bots", "show bots", "Shows the status of all bots", HandleShowBotsStatus);
  189. m_console.Commands.AddCommand(
  190. "Bots", false, "show bot", "show bot <bot-number>",
  191. "Shows the detailed status and settings of a particular bot.", HandleShowBotStatus);
  192. m_bots = new List<Bot>();
  193. }
  194. /// <summary>
  195. /// Startup number of bots specified in the starting arguments
  196. /// </summary>
  197. /// <param name="botcount">How many bots to start up</param>
  198. /// <param name="cs">The configuration for the bots to use</param>
  199. public void CreateBots(int botcount, IConfig startupConfig)
  200. {
  201. m_firstName = startupConfig.GetString("firstname");
  202. m_lastNameStem = startupConfig.GetString("lastname");
  203. m_password = startupConfig.GetString("password");
  204. m_loginUri = startupConfig.GetString("loginuri");
  205. m_fromBotNumber = startupConfig.GetInt("from", 0);
  206. m_wearSetting = startupConfig.GetString("wear", "no");
  207. m_startUri = ParseInputStartLocationToUri(startupConfig.GetString("start", "last"));
  208. Array.ForEach<string>(
  209. startupConfig.GetString("behaviours", "p").Split(new char[] { ',' }), b => m_defaultBehaviourSwitches.Add(b));
  210. for (int i = 0; i < botcount; i++)
  211. {
  212. lock (m_bots)
  213. {
  214. string lastName = string.Format("{0}_{1}", m_lastNameStem, i + m_fromBotNumber);
  215. CreateBot(
  216. this,
  217. CreateBehavioursFromAbbreviatedNames(m_defaultBehaviourSwitches),
  218. m_firstName, lastName, m_password, m_loginUri, m_startUri, m_wearSetting);
  219. }
  220. }
  221. }
  222. private List<IBehaviour> CreateBehavioursFromAbbreviatedNames(HashSet<string> abbreviatedNames)
  223. {
  224. // We must give each bot its own list of instantiated behaviours since they store state.
  225. List<IBehaviour> behaviours = new List<IBehaviour>();
  226. // Hard-coded for now
  227. foreach (string abName in abbreviatedNames)
  228. {
  229. IBehaviour newBehaviour = null;
  230. if (abName == "c")
  231. newBehaviour = new CrossBehaviour();
  232. if (abName == "g")
  233. newBehaviour = new GrabbingBehaviour();
  234. if (abName == "n")
  235. newBehaviour = new NoneBehaviour();
  236. if (abName == "p")
  237. newBehaviour = new PhysicsBehaviour();
  238. if (abName == "t")
  239. newBehaviour = new TeleportBehaviour();
  240. if (newBehaviour != null)
  241. {
  242. behaviours.Add(newBehaviour);
  243. }
  244. else
  245. {
  246. MainConsole.Instance.OutputFormat("No behaviour with abbreviated name {0} found", abName);
  247. }
  248. }
  249. return behaviours;
  250. }
  251. public void ConnectBots(int botcount)
  252. {
  253. ConnectingBots = true;
  254. Thread connectBotThread = new Thread(o => ConnectBotsInternal(botcount));
  255. connectBotThread.Name = "Bots connection thread";
  256. connectBotThread.Start();
  257. }
  258. private void ConnectBotsInternal(int botCount)
  259. {
  260. MainConsole.Instance.OutputFormat(
  261. "[BOT MANAGER]: Starting {0} bots connecting to {1}, location {2}, named {3} {4}_<n>",
  262. botCount,
  263. m_loginUri,
  264. m_startUri,
  265. m_firstName,
  266. m_lastNameStem);
  267. MainConsole.Instance.OutputFormat("[BOT MANAGER]: Delay between logins is {0}ms", LoginDelay);
  268. MainConsole.Instance.OutputFormat("[BOT MANAGER]: BotsSendAgentUpdates is {0}", InitBotSendAgentUpdates);
  269. MainConsole.Instance.OutputFormat("[BOT MANAGER]: InitBotRequestObjectTextures is {0}", InitBotRequestObjectTextures);
  270. int connectedBots = 0;
  271. for (int i = 0; i < m_bots.Count; i++)
  272. {
  273. lock (m_bots)
  274. {
  275. if (DisconnectingBots)
  276. {
  277. MainConsole.Instance.Output(
  278. "[BOT MANAGER]: Aborting bot connection due to user-initiated disconnection");
  279. break;
  280. }
  281. if (m_bots[i].ConnectionState == ConnectionState.Disconnected)
  282. {
  283. m_bots[i].Connect();
  284. connectedBots++;
  285. if (connectedBots >= botCount)
  286. break;
  287. // Stagger logins
  288. Thread.Sleep(LoginDelay);
  289. }
  290. }
  291. }
  292. ConnectingBots = false;
  293. }
  294. /// <summary>
  295. /// Parses the command line start location to a start string/uri that the login mechanism will recognize.
  296. /// </summary>
  297. /// <returns>
  298. /// The input start location to URI.
  299. /// </returns>
  300. /// <param name='startLocation'>
  301. /// Start location.
  302. /// </param>
  303. private string ParseInputStartLocationToUri(string startLocation)
  304. {
  305. if (startLocation == "home" || startLocation == "last")
  306. return startLocation;
  307. string regionName;
  308. // Just a region name or only one (!) extra component. Like a viewer, we will stick 128/128/0 on the end
  309. Vector3 startPos = new Vector3(128, 128, 0);
  310. string[] startLocationComponents = startLocation.Split('/');
  311. regionName = startLocationComponents[0];
  312. if (startLocationComponents.Length >= 2)
  313. {
  314. float.TryParse(startLocationComponents[1], out startPos.X);
  315. if (startLocationComponents.Length >= 3)
  316. {
  317. float.TryParse(startLocationComponents[2], out startPos.Y);
  318. if (startLocationComponents.Length >= 4)
  319. float.TryParse(startLocationComponents[3], out startPos.Z);
  320. }
  321. }
  322. return string.Format("uri:{0}&{1}&{2}&{3}", regionName, startPos.X, startPos.Y, startPos.Z);
  323. }
  324. /// <summary>
  325. /// This creates a bot but does not start it.
  326. /// </summary>
  327. /// <param name="bm"></param>
  328. /// <param name="behaviours">Behaviours for this bot to perform.</param>
  329. /// <param name="firstName">First name</param>
  330. /// <param name="lastName">Last name</param>
  331. /// <param name="password">Password</param>
  332. /// <param name="loginUri">Login URI</param>
  333. /// <param name="startLocation">Location to start the bot. Can be "last", "home" or a specific sim name.</param>
  334. /// <param name="wearSetting"></param>
  335. public void CreateBot(
  336. BotManager bm, List<IBehaviour> behaviours,
  337. string firstName, string lastName, string password, string loginUri, string startLocation, string wearSetting)
  338. {
  339. MainConsole.Instance.OutputFormat(
  340. "[BOT MANAGER]: Creating bot {0} {1}, behaviours are {2}",
  341. firstName, lastName, string.Join(",", behaviours.ConvertAll<string>(b => b.Name).ToArray()));
  342. Bot pb = new Bot(bm, behaviours, firstName, lastName, password, startLocation, loginUri);
  343. pb.wear = wearSetting;
  344. pb.Client.Settings.SEND_AGENT_UPDATES = InitBotSendAgentUpdates;
  345. pb.RequestObjectTextures = InitBotRequestObjectTextures;
  346. pb.OnConnected += handlebotEvent;
  347. pb.OnDisconnected += handlebotEvent;
  348. m_bots.Add(pb);
  349. }
  350. /// <summary>
  351. /// High level connnected/disconnected events so we can keep track of our threads by proxy
  352. /// </summary>
  353. /// <param name="callbot"></param>
  354. /// <param name="eventt"></param>
  355. private void handlebotEvent(Bot callbot, EventType eventt)
  356. {
  357. switch (eventt)
  358. {
  359. case EventType.CONNECTED:
  360. {
  361. m_log.Info("[" + callbot.FirstName + " " + callbot.LastName + "]: Connected");
  362. break;
  363. }
  364. case EventType.DISCONNECTED:
  365. {
  366. m_log.Info("[" + callbot.FirstName + " " + callbot.LastName + "]: Disconnected");
  367. break;
  368. }
  369. }
  370. }
  371. /// <summary>
  372. /// Standard CreateConsole routine
  373. /// </summary>
  374. /// <returns></returns>
  375. protected CommandConsole CreateConsole()
  376. {
  377. return new LocalConsole("pCampbot");
  378. }
  379. private void HandleConnect(string module, string[] cmd)
  380. {
  381. if (ConnectingBots)
  382. {
  383. MainConsole.Instance.Output("Still connecting bots. Please wait for previous process to complete.");
  384. return;
  385. }
  386. lock (m_bots)
  387. {
  388. int botsToConnect;
  389. int disconnectedBots = m_bots.Count(b => b.ConnectionState == ConnectionState.Disconnected);
  390. if (cmd.Length == 1)
  391. {
  392. botsToConnect = disconnectedBots;
  393. }
  394. else
  395. {
  396. if (!ConsoleUtil.TryParseConsoleNaturalInt(MainConsole.Instance, cmd[1], out botsToConnect))
  397. return;
  398. botsToConnect = Math.Min(botsToConnect, disconnectedBots);
  399. }
  400. MainConsole.Instance.OutputFormat("Connecting {0} bots", botsToConnect);
  401. ConnectBots(botsToConnect);
  402. }
  403. }
  404. private void HandleAddBehaviour(string module, string[] cmd)
  405. {
  406. if (cmd.Length < 3 || cmd.Length > 4)
  407. {
  408. MainConsole.Instance.OutputFormat("Usage: add behaviour <abbreviated-behaviour> [<bot-number>]");
  409. return;
  410. }
  411. string rawBehaviours = cmd[2];
  412. List<Bot> botsToEffect = new List<Bot>();
  413. if (cmd.Length == 3)
  414. {
  415. lock (m_bots)
  416. botsToEffect.AddRange(m_bots);
  417. }
  418. else
  419. {
  420. int botNumber;
  421. if (!ConsoleUtil.TryParseConsoleNaturalInt(MainConsole.Instance, cmd[3], out botNumber))
  422. return;
  423. Bot bot = GetBotFromNumber(botNumber);
  424. if (bot == null)
  425. {
  426. MainConsole.Instance.OutputFormat("Error: No bot found with number {0}", botNumber);
  427. return;
  428. }
  429. botsToEffect.Add(bot);
  430. }
  431. HashSet<string> rawAbbreviatedSwitchesToAdd = new HashSet<string>();
  432. Array.ForEach<string>(rawBehaviours.Split(new char[] { ',' }), b => rawAbbreviatedSwitchesToAdd.Add(b));
  433. foreach (Bot bot in botsToEffect)
  434. {
  435. List<IBehaviour> behavioursAdded = new List<IBehaviour>();
  436. foreach (IBehaviour behaviour in CreateBehavioursFromAbbreviatedNames(rawAbbreviatedSwitchesToAdd))
  437. {
  438. if (bot.AddBehaviour(behaviour))
  439. behavioursAdded.Add(behaviour);
  440. }
  441. MainConsole.Instance.OutputFormat(
  442. "Added behaviours {0} to bot {1}",
  443. string.Join(", ", behavioursAdded.ConvertAll<string>(b => b.Name).ToArray()), bot.Name);
  444. }
  445. }
  446. private void HandleRemoveBehaviour(string module, string[] cmd)
  447. {
  448. if (cmd.Length < 3 || cmd.Length > 4)
  449. {
  450. MainConsole.Instance.OutputFormat("Usage: remove behaviour <abbreviated-behaviour> [<bot-number>]");
  451. return;
  452. }
  453. string rawBehaviours = cmd[2];
  454. List<Bot> botsToEffect = new List<Bot>();
  455. if (cmd.Length == 3)
  456. {
  457. lock (m_bots)
  458. botsToEffect.AddRange(m_bots);
  459. }
  460. else
  461. {
  462. int botNumber;
  463. if (!ConsoleUtil.TryParseConsoleNaturalInt(MainConsole.Instance, cmd[3], out botNumber))
  464. return;
  465. Bot bot = GetBotFromNumber(botNumber);
  466. if (bot == null)
  467. {
  468. MainConsole.Instance.OutputFormat("Error: No bot found with number {0}", botNumber);
  469. return;
  470. }
  471. botsToEffect.Add(bot);
  472. }
  473. HashSet<string> abbreviatedBehavioursToRemove = new HashSet<string>();
  474. Array.ForEach<string>(rawBehaviours.Split(new char[] { ',' }), b => abbreviatedBehavioursToRemove.Add(b));
  475. foreach (Bot bot in botsToEffect)
  476. {
  477. List<IBehaviour> behavioursRemoved = new List<IBehaviour>();
  478. foreach (string b in abbreviatedBehavioursToRemove)
  479. {
  480. IBehaviour behaviour;
  481. if (bot.TryGetBehaviour(b, out behaviour))
  482. {
  483. bot.RemoveBehaviour(b);
  484. behavioursRemoved.Add(behaviour);
  485. }
  486. }
  487. MainConsole.Instance.OutputFormat(
  488. "Removed behaviours {0} to bot {1}",
  489. string.Join(", ", behavioursRemoved.ConvertAll<string>(b => b.Name).ToArray()), bot.Name);
  490. }
  491. }
  492. private void HandleDisconnect(string module, string[] cmd)
  493. {
  494. lock (m_bots)
  495. {
  496. int botsToDisconnect;
  497. int connectedBots = m_bots.Count(b => b.ConnectionState == ConnectionState.Connected);
  498. if (cmd.Length == 1)
  499. {
  500. botsToDisconnect = connectedBots;
  501. }
  502. else
  503. {
  504. if (!ConsoleUtil.TryParseConsoleNaturalInt(MainConsole.Instance, cmd[1], out botsToDisconnect))
  505. return;
  506. botsToDisconnect = Math.Min(botsToDisconnect, connectedBots);
  507. }
  508. DisconnectingBots = true;
  509. MainConsole.Instance.OutputFormat("Disconnecting {0} bots", botsToDisconnect);
  510. int disconnectedBots = 0;
  511. for (int i = m_bots.Count - 1; i >= 0; i--)
  512. {
  513. if (disconnectedBots >= botsToDisconnect)
  514. break;
  515. Bot thisBot = m_bots[i];
  516. if (thisBot.ConnectionState == ConnectionState.Connected)
  517. {
  518. Util.FireAndForget(o => thisBot.Disconnect());
  519. disconnectedBots++;
  520. }
  521. }
  522. DisconnectingBots = false;
  523. }
  524. }
  525. private void HandleSit(string module, string[] cmd)
  526. {
  527. lock (m_bots)
  528. {
  529. m_bots.ForEach(b => b.SitOnGround());
  530. }
  531. }
  532. private void HandleStand(string module, string[] cmd)
  533. {
  534. lock (m_bots)
  535. {
  536. m_bots.ForEach(b => b.Stand());
  537. }
  538. }
  539. private void HandleShutdown(string module, string[] cmd)
  540. {
  541. lock (m_bots)
  542. {
  543. int connectedBots = m_bots.Count(b => b.ConnectionState == ConnectionState.Connected);
  544. if (connectedBots > 0)
  545. {
  546. MainConsole.Instance.OutputFormat("Please disconnect {0} connected bots first", connectedBots);
  547. return;
  548. }
  549. }
  550. MainConsole.Instance.Output("Shutting down");
  551. Environment.Exit(0);
  552. }
  553. private void HandleSetBots(string module, string[] cmd)
  554. {
  555. string key = cmd[2];
  556. string rawValue = cmd[3];
  557. if (key == "SEND_AGENT_UPDATES")
  558. {
  559. bool newSendAgentUpdatesSetting;
  560. if (!ConsoleUtil.TryParseConsoleBool(MainConsole.Instance, rawValue, out newSendAgentUpdatesSetting))
  561. return;
  562. MainConsole.Instance.OutputFormat(
  563. "Setting SEND_AGENT_UPDATES to {0} for all bots", newSendAgentUpdatesSetting);
  564. lock (m_bots)
  565. m_bots.ForEach(b => b.Client.Settings.SEND_AGENT_UPDATES = newSendAgentUpdatesSetting);
  566. }
  567. else
  568. {
  569. MainConsole.Instance.Output("Error: Only setting currently available is SEND_AGENT_UPDATES");
  570. }
  571. }
  572. private void HandleShowRegions(string module, string[] cmd)
  573. {
  574. string outputFormat = "{0,-30} {1, -20} {2, -5} {3, -5}";
  575. MainConsole.Instance.OutputFormat(outputFormat, "Name", "Handle", "X", "Y");
  576. lock (RegionsKnown)
  577. {
  578. foreach (GridRegion region in RegionsKnown.Values)
  579. {
  580. MainConsole.Instance.OutputFormat(
  581. outputFormat, region.Name, region.RegionHandle, region.X, region.Y);
  582. }
  583. }
  584. }
  585. private void HandleShowBotsStatus(string module, string[] cmd)
  586. {
  587. ConsoleDisplayTable cdt = new ConsoleDisplayTable();
  588. cdt.AddColumn("Name", 24);
  589. cdt.AddColumn("Region", 24);
  590. cdt.AddColumn("Status", 13);
  591. cdt.AddColumn("Conns", 5);
  592. cdt.AddColumn("Behaviours", 20);
  593. Dictionary<ConnectionState, int> totals = new Dictionary<ConnectionState, int>();
  594. foreach (object o in Enum.GetValues(typeof(ConnectionState)))
  595. totals[(ConnectionState)o] = 0;
  596. lock (m_bots)
  597. {
  598. foreach (Bot bot in m_bots)
  599. {
  600. Simulator currentSim = bot.Client.Network.CurrentSim;
  601. totals[bot.ConnectionState]++;
  602. cdt.AddRow(
  603. bot.Name,
  604. currentSim != null ? currentSim.Name : "(none)",
  605. bot.ConnectionState,
  606. bot.SimulatorsCount,
  607. string.Join(",", bot.Behaviours.Keys.ToArray()));
  608. }
  609. }
  610. MainConsole.Instance.Output(cdt.ToString());
  611. ConsoleDisplayList cdl = new ConsoleDisplayList();
  612. foreach (KeyValuePair<ConnectionState, int> kvp in totals)
  613. cdl.AddRow(kvp.Key, kvp.Value);
  614. MainConsole.Instance.Output(cdl.ToString());
  615. }
  616. private void HandleShowBotStatus(string module, string[] cmd)
  617. {
  618. if (cmd.Length != 3)
  619. {
  620. MainConsole.Instance.Output("Usage: show bot <n>");
  621. return;
  622. }
  623. int botNumber;
  624. if (!ConsoleUtil.TryParseConsoleInt(MainConsole.Instance, cmd[2], out botNumber))
  625. return;
  626. Bot bot = GetBotFromNumber(botNumber);
  627. if (bot == null)
  628. {
  629. MainConsole.Instance.OutputFormat("Error: No bot found with number {0}", botNumber);
  630. return;
  631. }
  632. ConsoleDisplayList cdl = new ConsoleDisplayList();
  633. cdl.AddRow("Name", bot.Name);
  634. cdl.AddRow("Status", bot.ConnectionState);
  635. Simulator currentSim = bot.Client.Network.CurrentSim;
  636. cdl.AddRow("Region", currentSim != null ? currentSim.Name : "(none)");
  637. List<Simulator> connectedSimulators = bot.Simulators;
  638. List<string> simulatorNames = connectedSimulators.ConvertAll<string>(cs => cs.Name);
  639. cdl.AddRow("Connections", string.Join(", ", simulatorNames.ToArray()));
  640. MainConsole.Instance.Output(cdl.ToString());
  641. MainConsole.Instance.Output("Settings");
  642. ConsoleDisplayList statusCdl = new ConsoleDisplayList();
  643. statusCdl.AddRow(
  644. "Behaviours",
  645. string.Join(", ", bot.Behaviours.Values.ToList().ConvertAll<string>(b => b.Name).ToArray()));
  646. GridClient botClient = bot.Client;
  647. statusCdl.AddRow("SEND_AGENT_UPDATES", botClient.Settings.SEND_AGENT_UPDATES);
  648. MainConsole.Instance.Output(statusCdl.ToString());
  649. }
  650. /// <summary>
  651. /// Get a specific bot from its number.
  652. /// </summary>
  653. /// <returns>null if no bot was found</returns>
  654. /// <param name='botNumber'></param>
  655. private Bot GetBotFromNumber(int botNumber)
  656. {
  657. string name = GenerateBotNameFromNumber(botNumber);
  658. Bot bot;
  659. lock (m_bots)
  660. bot = m_bots.Find(b => b.Name == name);
  661. return bot;
  662. }
  663. private string GenerateBotNameFromNumber(int botNumber)
  664. {
  665. return string.Format("{0} {1}_{2}", m_firstName, m_lastNameStem, botNumber);
  666. }
  667. internal void Grid_GridRegion(object o, GridRegionEventArgs args)
  668. {
  669. lock (RegionsKnown)
  670. {
  671. GridRegion newRegion = args.Region;
  672. if (RegionsKnown.ContainsKey(newRegion.RegionHandle))
  673. {
  674. return;
  675. }
  676. else
  677. {
  678. m_log.DebugFormat(
  679. "[BOT MANAGER]: Adding {0} {1} to known regions", newRegion.Name, newRegion.RegionHandle);
  680. RegionsKnown[newRegion.RegionHandle] = newRegion;
  681. }
  682. }
  683. }
  684. }
  685. }