Exemplo n.º 1
0
        public override IEnumerable <Guid> List(int maxResults, DateTime?start = null, DateTime?finish = null, ListResultsOrder orderBy = ListResultsOrder.Descending)
        {
            IMongoQuery query = null;

            if (start != null)
            {
                query = Query.And(Query.GT("Started", (DateTime)start));
            }
            if (finish != null)
            {
                query = Query.And(Query.LT("Started", (DateTime)finish));
            }

            var profilers = Profilers.Find(query).Take(maxResults);

            if (orderBy == ListResultsOrder.Descending)
            {
                profilers = profilers.OrderByDescending(p => p.Started);
            }
            else
            {
                profilers = profilers.OrderBy(p => p.Started);
            }

            return(profilers.Select(p => Guid.Parse(p.Id)));
        }
Exemplo n.º 2
0
        /// <summary>
        /// Stores <param name="profiler"/> to MongoDB under its <see cref="MiniProfiler.Id"/>;
        /// stores all child Timings and SqlTimings to their respective tables.
        /// </summary>
        public override void Save(MiniProfiler profiler)
        {
            var profilerPoco = new MiniProfilerPoco
            {
                Id                                   = profiler.Id.ToString(),
                Name                                 = Truncate(profiler.Name, 200),
                Started                              = profiler.Started,
                MachineName                          = Truncate(profiler.MachineName, 100),
                User                                 = Truncate(profiler.User, 100),
                Level                                = profiler.Level,
                RootTimingId                         = profiler.Root.Id,
                DurationMilliseconds                 = (double)profiler.DurationMilliseconds,
                DurationMillisecondsInSql            = (double)profiler.DurationMillisecondsInSql,
                HasSqlTimings                        = profiler.HasSqlTimings,
                HasDuplicateSqlTimings               = profiler.HasDuplicateSqlTimings,
                HasTrivialTimings                    = profiler.HasTrivialTimings,
                HasAllTrivialTimings                 = profiler.HasAllTrivialTimings,
                TrivialDurationThresholdMilliseconds = (double)profiler.TrivialDurationThresholdMilliseconds,
                HasUserViewed                        = profiler.HasUserViewed
            };

            var result = Profilers.Save(profilerPoco, SafeMode.True);

            if (result.UpdatedExisting == false)
            {
                //Save Root Timing
                SaveTiming(profiler, profiler.Root);
            }

            // we may have a missing client timing - re save
            if (profiler.ClientTimings != null)
            {
                SaveClientTiming(profiler);
            }
        }
Exemplo n.º 3
0
        public void UnaryCallPerformance()
        {
            var profiler = new BasicProfiler();

            Profilers.SetForCurrentThread(profiler);

            helper.UnaryHandler = new UnaryServerMethod <string, string>(async(request, context) =>
            {
                return(request);
            });

            var callDetails = helper.CreateUnaryCall();

            for (int i = 0; i < 3000; i++)
            {
                Calls.BlockingUnaryCall(callDetails, "ABC");
            }

            profiler.Reset();

            for (int i = 0; i < 3000; i++)
            {
                Calls.BlockingUnaryCall(callDetails, "ABC");
            }
            profiler.Dump("latency_trace_csharp.txt");
        }
Exemplo n.º 4
0
 private static Profilers_FFI Convert(Profilers data)
 {
     return(new Profilers_FFI
     {
         profilers = Convert(data.profilers),
     });
 }
Exemplo n.º 5
0
        private void RunUnary(Channel channel, IInterarrivalTimer timer, BasicProfiler optionalProfiler)
        {
            if (optionalProfiler != null)
            {
                Profilers.SetForCurrentThread(optionalProfiler);
            }

            bool profilerReset = false;

            var client    = new BenchmarkService.BenchmarkServiceClient(channel);
            var request   = CreateSimpleRequest();
            var stopwatch = new Stopwatch();

            while (!stoppedCts.Token.IsCancellationRequested)
            {
                // after the first stats reset, also reset the profiler.
                if (optionalProfiler != null && !profilerReset && statsResetCount.Count > 0)
                {
                    optionalProfiler.Reset();
                    profilerReset = true;
                }

                stopwatch.Restart();
                client.UnaryCall(request);
                stopwatch.Stop();

                // spec requires data point in nanoseconds.
                threadLocalHistogram.Value.AddObservation(stopwatch.Elapsed.TotalSeconds * SecondsToNanos);

                timer.WaitForNext();
            }
        }
Exemplo n.º 6
0
        /// <summary>
        /// Handler for unary response completion.
        /// </summary>
        private void HandleUnaryResponse(bool success, ClientSideStatus receivedStatus, byte[] receivedMessage, Metadata responseHeaders)
        {
            using (Profilers.ForCurrentThread().NewScope("AsyncCall.HandleUnaryResponse"))
            {
                TResponse msg = default(TResponse);
                var       deserializeException = success ? TryDeserialize(receivedMessage, out msg) : null;

                lock (myLock)
                {
                    finished = true;

                    if (deserializeException != null && receivedStatus.Status.StatusCode == StatusCode.OK)
                    {
                        receivedStatus = new ClientSideStatus(DeserializeResponseFailureStatus, receivedStatus.Trailers);
                    }
                    finishedStatus = receivedStatus;

                    ReleaseResourcesIfPossible();
                }

                responseHeadersTcs.SetResult(responseHeaders);

                var status = receivedStatus.Status;

                if (!success || status.StatusCode != StatusCode.OK)
                {
                    unaryResponseTcs.SetException(new RpcException(status));
                    return;
                }

                unaryResponseTcs.SetResult(msg);
            }
        }
Exemplo n.º 7
0
        /// <summary>
        /// Stores <param name="profiler"/> to MongoDB under its <see cref="MiniProfiler.Id"/>;
        /// stores all child Timings and SqlTimings to their respective tables.
        /// </summary>
        public override void Save(MiniProfiler profiler)
        {
            var miniProfilerPoco = new MiniProfilerPoco
            {
                Id                          = profiler.Id,
                RootTimingId                = profiler.Root != null ? profiler.Root.Id : (Guid?)null,
                Name                        = profiler.Name,
                Started                     = profiler.Started,
                DurationMilliseconds        = (double)profiler.DurationMilliseconds,
                User                        = profiler.UserName,
                HasUserViewed               = profiler.HasUserViewed,
                MachineName                 = profiler.MachineName,
                CustomLinksJson             = profiler.CustomLinksJson,
                ClientTimingsRedirectCounts = profiler.ClientTimings != null ? profiler.ClientTimings.RedirectCount : (int?)null
            };

            var result = Profilers.Save(miniProfilerPoco, WriteConcern.Acknowledged);

            if (!result.UpdatedExisting)
            {
                SaveTiming(profiler.Root);
            }

            SaveClientTimings(profiler);
        }
Exemplo n.º 8
0
        /// <summary>
        /// Body of the polling thread.
        /// </summary>
        private void RunHandlerLoop(CompletionQueueSafeHandle cq, IProfiler optionalProfiler)
        {
            if (optionalProfiler != null)
            {
                Profilers.SetForCurrentThread(optionalProfiler);
            }

            CompletionQueueEvent ev;

            do
            {
                ev = cq.Next();
                if (ev.type == CompletionQueueEvent.CompletionType.OpComplete)
                {
                    bool   success = (ev.success != 0);
                    IntPtr tag     = ev.tag;
                    try
                    {
                        var callback = cq.CompletionRegistry.Extract(tag);
                        callback(success);
                    }
                    catch (Exception e)
                    {
                        Logger.Error(e, "Exception occured while invoking completion delegate");
                    }
                }
            }while (ev.type != CompletionQueueEvent.CompletionType.Shutdown);
        }
Exemplo n.º 9
0
 public CompletionQueueEvent Pluck(IntPtr tag)
 {
     using (Profilers.ForCurrentThread().NewScope("CompletionQueueSafeHandle.Pluck"))
     {
         return(grpcsharp_completion_queue_pluck(this, tag));
     }
 }
Exemplo n.º 10
0
 protected byte[] UnsafeSerialize(TWrite msg)
 {
     using (Profilers.ForCurrentThread().NewScope("AsyncCallBase.UnsafeSerialize"))
     {
         return(serializer(msg));
     }
 }
Exemplo n.º 11
0
 public void StartUnary(BatchContextSafeHandle ctx, byte[] payload, MetadataArraySafeHandle metadataArray, WriteFlags writeFlags)
 {
     using (Profilers.ForCurrentThread().NewScope("CallSafeHandle.StartUnary"))
     {
         Native.grpcsharp_call_start_unary(this, ctx, payload, new UIntPtr((ulong)payload.Length), metadataArray, writeFlags)
         .CheckOk();
     }
 }
Exemplo n.º 12
0
 void Update()
 {
     Profilers.BeginSample((int)EProfilerSample.Sample3);
     if (ud != null)
     {
         ud(self);
     }
     Profilers.EndSample();
 }
Exemplo n.º 13
0
        /// <summary>
        /// Returns a list of <see cref="MiniProfiler.Id"/>s that haven't been seen by <paramref name="user"/>.
        /// </summary>
        /// <param name="user">User identified by the current <see cref="MiniProfiler.Settings.UserProvider"/>.</param>
        public override List <Guid> GetUnviewedIds(string user)
        {
            var query = Query.And(
                Query <MiniProfilerPoco> .EQ(p => p.User, user),
                Query <MiniProfilerPoco> .EQ(p => p.HasUserViewed, false));
            var guids = Profilers.Find(query).Select(p => p.Id).ToList();

            return(guids);
        }
Exemplo n.º 14
0
        /// <summary>
        /// Body of the polling thread.
        /// </summary>
        private void RunHandlerLoop(CompletionQueueSafeHandle cq, IProfiler optionalProfiler)
        {
            if (optionalProfiler != null)
            {
                Profilers.SetForCurrentThread(optionalProfiler);
            }

            CompletionQueueEvent ev;

            do
            {
                ev = cq.Next();
                if (ev.type == CompletionQueueEvent.CompletionType.OpComplete)
                {
                    bool   success = (ev.success != 0);
                    IntPtr tag     = ev.tag;
                    try
                    {
                        var callback = cq.CompletionRegistry.Extract(tag);
                        // Use cached delegates to avoid unnecessary allocations
                        if (!inlineHandlers)
                        {
                            queuedContinuationCounter.Increment();
                            ThreadPool.QueueUserWorkItem(success ? runCompletionQueueEventCallbackSuccess : runCompletionQueueEventCallbackFailure, callback);
                        }
                        else
                        {
                            RunCompletionQueueEventCallback(callback, success);
                        }
                    }
                    catch (Exception e)
                    {
                        Logger.Error(e, "Exception occured while extracting event from completion registry.");
                    }
                }
            }while (ev.type != CompletionQueueEvent.CompletionType.Shutdown);

            // Continuations are running on default threadpool that consists of background threads.
            // GrpcThreadPool thread (a foreground thread) will not exit unless all queued work had
            // been finished to prevent terminating the continuations queued prematurely.
            int sleepIterations = 0;

            while (queuedContinuationCounter.Count != 0)
            {
                // Only happens on shutdown and having pending continuations shouldn't very common,
                // so sleeping here for a little bit is fine.
                if (sleepIterations >= MaxFinishContinuationsSleepTotalMillis / FinishContinuationsSleepMillis)
                {
                    Logger.Warning("Shutting down gRPC thread [{0}] with unfinished callbacks (Timed out waiting for callbacks to finish).",
                                   Thread.CurrentThread.Name);
                    break;
                }
                Thread.Sleep(FinishContinuationsSleepMillis);
                sleepIterations++;
            }
        }
Exemplo n.º 15
0
        /// <summary>
        /// Sets the profiler as view
        /// </summary>
        public override void SetViewed(string user, Guid id)
        {
            var profiler = Profilers.FindOne(Query.EQ("_id", id.ToString()));

            if (profiler != null)
            {
                profiler.HasUserViewed = true;
                Profilers.Save(profiler);
            }
        }
Exemplo n.º 16
0
        private unsafe static Profilers[] Convert(Arr <Profilers_FFI> arr)
        {
            var array_ffi = CopyArray <Profilers_FFI>(arr.ptr, arr.size);
            var array     = new Profilers[arr.size];

            for (int i = 0; i < arr.size; ++i)
            {
                array[i] = Convert(array_ffi[i]);
            }
            return(array);
        }
Exemplo n.º 17
0
        private void Initialize(CompletionQueueSafeHandle cq)
        {
            using (Profilers.ForCurrentThread().NewScope("AsyncCall.Initialize"))
            {
                var call = CreateNativeCall(cq);

                details.Channel.AddCallReference(this);
                InitializeInternal(call);
                RegisterCancellationCallback();
            }
        }
Exemplo n.º 18
0
        // TODO: this method is not Async, so it shouldn't be in AsyncCall class, but
        // it is reusing fair amount of code in this class, so we are leaving it here.
        /// <summary>
        /// Blocking unary request - unary response call.
        /// </summary>
        public TResponse UnaryCall(TRequest msg)
        {
            var profiler = Profilers.ForCurrentThread();

            using (profiler.NewScope("AsyncCall.UnaryCall"))
                using (CompletionQueueSafeHandle cq = CompletionQueueSafeHandle.CreateSync())
                {
                    byte[] payload = UnsafeSerialize(msg);

                    unaryResponseTcs = new TaskCompletionSource <TResponse>();

                    lock (myLock)
                    {
                        GrpcPreconditions.CheckState(!started);
                        started = true;
                        Initialize(cq);

                        halfcloseRequested = true;
                        readingDone        = true;
                    }

                    using (var metadataArray = MetadataArraySafeHandle.Create(details.Options.Headers))
                    {
                        var ctx = details.Channel.Environment.BatchContextPool.Lease();
                        try
                        {
                            call.StartUnary(ctx, payload, GetWriteFlagsForCall(), metadataArray, details.Options.Flags);
                            var  ev      = cq.Pluck(ctx.Handle);
                            bool success = (ev.success != 0);
                            try
                            {
                                using (profiler.NewScope("AsyncCall.UnaryCall.HandleBatch"))
                                {
                                    HandleUnaryResponse(success, ctx.GetReceivedStatusOnClient(), ctx.GetReceivedMessage(), ctx.GetReceivedInitialMetadata());
                                }
                            }
                            catch (Exception e)
                            {
                                Logger.Error(e, "Exception occurred while invoking completion delegate.");
                            }
                        }
                        finally
                        {
                            ctx.Recycle();
                        }
                    }

                    // Once the blocking call returns, the result should be available synchronously.
                    // Note that GetAwaiter().GetResult() doesn't wrap exceptions in AggregateException.
                    return(unaryResponseTcs.Task.GetAwaiter().GetResult());
                }
        }
Exemplo n.º 19
0
 public CallSafeHandle CreateCall(CompletionRegistry registry, CallSafeHandle parentCall, ContextPropagationFlags propagationMask, CompletionQueueSafeHandle cq, string method, string host, Timespec deadline, CallCredentialsSafeHandle credentials)
 {
     using (Profilers.ForCurrentThread().NewScope("ChannelSafeHandle.CreateCall"))
     {
         var result = Native.grpcsharp_channel_create_call(this, parentCall, propagationMask, cq, method, host, deadline);
         if (credentials != null)
         {
             result.SetCredentials(credentials);
         }
         result.Initialize(registry, cq);
         return(result);
     }
 }
Exemplo n.º 20
0
 public static MetadataArraySafeHandle Create(Metadata metadata)
 {
     using (Profilers.ForCurrentThread().NewScope("MetadataArraySafeHandle.Create"))
     {
         // TODO(jtattermusch): we might wanna check that the metadata is readonly
         var metadataArray = Native.grpcsharp_metadata_array_create(new UIntPtr((ulong)metadata.Count));
         for (int i = 0; i < metadata.Count; i++)
         {
             var valueBytes = metadata[i].GetSerializedValueUnsafe();
             Native.grpcsharp_metadata_array_add(metadataArray, metadata[i].Key, valueBytes, new UIntPtr((ulong)valueBytes.Length));
         }
         return(metadataArray);
     }
 }
Exemplo n.º 21
0
        /// <summary>
        /// Handler for unary response completion.
        /// </summary>
        private void HandleUnaryResponse(bool success, ClientSideStatus receivedStatus, byte[] receivedMessage, Metadata responseHeaders)
        {
            // NOTE: because this event is a result of batch containing GRPC_OP_RECV_STATUS_ON_CLIENT,
            // success will be always set to true.

            using (Profilers.ForCurrentThread().NewScope("AsyncCall.HandleUnaryResponse"))
            {
                AsyncSubject <Unit> delayedStreamingWriteTcs = null;
                TResponse           msg  = default(TResponse);
                var deserializeException = TryDeserialize(receivedMessage, out msg);

                lock (myLock)
                {
                    finished = true;

                    if (deserializeException != null && receivedStatus.Status.StatusCode == StatusCode.OK)
                    {
                        receivedStatus = new ClientSideStatus(DeserializeResponseFailureStatus, receivedStatus.Trailers);
                    }
                    finishedStatus = receivedStatus;

                    if (isStreamingWriteCompletionDelayed)
                    {
                        delayedStreamingWriteTcs = streamingWriteTcs;
                        streamingWriteTcs        = null;
                    }

                    ReleaseResourcesIfPossible();
                }

                responseHeadersTcs.OnNext(responseHeaders);
                responseHeadersTcs.OnCompleted();

                if (delayedStreamingWriteTcs != null)
                {
                    delayedStreamingWriteTcs.OnError(GetRpcExceptionClientOnly());
                }

                var status = receivedStatus.Status;
                if (status.StatusCode != StatusCode.OK)
                {
                    unaryResponseTcs.OnError(new RpcException(status, () => (finishedStatus.HasValue) ? GetTrailers() : null));
                    return;
                }

                unaryResponseTcs.OnNext(msg);
                unaryResponseTcs.OnCompleted();
            }
        }
Exemplo n.º 22
0
 /// <summary>
 /// If there are no more pending actions and no new actions can be started, releases
 /// the underlying native resources.
 /// </summary>
 protected bool ReleaseResourcesIfPossible()
 {
     using (Profilers.ForCurrentThread().NewScope("AsyncCallBase.ReleaseResourcesIfPossible"))
     {
         if (!disposed && call != null)
         {
             bool noMoreSendCompletions = sendCompletionDelegate == null && (halfcloseRequested || cancelRequested || finished);
             if (noMoreSendCompletions && readingDone && finished)
             {
                 ReleaseResources();
                 return(true);
             }
         }
         return(false);
     }
 }
Exemplo n.º 23
0
 protected Exception TryDeserialize(byte[] payload, out TRead msg)
 {
     using (Profilers.ForCurrentThread().NewScope("AsyncCallBase.TryDeserialize"))
     {
         try
         {
             msg = deserializer(payload);
             return(null);
         }
         catch (Exception e)
         {
             msg = default(TRead);
             return(e);
         }
     }
 }
        /// <summary>
        /// Adds an item to the manager (used by Profiler class)
        /// </summary>
        /// <param name="FunctionName">Function name/identifier</param>
        /// <param name="StartTime">Start time (in ms)</param>
        /// <param name="StopTime">Stop time (in ms)</param>
        public virtual void AddItem(string FunctionName, int StartTime, int StopTime)
        {
            ProfilerInfo Profiler = Profilers.Find(x => x.FunctionName == FunctionName);

            if (Profiler == null)
            {
                Profiler = new ProfilerInfo();
                Profiler.FunctionName = FunctionName;
                Profilers.Add(Profiler);
            }
            int Time = (StopTime - StartTime);

            Profiler.TotalTime += Time;
            Profiler.MaxTime    = Profiler.MaxTime.Max(Time);
            Profiler.MinTime    = Profiler.MinTime.Min(Time);
            ++Profiler.TimesCalled;
        }
Exemplo n.º 25
0
        /// <summary>
        /// Loads the MiniProfiler identifed by 'id' from the database.
        /// </summary>
        public override MiniProfiler Load(Guid id)
        {
            var query = Query.EQ("_id", id.ToString());

            var profilerPoco = Profilers.FindOne(query);

            if (profilerPoco != null)
            {
                var profiler = new MiniProfiler
                {
                    Id            = Guid.Parse(profilerPoco.Id),
                    Name          = profilerPoco.Name,
                    Started       = profilerPoco.Started,
                    MachineName   = profilerPoco.MachineName,
                    User          = profilerPoco.User,
                    Level         = profilerPoco.Level,
                    HasUserViewed = profilerPoco.HasUserViewed
                };

                if (profiler != null)  //This is very similar to the Load logic in the SqlServerStorage.
                //Perhaps another abstraction layer(or moving some logic into the Base) which both Mongo and Sql inherit from would eliminate somewhat repetitive code.
                {
                    var           timings          = LoadTimings(profiler.Id);
                    var           sqlTimings       = LoadSqlTimings(profiler.Id);
                    var           sqlParams        = LoadSqlTimingParameters(profiler.Id);
                    var           clientTimingList = LoadClientTimings(profiler.Id);
                    ClientTimings clientTimings    = null;
                    if (clientTimingList.Count > 0)
                    {
                        clientTimings         = new ClientTimings();
                        clientTimings.Timings = clientTimingList;
                    }

                    MapTimings(profiler, timings, sqlTimings, sqlParams, clientTimings);
                }

                profiler.OnDeserialized(new StreamingContext());

                return(profiler);
            }

            return(null);
        }
Exemplo n.º 26
0
        private INativeCall CreateNativeCall(CompletionQueueSafeHandle cq)
        {
            using (Profilers.ForCurrentThread().NewScope("AsyncCall.CreateNativeCall"))
            {
                if (injectedNativeCall != null)
                {
                    return(injectedNativeCall);  // allows injecting a mock INativeCall in tests.
                }

                var parentCall = details.Options.PropagationToken != null ? details.Options.PropagationToken.ParentCall : CallSafeHandle.NullInstance;

                var credentials = details.Options.Credentials;
                using (var nativeCredentials = credentials != null ? credentials.ToNativeCredentials() : null)
                {
                    var result = details.Channel.Handle.CreateCall(
                        parentCall, ContextPropagationToken.DefaultMask, cq,
                        details.Method, details.Host, Timespec.FromDateTime(details.Options.Deadline.Value), nativeCredentials);
                    return(result);
                }
            }
        }
Exemplo n.º 27
0
        /// <summary>
        /// Loads the MiniProfiler identifed by 'id' from the database.
        /// </summary>
        public override MiniProfiler Load(Guid id)
        {
            var profilerPoco = Profilers.FindOne(Query <MiniProfilerPoco> .EQ(poco => poco.Id, id));
            var miniProfiler = ProfilerPocoToProfiler(profilerPoco);

            if (miniProfiler != null)
            {
                var rootTiming = miniProfiler.RootTimingId.HasValue
                    ? LoadTiming(miniProfiler.RootTimingId.Value)
                    : null;

                if (rootTiming != null)
                {
                    miniProfiler.Root = rootTiming;
                }

                miniProfiler.ClientTimings = LoadClientTimings(miniProfiler);
            }

            return(miniProfiler);
        }
Exemplo n.º 28
0
        /// <summary>
        /// Body of the polling thread.
        /// </summary>
        private void RunHandlerLoop(CompletionQueueSafeHandle cq, IProfiler optionalProfiler)
        {
            if (optionalProfiler != null)
            {
                Profilers.SetForCurrentThread(optionalProfiler);
            }

            CompletionQueueEvent ev;

            do
            {
                ev = cq.Next();
                if (ev.type == CompletionQueueEvent.CompletionType.OpComplete)
                {
                    bool   success = (ev.success != 0);
                    IntPtr tag     = ev.tag;
                    try
                    {
                        var callback = cq.CompletionRegistry.Extract(tag);
                        // Use cached delegates to avoid unnecessary allocations
                        if (!inlineHandlers)
                        {
                            ThreadPool.QueueUserWorkItem(success ? RunCompletionQueueEventCallbackSuccess : RunCompletionQueueEventCallbackFailure, callback);
                        }
                        else
                        {
                            RunCompletionQueueEventCallback(callback, success);
                        }
                    }
                    catch (Exception e)
                    {
                        Logger.Error(e, "Exception occured while extracting event from completion registry.");
                    }
                }
            }while (ev.type != CompletionQueueEvent.CompletionType.Shutdown);
        }
        /// <summary>
        /// Handler for unary response completion.
        /// </summary>
        private void HandleUnaryResponse(bool success, ClientSideStatus receivedStatus, byte[] receivedMessage, Metadata responseHeaders)
        {
            // NOTE: because this event is a result of batch containing GRPC_OP_RECV_STATUS_ON_CLIENT,
            // success will be always set to true.

            using (Profilers.ForCurrentThread().NewScope("AsyncCall.HandleUnaryResponse"))
            {
                TResponse msg = default(TResponse);
                var       deserializeException = TryDeserialize(receivedMessage, out msg);

                lock (myLock)
                {
                    finished = true;

                    if (deserializeException != null && receivedStatus.Status.StatusCode == StatusCode.OK)
                    {
                        receivedStatus = new ClientSideStatus(DeserializeResponseFailureStatus, receivedStatus.Trailers);
                    }
                    finishedStatus = receivedStatus;

                    ReleaseResourcesIfPossible();
                }

                responseHeadersTcs.SetResult(responseHeaders);

                var status = receivedStatus.Status;

                if (status.StatusCode != StatusCode.OK)
                {
                    unaryResponseTcs.SetException(new RpcException(status));
                    return;
                }

                unaryResponseTcs.SetResult(msg);
            }
        }
Exemplo n.º 30
0
        public override bool Execute()
        {
            // NETCORE SAMPLE
            // mono --debug packager.exe --debugrt --emscripten-sdkdir=$(EMSCRIPTEN_SDK_DIR) --mono-sdkdir=$(TOP)/sdks/out -appdir=bin/hello-netcore --nobinding --builddir=obj/hello-netcore --framework=netcoreapp3.0 --netcore-sdkdir=$(NETCOREAPP_DIR) --template=runtime-tests.js --linker samples/hello/bin/Debug/netcoreapp3.0/hello.dll

            // AOT SAMPLE
            // mono --debug packager.exe --emscripten-sdkdir=$(EMSCRIPTEN_SDK_DIR) --mono-sdkdir=$(TOP)/sdks/out -appdir=bin/aot-sample --nobinding --builddir=obj/aot-sample --aot --template=runtime-tests.js --pinvoke-libs=libfoo hello.exe

            Log.LogMessage(MessageImportance.High, $"PACKAGER TASK: {MonoWasmRoot} {RootAssemblies.Length}");

            var deploy_prefix = "managed";
            var vfs_prefix    = "managed";
            var emit_ninja    = false;
            var copyType      = CopyType.Default;
            var ee_mode       = ExecMode.Interp;
            var build_wasm    = EnableAOT;

            if (EnableAOT)
            {
                ee_mode = ExecMode.AotInterp;
            }

            out_prefix = Environment.CurrentDirectory;
            app_prefix = Environment.CurrentDirectory;

            if (MonoSdkRoot == null)
            {
                MonoSdkRoot = Path.Combine(MonoWasmRoot, "sdks", "out");
            }

            var tool_prefix = Path.Combine(MonoWasmRoot, "sdk", "wasm");

            framework_prefix   = Path.Combine(MonoWasmRoot, "sdk", "wasm", "framework");
            bcl_prefix         = Path.Combine(MonoSdkRoot, "wasm-bcl/wasm");
            bcl_tools_prefix   = Path.Combine(MonoSdkRoot, "wasm-bcl/wasm_tools");
            bcl_facades_prefix = Path.Combine(bcl_prefix, "Facades");

            foreach (var ra in RootAssemblies)
            {
                AssemblyKind kind;
                var          resolved = Resolve(ra, out kind);
                Import(resolved, kind);
            }

            if (AddBinding)
            {
                var bindings = ResolveFramework(BINDINGS_ASM_NAME + ".dll");
                Import(bindings, AssemblyKind.Framework);
                var http = ResolveFramework(HTTP_ASM_NAME + ".dll");
                Import(http, AssemblyKind.Framework);
                var websockets = ResolveFramework(WEBSOCKETS_ASM_NAME + ".dll");
                Import(websockets, AssemblyKind.Framework);
            }

            if (EnableAOT)
            {
                var to_aot = new Dictionary <string, bool> ();
                to_aot["mscorlib"] = true;
                if (AotAssemblies != null)
                {
                    foreach (var s in AotAssemblies)
                    {
                        to_aot[s] = true;
                    }
                }
                foreach (var ass in assemblies)
                {
                    if (AotAssemblies == null || to_aot.ContainsKey(ass.name))
                    {
                        ass.aot = true;
                        to_aot.Remove(ass.name);
                    }
                }
                if (to_aot.Count > 0)
                {
                    Log.LogError($"Unknown assembly name '{to_aot.Keys.ToArray ()[0]}' in --aot-assemblies option.");
                    return(false);
                }
            }

            if (BuildDir != null)
            {
                emit_ninja = true;
                if (!Directory.Exists(BuildDir))
                {
                    Directory.CreateDirectory(BuildDir);
                }
            }

            if (!emit_ninja)
            {
                if (!Directory.Exists(out_prefix))
                {
                    Directory.CreateDirectory(out_prefix);
                }
                var bcl_dir = Path.Combine(out_prefix, deploy_prefix);
                if (Directory.Exists(bcl_dir))
                {
                    Directory.Delete(bcl_dir, true);
                }
                Directory.CreateDirectory(bcl_dir);
                foreach (var f in file_list)
                {
                    CopyFile(f, Path.Combine(bcl_dir, Path.GetFileName(f)), copyType);
                }
            }

            if (deploy_prefix.EndsWith("/"))
            {
                deploy_prefix = deploy_prefix.Substring(0, deploy_prefix.Length - 1);
            }
            if (vfs_prefix.EndsWith("/"))
            {
                vfs_prefix = vfs_prefix.Substring(0, vfs_prefix.Length - 1);
            }

            // the linker does not consider these core by default
            var wasm_core_assemblies = new Dictionary <string, bool> ();

            if (AddBinding)
            {
                wasm_core_assemblies[BINDINGS_ASM_NAME]   = true;
                wasm_core_assemblies[HTTP_ASM_NAME]       = true;
                wasm_core_assemblies[WEBSOCKETS_ASM_NAME] = true;
            }
            // wasm core bindings module
            var wasm_core_bindings = string.Empty;

            if (AddBinding)
            {
                wasm_core_bindings = BINDINGS_MODULE;
            }
            // wasm core bindings support file
            var wasm_core_support         = string.Empty;
            var wasm_core_support_library = string.Empty;

            if (AddBinding)
            {
                wasm_core_support         = BINDINGS_MODULE_SUPPORT;
                wasm_core_support_library = $"--js-library {BINDINGS_MODULE_SUPPORT}";
            }

#if REMOVED
            var runtime_js = Path.Combine(emit_ninja ? BuildDir : out_prefix, "runtime.js");
            if (emit_ninja)
            {
                File.Delete(runtime_js);
                File.Copy(Path.Combine(MonoWasmRoot, "sdks", "wasm", RuntimeTemplate), runtime_js);
            }
            else
            {
                if (File.Exists(runtime_js) && (File.Exists(RuntimeTemplate)))
                {
                    CopyFile(RuntimeTemplate, runtime_js, CopyType.IfNewer, $"runtime template <{RuntimeTemplate}> ");
                }
                else
                {
                    if (File.Exists(RuntimeTemplate))
                    {
                        CopyFile(RuntimeTemplate, runtime_js, CopyType.IfNewer, $"runtime template <{RuntimeTemplate}> ");
                    }
                    else
                    {
                        var runtime_gen = "\nvar Module = {\n\tonRuntimeInitialized: function () {\n\t\tMONO.mono_load_runtime_and_bcl (\n\t\tconfig.vfs_prefix,\n\t\tconfig.deploy_prefix,\n\t\tconfig.enable_debugging,\n\t\tconfig.file_list,\n\t\tfunction () {\n\t\t\tApp.init ();\n\t\t}\n\t)\n\t},\n};";
                        File.Delete(runtime_js);
                        File.WriteAllText(runtime_js, runtime_gen);
                    }
                }
            }
#endif

            AssemblyData dedup_asm = null;

            if (EnableDedup)
            {
                dedup_asm = new AssemblyData
                {
                    name         = "aot-dummy",
                    filename     = "aot-dummy.dll",
                    bc_path      = "$builddir/aot-dummy.dll.bc",
                    o_path       = "$builddir/aot-dummy.dll.o",
                    app_path     = "$appdir/$deploy_prefix/aot-dummy.dll",
                    linkout_path = "$builddir/linker-out/aot-dummy.dll",
                    aot          = true
                };
                assemblies.Add(dedup_asm);
                file_list.Add("aot-dummy.dll");
            }

            var file_list_str = string.Join(",", file_list.Select(f => $"\"{Path.GetFileName (f)}\"").Distinct());
            var config        = String.Format("config = {{\n \tvfs_prefix: \"{0}\",\n \tdeploy_prefix: \"{1}\",\n \tenable_debugging: {2},\n \tfile_list: [ {3} ],\n", vfs_prefix, deploy_prefix, enable_debug ? "1" : "0", file_list_str);
            config += "}\n";
            var config_js = Path.Combine(emit_ninja ? BuildDir : out_prefix, "mono-config.js");
            File.Delete(config_js);
            File.WriteAllText(config_js, config);

            string runtime_dir;
            if (EnableThreads)
            {
                runtime_dir = Path.Combine(tool_prefix, UseReleaseRuntime ? "builds/threads-release" : "builds/threads-debug");
            }
            else
            {
                runtime_dir = Path.Combine(tool_prefix, UseReleaseRuntime ? "builds/release" : "builds/debug");
            }
            if (!emit_ninja)
            {
                var interp_files = new List <string> {
                    "mono.js", "mono.wasm"
                };
                if (EnableThreads)
                {
                    interp_files.Add("mono.worker.js");
                    interp_files.Add("mono.js.mem");
                }
                foreach (var fname in interp_files)
                {
                    File.Delete(Path.Combine(out_prefix, fname));
                    File.Copy(
                        Path.Combine(runtime_dir, fname),
                        Path.Combine(out_prefix, fname));
                }

                foreach (var asset in Assets)
                {
                    CopyFile(asset, Path.Combine(out_prefix, Path.GetFileName(asset)), copyType, "Asset: ");
                }
            }

            if (!emit_ninja)
            {
                return(true);
            }

            if (build_wasm)
            {
                if (MonoSdkRoot == null)
                {
                    Log.LogError("The `MonoSdkRoot` argument is required.");
                    return(false);
                }
                if (EmscriptenSdkDir == null)
                {
                    Log.LogError("The `EmscriptenSdkDir` argument is required.");
                    return(false);
                }
                GenDriver(BuildDir, Profilers.ToList(), ee_mode, LinkICalls);
            }

            Log.LogMessage("PACKAGER DONE!");

            return(true);
        }