1
0

BotManager.cs 36 KB

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