Ejemplo n.º 1
0
        /// <summary>
        /// Static ctor
        /// Sets up the default roles
        /// </summary>
        static Role()
        {
            ProcessName first      = "role-first";
            ProcessName second     = "role-second";
            ProcessName third      = "role-third";
            ProcessName last       = "role-last";
            ProcessName next       = "role-next";
            ProcessName prev       = "role-prev";
            ProcessName broadcast  = "role-broadcast";
            ProcessName leastBusy  = "role-least-busy";
            ProcessName random     = "role-random";
            ProcessName roundRobin = "role-round-robin";

            var nextNode = fun((bool fwd) => fun((ProcessId leaf) =>
            {
                var self    = leaf.Take(1).Name;
                var isNext  = false;
                var nodeMap = Nodes(leaf);

                var nodes = fwd
                    ? MEnumerable <ClusterNode> .Inst.Append(nodeMap.Values, nodeMap.Values)
                    : MEnumerable <ClusterNode> .Inst.Append(nodeMap.Values, nodeMap.Values).Reverse(); //< TODO: Inefficient

                foreach (var node in nodes)
                {
                    if (isNext)
                    {
                        return(new[] { ProcessId.Top[node.NodeName].Append(leaf.Skip(1)) }.AsEnumerable());
                    }

                    if (node.NodeName == self)
                    {
                        isNext = true;
                    }
                }
                return(new ProcessId[0].AsEnumerable());
            }));

            // Next
            nextRoot = Dispatch.register(next, nextNode(true));

            // Prev
            prevRoot = Dispatch.register(prev, nextNode(false));

            // First
            First = Dispatch.register(first, leaf => NodeIds(leaf).Take(1));

            // Second
            Second = Dispatch.register(second, leaf => NodeIds(leaf).Skip(1).Take(1));

            // Third
            Third = Dispatch.register(third, leaf => NodeIds(leaf).Skip(2).Take(1));

            // Last
            Last = Dispatch.register(last, leaf => NodeIds(leaf).Reverse().Take(1));

            // Broadcast
            Broadcast = Dispatch.register(broadcast, NodeIds);

            // Least busy
            LeastBusy = Dispatch.register(leastBusy, leaf =>
                                          NodeIds(leaf)
                                          .Map(pid => Tuple(inboxCount(pid), pid))
                                          .OrderBy(tup => tup.Item1)
                                          .Map(tup => tup.Item2)
                                          .Take(1));

            // Random
            Random = Dispatch.register(random, leaf => {
                var workers = NodeIds(leaf).ToArray();
                return(new ProcessId[1] {
                    workers[Prelude.random(workers.Length)]
                });
            });

            // Round-robin
            object            sync            = new object();
            Map <string, int> roundRobinState = Map <string, int>();

            RoundRobin = Dispatch.register(roundRobin, leaf => {
                var key     = leaf.ToString();
                var workers = NodeIds(leaf).ToArray();
                int index   = 0;
                lock (sync)
                {
                    roundRobinState = roundRobinState.AddOrUpdate(key, x => { index = x % workers.Length; return(x + 1); }, 0);
                }
                return(new ProcessId[1] {
                    workers[index]
                });
            });
        }
Ejemplo n.º 2
0
 private static Option <T> GetOneOrMerge <T>(Option <T> l, Option <T> r, Func <T, T, T> merge)
 {
     return(Prelude.match(l,
                          Some: (lvalue) => Prelude.match(r, Some: (rvalue) => merge(lvalue, rvalue), None: () => lvalue),
                          None: () => r));
 }
Ejemplo n.º 3
0
 protected override Option<char> ParseT(string value) => Prelude.parseChar(value);
Ejemplo n.º 4
0
 public static HashMap <A, HashMap <B, T> > AddOrUpdate <A, B, T>(this HashMap <A, HashMap <B, T> > self, A outerKey, B innerKey, Func <T, T> Some, Func <T> None) =>
 self.AddOrUpdate(
     outerKey,
     b => b.AddOrUpdate(innerKey, Some, None),
     () => Prelude.HashMap(Tuple(innerKey, None()))
     );
Ejemplo n.º 5
0
 public static bool IsTweekIdentity(this ClaimsPrincipal identity)
 {
     return(Prelude.Optional(identity.FindFirst("iss")).Match(c => c.Value.Equals("tweek"), () => false));
 }
Ejemplo n.º 6
0
 protected override Option <byte> ParseT(string value) => Prelude.parseByte(value);
Ejemplo n.º 7
0
 List <iCS_EngineObject> EditorToEngineList(List <iCS_EditorObject> editorObjects)
 {
     return(Prelude.map(eo => (eo != null ? eo.EngineObject : null), editorObjects));
 }
Ejemplo n.º 8
0
        public void ConsTest1()
        {
            var test = Prelude.Cons(1, Prelude.Cons(2, Prelude.Cons(3, Prelude.Cons(4, Prelude.Cons(5, LanguageExt.List.empty <int>())))));

            var array = test.ToArray();

            Assert.True(array[0] == 1);
            Assert.True(array[1] == 2);
            Assert.True(array[2] == 3);
            Assert.True(array[3] == 4);
            Assert.True(array[4] == 5);
        }
Ejemplo n.º 9
0
 protected Stck <int> CreateDataType()
 => new Stck <int>(Prelude.Range(1, 100));
Ejemplo n.º 10
0
        static Dispatch()
        {
            ProcessName broadcast  = "broadcast";
            ProcessName leastBusy  = "least-busy";
            ProcessName random     = "random";
            ProcessName roundRobin = "round-robin";

            ProcessName first  = "first";
            ProcessName second = "second";
            ProcessName third  = "third";
            ProcessName last   = "last";

            var processes = fun((ProcessId leaf) =>
            {
                if (!leaf.IsValid)
                {
                    return(new ProcessId[0]);
                }
                if (leaf.IsSelection)
                {
                    return(leaf.GetSelection());
                }
                if (leaf.Head().Name == "disp")
                {
                    leaf = leaf.Skip(1);
                    if (!leaf.IsValid)
                    {
                        return(new ProcessId[0]);
                    }
                    return(getFunc(leaf.Head().Name)(leaf.Skip(1)));
                }
                return(new ProcessId[1] {
                    leaf
                });
            });

            // Broadcast
            Broadcast = register(broadcast, processes);

            // First
            First = register(first, leaf => processes(leaf).Take(1));

            // Second
            Second = register(second, leaf => processes(leaf).Skip(1).Take(1));

            // Third
            Third = register(third, leaf => processes(leaf).Skip(2).Take(1));

            // Last
            Last = register(last, leaf => processes(leaf).Reverse().Take(1));

            // Least busy
            LeastBusy = register(leastBusy, leaf =>
                                 processes(leaf)
                                 .Map(pid => Tuple(inboxCount(pid), pid))
                                 .OrderBy(tup => tup.Item1)
                                 .Map(tup => tup.Item2)
                                 .Take(1));

            // Random
            Random = register(random, leaf => {
                var workers = processes(leaf).ToArray();
                return(new ProcessId[1] {
                    workers[Prelude.random(workers.Length)]
                });
            });

            // Round-robin
            object            sync            = new object();
            Map <string, int> roundRobinState = Map <string, int>();

            RoundRobin = register(roundRobin, leaf => {
                var key     = leaf.ToString();
                var workers = processes(leaf).ToArray();
                int index   = 0;
                lock (sync)
                {
                    roundRobinState = roundRobinState.AddOrUpdate(key, x => { index = x % workers.Length; return(x + 1); }, 0);
                }
                return(new ProcessId[1] {
                    workers[index]
                });
            });
        }
Ejemplo n.º 11
0
        public static async Task <Either <PowershellFailure, TypedPsObject <VirtualMachineInfo> > > VirtualDisk(
            VMDiskStorageSettings diskSettings,
            IPowershellEngine engine,
            TypedPsObject <VirtualMachineInfo> vmInfo,
            Seq <CurrentVMDiskStorageSettings> currentStorageSettings,
            Func <string, Task> reportProgress)
        {
            var currentSettings =
                currentStorageSettings.Find(x => diskSettings.Path.Equals(x.Path, StringComparison.OrdinalIgnoreCase) &&
                                            diskSettings.Name.Equals(x.Name, StringComparison.InvariantCultureIgnoreCase));
            var frozenOptional = currentSettings.Map(x => x.Frozen);

            if (frozenOptional.IsSome && frozenOptional.ValueUnsafe())
            {
                await reportProgress($"Skipping disk '{diskSettings.Name}': storage management is disabled for this disk.").ConfigureAwait(false);

                return(vmInfo);
            }



            return(await diskSettings.AttachPath.Map(async (vhdPath) =>
            {
                if (!File.Exists(vhdPath))
                {
                    await reportProgress($"Create VHD: {diskSettings.Name}").ConfigureAwait(false);

                    var createDiskResult = await diskSettings.ParentPath.Match(Some: parentPath =>
                    {
                        return engine.RunAsync(PsCommandBuilder.Create().Script(
                                                   $"New-VHD -Path \"{vhdPath}\" -ParentPath \"{parentPath}\" -Differencing"));
                    },
                                                                               None: () =>
                    {
                        return engine.RunAsync(PsCommandBuilder.Create().Script(
                                                   $"New-VHD -Path \"{vhdPath}\" -Dynamic -SizeBytes {diskSettings.SizeBytes}"));
                    });

                    if (createDiskResult.IsLeft)
                    {
                        return Prelude.Left(createDiskResult.LeftAsEnumerable().FirstOrDefault());
                    }
                }

                var sizeResult = await engine
                                 .GetObjectsAsync <VhdInfo>(new PsCommandBuilder().AddCommand("get-vhd").AddArgument(vhdPath))
                                 .BindAsync(x => x.HeadOrLeft(new PowershellFailure())).BindAsync(async(vhdInfo) =>
                {
                    if (vhdInfo.Value.Size != diskSettings.SizeBytes && diskSettings.SizeBytes > 0)
                    {
                        var gb = Math.Round(diskSettings.SizeBytes / 1024d / 1024 / 1024, 1);
                        await reportProgress(
                            $"Resizing disk {diskSettings.Name} to {gb} GB");
                        return await engine.RunAsync(PsCommandBuilder.Create().AddCommand("Resize-VHD")
                                                     .AddArgument(vhdPath)
                                                     .AddParameter("Size", diskSettings.SizeBytes));
                    }

                    return Unit.Default;
                });

                if (sizeResult.IsLeft)
                {
                    return Prelude.Left(sizeResult.LeftAsEnumerable().FirstOrDefault());
                }


                return await GetOrCreateInfoAsync(vmInfo,
                                                  i => i.HardDrives,
                                                  disk => currentSettings.Map(x => x.AttachedVMId) == disk.Id,
                                                  async() =>
                {
                    await reportProgress($"Attaching disk {diskSettings.Name} to controller: {diskSettings.ControllerNumber}, Location: {diskSettings.ControllerLocation}").ConfigureAwait(false);
                    return (await engine.GetObjectsAsync <HardDiskDriveInfo>(PsCommandBuilder.Create()
                                                                             .AddCommand("Add-VMHardDiskDrive")
                                                                             .AddParameter("VM", vmInfo.PsObject)
                                                                             .AddParameter("Path", vhdPath)
                                                                             .AddParameter("ControllerNumber", diskSettings.ControllerNumber)
                                                                             .AddParameter("ControllerLocation", diskSettings.ControllerLocation)
                                                                             .AddParameter("PassThru")
                                                                             ).ConfigureAwait(false));
                }).BindAsync(_ => vmInfo.RecreateOrReload(engine))


                .ConfigureAwait(false);
            }).IfNone(vmInfo.RecreateOrReload(engine)));
        }
Ejemplo n.º 12
0
 protected override Option <double> ParseT(string value) => Prelude.parseDouble(value);
Ejemplo n.º 13
0
 protected override Option <short> ParseT(string value) => Prelude.parseShort(value);
Ejemplo n.º 14
0
 protected override Option <decimal> ParseT(string value) => Prelude.parseDecimal(value);
 public static Option <Money> StopLossPrice(Money accountRisk, Money entryPrice, Quantity shares) =>
 Prelude.Try(() => (shares * entryPrice - accountRisk) / shares)
 .Map(pq => pq.PerShare)
 .Map(Money)
 .ToOption();
Ejemplo n.º 16
0
 public void parseTimeSpan_valid() =>
 Assert.Equal(Prelude.Some(new TimeSpan(0, 0, 0, 19, 12)), Prelude.parseTimeSpan("00:00:19.0120000"));
 public static Option <Percent> Risk(Money capital, Money accountRisk) =>
 Prelude.Try(() => accountRisk / capital)
 .Map(PercentExtensions.ToPercent)
 .ToOption();
Ejemplo n.º 18
0
 public void parseTimeSpan_multipleInvalid(string input) => Assert.Equal(Prelude.None, Prelude.parseTimeSpan(input));
Ejemplo n.º 19
0
 internal static T NullReturn <T>(T value) =>
 Prelude.isnull(value)
         ? Prelude.raise <T>(new ResultIsNullException())
         : value;
Ejemplo n.º 20
0
 protected override Option <TimeSpan> ParseT(string value) => Prelude.parseTimeSpan(value);
Ejemplo n.º 21
0
 public Try <T> ConvertTo(AbapValue abapValue)
 {
     return(Prelude.Try(() => (T)Convert.ChangeType(abapValue, typeof(T), CultureInfo.InvariantCulture)));
 }
Ejemplo n.º 22
0
 public TryOptionAsync <B> Map(TryOptionAsync <A> ma, Func <A, B> f) =>
 default(MTryOptionAsync <A>).Bind <MTryOptionAsync <B>, TryOptionAsync <B>, B>(ma, a => Prelude.TryOptionAsync(f(a)));
Ejemplo n.º 23
0
 public static HashMap <A, HashMap <B, T> > AddOrUpdate <A, B, T>(this HashMap <A, HashMap <B, T> > self, A outerKey, B innerKey, T value) =>
 self.AddOrUpdate(
     outerKey,
     b => b.AddOrUpdate(innerKey, _ => value, value),
     () => Prelude.HashMap(Tuple(innerKey, value))
     );
Ejemplo n.º 24
0
 public TryOptionAsync <B> MapAsync(TryOptionAsync <A> ma, Func <A, Task <B> > f) =>
 default(MTryOptionAsync <A>).BindAsync <MTryOptionAsync <B>, TryOptionAsync <B>, B>(ma, async a => Prelude.TryOptionAsync(await f(a)));
Ejemplo n.º 25
0
 protected override Option <uint> ParseT(string value) => Prelude.parseUInt(value);
Ejemplo n.º 26
0
 public int GetHashCode(Que <A> x) =>
 Prelude.hash <HashA, A>(x);
Ejemplo n.º 27
0
 public static GetRule With(string path, IRule rule)
 {
     return(fnPath => path == fnPath?Prelude.Some(rule) : Prelude.None);
 }
Ejemplo n.º 28
0
 public static Eff <A> ToEff <A>(this Try <A> ma) =>
 Prelude.EffMaybe(() =>
                  ma.Match(Succ: Fin <A> .Succ,
                           Fail: e => Fin <A> .Fail(e)));
Ejemplo n.º 29
0
 public static Eff <A> ToEff <A>(this TryOption <A> ma) =>
 Prelude.EffMaybe(() =>
                  ma.Match(Some: Fin <A> .Succ,
                           None: () => Fin <A> .Fail(Errors.None),
                           Fail: e => Fin <A> .Fail(e)));
Ejemplo n.º 30
0
 protected override Option <DateTimeOffset> ParseT(string value) => Prelude.parseDateTimeOffset(value);