BotManager.cs 35 KB

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