예제 #1
0
    public void DirectionInput(int tick, GameObject SourceInstance, IElectricityIO ComingFrom, IElectricityIO PassOn = null)
    {
        //Logger.Log(SourceInstance.ToString() + " < SourceInstance " + ComingFrom.ToString() + " < ComingFrom " + this.name + " < this " );
        if (connections.Count > 2)
        {
            ElectricityFunctions.DirectionInput(tick, SourceInstance, ComingFrom, this);
            FirstPresentInspector = FirstPresent;
        }
        else
        {
            int SourceInstanceID = SourceInstance.GetInstanceID();
            if (!(Upstream.ContainsKey(SourceInstanceID)))
            {
                Upstream [SourceInstanceID] = new HashSet <IElectricityIO> ();
            }
            if (!(Downstream.ContainsKey(SourceInstanceID)))
            {
                Downstream [SourceInstanceID] = new HashSet <IElectricityIO> ();
            }
            if (FirstPresent == 0)
            {
                //Logger.Log ("to It's been claimed", Category.Electrical);
                FirstPresent = SourceInstanceID;
                //Thiswire.FirstPresentInspector = SourceInstanceID;
            }

            if (ComingFrom != null)
            {
                Upstream [SourceInstanceID].Add(ComingFrom);
            }
            CameFromMemory = PassOn;
            SourceInstance.GetComponent <IProvidePower> ().DirectionWorkOnNextList.Add(this);
        }
    }
예제 #2
0
        private string ValidateTrace(Downstream target, TraceResponse resp, string service, int level, string traceID, bool sampled, string baggage)
        {
            if (!EqualTraceIDs(traceID, resp.Span.TraceId))
            {
                return($"Trace ID mismatch in S{level}({service}): expected {traceID}, received {resp.Span.TraceId}");
            }
            if (baggage != resp.Span.Baggage)
            {
                return($"Baggage mismatch in S{level}({service}): expected {baggage}, received {resp.Span.Baggage}");
            }
            if (sampled != resp.Span.Sampled)
            {
                return($"Sampled mismatch in S{level}({service}): expected {sampled}, received {resp.Span.Sampled}");
            }
            if (target != null)
            {
                if (resp.Downstream == null)
                {
                    return($"Missing downstream in S{level}({service})");
                }

                return(ValidateTrace(target.Downstream_, resp.Downstream, target.Host, level + 1, traceID, sampled, baggage));
            }

            if (resp.Downstream != null)
            {
                return($"Unexpected downstream in S{level}({service})");
            }

            return(null);
        }
예제 #3
0
        public async Task <TraceResponse> PrepareResponseAsync(Downstream downstream)
        {
            var response = new TraceResponse(ObserveSpan());

            if (downstream != null)
            {
                var downstreamResponse = await CallDownstreamAsync(downstream);

                response.Downstream = downstreamResponse;
            }

            return(response);
        }
예제 #4
0
        private void downStreamOutput(Downstream down)
        {
            switch (down.Routing)
            {
            case RoutingType.hashing:
                break;

            case RoutingType.primary:
                replicateTuplesToNode(down.TargetIPs.First()).makeNodeWork();    /*TODO - make it work*/
                break;

            case RoutingType.random:
                Random rnd1 = new Random();
                replicateTuplesToNode(down.TargetIPs[rnd1.Next(down.TargetIPs.Count)]).makeNodeWork();
                break;
            }
        }
예제 #5
0
        private async Task <TraceResponse> CallDownstreamHttpAsync(Downstream downstream)
        {
            var downstreamUrl = $"http://{downstream.Host}:{downstream.Port}/join_trace";

            _logger.LogInformation("Calling downstream http {serviceName} at {downstream}", downstream.ServiceName, downstreamUrl);

            var jsonContent = JsonSerializer.Serialize(new JoinTraceRequest(downstream.ServerRole, downstream.Downstream_));
            var resp        = await _client.PostAsync(downstreamUrl, new StringContent(jsonContent, Encoding.UTF8, "application/json"));

            if (!resp.IsSuccessStatusCode)
            {
                _logger.LogError("Received response with status code {statusCode}", resp.StatusCode);
                return(null);
            }
            var response = await JsonSerializer.DeserializeAsync <TraceResponse>(await resp.Content.ReadAsStreamAsync());

            _logger.LogInformation("Received response {response}", response);
            return(response);
        }
예제 #6
0
        public ChainSetup(
            Func <Flow <TIn, TIn, NotUsed>, Flow <TIn, TOut, TMat> > stream,
            ActorMaterializerSettings settings,
            ActorMaterializer materializer,
            Func <Source <TOut, NotUsed>, ActorMaterializer, IPublisher <TOut> > toPublisher,
            TestKitBase system)
        {
            Settings = settings;
            System   = system;

            Upstream   = system.CreateManualPublisherProbe <TIn>();
            Downstream = system.CreateSubscriberProbe <TOut>();

            var s = Source.FromPublisher(Upstream).Via(stream(Flow.Identity <TIn>().Select(x => x).Named("buh")));

            Publisher            = toPublisher(s, materializer);
            UpstreamSubscription = Upstream.ExpectSubscription();
            Publisher.Subscribe(Downstream);
            DownstreamSubscription = Downstream.ExpectSubscription();
        }
예제 #7
0
        private Task <TraceResponse> CallDownstreamAsync(Downstream downstream)
        {
            _logger.LogInformation("Calling downstream {downstream}", downstream);
            _logger.LogInformation(
                "Downstream service {serviceName} -> {host}:{port}",
                downstream.ServiceName,
                downstream.Host,
                downstream.Port);

            var transport = downstream.Transport;

            switch (transport)
            {
            case Constants.TRANSPORT_HTTP:
                return(CallDownstreamHttpAsync(downstream));

            default:
                return(Task.FromResult(new TraceResponse("Unrecognized transport received: " + transport)));
            }
        }
예제 #8
0
            public bool ShakeIt()
            {
                var oneMilli = TimeSpan.FromMilliseconds(1);
                var marker   = new object();
                var u        = Upstream.ReceiveWhile(oneMilli, filter: msg =>
                {
                    if (msg is TestPublisher.RequestMore)
                    {
                        var more = (TestPublisher.RequestMore)msg;
                        DebugLog($"Operation requests {more.NrOfElements}");
                        _pendingRequests += more.NrOfElements;
                        return(marker);
                    }
                    return(null);
                });
                var d = Downstream.ReceiveWhile(oneMilli, filter: msg => msg.Match()
                                                .With <TestSubscriber.OnNext <TOut> >(next =>
                {
                    DebugLog($"Operation produces [{next.Element}]");
                    if (_outstandingDemand == 0)
                    {
                        throw new Exception("operation produced while there was no demand");
                    }
                    _outstandingDemand--;
                    _currentScript = _currentScript.ConsumeOutput(next.Element);
                })
                                                .With <TestSubscriber.OnComplete>(complete =>
                {
                    _currentScript = _currentScript.Complete();
                })
                                                .With <TestSubscriber.OnError>(error =>
                {
                    _currentScript = _currentScript.Error(error.Cause);
                })
                                                .WasHandled
                    ? marker
                    : null);

                return(u.Concat(d).Any(x => x == marker));
            }
예제 #9
0
            /// <summary>
            /// Run method starts the .NET equivalent of SFZ fuzzer main loop.
            /// </summary>
            /// <param name="action">
            /// Some action that calls the instrumented library. The stream
            /// argument passed to the action contains the serialized input data.
            /// </param>
            public static unsafe void RunSfz(string[] args, Action <byte[]> action)
            {
                Console.WriteLine("Starting Sfz Main");

                int[] fileDescriptors = ReadFileDescriptors(args);
                int   fdIn            = fileDescriptors[0];
                int   fdOut           = fileDescriptors[1];

                Console.Write("GO_FUZZ_IN_FD: " + fdIn);
                Console.WriteLine(" GO_FUZZ_OUT_FD: " + fdOut);

                string[] commName = ReadSharedMemoryNames(args);

                using (SafeFileHandle inPipeHandle = new SafeFileHandle(new IntPtr(fdIn), true),
                       outPipeHandle = new SafeFileHandle(new IntPtr(fdOut), true))
                {
                    // Use the filehandles
                    Stream inStream  = new FileStream(inPipeHandle, FileAccess.Read);
                    Stream outStream = new FileStream(outPipeHandle, FileAccess.Write);
                    Console.WriteLine("created inStream and outStream");

                    //MemoryMappedFileSecurity security = new MemoryMappedFileSecurity();
                    //security.AddAccessRule(new AccessRule<MemoryMappedFileRights>(("Everyone"),
                    //    MemoryMappedFileRights.FullControl, AccessControlType.Allow));
                    //Console.WriteLine("created security");

                    using (
                        MemoryMappedFile comm0 = MemoryMappedFile.OpenExisting(commName[0],
                                                                               MemoryMappedFileRights.ReadWrite, HandleInheritability.Inheritable),
                        comm1 = MemoryMappedFile.OpenExisting(commName[1], MemoryMappedFileRights.ReadWrite,
                                                              HandleInheritability.Inheritable),
                        comm2 = MemoryMappedFile.OpenExisting(commName[2], MemoryMappedFileRights.ReadWrite,
                                                              HandleInheritability.Inheritable),
                        comm3 = MemoryMappedFile.OpenExisting(commName[3], MemoryMappedFileRights.ReadWrite,
                                                              HandleInheritability.Inheritable))
                    {
                        const int MaxInputSize     = 1 << 24;
                        const int ReturnResultSize = 1 << 25;
                        const int CoverSize        = 64 << 10;
                        const int SonarRegionSize  = 1 << 20;

                        var cover = new byte[CoverSize];
                        fixed(byte *coverPtr = cover)
                        {
                            var trace = new TraceWrapper(coverPtr);

                            Console.WriteLine("created commX objects");

                            var comm0Accessor = comm0.CreateViewAccessor(0, MaxInputSize);
                            var comm1Accessor = comm1.CreateViewAccessor(0, ReturnResultSize);
                            var comm2Accessor = comm2.CreateViewAccessor(0, CoverSize);
                            var comm3Accessor = comm3.CreateViewAccessor(0, SonarRegionSize);

                            Console.WriteLine("created commX accessors");

                            while (true)
                            {
                                int  fnidx       = 0;
                                long inputLength = 0;
                                (fnidx, inputLength) = ReadIndexAndLength(inStream);

                                // read inputBuffer data from comm0
                                var inputBuffer = new byte[inputLength];
                                comm0Accessor.ReadArray(0, inputBuffer, 0, (int)inputLength);
                                for (int i = 0; i < inputLength; i++)
                                {
                                    inputBuffer[i] = comm0Accessor.ReadByte(i);
                                }

                                var inputString = Encoding.UTF8.GetString(inputBuffer);
                                Console.WriteLine("downstream: " + Encoding.UTF8.GetString(inputBuffer));
                                var downstream = new Downstream();
                                try
                                {
                                    downstream = JsonSerializer.Deserialize <Downstream>(inputString);
                                }
                                catch (Exception ex)
                                {
                                    Console.WriteLine("downstream deserialization exception: " + ex.Message);
                                }

                                //var downstream = FlatBufferSerializer.Default.Parse<Downstream>(inputBuffer);
                                Console.WriteLine("downstream deserialized");

                                Upstream upstream = NewUpstreamObj();

                                long res   = 0;
                                long ns    = 0;
                                long sonar = 0;

                                var seed = downstream.Seed;
                                if (seed != null && seed.Data != null && seed.Data.Length >= 1)
                                {
                                    ConfigEntry entry = seed.Data[0];
                                    var         value = entry.Value;

                                    if (entry.Value != null)
                                    {
                                        Console.WriteLine("got entry value: " + value);

                                        // Start the clock
                                        var nsStart = DateTime.UtcNow.Ticks;

                                        try
                                        {
                                            // Actually run the function to fuzz
                                            byte[] buffer = Encoding.UTF8.GetBytes(value);
                                            action(buffer);
                                            Console.Write("exec fuzz method");
                                        }
                                        catch (Exception exception)
                                        {
                                            ns = DateTime.UtcNow.Ticks - nsStart;
                                            Console.WriteLine("ns: " + ns);

                                            upstream.Crashed       = true;
                                            upstream.HasFailed     = true;
                                            upstream.ResultMessage = exception.ToString();
                                        }
                                    }
                                    else
                                    {
                                        Console.WriteLine("null entry value!");
                                        var nsStart = DateTime.UtcNow.Ticks;
                                        try
                                        {
                                            // Actually run the function to fuzz
                                            byte[] buffer = Encoding.UTF8.GetBytes("<html><body><h1>h1</h1><p>p</p></body></html>");
                                            action(buffer);
                                            Console.Write("exec fuzz method");
                                        }
                                        catch (Exception exception)
                                        {
                                            ns = DateTime.UtcNow.Ticks - nsStart;
                                            Console.WriteLine("ns: " + ns);

                                            upstream.Crashed       = true;
                                            upstream.HasFailed     = true;
                                            upstream.ResultMessage = exception.ToString();
                                        }
                                    }
                                }
                                else
                                {
                                    Console.WriteLine("zero entries!");
                                    var nsStart = DateTime.UtcNow.Ticks;
                                    try
                                    {
                                        // Actually run the function to fuzz
                                        byte[] buffer = Encoding.UTF8.GetBytes("<html><body><h1>h1</h1><p>p</p></body></html>");
                                        action(buffer);
                                        Console.Write("exec fuzz method");
                                    }
                                    catch (Exception exception)
                                    {
                                        ns = DateTime.UtcNow.Ticks - nsStart;
                                        Console.WriteLine("ns: " + ns);

                                        upstream.Crashed       = true;
                                        upstream.HasFailed     = true;
                                        upstream.ResultMessage = exception.ToString();
                                    }
                                }

                                for (int i = 0; i < cover.Length; i++)
                                {
                                    if (cover[i] != 0)
                                    {
                                        Console.WriteLine("nonzero cover!");
                                    }
                                }

                                // copy cover to shared memory
                                for (int i = 0; i < cover.Length; i++)
                                {
                                    comm2Accessor.Write(i, cover[i]);
                                }
                                comm2Accessor.Flush();

                                ReturnResult(comm1Accessor, outStream, res, ns, sonar, upstream);
                            }
                        }
                    }
                }
            }
예제 #10
0
 public static HttpDownstreamOptions GetHttpDownstreamOptions(this Downstream downstream)
 {
     return(downstream.Data["Options"] as HttpDownstreamOptions);
 }
예제 #11
0
 public static RabbitMqDownstreamOptions GetRabbitMqDownstreamOptions(this Downstream downstream)
 {
     return(downstream.Data["Options"] as RabbitMqDownstreamOptions);
 }
예제 #12
0
        public async Task <ActionResult> Client(string behavior, string client, string s1name, string s2name, string s2transport, string s3name, string s3transport,
                                                bool sampled)
        {
            if (behavior != "trace")
            {
                return(ResultFromCrossdock(CrossdockResult.Result.Error, $"Unknown behavior: {behavior}"));
            }
            if (client != "csharp")
            {
                return(ResultFromCrossdock(CrossdockResult.Result.Error, $"Unknown client: {client}"));
            }
            if (string.IsNullOrEmpty(s1name))
            {
                return(ResultFromCrossdock(CrossdockResult.Result.Error, $"Value must not be null or empty: {s1name}"));
            }
            if (string.IsNullOrEmpty(s2name))
            {
                return(ResultFromCrossdock(CrossdockResult.Result.Error, $"Value must not be null or empty: {s2name}"));
            }
            if (string.IsNullOrEmpty(s2transport))
            {
                return(ResultFromCrossdock(CrossdockResult.Result.Error, $"Value must not be null or empty: {s2transport}"));
            }
            if (string.IsNullOrEmpty(s3name))
            {
                return(ResultFromCrossdock(CrossdockResult.Result.Error, $"Value must not be null or empty: {s3name}"));
            }
            if (string.IsNullOrEmpty(s3transport))
            {
                return(ResultFromCrossdock(CrossdockResult.Result.Error, $"Value must not be null or empty: {s3transport}"));
            }

            var baggage = RandomBaggage();
            var level3  = new Downstream(s3name, s3name, TransportToPort(s3transport), StringToTransport(s3transport), "S3", null);
            var level2  = new Downstream(s2name, s2name, TransportToPort(s2transport), StringToTransport(s2transport), "S2", level3);
            var level1  = new StartTraceRequest("S1", sampled, baggage, level2);

            var response = await StartTraceAsync(s1name, level1);

            if (response == null || !string.IsNullOrEmpty(response.NotImplementedError))
            {
                return(ResultFromCrossdock(CrossdockResult.Result.Error, response?.NotImplementedError));
            }

            for (var r = response; r != null; r = r.Downstream)
            {
                if (!string.IsNullOrEmpty(r.NotImplementedError))
                {
                    _logger.LogInformation("SKIP: {reason}", r.NotImplementedError);
                    return(ResultFromCrossdock(CrossdockResult.Result.Skip, r.NotImplementedError));
                }
            }

            var traceID = response.Span.TraceId;

            if (string.IsNullOrEmpty(traceID))
            {
                return(ResultFromCrossdock(CrossdockResult.Result.Error, $"Trace ID is empty in S1({s1name})"));
            }

            var result = ValidateTrace(level1.Downstream, response, s1name, 1, traceID, sampled, baggage);

            if (result != null)
            {
                return(ResultFromCrossdock(CrossdockResult.Result.Error, result));
            }

            _logger.LogInformation("PASS");
            return(ResultFromCrossdock(CrossdockResult.Result.Success, "trace checks out"));
        }