BotManager.cs 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986
  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 OpenSim.Framework.Monitoring;
  41. using pCampBot.Interfaces;
  42. namespace pCampBot
  43. {
  44. public enum BotManagerBotConnectingState
  45. {
  46. Initializing,
  47. Ready,
  48. Connecting,
  49. Disconnecting
  50. }
  51. /// <summary>
  52. /// Thread/Bot manager for the application
  53. /// </summary>
  54. public class BotManager
  55. {
  56. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  57. public const int DefaultLoginDelay = 5000;
  58. /// <summary>
  59. /// Is pCampbot ready to connect or currently in the process of connecting or disconnecting bots?
  60. /// </summary>
  61. public BotManagerBotConnectingState BotConnectingState { get; private set; }
  62. /// <summary>
  63. /// Used to control locking as we can't lock an enum.
  64. /// </summary>
  65. private object BotConnectingStateChangeObject = new object();
  66. /// <summary>
  67. /// Delay between logins of multiple bots.
  68. /// </summary>
  69. /// <remarks>TODO: This value needs to be configurable by a command line argument.</remarks>
  70. public int LoginDelay { get; set; }
  71. /// <summary>
  72. /// Command console
  73. /// </summary>
  74. protected CommandConsole m_console;
  75. /// <summary>
  76. /// Controls whether bots start out sending agent updates on connection.
  77. /// </summary>
  78. public bool InitBotSendAgentUpdates { get; set; }
  79. /// <summary>
  80. /// Controls whether bots request textures for the object information they receive
  81. /// </summary>
  82. public bool InitBotRequestObjectTextures { get; set; }
  83. /// <summary>
  84. /// Created bots, whether active or inactive.
  85. /// </summary>
  86. protected List<Bot> m_bots;
  87. /// <summary>
  88. /// Random number generator.
  89. /// </summary>
  90. public Random Rng { get; private set; }
  91. /// <summary>
  92. /// Track the assets we have and have not received so we don't endlessly repeat requests.
  93. /// </summary>
  94. public Dictionary<UUID, bool> AssetsReceived { get; private set; }
  95. /// <summary>
  96. /// The regions that we know about.
  97. /// </summary>
  98. public Dictionary<ulong, GridRegion> RegionsKnown { get; private set; }
  99. /// <summary>
  100. /// First name for bots
  101. /// </summary>
  102. private string m_firstName;
  103. /// <summary>
  104. /// Last name stem for bots
  105. /// </summary>
  106. private string m_lastNameStem;
  107. /// <summary>
  108. /// Password for bots
  109. /// </summary>
  110. private string m_password;
  111. /// <summary>
  112. /// Login URI for bots.
  113. /// </summary>
  114. private string m_loginUri;
  115. /// <summary>
  116. /// Start location for bots.
  117. /// </summary>
  118. private string m_startUri;
  119. /// <summary>
  120. /// Postfix bot number at which bot sequence starts.
  121. /// </summary>
  122. private int m_fromBotNumber;
  123. /// <summary>
  124. /// Wear setting for bots.
  125. /// </summary>
  126. private string m_wearSetting;
  127. /// <summary>
  128. /// Behaviour switches for bots.
  129. /// </summary>
  130. private HashSet<string> m_defaultBehaviourSwitches = new HashSet<string>();
  131. /// <summary>
  132. /// Collects general information on this server (which reveals this to be a misnamed class).
  133. /// </summary>
  134. private ServerStatsCollector m_serverStatsCollector;
  135. /// <summary>
  136. /// Constructor Creates MainConsole.Instance to take commands and provide the place to write data
  137. /// </summary>
  138. public BotManager()
  139. {
  140. // We set this to avoid issues with bots running out of HTTP connections if many are run from a single machine
  141. // to multiple regions.
  142. Settings.MAX_HTTP_CONNECTIONS = int.MaxValue;
  143. // System.Threading.ThreadPool.SetMaxThreads(600, 240);
  144. //
  145. // int workerThreads, iocpThreads;
  146. // System.Threading.ThreadPool.GetMaxThreads(out workerThreads, out iocpThreads);
  147. // Console.WriteLine("ThreadPool.GetMaxThreads {0} {1}", workerThreads, iocpThreads);
  148. InitBotSendAgentUpdates = true;
  149. InitBotRequestObjectTextures = true;
  150. LoginDelay = DefaultLoginDelay;
  151. Rng = new Random(Environment.TickCount);
  152. AssetsReceived = new Dictionary<UUID, bool>();
  153. RegionsKnown = new Dictionary<ulong, GridRegion>();
  154. m_console = CreateConsole();
  155. MainConsole.Instance = m_console;
  156. // Make log4net see the console
  157. //
  158. ILoggerRepository repository = LogManager.GetRepository();
  159. IAppender[] appenders = repository.GetAppenders();
  160. OpenSimAppender consoleAppender = null;
  161. foreach (IAppender appender in appenders)
  162. {
  163. if (appender.Name == "Console")
  164. {
  165. consoleAppender = (OpenSimAppender)appender;
  166. consoleAppender.Console = m_console;
  167. break;
  168. }
  169. }
  170. m_console.Commands.AddCommand(
  171. "Bots", false, "shutdown", "shutdown", "Shutdown bots and exit", HandleShutdown);
  172. m_console.Commands.AddCommand(
  173. "Bots", false, "quit", "quit", "Shutdown bots and exit", HandleShutdown);
  174. m_console.Commands.AddCommand(
  175. "Bots", false, "connect", "connect [<n>]", "Connect bots",
  176. "If an <n> is given, then the first <n> disconnected bots by postfix number are connected.\n"
  177. + "If no <n> is given, then all currently disconnected bots are connected.",
  178. HandleConnect);
  179. m_console.Commands.AddCommand(
  180. "Bots", false, "disconnect", "disconnect [<n>]", "Disconnect bots",
  181. "Disconnecting bots will interupt any bot connection process, including connection on startup.\n"
  182. + "If an <n> is given, then the last <n> connected bots by postfix number are disconnected.\n"
  183. + "If no <n> is given, then all currently connected bots are disconnected.",
  184. HandleDisconnect);
  185. m_console.Commands.AddCommand(
  186. "Bots", false, "add behaviour", "add behaviour <abbreviated-name> [<bot-number>]",
  187. "Add a behaviour to a bot",
  188. "If no bot number is specified then behaviour is added to all bots.\n"
  189. + "Can be performed on connected or disconnected bots.",
  190. HandleAddBehaviour);
  191. m_console.Commands.AddCommand(
  192. "Bots", false, "remove behaviour", "remove behaviour <abbreviated-name> [<bot-number>]",
  193. "Remove a behaviour from a bot",
  194. "If no bot number is specified then behaviour is added to all bots.\n"
  195. + "Can be performed on connected or disconnected bots.",
  196. HandleRemoveBehaviour);
  197. m_console.Commands.AddCommand(
  198. "Bots", false, "sit", "sit", "Sit all bots on the ground.",
  199. HandleSit);
  200. m_console.Commands.AddCommand(
  201. "Bots", false, "stand", "stand", "Stand all bots.",
  202. HandleStand);
  203. m_console.Commands.AddCommand(
  204. "Bots", false, "set bots", "set bots <key> <value>", "Set a setting for all bots.", HandleSetBots);
  205. m_console.Commands.AddCommand(
  206. "Bots", false, "show regions", "show regions", "Show regions known to bots", HandleShowRegions);
  207. m_console.Commands.AddCommand(
  208. "Bots", false, "show bots", "show bots", "Shows the status of all bots.", HandleShowBotsStatus);
  209. m_console.Commands.AddCommand(
  210. "Bots", false, "show bot", "show bot <bot-number>",
  211. "Shows the detailed status and settings of a particular bot.", HandleShowBotStatus);
  212. m_console.Commands.AddCommand(
  213. "Debug",
  214. false,
  215. "debug lludp packet",
  216. "debug lludp packet <level> <avatar-first-name> <avatar-last-name>",
  217. "Turn on received packet logging.",
  218. "If level > 0 then all received packets that are not duplicates are logged.\n"
  219. + "If level <= 0 then no received packets are logged.",
  220. HandleDebugLludpPacketCommand);
  221. m_console.Commands.AddCommand(
  222. "Bots", false, "show status", "show status", "Shows pCampbot status.", HandleShowStatus);
  223. m_bots = new List<Bot>();
  224. Watchdog.Enabled = true;
  225. StatsManager.RegisterConsoleCommands(m_console);
  226. m_serverStatsCollector = new ServerStatsCollector();
  227. m_serverStatsCollector.Initialise(null);
  228. m_serverStatsCollector.Enabled = true;
  229. m_serverStatsCollector.Start();
  230. BotConnectingState = BotManagerBotConnectingState.Ready;
  231. }
  232. /// <summary>
  233. /// Startup number of bots specified in the starting arguments
  234. /// </summary>
  235. /// <param name="botcount">How many bots to start up</param>
  236. /// <param name="cs">The configuration for the bots to use</param>
  237. public void CreateBots(int botcount, IConfig startupConfig)
  238. {
  239. m_firstName = startupConfig.GetString("firstname");
  240. m_lastNameStem = startupConfig.GetString("lastname");
  241. m_password = startupConfig.GetString("password");
  242. m_loginUri = startupConfig.GetString("loginuri");
  243. m_fromBotNumber = startupConfig.GetInt("from", 0);
  244. m_wearSetting = startupConfig.GetString("wear", "no");
  245. m_startUri = ParseInputStartLocationToUri(startupConfig.GetString("start", "last"));
  246. Array.ForEach<string>(
  247. startupConfig.GetString("behaviours", "p").Split(new char[] { ',' }), b => m_defaultBehaviourSwitches.Add(b));
  248. for (int i = 0; i < botcount; i++)
  249. {
  250. lock (m_bots)
  251. {
  252. string lastName = string.Format("{0}{1}", m_lastNameStem, i + m_fromBotNumber);
  253. CreateBot(
  254. this,
  255. CreateBehavioursFromAbbreviatedNames(m_defaultBehaviourSwitches),
  256. m_firstName, lastName, m_password, m_loginUri, m_startUri, m_wearSetting);
  257. }
  258. }
  259. }
  260. private List<IBehaviour> CreateBehavioursFromAbbreviatedNames(HashSet<string> abbreviatedNames)
  261. {
  262. // We must give each bot its own list of instantiated behaviours since they store state.
  263. List<IBehaviour> behaviours = new List<IBehaviour>();
  264. // Hard-coded for now
  265. foreach (string abName in abbreviatedNames)
  266. {
  267. IBehaviour newBehaviour = null;
  268. if (abName == "c")
  269. newBehaviour = new CrossBehaviour();
  270. if (abName == "g")
  271. newBehaviour = new GrabbingBehaviour();
  272. if (abName == "n")
  273. newBehaviour = new NoneBehaviour();
  274. if (abName == "p")
  275. newBehaviour = new PhysicsBehaviour();
  276. if (abName == "t")
  277. newBehaviour = new TeleportBehaviour();
  278. if (abName == "tw")
  279. newBehaviour = new TwitchyBehaviour();
  280. if (abName == "ph2")
  281. newBehaviour = new PhysicsBehaviour2();
  282. if (abName == "inv")
  283. newBehaviour = new InventoryDownloadBehaviour();
  284. if (newBehaviour != null)
  285. {
  286. behaviours.Add(newBehaviour);
  287. }
  288. else
  289. {
  290. MainConsole.Instance.Output("No behaviour with abbreviated name {0} found", null, abName);
  291. }
  292. }
  293. return behaviours;
  294. }
  295. public void ConnectBots(int botcount)
  296. {
  297. lock (BotConnectingStateChangeObject)
  298. {
  299. if (BotConnectingState != BotManagerBotConnectingState.Ready)
  300. {
  301. MainConsole.Instance.Output(
  302. "Bot connecting status is {0}. Please wait for previous process to complete.", null, BotConnectingState);
  303. return;
  304. }
  305. BotConnectingState = BotManagerBotConnectingState.Connecting;
  306. }
  307. Thread connectBotThread = new Thread(o => ConnectBotsInternal(botcount));
  308. connectBotThread.Name = "Bots connection thread";
  309. connectBotThread.Start();
  310. }
  311. private void ConnectBotsInternal(int botCount)
  312. {
  313. m_log.InfoFormat(
  314. "[BOT MANAGER]: Starting {0} bots connecting to {1}, location {2}, named {3} {4}_<n>",
  315. botCount,
  316. m_loginUri,
  317. m_startUri,
  318. m_firstName,
  319. m_lastNameStem);
  320. m_log.DebugFormat("[BOT MANAGER]: Delay between logins is {0}ms", LoginDelay);
  321. m_log.DebugFormat("[BOT MANAGER]: BotsSendAgentUpdates is {0}", InitBotSendAgentUpdates);
  322. m_log.DebugFormat("[BOT MANAGER]: InitBotRequestObjectTextures is {0}", InitBotRequestObjectTextures);
  323. List<Bot> botsToConnect = new List<Bot>();
  324. lock (m_bots)
  325. {
  326. foreach (Bot bot in m_bots)
  327. {
  328. if (bot.ConnectionState == ConnectionState.Disconnected)
  329. botsToConnect.Add(bot);
  330. if (botsToConnect.Count >= botCount)
  331. break;
  332. }
  333. }
  334. foreach (Bot bot in botsToConnect)
  335. {
  336. lock (BotConnectingStateChangeObject)
  337. {
  338. if (BotConnectingState != BotManagerBotConnectingState.Connecting)
  339. {
  340. MainConsole.Instance.Output(
  341. "[BOT MANAGER]: Aborting bot connection due to user-initiated disconnection");
  342. return;
  343. }
  344. }
  345. bot.Connect();
  346. // Stagger logins
  347. Thread.Sleep(LoginDelay);
  348. }
  349. lock (BotConnectingStateChangeObject)
  350. {
  351. if (BotConnectingState == BotManagerBotConnectingState.Connecting)
  352. BotConnectingState = BotManagerBotConnectingState.Ready;
  353. }
  354. }
  355. /// <summary>
  356. /// Parses the command line start location to a start string/uri that the login mechanism will recognize.
  357. /// </summary>
  358. /// <returns>
  359. /// The input start location to URI.
  360. /// </returns>
  361. /// <param name='startLocation'>
  362. /// Start location.
  363. /// </param>
  364. private string ParseInputStartLocationToUri(string startLocation)
  365. {
  366. if (startLocation == "home" || startLocation == "last")
  367. return startLocation;
  368. string regionName;
  369. // Just a region name or only one (!) extra component. Like a viewer, we will stick 128/128/0 on the end
  370. Vector3 startPos = new Vector3(128, 128, 0);
  371. string[] startLocationComponents = startLocation.Split('/');
  372. regionName = startLocationComponents[0];
  373. if (startLocationComponents.Length >= 2)
  374. {
  375. float.TryParse(startLocationComponents[1], out startPos.X);
  376. if (startLocationComponents.Length >= 3)
  377. {
  378. float.TryParse(startLocationComponents[2], out startPos.Y);
  379. if (startLocationComponents.Length >= 4)
  380. float.TryParse(startLocationComponents[3], out startPos.Z);
  381. }
  382. }
  383. return string.Format("uri:{0}&{1}&{2}&{3}", regionName, startPos.X, startPos.Y, startPos.Z);
  384. }
  385. /// <summary>
  386. /// This creates a bot but does not start it.
  387. /// </summary>
  388. /// <param name="bm"></param>
  389. /// <param name="behaviours">Behaviours for this bot to perform.</param>
  390. /// <param name="firstName">First name</param>
  391. /// <param name="lastName">Last name</param>
  392. /// <param name="password">Password</param>
  393. /// <param name="loginUri">Login URI</param>
  394. /// <param name="startLocation">Location to start the bot. Can be "last", "home" or a specific sim name.</param>
  395. /// <param name="wearSetting"></param>
  396. public void CreateBot(
  397. BotManager bm, List<IBehaviour> behaviours,
  398. string firstName, string lastName, string password, string loginUri, string startLocation, string wearSetting)
  399. {
  400. MainConsole.Instance.Output(
  401. "[BOT MANAGER]: Creating bot {0} {1}, behaviours are {2}",
  402. null,
  403. firstName, lastName, string.Join(",", behaviours.ConvertAll<string>(b => b.Name).ToArray()));
  404. Bot pb = new Bot(bm, behaviours, firstName, lastName, password, startLocation, loginUri);
  405. pb.wear = wearSetting;
  406. pb.Client.Settings.SEND_AGENT_UPDATES = InitBotSendAgentUpdates;
  407. pb.RequestObjectTextures = InitBotRequestObjectTextures;
  408. pb.OnConnected += handlebotEvent;
  409. pb.OnDisconnected += handlebotEvent;
  410. m_bots.Add(pb);
  411. }
  412. /// <summary>
  413. /// High level connnected/disconnected events so we can keep track of our threads by proxy
  414. /// </summary>
  415. /// <param name="callbot"></param>
  416. /// <param name="eventt"></param>
  417. private void handlebotEvent(Bot callbot, EventType eventt)
  418. {
  419. switch (eventt)
  420. {
  421. case EventType.CONNECTED:
  422. {
  423. m_log.Info("[" + callbot.FirstName + " " + callbot.LastName + "]: Connected");
  424. break;
  425. }
  426. case EventType.DISCONNECTED:
  427. {
  428. m_log.Info("[" + callbot.FirstName + " " + callbot.LastName + "]: Disconnected");
  429. break;
  430. }
  431. }
  432. }
  433. /// <summary>
  434. /// Standard CreateConsole routine
  435. /// </summary>
  436. /// <returns></returns>
  437. protected CommandConsole CreateConsole()
  438. {
  439. return new LocalConsole("pCampbot");
  440. }
  441. private void HandleConnect(string module, string[] cmd)
  442. {
  443. lock (m_bots)
  444. {
  445. int botsToConnect;
  446. int disconnectedBots = m_bots.Count(b => b.ConnectionState == ConnectionState.Disconnected);
  447. if (cmd.Length == 1)
  448. {
  449. botsToConnect = disconnectedBots;
  450. }
  451. else
  452. {
  453. if (!ConsoleUtil.TryParseConsoleNaturalInt(MainConsole.Instance, cmd[1], out botsToConnect))
  454. return;
  455. botsToConnect = Math.Min(botsToConnect, disconnectedBots);
  456. }
  457. MainConsole.Instance.Output("Connecting {0} bots", null, botsToConnect);
  458. ConnectBots(botsToConnect);
  459. }
  460. }
  461. private void HandleAddBehaviour(string module, string[] cmd)
  462. {
  463. if (cmd.Length < 3 || cmd.Length > 4)
  464. {
  465. MainConsole.Instance.Output("Usage: add behaviour <abbreviated-behaviour> [<bot-number>]");
  466. return;
  467. }
  468. string rawBehaviours = cmd[2];
  469. List<Bot> botsToEffect = new List<Bot>();
  470. if (cmd.Length == 3)
  471. {
  472. lock (m_bots)
  473. botsToEffect.AddRange(m_bots);
  474. }
  475. else
  476. {
  477. int botNumber;
  478. if (!ConsoleUtil.TryParseConsoleNaturalInt(MainConsole.Instance, cmd[3], out botNumber))
  479. return;
  480. Bot bot = GetBotFromNumber(botNumber);
  481. if (bot == null)
  482. {
  483. MainConsole.Instance.Output("Error: No bot found with number {0}", null, botNumber);
  484. return;
  485. }
  486. botsToEffect.Add(bot);
  487. }
  488. HashSet<string> rawAbbreviatedSwitchesToAdd = new HashSet<string>();
  489. Array.ForEach<string>(rawBehaviours.Split(new char[] { ',' }), b => rawAbbreviatedSwitchesToAdd.Add(b));
  490. foreach (Bot bot in botsToEffect)
  491. {
  492. List<IBehaviour> behavioursAdded = new List<IBehaviour>();
  493. foreach (IBehaviour behaviour in CreateBehavioursFromAbbreviatedNames(rawAbbreviatedSwitchesToAdd))
  494. {
  495. if (bot.AddBehaviour(behaviour))
  496. behavioursAdded.Add(behaviour);
  497. }
  498. MainConsole.Instance.Output(
  499. "Added behaviours {0} to bot {1}",
  500. null,
  501. string.Join(", ", behavioursAdded.ConvertAll<string>(b => b.Name).ToArray()), bot.Name);
  502. }
  503. }
  504. private void HandleRemoveBehaviour(string module, string[] cmd)
  505. {
  506. if (cmd.Length < 3 || cmd.Length > 4)
  507. {
  508. MainConsole.Instance.Output("Usage: remove behaviour <abbreviated-behaviour> [<bot-number>]");
  509. return;
  510. }
  511. string rawBehaviours = cmd[2];
  512. List<Bot> botsToEffect = new List<Bot>();
  513. if (cmd.Length == 3)
  514. {
  515. lock (m_bots)
  516. botsToEffect.AddRange(m_bots);
  517. }
  518. else
  519. {
  520. int botNumber;
  521. if (!ConsoleUtil.TryParseConsoleNaturalInt(MainConsole.Instance, cmd[3], out botNumber))
  522. return;
  523. Bot bot = GetBotFromNumber(botNumber);
  524. if (bot == null)
  525. {
  526. MainConsole.Instance.Output("Error: No bot found with number {0}", null, botNumber);
  527. return;
  528. }
  529. botsToEffect.Add(bot);
  530. }
  531. HashSet<string> abbreviatedBehavioursToRemove = new HashSet<string>();
  532. Array.ForEach<string>(rawBehaviours.Split(new char[] { ',' }), b => abbreviatedBehavioursToRemove.Add(b));
  533. foreach (Bot bot in botsToEffect)
  534. {
  535. List<IBehaviour> behavioursRemoved = new List<IBehaviour>();
  536. foreach (string b in abbreviatedBehavioursToRemove)
  537. {
  538. IBehaviour behaviour;
  539. if (bot.TryGetBehaviour(b, out behaviour))
  540. {
  541. bot.RemoveBehaviour(b);
  542. behavioursRemoved.Add(behaviour);
  543. }
  544. }
  545. MainConsole.Instance.Output(
  546. "Removed behaviours {0} from bot {1}",
  547. null,
  548. string.Join(", ", behavioursRemoved.ConvertAll<string>(b => b.Name).ToArray()), bot.Name);
  549. }
  550. }
  551. private void HandleDisconnect(string module, string[] cmd)
  552. {
  553. List<Bot> connectedBots;
  554. int botsToDisconnectCount;
  555. lock (m_bots)
  556. connectedBots = m_bots.FindAll(b => b.ConnectionState == ConnectionState.Connected);
  557. if (cmd.Length == 1)
  558. {
  559. botsToDisconnectCount = connectedBots.Count;
  560. }
  561. else
  562. {
  563. if (!ConsoleUtil.TryParseConsoleNaturalInt(MainConsole.Instance, cmd[1], out botsToDisconnectCount))
  564. return;
  565. botsToDisconnectCount = Math.Min(botsToDisconnectCount, connectedBots.Count);
  566. }
  567. lock (BotConnectingStateChangeObject)
  568. BotConnectingState = BotManagerBotConnectingState.Disconnecting;
  569. Thread disconnectBotThread = new Thread(o => DisconnectBotsInternal(connectedBots, botsToDisconnectCount));
  570. disconnectBotThread.Name = "Bots disconnection thread";
  571. disconnectBotThread.Start();
  572. }
  573. private void DisconnectBotsInternal(List<Bot> connectedBots, int disconnectCount)
  574. {
  575. MainConsole.Instance.Output("Disconnecting {0} bots", null, disconnectCount);
  576. int disconnectedBots = 0;
  577. for (int i = connectedBots.Count - 1; i >= 0; i--)
  578. {
  579. if (disconnectedBots >= disconnectCount)
  580. break;
  581. Bot thisBot = connectedBots[i];
  582. if (thisBot.ConnectionState == ConnectionState.Connected)
  583. {
  584. ThreadPool.QueueUserWorkItem(o => thisBot.Disconnect());
  585. disconnectedBots++;
  586. }
  587. }
  588. lock (BotConnectingStateChangeObject)
  589. BotConnectingState = BotManagerBotConnectingState.Ready;
  590. }
  591. private void HandleSit(string module, string[] cmd)
  592. {
  593. lock (m_bots)
  594. {
  595. foreach (Bot bot in m_bots)
  596. {
  597. if (bot.ConnectionState == ConnectionState.Connected)
  598. {
  599. MainConsole.Instance.Output("Sitting bot {0} on ground.", null, bot.Name);
  600. bot.SitOnGround();
  601. }
  602. }
  603. }
  604. }
  605. private void HandleStand(string module, string[] cmd)
  606. {
  607. lock (m_bots)
  608. {
  609. foreach (Bot bot in m_bots)
  610. {
  611. if (bot.ConnectionState == ConnectionState.Connected)
  612. {
  613. MainConsole.Instance.Output("Standing bot {0} from ground.", null, bot.Name);
  614. bot.Stand();
  615. }
  616. }
  617. }
  618. }
  619. private void HandleShutdown(string module, string[] cmd)
  620. {
  621. lock (m_bots)
  622. {
  623. int connectedBots = m_bots.Count(b => b.ConnectionState == ConnectionState.Connected);
  624. if (connectedBots > 0)
  625. {
  626. MainConsole.Instance.Output("Please disconnect {0} connected bots first", null, connectedBots);
  627. return;
  628. }
  629. }
  630. MainConsole.Instance.Output("Shutting down");
  631. m_serverStatsCollector.Close();
  632. Environment.Exit(0);
  633. }
  634. private void HandleSetBots(string module, string[] cmd)
  635. {
  636. string key = cmd[2];
  637. string rawValue = cmd[3];
  638. if (key == "SEND_AGENT_UPDATES")
  639. {
  640. bool newSendAgentUpdatesSetting;
  641. if (!ConsoleUtil.TryParseConsoleBool(MainConsole.Instance, rawValue, out newSendAgentUpdatesSetting))
  642. return;
  643. MainConsole.Instance.Output("Setting SEND_AGENT_UPDATES to {0} for all bots",
  644. null, newSendAgentUpdatesSetting);
  645. lock (m_bots)
  646. m_bots.ForEach(b => b.Client.Settings.SEND_AGENT_UPDATES = newSendAgentUpdatesSetting);
  647. }
  648. else
  649. {
  650. MainConsole.Instance.Output("Error: Only setting currently available is SEND_AGENT_UPDATES");
  651. }
  652. }
  653. private void HandleDebugLludpPacketCommand(string module, string[] args)
  654. {
  655. if (args.Length != 6)
  656. {
  657. MainConsole.Instance.Output("Usage: debug lludp packet <level> <bot-first-name> <bot-last-name>");
  658. return;
  659. }
  660. int level;
  661. if (!ConsoleUtil.TryParseConsoleInt(MainConsole.Instance, args[3], out level))
  662. return;
  663. string botFirstName = args[4];
  664. string botLastName = args[5];
  665. Bot bot;
  666. lock (m_bots)
  667. bot = m_bots.FirstOrDefault(b => b.FirstName == botFirstName && b.LastName == botLastName);
  668. if (bot == null)
  669. {
  670. MainConsole.Instance.Output("No bot named {0} {1}", null, botFirstName, botLastName);
  671. return;
  672. }
  673. bot.PacketDebugLevel = level;
  674. MainConsole.Instance.Output("Set debug level of {0} to {1}", null, bot.Name, bot.PacketDebugLevel);
  675. }
  676. private void HandleShowRegions(string module, string[] cmd)
  677. {
  678. string outputFormat = "{0,-30} {1, -20} {2, -5} {3, -5}";
  679. MainConsole.Instance.Output(outputFormat, null, "Name", "Handle", "X", "Y");
  680. lock (RegionsKnown)
  681. {
  682. foreach (GridRegion region in RegionsKnown.Values)
  683. {
  684. MainConsole.Instance.Output(
  685. outputFormat, null, region.Name, region.RegionHandle, region.X, region.Y);
  686. }
  687. }
  688. }
  689. private void HandleShowStatus(string module, string[] cmd)
  690. {
  691. ConsoleDisplayList cdl = new ConsoleDisplayList();
  692. cdl.AddRow("Bot connecting state", BotConnectingState);
  693. MainConsole.Instance.Output(cdl.ToString());
  694. }
  695. private void HandleShowBotsStatus(string module, string[] cmd)
  696. {
  697. ConsoleDisplayTable cdt = new ConsoleDisplayTable();
  698. cdt.AddColumn("Name", 24);
  699. cdt.AddColumn("Region", 24);
  700. cdt.AddColumn("Status", 13);
  701. cdt.AddColumn("Conns", 5);
  702. cdt.AddColumn("Behaviours", 20);
  703. Dictionary<ConnectionState, int> totals = new Dictionary<ConnectionState, int>();
  704. foreach (object o in Enum.GetValues(typeof(ConnectionState)))
  705. totals[(ConnectionState)o] = 0;
  706. lock (m_bots)
  707. {
  708. foreach (Bot bot in m_bots)
  709. {
  710. Simulator currentSim = bot.Client.Network.CurrentSim;
  711. totals[bot.ConnectionState]++;
  712. cdt.AddRow(
  713. bot.Name,
  714. currentSim != null ? currentSim.Name : "(none)",
  715. bot.ConnectionState,
  716. bot.SimulatorsCount,
  717. string.Join(",", bot.Behaviours.Keys.ToArray()));
  718. }
  719. }
  720. MainConsole.Instance.Output(cdt.ToString());
  721. ConsoleDisplayList cdl = new ConsoleDisplayList();
  722. foreach (KeyValuePair<ConnectionState, int> kvp in totals)
  723. cdl.AddRow(kvp.Key, kvp.Value);
  724. MainConsole.Instance.Output(cdl.ToString());
  725. }
  726. private void HandleShowBotStatus(string module, string[] cmd)
  727. {
  728. if (cmd.Length != 3)
  729. {
  730. MainConsole.Instance.Output("Usage: show bot <n>");
  731. return;
  732. }
  733. int botNumber;
  734. if (!ConsoleUtil.TryParseConsoleInt(MainConsole.Instance, cmd[2], out botNumber))
  735. return;
  736. Bot bot = GetBotFromNumber(botNumber);
  737. if (bot == null)
  738. {
  739. MainConsole.Instance.Output("Error: No bot found with number {0}", null, botNumber);
  740. return;
  741. }
  742. ConsoleDisplayList cdl = new ConsoleDisplayList();
  743. cdl.AddRow("Name", bot.Name);
  744. cdl.AddRow("Status", bot.ConnectionState);
  745. Simulator currentSim = bot.Client.Network.CurrentSim;
  746. cdl.AddRow("Region", currentSim != null ? currentSim.Name : "(none)");
  747. List<Simulator> connectedSimulators = bot.Simulators;
  748. List<string> simulatorNames = connectedSimulators.ConvertAll<string>(cs => cs.Name);
  749. cdl.AddRow("Connections", string.Join(", ", simulatorNames.ToArray()));
  750. MainConsole.Instance.Output(cdl.ToString());
  751. MainConsole.Instance.Output("Settings");
  752. ConsoleDisplayList statusCdl = new ConsoleDisplayList();
  753. statusCdl.AddRow(
  754. "Behaviours",
  755. string.Join(", ", bot.Behaviours.Values.ToList().ConvertAll<string>(b => b.Name).ToArray()));
  756. GridClient botClient = bot.Client;
  757. statusCdl.AddRow("SEND_AGENT_UPDATES", botClient.Settings.SEND_AGENT_UPDATES);
  758. MainConsole.Instance.Output(statusCdl.ToString());
  759. }
  760. /// <summary>
  761. /// Get a specific bot from its number.
  762. /// </summary>
  763. /// <returns>null if no bot was found</returns>
  764. /// <param name='botNumber'></param>
  765. private Bot GetBotFromNumber(int botNumber)
  766. {
  767. string name = GenerateBotNameFromNumber(botNumber);
  768. Bot bot;
  769. lock (m_bots)
  770. bot = m_bots.Find(b => b.Name == name);
  771. return bot;
  772. }
  773. private string GenerateBotNameFromNumber(int botNumber)
  774. {
  775. return string.Format("{0} {1}{2}", m_firstName, m_lastNameStem, botNumber);
  776. }
  777. internal void Grid_GridRegion(object o, GridRegionEventArgs args)
  778. {
  779. lock (RegionsKnown)
  780. {
  781. GridRegion newRegion = args.Region;
  782. if (RegionsKnown.ContainsKey(newRegion.RegionHandle))
  783. {
  784. return;
  785. }
  786. else
  787. {
  788. m_log.DebugFormat(
  789. "[BOT MANAGER]: Adding {0} {1} to known regions", newRegion.Name, newRegion.RegionHandle);
  790. RegionsKnown[newRegion.RegionHandle] = newRegion;
  791. }
  792. }
  793. }
  794. }
  795. }