BotManager.cs 30 KB

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