BotManager.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSimulator Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. using System;
  28. using System.Collections.Generic;
  29. using System.Linq;
  30. using System.Reflection;
  31. using System.Threading;
  32. using OpenMetaverse;
  33. using log4net;
  34. using log4net.Appender;
  35. using log4net.Core;
  36. using log4net.Repository;
  37. using Nini.Config;
  38. using OpenSim.Framework;
  39. using OpenSim.Framework.Console;
  40. using pCampBot.Interfaces;
  41. namespace pCampBot
  42. {
  43. /// <summary>
  44. /// Thread/Bot manager for the application
  45. /// </summary>
  46. public class BotManager
  47. {
  48. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  49. public const int DefaultLoginDelay = 5000;
  50. /// <summary>
  51. /// Delay between logins of multiple bots.
  52. /// </summary>
  53. /// <remarks>TODO: This value needs to be configurable by a command line argument.</remarks>
  54. public int LoginDelay { get; set; }
  55. /// <summary>
  56. /// Command console
  57. /// </summary>
  58. protected CommandConsole m_console;
  59. /// <summary>
  60. /// Created bots, whether active or inactive.
  61. /// </summary>
  62. protected List<Bot> m_lBot;
  63. /// <summary>
  64. /// Random number generator.
  65. /// </summary>
  66. public Random Rng { get; private set; }
  67. /// <summary>
  68. /// Overall configuration.
  69. /// </summary>
  70. public IConfig Config { get; private set; }
  71. /// <summary>
  72. /// Track the assets we have and have not received so we don't endlessly repeat requests.
  73. /// </summary>
  74. public Dictionary<UUID, bool> AssetsReceived { get; private set; }
  75. /// <summary>
  76. /// The regions that we know about.
  77. /// </summary>
  78. public Dictionary<ulong, GridRegion> RegionsKnown { get; private set; }
  79. /// <summary>
  80. /// Constructor Creates MainConsole.Instance to take commands and provide the place to write data
  81. /// </summary>
  82. public BotManager()
  83. {
  84. LoginDelay = DefaultLoginDelay;
  85. Rng = new Random(Environment.TickCount);
  86. AssetsReceived = new Dictionary<UUID, bool>();
  87. RegionsKnown = new Dictionary<ulong, GridRegion>();
  88. m_console = CreateConsole();
  89. MainConsole.Instance = m_console;
  90. // Make log4net see the console
  91. //
  92. ILoggerRepository repository = LogManager.GetRepository();
  93. IAppender[] appenders = repository.GetAppenders();
  94. OpenSimAppender consoleAppender = null;
  95. foreach (IAppender appender in appenders)
  96. {
  97. if (appender.Name == "Console")
  98. {
  99. consoleAppender = (OpenSimAppender)appender;
  100. consoleAppender.Console = m_console;
  101. break;
  102. }
  103. }
  104. m_console.Commands.AddCommand("bot", false, "shutdown",
  105. "shutdown",
  106. "Shutdown bots and exit", HandleShutdown);
  107. m_console.Commands.AddCommand("bot", false, "quit",
  108. "quit",
  109. "Shutdown bots and exit",
  110. HandleShutdown);
  111. m_console.Commands.AddCommand("bot", false, "show regions",
  112. "show regions",
  113. "Show regions known to bots",
  114. HandleShowRegions);
  115. m_console.Commands.AddCommand("bot", false, "show bots",
  116. "show bots",
  117. "Shows the status of all bots",
  118. HandleShowStatus);
  119. // m_console.Commands.AddCommand("bot", false, "add bots",
  120. // "add bots <number>",
  121. // "Add more bots", HandleAddBots);
  122. m_lBot = new List<Bot>();
  123. }
  124. /// <summary>
  125. /// Startup number of bots specified in the starting arguments
  126. /// </summary>
  127. /// <param name="botcount">How many bots to start up</param>
  128. /// <param name="cs">The configuration for the bots to use</param>
  129. public void dobotStartup(int botcount, IConfig cs)
  130. {
  131. Config = cs;
  132. string firstName = cs.GetString("firstname");
  133. string lastNameStem = cs.GetString("lastname");
  134. string password = cs.GetString("password");
  135. string loginUri = cs.GetString("loginuri");
  136. HashSet<string> behaviourSwitches = new HashSet<string>();
  137. Array.ForEach<string>(
  138. cs.GetString("behaviours", "p").Split(new char[] { ',' }), b => behaviourSwitches.Add(b));
  139. MainConsole.Instance.OutputFormat(
  140. "[BOT MANAGER]: Starting {0} bots connecting to {1}, named {2} {3}_<n>",
  141. botcount,
  142. loginUri,
  143. firstName,
  144. lastNameStem);
  145. MainConsole.Instance.OutputFormat("[BOT MANAGER]: Delay between logins is {0}ms", LoginDelay);
  146. for (int i = 0; i < botcount; i++)
  147. {
  148. string lastName = string.Format("{0}_{1}", lastNameStem, i);
  149. // We must give each bot its own list of instantiated behaviours since they store state.
  150. List<IBehaviour> behaviours = new List<IBehaviour>();
  151. // Hard-coded for now
  152. if (behaviourSwitches.Contains("p"))
  153. behaviours.Add(new PhysicsBehaviour());
  154. if (behaviourSwitches.Contains("g"))
  155. behaviours.Add(new GrabbingBehaviour());
  156. if (behaviourSwitches.Contains("t"))
  157. behaviours.Add(new TeleportBehaviour());
  158. if (behaviourSwitches.Contains("c"))
  159. behaviours.Add(new CrossBehaviour());
  160. StartBot(this, behaviours, firstName, lastName, password, loginUri);
  161. }
  162. }
  163. // /// <summary>
  164. // /// Add additional bots (and threads) to our bot pool
  165. // /// </summary>
  166. // /// <param name="botcount">How Many of them to add</param>
  167. // public void addbots(int botcount)
  168. // {
  169. // int len = m_td.Length;
  170. // Thread[] m_td2 = new Thread[len + botcount];
  171. // for (int i = 0; i < len; i++)
  172. // {
  173. // m_td2[i] = m_td[i];
  174. // }
  175. // m_td = m_td2;
  176. // int newlen = len + botcount;
  177. // for (int i = len; i < newlen; i++)
  178. // {
  179. // startupBot(Config);
  180. // }
  181. // }
  182. /// <summary>
  183. /// This starts up the bot and stores the thread for the bot in the thread array
  184. /// </summary>
  185. /// <param name="bm"></param>
  186. /// <param name="behaviours">Behaviours for this bot to perform.</param>
  187. /// <param name="firstName">First name</param>
  188. /// <param name="lastName">Last name</param>
  189. /// <param name="password">Password</param>
  190. /// <param name="loginUri">Login URI</param>
  191. public void StartBot(
  192. BotManager bm, List<IBehaviour> behaviours,
  193. string firstName, string lastName, string password, string loginUri)
  194. {
  195. MainConsole.Instance.OutputFormat(
  196. "[BOT MANAGER]: Starting bot {0} {1}, behaviours are {2}",
  197. firstName, lastName, string.Join(",", behaviours.ConvertAll<string>(b => b.Name).ToArray()));
  198. Bot pb = new Bot(bm, behaviours, firstName, lastName, password, loginUri);
  199. pb.OnConnected += handlebotEvent;
  200. pb.OnDisconnected += handlebotEvent;
  201. lock (m_lBot)
  202. m_lBot.Add(pb);
  203. Thread pbThread = new Thread(pb.startup);
  204. pbThread.Name = pb.Name;
  205. pbThread.IsBackground = true;
  206. pbThread.Start();
  207. // Stagger logins
  208. Thread.Sleep(LoginDelay);
  209. }
  210. /// <summary>
  211. /// High level connnected/disconnected events so we can keep track of our threads by proxy
  212. /// </summary>
  213. /// <param name="callbot"></param>
  214. /// <param name="eventt"></param>
  215. private void handlebotEvent(Bot callbot, EventType eventt)
  216. {
  217. switch (eventt)
  218. {
  219. case EventType.CONNECTED:
  220. m_log.Info("[" + callbot.FirstName + " " + callbot.LastName + "]: Connected");
  221. break;
  222. case EventType.DISCONNECTED:
  223. m_log.Info("[" + callbot.FirstName + " " + callbot.LastName + "]: Disconnected");
  224. lock (m_lBot)
  225. {
  226. if (m_lBot.TrueForAll(b => b.ConnectionState == ConnectionState.Disconnected))
  227. Environment.Exit(0);
  228. break;
  229. }
  230. }
  231. }
  232. /// <summary>
  233. /// Shut down all bots
  234. /// </summary>
  235. /// <remarks>
  236. /// We launch each shutdown on its own thread so that a slow shutting down bot doesn't hold up all the others.
  237. /// </remarks>
  238. public void doBotShutdown()
  239. {
  240. lock (m_lBot)
  241. {
  242. foreach (Bot bot in m_lBot)
  243. {
  244. Bot thisBot = bot;
  245. Util.FireAndForget(o => thisBot.shutdown());
  246. }
  247. }
  248. }
  249. /// <summary>
  250. /// Standard CreateConsole routine
  251. /// </summary>
  252. /// <returns></returns>
  253. protected CommandConsole CreateConsole()
  254. {
  255. return new LocalConsole("pCampbot");
  256. }
  257. private void HandleShutdown(string module, string[] cmd)
  258. {
  259. m_log.Info("[BOTMANAGER]: Shutting down bots");
  260. doBotShutdown();
  261. }
  262. private void HandleShowRegions(string module, string[] cmd)
  263. {
  264. string outputFormat = "{0,-30} {1, -20} {2, -5} {3, -5}";
  265. MainConsole.Instance.OutputFormat(outputFormat, "Name", "Handle", "X", "Y");
  266. lock (RegionsKnown)
  267. {
  268. foreach (GridRegion region in RegionsKnown.Values)
  269. {
  270. MainConsole.Instance.OutputFormat(
  271. outputFormat, region.Name, region.RegionHandle, region.X, region.Y);
  272. }
  273. }
  274. }
  275. private void HandleShowStatus(string module, string[] cmd)
  276. {
  277. string outputFormat = "{0,-30} {1, -30} {2,-14}";
  278. MainConsole.Instance.OutputFormat(outputFormat, "Name", "Region", "Status");
  279. lock (m_lBot)
  280. {
  281. foreach (Bot pb in m_lBot)
  282. {
  283. Simulator currentSim = pb.Client.Network.CurrentSim;
  284. MainConsole.Instance.OutputFormat(
  285. outputFormat,
  286. pb.Name, currentSim != null ? currentSim.Name : "(none)", pb.ConnectionState);
  287. }
  288. }
  289. }
  290. /*
  291. private void HandleQuit(string module, string[] cmd)
  292. {
  293. m_console.Warn("DANGER", "This should only be used to quit the program if you've already used the shutdown command and the program hasn't quit");
  294. Environment.Exit(0);
  295. }
  296. */
  297. //
  298. // private void HandleAddBots(string module, string[] cmd)
  299. // {
  300. // int newbots = 0;
  301. //
  302. // if (cmd.Length > 2)
  303. // {
  304. // Int32.TryParse(cmd[2], out newbots);
  305. // }
  306. // if (newbots > 0)
  307. // addbots(newbots);
  308. // }
  309. internal void Grid_GridRegion(object o, GridRegionEventArgs args)
  310. {
  311. lock (RegionsKnown)
  312. {
  313. GridRegion newRegion = args.Region;
  314. if (RegionsKnown.ContainsKey(newRegion.RegionHandle))
  315. {
  316. return;
  317. }
  318. else
  319. {
  320. m_log.DebugFormat(
  321. "[BOT MANAGER]: Adding {0} {1} to known regions", newRegion.Name, newRegion.RegionHandle);
  322. RegionsKnown[newRegion.RegionHandle] = newRegion;
  323. }
  324. }
  325. }
  326. }
  327. }