public async Task FileSystemLock_VerifyMessageFromSettings()
        {
            using (var target = new TestFolder())
                using (var cache = new LocalCache())
                {
                    var log        = new TestLogger();
                    var fileSystem = new PhysicalFileSystem(cache, UriUtility.CreateUri(target.Root));
                    var settings   = new LocalSettings();
                    settings.FeedLockMessage = "FROMSETTINGS!!";
                    var lockMessage = Guid.NewGuid().ToString();

                    await InitCommand.RunAsync(settings, fileSystem, log);

                    var lockObj = await SourceUtility.VerifyInitAndLock(settings, fileSystem, lockMessage, log, CancellationToken.None);

                    lockObj.IsLocked.Should().BeTrue();

                    var path = Path.Combine(target.Root, ".lock");
                    var json = JObject.Parse(File.ReadAllText(path));

                    json["message"].ToString().Should().Be("FROMSETTINGS!!");
                    json["date"].ToString().Should().NotBeNullOrEmpty();
                    json["pid"].ToString().Should().NotBeNullOrEmpty();
                }
        }
Exemple #2
0
        public async Task GivenThatABaseUriChangesVerifyValidationFails()
        {
            using (var target = new TestFolder())
                using (var cache = new LocalCache())
                {
                    var log      = new TestLogger();
                    var settings = new LocalSettings();


                    var fileSystem1 = new PhysicalFileSystem(cache, UriUtility.CreateUri(target.Root), UriUtility.CreateUri("https://tempuri.org/"));
                    var fileSystem2 = new PhysicalFileSystem(cache, UriUtility.CreateUri(target.Root), UriUtility.CreateUri("https://tempuri.org/b/"));

                    await InitCommand.RunAsync(settings, fileSystem1, log);

                    await SourceUtility.EnsureBaseUriMatchesFeed(fileSystem1, log, CancellationToken.None);

                    InvalidDataException foundEx = null;

                    try
                    {
                        await SourceUtility.EnsureBaseUriMatchesFeed(fileSystem2, log, CancellationToken.None);
                    }
                    catch (InvalidDataException ex)
                    {
                        foundEx = ex;
                    }

                    foundEx.Message.Should().Contain("https://tempuri.org/");
                }
        }
Exemple #3
0
        public void SubFeed_VerifySubFeedPathMustBeOnPath()
        {
            using (var target = new TestFolder())
                using (var cache = new LocalCache())
                {
                    var root       = UriUtility.CreateUri(target.Root);
                    var fileSystem = new PhysicalFileSystem(cache, root, root, feedSubPath: "feedA");

                    Assert.Throws <ArgumentException>(() => SourceUtility.ValidateFileSystem(fileSystem));
                }
        }
Exemple #4
0
        public void Execute( )
        {
            RiverSystemScenario testScenario;
            RiverSystemProject  testProject;

            TestHelperRiverSystem.getAPreconfiguredTestScenarioWithAWBM(3, out testProject,
                                                                        out testScenario);

            IObjectiveEvaluator <MetaParameterSet> evaluator        = buildNewEvaluator(testScenario);
            ICandidateFactory <MetaParameterSet>   candidateFactory = new LumpedAWBMFactory(testScenario, new BasicRngFactory(123));

            int pSetNumber = 5;

            IObjectiveScores[]     scores = new IObjectiveScores[pSetNumber];
            ISystemConfiguration[] pSets  = new ISystemConfiguration[pSetNumber];


            int k = 0;

            foreach (Catchment c in testScenario.Network.catchmentList)
            {
                foreach (StandardFunctionalUnit fu in c.FunctionalUnits)
                {
                    var list = AccessorMemberInfo.GetFieldsAndPropertiesList(fu.rainfallRunoffModel.GetType(), typeof(double), typeof(ParameterAttribute));
                    foreach (MemberInfo m in list)
                    {
                        string metaParameterName = "$tag" + k++;
                        UpdateFunctionBuilder.CreateMetaParameter(testScenario, metaParameterName);
                        UpdateFunctionBuilder.CreateUpdateFunctionWithLinkToMetaParameter(testScenario, metaParameterName, m, fu.rainfallRunoffModel);
                    }
                }
            }

            for (int i = 0; i < scores.Length; i++)
            {
                pSets[i] = candidateFactory.CreateRandomCandidate();

                //Do we need to reset the model states??
                scores[i] = evaluator.EvaluateScore((MetaParameterSet)pSets[i]);

                //print Params after each iteration
                LumpedAWBMFactory.printPrams(testScenario, pSets[i]);
            }
            IObjectiveScores[] paretoScores = ParetoRanking <IObjectiveScores> .GetParetoFront(scores);


            SourceUtility.PrintObjScores(scores);
            Console.WriteLine("----------------------------------------");
            SourceUtility.PrintObjScores(paretoScores);
        }
Exemple #5
0
        public async Task FileSystem_VerifyFileSystemResetOnLock()
        {
            using (var target = new TestFolder())
                using (var cache = new LocalCache())
                {
                    var log         = new TestLogger();
                    var fileSystem1 = new PhysicalFileSystem(cache, UriUtility.CreateUri(target.Root));
                    var settings    = new LocalSettings();
                    var lockMessage = Guid.NewGuid().ToString();

                    await InitCommand.RunAsync(settings, fileSystem1, log);

                    // Verify that files work normally
                    var testFile = fileSystem1.Get("test.json");
                    await testFile.GetJsonOrNull(log, CancellationToken.None);

                    var testFile2 = fileSystem1.Get("test2.json");
                    fileSystem1.Files.Count.Should().BeGreaterThan(1);

                    // Lock the feed to reset it
                    var lockObj1 = await SourceUtility.VerifyInitAndLock(settings, fileSystem1, lockMessage, log, CancellationToken.None);

                    lockObj1.IsLocked.Should().BeTrue();

                    // 1 file should be found since it loads the index
                    fileSystem1.Files.Count.Should().Be(1);
                    InvalidOperationException failureEx = null;

                    try
                    {
                        // Verify the old file no longer works
                        await testFile.GetJsonOrNull(log, CancellationToken.None);

                        await testFile2.GetJsonOrNull(log, CancellationToken.None);
                    }
                    catch (InvalidOperationException ex)
                    {
                        failureEx = ex;
                    }

                    failureEx.Should().NotBeNull();
                }
        }
Exemple #6
0
        public void Execute( )
        {
            RiverSystemScenario testScenario;
            RiverSystemProject testProject;
            TestHelperRiverSystem.getAPreconfiguredTestScenarioWithAWBM( 3, out testProject,
                                                                         out testScenario );
            
            IObjectiveEvaluator<MetaParameterSet> evaluator = buildNewEvaluator( testScenario );
            //ICandidateFactory<MetaParameterSet> candidateFactory = new LumpedAWBMFactory( testScenario, new BasicRngFactory(123) );

            var evolutionEngine = new CSIRO.Metaheuristics.Optimization.ShuffledComplexEvolution<MetaParameterSet>( );

            
            IObjectiveScores[] paretoScores = ParetoRanking<IObjectiveScores>.GetParetoFront( scores );
           

            SourceUtility.PrintObjScores( scores );
            Console.WriteLine("----------------------------------------");
            SourceUtility.PrintObjScores( paretoScores );
        }
        public async Task FileSystemLock_VerifyMessageShownInLog()
        {
            using (var target = new TestFolder())
                using (var cache = new LocalCache())
                {
                    var log         = new TestLogger();
                    var log2        = new TestLogger();
                    var fileSystem1 = new PhysicalFileSystem(cache, UriUtility.CreateUri(target.Root));
                    var fileSystem2 = new PhysicalFileSystem(cache, UriUtility.CreateUri(target.Root));
                    var settings    = new LocalSettings();
                    var lockMessage = Guid.NewGuid().ToString();

                    await InitCommand.RunAsync(settings, fileSystem1, log);

                    var lockObj1 = await SourceUtility.VerifyInitAndLock(settings, fileSystem1, lockMessage, log, CancellationToken.None);

                    lockObj1.IsLocked.Should().BeTrue();

                    var lockObj2Task = Task.Run(async() => await SourceUtility.VerifyInitAndLock(settings, fileSystem2, lockMessage, log2, CancellationToken.None));

                    while (!log2.GetMessages().Contains($"Feed is locked by: {lockMessage}"))
                    {
                        await Task.Delay(10);
                    }

                    lockObj1.Release();
                    var lockObj2 = await lockObj2Task;

                    while (!lockObj2.IsLocked)
                    {
                        await Task.Delay(10);
                    }

                    lockObj1.IsLocked.Should().BeFalse();
                    lockObj2.IsLocked.Should().BeTrue();
                }
        }
Exemple #8
0
        /// <summary>
        /// Entry point of the application
        /// </summary>
        public static void Main()
        {
            // Setup LOG4NET
            XmlConfigurator.Configure();

            // Load configuration
            var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            var mudpieConfigurationSection = (MudpieConfigurationSection)config.GetSection("mudpie");

            Debug.Assert(mudpieConfigurationSection != null, "mudpieConfigurationSection != null");
            Logger.InfoFormat("Loaded configuration from {0}", config.FilePath);

            var godPlayer = new Player("God", 2, "god")
            {
                Aliases    = new[] { "Jehovah", "Yahweh", "Allah" },
                DbRef      = 2,
                Properties = new[]
                {
                    new Property
                    {
                        Name  = "_/de",
                        Value = "The Creator",
                        Owner = 2
                    }
                },
                Location = 1
            };

            using (var redis = new StackExchangeRedisCacheClient(new NewtonsoftSerializer()))
            {
                Debug.Assert(redis != null, "redis != null");

                // Setup scripting engine
                var scriptingEngine = new Engine(redis);

                // Setup server process
                Debug.Assert(mudpieConfigurationSection.Ports != null, "mudpieConfigurationSection.Ports != null");
                var server = new Server(mudpieConfigurationSection.Ports.Select(p => p.Port).ToArray(), scriptingEngine)
                {
                    ShowBytes    = true,
                    ShowCommands = false,
                    ShowData     = true
                };

                // Seed data
                Task.Run(async() =>
                {
                    if (!await redis.ExistsAsync("mudpie::dbref:counter"))
                    {
                        Console.WriteLine("Redis database is not seeded with any data.  Creating seed data...");

                        // VOID
                        var voidRoom = new Room("The Void", godPlayer.DbRef)
                        {
                            DbRef      = 1,
                            Properties = new[]
                            {
                                new Property(Property.DESCRIPTION, "An infinite emptiness of nothing.", 2)
                            }
                        };
                        await voidRoom.SaveAsync(redis, server.CancellationToken);

                        // GOD
                        using (var godPassword = new SecureString())
                        {
                            foreach (var c in "god")
                            {
                                godPassword.AppendChar(c);
                            }

                            godPlayer.SetPassword(godPassword);
                            godPassword.Clear();
                        }

                        await godPlayer.SaveAsync(redis, server.CancellationToken);

                        var nextAvailableDbRef    = 3;
                        var registerProgramToVoid = new Func <string, string[], string, int, ICacheClient, Task <int> >(async(name, aliases, desc, nextDbRef, cacheClient) =>
                        {
                            var source = await SourceUtility.GetSourceCodeLinesAsync(mudpieConfigurationSection, name);
                            Debug.Assert(source != null, $"Unable to find source code for program {name}");
                            var nameProgram = new Mudpie.Server.Data.Program(name, godPlayer.DbRef, source)
                            {
                                DbRef      = nextDbRef,
                                Properties = new[]
                                {
                                    new Property(Property.DESCRIPTION, desc, godPlayer.DbRef)
                                },
                                Interactive = false
                            };
                            await nameProgram.SaveAsync(cacheClient, server.CancellationToken);

                            // LINK-NAME-ROOM
                            var linkName = new Link(System.IO.Path.GetFileNameWithoutExtension(name), godPlayer.DbRef)
                            {
                                Aliases = aliases,
                                DbRef   = nextDbRef + 1,
                                Target  = nextDbRef
                            };
                            await linkName.MoveAsync(voidRoom.DbRef, cacheClient, server.CancellationToken);
                            var void2 = ObjectBase.GetAsync(cacheClient, voidRoom.DbRef, server.CancellationToken).Result;
                            if (void2 == null)
                            {
                                throw new InvalidOperationException("void2 cannot be null");
                            }

                            return(nextDbRef + 2);
                        });

                        // @NAME
                        nextAvailableDbRef = await registerProgramToVoid.Invoke("@create.msc", new[] { "create", "make" }, "Creates new things", nextAvailableDbRef, redis);
                        nextAvailableDbRef = await registerProgramToVoid.Invoke("@describe.msc", new[] { "@desc", "describe" }, "Sets the description of an object", nextAvailableDbRef, redis);
                        nextAvailableDbRef = await registerProgramToVoid.Invoke("@dig.msc", new[] { "dig" }, "Creates new rooms", nextAvailableDbRef, redis);
                        nextAvailableDbRef = await registerProgramToVoid.Invoke("@name.msc", new[] { "rename" }, "Rename objects", nextAvailableDbRef, redis);
                        nextAvailableDbRef = await registerProgramToVoid.Invoke("inventory.msc", new[] { "i", "inv" }, "Lists the items you are carrying", nextAvailableDbRef, redis);
                        nextAvailableDbRef = await registerProgramToVoid.Invoke("look.msc", new[] { "l" }, "Displays information about your surroundings, or an object.", nextAvailableDbRef, redis);

                        await redis.Database.StringSetAsync("mudpie::dbref:counter", nextAvailableDbRef);
                    }
                    else
                    {
                        // Ensure we can read Void and God
                        var voidRoom = await Room.GetAsync(redis, 1, server.CancellationToken);
                        Debug.Assert(voidRoom != null, "voidRoom != null");

                        godPlayer = await Player.GetAsync(redis, 2, server.CancellationToken);
                        Debug.Assert(godPlayer != null, "godPlayer != null");

                        var godComposed = await CacheManager.LookupOrRetrieveAsync(2, redis, async(d, token) => await Player.GetAsync(redis, d, token), server.CancellationToken);
                        Debug.Assert(godComposed != null, "godComposed != null");
                    }

                    /*else
                     * {
                     *  Console.WriteLine("Redis database is seeded with data.  BLOWING IT AWAY DATA...");
                     *
                     *  System.Console.WriteLine("Deleting ROOMS...");
                     *  foreach (var roomId in await redis.SetMembersAsync<string>("mudpie::rooms"))
                     *      await redis.RemoveAsync($"mudpie::room:{roomId}");
                     *  await redis.RemoveAsync("mudpie::rooms");
                     *
                     *  System.Console.WriteLine("Deleting USERS...");
                     *  foreach (var playerId in await redis.SetMembersAsync<string>("mudpie::players"))
                     *      await redis.RemoveAsync($"mudpie::player:{playerId}");
                     *  await redis.RemoveAsync("mudpie::players");
                     * }*/
                    return(0);
                }).Wait();

                // Listen for connections
                server.Start();

                Console.WriteLine("\r\nPress ~ to quit the server console");
                while (Console.ReadKey().Key != ConsoleKey.Oem3)
                {
                }

                Console.WriteLine("\r\nShutting down server...");
                server.Stop();
                Console.WriteLine("\r\nServer is shut down. End of line.");
            }
        }