BotManager.cs 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983
  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.OutputFormat("No behaviour with abbreviated name {0} found", 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.OutputFormat(
  302. "Bot connecting status is {0}. Please wait for previous process to complete.", 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.OutputFormat(
  401. "[BOT MANAGER]: Creating bot {0} {1}, behaviours are {2}",
  402. firstName, lastName, string.Join(",", behaviours.ConvertAll<string>(b => b.Name).ToArray()));
  403. Bot pb = new Bot(bm, behaviours, firstName, lastName, password, startLocation, loginUri);
  404. pb.wear = wearSetting;
  405. pb.Client.Settings.SEND_AGENT_UPDATES = InitBotSendAgentUpdates;
  406. pb.RequestObjectTextures = InitBotRequestObjectTextures;
  407. pb.OnConnected += handlebotEvent;
  408. pb.OnDisconnected += handlebotEvent;
  409. m_bots.Add(pb);
  410. }
  411. /// <summary>
  412. /// High level connnected/disconnected events so we can keep track of our threads by proxy
  413. /// </summary>
  414. /// <param name="callbot"></param>
  415. /// <param name="eventt"></param>
  416. private void handlebotEvent(Bot callbot, EventType eventt)
  417. {
  418. switch (eventt)
  419. {
  420. case EventType.CONNECTED:
  421. {
  422. m_log.Info("[" + callbot.FirstName + " " + callbot.LastName + "]: Connected");
  423. break;
  424. }
  425. case EventType.DISCONNECTED:
  426. {
  427. m_log.Info("[" + callbot.FirstName + " " + callbot.LastName + "]: Disconnected");
  428. break;
  429. }
  430. }
  431. }
  432. /// <summary>
  433. /// Standard CreateConsole routine
  434. /// </summary>
  435. /// <returns></returns>
  436. protected CommandConsole CreateConsole()
  437. {
  438. return new LocalConsole("pCampbot");
  439. }
  440. private void HandleConnect(string module, string[] cmd)
  441. {
  442. lock (m_bots)
  443. {
  444. int botsToConnect;
  445. int disconnectedBots = m_bots.Count(b => b.ConnectionState == ConnectionState.Disconnected);
  446. if (cmd.Length == 1)
  447. {
  448. botsToConnect = disconnectedBots;
  449. }
  450. else
  451. {
  452. if (!ConsoleUtil.TryParseConsoleNaturalInt(MainConsole.Instance, cmd[1], out botsToConnect))
  453. return;
  454. botsToConnect = Math.Min(botsToConnect, disconnectedBots);
  455. }
  456. MainConsole.Instance.OutputFormat("Connecting {0} bots", botsToConnect);
  457. ConnectBots(botsToConnect);
  458. }
  459. }
  460. private void HandleAddBehaviour(string module, string[] cmd)
  461. {
  462. if (cmd.Length < 3 || cmd.Length > 4)
  463. {
  464. MainConsole.Instance.OutputFormat("Usage: add behaviour <abbreviated-behaviour> [<bot-number>]");
  465. return;
  466. }
  467. string rawBehaviours = cmd[2];
  468. List<Bot> botsToEffect = new List<Bot>();
  469. if (cmd.Length == 3)
  470. {
  471. lock (m_bots)
  472. botsToEffect.AddRange(m_bots);
  473. }
  474. else
  475. {
  476. int botNumber;
  477. if (!ConsoleUtil.TryParseConsoleNaturalInt(MainConsole.Instance, cmd[3], out botNumber))
  478. return;
  479. Bot bot = GetBotFromNumber(botNumber);
  480. if (bot == null)
  481. {
  482. MainConsole.Instance.OutputFormat("Error: No bot found with number {0}", botNumber);
  483. return;
  484. }
  485. botsToEffect.Add(bot);
  486. }
  487. HashSet<string> rawAbbreviatedSwitchesToAdd = new HashSet<string>();
  488. Array.ForEach<string>(rawBehaviours.Split(new char[] { ',' }), b => rawAbbreviatedSwitchesToAdd.Add(b));
  489. foreach (Bot bot in botsToEffect)
  490. {
  491. List<IBehaviour> behavioursAdded = new List<IBehaviour>();
  492. foreach (IBehaviour behaviour in CreateBehavioursFromAbbreviatedNames(rawAbbreviatedSwitchesToAdd))
  493. {
  494. if (bot.AddBehaviour(behaviour))
  495. behavioursAdded.Add(behaviour);
  496. }
  497. MainConsole.Instance.OutputFormat(
  498. "Added behaviours {0} to bot {1}",
  499. string.Join(", ", behavioursAdded.ConvertAll<string>(b => b.Name).ToArray()), bot.Name);
  500. }
  501. }
  502. private void HandleRemoveBehaviour(string module, string[] cmd)
  503. {
  504. if (cmd.Length < 3 || cmd.Length > 4)
  505. {
  506. MainConsole.Instance.OutputFormat("Usage: remove behaviour <abbreviated-behaviour> [<bot-number>]");
  507. return;
  508. }
  509. string rawBehaviours = cmd[2];
  510. List<Bot> botsToEffect = new List<Bot>();
  511. if (cmd.Length == 3)
  512. {
  513. lock (m_bots)
  514. botsToEffect.AddRange(m_bots);
  515. }
  516. else
  517. {
  518. int botNumber;
  519. if (!ConsoleUtil.TryParseConsoleNaturalInt(MainConsole.Instance, cmd[3], out botNumber))
  520. return;
  521. Bot bot = GetBotFromNumber(botNumber);
  522. if (bot == null)
  523. {
  524. MainConsole.Instance.OutputFormat("Error: No bot found with number {0}", botNumber);
  525. return;
  526. }
  527. botsToEffect.Add(bot);
  528. }
  529. HashSet<string> abbreviatedBehavioursToRemove = new HashSet<string>();
  530. Array.ForEach<string>(rawBehaviours.Split(new char[] { ',' }), b => abbreviatedBehavioursToRemove.Add(b));
  531. foreach (Bot bot in botsToEffect)
  532. {
  533. List<IBehaviour> behavioursRemoved = new List<IBehaviour>();
  534. foreach (string b in abbreviatedBehavioursToRemove)
  535. {
  536. IBehaviour behaviour;
  537. if (bot.TryGetBehaviour(b, out behaviour))
  538. {
  539. bot.RemoveBehaviour(b);
  540. behavioursRemoved.Add(behaviour);
  541. }
  542. }
  543. MainConsole.Instance.OutputFormat(
  544. "Removed behaviours {0} from bot {1}",
  545. string.Join(", ", behavioursRemoved.ConvertAll<string>(b => b.Name).ToArray()), bot.Name);
  546. }
  547. }
  548. private void HandleDisconnect(string module, string[] cmd)
  549. {
  550. List<Bot> connectedBots;
  551. int botsToDisconnectCount;
  552. lock (m_bots)
  553. connectedBots = m_bots.FindAll(b => b.ConnectionState == ConnectionState.Connected);
  554. if (cmd.Length == 1)
  555. {
  556. botsToDisconnectCount = connectedBots.Count;
  557. }
  558. else
  559. {
  560. if (!ConsoleUtil.TryParseConsoleNaturalInt(MainConsole.Instance, cmd[1], out botsToDisconnectCount))
  561. return;
  562. botsToDisconnectCount = Math.Min(botsToDisconnectCount, connectedBots.Count);
  563. }
  564. lock (BotConnectingStateChangeObject)
  565. BotConnectingState = BotManagerBotConnectingState.Disconnecting;
  566. Thread disconnectBotThread = new Thread(o => DisconnectBotsInternal(connectedBots, botsToDisconnectCount));
  567. disconnectBotThread.Name = "Bots disconnection thread";
  568. disconnectBotThread.Start();
  569. }
  570. private void DisconnectBotsInternal(List<Bot> connectedBots, int disconnectCount)
  571. {
  572. MainConsole.Instance.OutputFormat("Disconnecting {0} bots", disconnectCount);
  573. int disconnectedBots = 0;
  574. for (int i = connectedBots.Count - 1; i >= 0; i--)
  575. {
  576. if (disconnectedBots >= disconnectCount)
  577. break;
  578. Bot thisBot = connectedBots[i];
  579. if (thisBot.ConnectionState == ConnectionState.Connected)
  580. {
  581. ThreadPool.QueueUserWorkItem(o => thisBot.Disconnect());
  582. disconnectedBots++;
  583. }
  584. }
  585. lock (BotConnectingStateChangeObject)
  586. BotConnectingState = BotManagerBotConnectingState.Ready;
  587. }
  588. private void HandleSit(string module, string[] cmd)
  589. {
  590. lock (m_bots)
  591. {
  592. foreach (Bot bot in m_bots)
  593. {
  594. if (bot.ConnectionState == ConnectionState.Connected)
  595. {
  596. MainConsole.Instance.OutputFormat("Sitting bot {0} on ground.", bot.Name);
  597. bot.SitOnGround();
  598. }
  599. }
  600. }
  601. }
  602. private void HandleStand(string module, string[] cmd)
  603. {
  604. lock (m_bots)
  605. {
  606. foreach (Bot bot in m_bots)
  607. {
  608. if (bot.ConnectionState == ConnectionState.Connected)
  609. {
  610. MainConsole.Instance.OutputFormat("Standing bot {0} from ground.", bot.Name);
  611. bot.Stand();
  612. }
  613. }
  614. }
  615. }
  616. private void HandleShutdown(string module, string[] cmd)
  617. {
  618. lock (m_bots)
  619. {
  620. int connectedBots = m_bots.Count(b => b.ConnectionState == ConnectionState.Connected);
  621. if (connectedBots > 0)
  622. {
  623. MainConsole.Instance.OutputFormat("Please disconnect {0} connected bots first", connectedBots);
  624. return;
  625. }
  626. }
  627. MainConsole.Instance.Output("Shutting down");
  628. m_serverStatsCollector.Close();
  629. Environment.Exit(0);
  630. }
  631. private void HandleSetBots(string module, string[] cmd)
  632. {
  633. string key = cmd[2];
  634. string rawValue = cmd[3];
  635. if (key == "SEND_AGENT_UPDATES")
  636. {
  637. bool newSendAgentUpdatesSetting;
  638. if (!ConsoleUtil.TryParseConsoleBool(MainConsole.Instance, rawValue, out newSendAgentUpdatesSetting))
  639. return;
  640. MainConsole.Instance.OutputFormat(
  641. "Setting SEND_AGENT_UPDATES to {0} for all bots", newSendAgentUpdatesSetting);
  642. lock (m_bots)
  643. m_bots.ForEach(b => b.Client.Settings.SEND_AGENT_UPDATES = newSendAgentUpdatesSetting);
  644. }
  645. else
  646. {
  647. MainConsole.Instance.Output("Error: Only setting currently available is SEND_AGENT_UPDATES");
  648. }
  649. }
  650. private void HandleDebugLludpPacketCommand(string module, string[] args)
  651. {
  652. if (args.Length != 6)
  653. {
  654. MainConsole.Instance.OutputFormat("Usage: debug lludp packet <level> <bot-first-name> <bot-last-name>");
  655. return;
  656. }
  657. int level;
  658. if (!ConsoleUtil.TryParseConsoleInt(MainConsole.Instance, args[3], out level))
  659. return;
  660. string botFirstName = args[4];
  661. string botLastName = args[5];
  662. Bot bot;
  663. lock (m_bots)
  664. bot = m_bots.FirstOrDefault(b => b.FirstName == botFirstName && b.LastName == botLastName);
  665. if (bot == null)
  666. {
  667. MainConsole.Instance.OutputFormat("No bot named {0} {1}", botFirstName, botLastName);
  668. return;
  669. }
  670. bot.PacketDebugLevel = level;
  671. MainConsole.Instance.OutputFormat("Set debug level of {0} to {1}", bot.Name, bot.PacketDebugLevel);
  672. }
  673. private void HandleShowRegions(string module, string[] cmd)
  674. {
  675. string outputFormat = "{0,-30} {1, -20} {2, -5} {3, -5}";
  676. MainConsole.Instance.OutputFormat(outputFormat, "Name", "Handle", "X", "Y");
  677. lock (RegionsKnown)
  678. {
  679. foreach (GridRegion region in RegionsKnown.Values)
  680. {
  681. MainConsole.Instance.OutputFormat(
  682. outputFormat, region.Name, region.RegionHandle, region.X, region.Y);
  683. }
  684. }
  685. }
  686. private void HandleShowStatus(string module, string[] cmd)
  687. {
  688. ConsoleDisplayList cdl = new ConsoleDisplayList();
  689. cdl.AddRow("Bot connecting state", BotConnectingState);
  690. MainConsole.Instance.Output(cdl.ToString());
  691. }
  692. private void HandleShowBotsStatus(string module, string[] cmd)
  693. {
  694. ConsoleDisplayTable cdt = new ConsoleDisplayTable();
  695. cdt.AddColumn("Name", 24);
  696. cdt.AddColumn("Region", 24);
  697. cdt.AddColumn("Status", 13);
  698. cdt.AddColumn("Conns", 5);
  699. cdt.AddColumn("Behaviours", 20);
  700. Dictionary<ConnectionState, int> totals = new Dictionary<ConnectionState, int>();
  701. foreach (object o in Enum.GetValues(typeof(ConnectionState)))
  702. totals[(ConnectionState)o] = 0;
  703. lock (m_bots)
  704. {
  705. foreach (Bot bot in m_bots)
  706. {
  707. Simulator currentSim = bot.Client.Network.CurrentSim;
  708. totals[bot.ConnectionState]++;
  709. cdt.AddRow(
  710. bot.Name,
  711. currentSim != null ? currentSim.Name : "(none)",
  712. bot.ConnectionState,
  713. bot.SimulatorsCount,
  714. string.Join(",", bot.Behaviours.Keys.ToArray()));
  715. }
  716. }
  717. MainConsole.Instance.Output(cdt.ToString());
  718. ConsoleDisplayList cdl = new ConsoleDisplayList();
  719. foreach (KeyValuePair<ConnectionState, int> kvp in totals)
  720. cdl.AddRow(kvp.Key, kvp.Value);
  721. MainConsole.Instance.Output(cdl.ToString());
  722. }
  723. private void HandleShowBotStatus(string module, string[] cmd)
  724. {
  725. if (cmd.Length != 3)
  726. {
  727. MainConsole.Instance.Output("Usage: show bot <n>");
  728. return;
  729. }
  730. int botNumber;
  731. if (!ConsoleUtil.TryParseConsoleInt(MainConsole.Instance, cmd[2], out botNumber))
  732. return;
  733. Bot bot = GetBotFromNumber(botNumber);
  734. if (bot == null)
  735. {
  736. MainConsole.Instance.OutputFormat("Error: No bot found with number {0}", botNumber);
  737. return;
  738. }
  739. ConsoleDisplayList cdl = new ConsoleDisplayList();
  740. cdl.AddRow("Name", bot.Name);
  741. cdl.AddRow("Status", bot.ConnectionState);
  742. Simulator currentSim = bot.Client.Network.CurrentSim;
  743. cdl.AddRow("Region", currentSim != null ? currentSim.Name : "(none)");
  744. List<Simulator> connectedSimulators = bot.Simulators;
  745. List<string> simulatorNames = connectedSimulators.ConvertAll<string>(cs => cs.Name);
  746. cdl.AddRow("Connections", string.Join(", ", simulatorNames.ToArray()));
  747. MainConsole.Instance.Output(cdl.ToString());
  748. MainConsole.Instance.Output("Settings");
  749. ConsoleDisplayList statusCdl = new ConsoleDisplayList();
  750. statusCdl.AddRow(
  751. "Behaviours",
  752. string.Join(", ", bot.Behaviours.Values.ToList().ConvertAll<string>(b => b.Name).ToArray()));
  753. GridClient botClient = bot.Client;
  754. statusCdl.AddRow("SEND_AGENT_UPDATES", botClient.Settings.SEND_AGENT_UPDATES);
  755. MainConsole.Instance.Output(statusCdl.ToString());
  756. }
  757. /// <summary>
  758. /// Get a specific bot from its number.
  759. /// </summary>
  760. /// <returns>null if no bot was found</returns>
  761. /// <param name='botNumber'></param>
  762. private Bot GetBotFromNumber(int botNumber)
  763. {
  764. string name = GenerateBotNameFromNumber(botNumber);
  765. Bot bot;
  766. lock (m_bots)
  767. bot = m_bots.Find(b => b.Name == name);
  768. return bot;
  769. }
  770. private string GenerateBotNameFromNumber(int botNumber)
  771. {
  772. return string.Format("{0} {1}{2}", m_firstName, m_lastNameStem, botNumber);
  773. }
  774. internal void Grid_GridRegion(object o, GridRegionEventArgs args)
  775. {
  776. lock (RegionsKnown)
  777. {
  778. GridRegion newRegion = args.Region;
  779. if (RegionsKnown.ContainsKey(newRegion.RegionHandle))
  780. {
  781. return;
  782. }
  783. else
  784. {
  785. m_log.DebugFormat(
  786. "[BOT MANAGER]: Adding {0} {1} to known regions", newRegion.Name, newRegion.RegionHandle);
  787. RegionsKnown[newRegion.RegionHandle] = newRegion;
  788. }
  789. }
  790. }
  791. }
  792. }