Skip to content

Commit

Permalink
Tracing via dotnet ActivitySource
Browse files Browse the repository at this point in the history
  • Loading branch information
T-Gro committed Oct 10, 2022
1 parent 80459f9 commit a776c86
Show file tree
Hide file tree
Showing 11 changed files with 109 additions and 262 deletions.
9 changes: 7 additions & 2 deletions src/Compiler/Checking/CheckDeclarations.fs
Original file line number Diff line number Diff line change
Expand Up @@ -5173,7 +5173,12 @@ let CheckOneImplFile
let infoReader = InfoReader(g, amap)

cancellable {
use _ = Activity.instance.Start "CheckOneImplFile" [|"fileName", fileName; "qualifiedNameOfFile", qualNameOfFile.Text|]
use _ =
Activity.Start "CheckDeclarations.CheckOneImplFile"
[|
"fileName", fileName
"qualifiedNameOfFile", qualNameOfFile.Text
|]
let cenv =
cenv.Create (g, isScript, niceNameGen, amap, thisCcu, false, Option.isSome rootSigOpt,
conditionalDefines, tcSink, (LightweightTcValForUsingInBuildMethodCall g), isInternalTestSpanStackReferring,
Expand Down Expand Up @@ -5302,7 +5307,7 @@ let CheckOneImplFile
let CheckOneSigFile (g, niceNameGen, amap, thisCcu, checkForErrors, conditionalDefines, tcSink, isInternalTestSpanStackReferring) tcEnv (ParsedSigFileInput (fileName = fileName; qualifiedNameOfFile = qualNameOfFile; modules = sigFileFrags)) =
cancellable {
use _ =
Activity.instance.Start "CheckOneSigFile"
Activity.Start "CheckDeclarations.CheckOneSigFile"
[|
"fileName", fileName
"qualifiedNameOfFile", qualNameOfFile.Text
Expand Down
12 changes: 6 additions & 6 deletions src/Compiler/Driver/CompilerOptions.fs
Original file line number Diff line number Diff line change
Expand Up @@ -2304,13 +2304,13 @@ let PrintWholeAssemblyImplementation (tcConfig: TcConfig) outfile header expr =
//----------------------------------------------------------------------------

let mutable tPrev: (DateTime * DateTime * float * int[]) option = None
let mutable nPrev: string option = None

let ReportTime (tcConfig: TcConfig) descr =
let mutable nPrev: (string * IDisposable) option = None

let ReportTime (tcConfig: TcConfig) descr =
match nPrev with
| None -> ()
| Some prevDescr ->
| Some (prevDescr,prevActivity) ->
use _ = prevActivity // Finish the previous diagnostics activity by .Dispose() at the end of this block
if tcConfig.pause then
dprintf "[done '%s', entering '%s'] press <enter> to continue... " prevDescr descr
Console.ReadLine() |> ignore
Expand Down Expand Up @@ -2349,7 +2349,7 @@ let ReportTime (tcConfig: TcConfig) descr =

let tStart =
match tPrev, nPrev with
| Some (tStart, tPrev, utPrev, gcPrev), Some prevDescr ->
| Some (tStart, tPrev, utPrev, gcPrev), Some (prevDescr, _) ->
let spanGC = [| for i in 0..maxGen -> GC.CollectionCount i - gcPrev[i] |]
let t = tNow - tStart
let tDelta = tNow - tPrev
Expand All @@ -2376,7 +2376,7 @@ let ReportTime (tcConfig: TcConfig) descr =

tPrev <- Some(tStart, tNow, utNow, gcNow)

nPrev <- Some descr
nPrev <- Some (descr, Activity.StartNoTags descr)

let ignoreFailureOnMono1_1_16 f =
try
Expand Down
5 changes: 1 addition & 4 deletions src/Compiler/Driver/ParseAndCheckInputs.fs
Original file line number Diff line number Diff line change
Expand Up @@ -1138,7 +1138,7 @@ let CheckOneInput

cancellable {
try
use _ = Activity.instance.Start "CheckOneInput" [| "inputName", inp.FileName |]
use _ = Activity.Start "ParseAndCheckInputs.CheckOneInput" [| "inputName", inp.FileName |]

CheckSimulateException tcConfig

Expand Down Expand Up @@ -1320,10 +1320,8 @@ let CheckMultipleInputsFinish (results, tcState: TcState) =

let CheckOneInputAndFinish (checkForErrors, tcConfig: TcConfig, tcImports, tcGlobals, prefixPathOpt, tcSink, tcState, input) =
cancellable {
Logger.LogBlockStart LogCompilerFunctionId.CompileOps_TypeCheckOneInputAndFinishEventually
let! results, tcState = CheckOneInput(checkForErrors, tcConfig, tcImports, tcGlobals, prefixPathOpt, tcSink, tcState, input, false)
let result = CheckMultipleInputsFinish([ results ], tcState)
Logger.LogBlockStop LogCompilerFunctionId.CompileOps_TypeCheckOneInputAndFinishEventually
return result
}

Expand All @@ -1341,7 +1339,6 @@ let CheckClosedInputSetFinish (declaredImpls: CheckedImplFile list, tcState) =
tcState, declaredImpls, ccuContents

let CheckClosedInputSet (ctok, checkForErrors, tcConfig, tcImports, tcGlobals, prefixPathOpt, tcState, inputs) =
use tcActivity = Activity.instance.StartNoTags("CheckClosedInputSet")
// tcEnvAtEndOfLastFile is the environment required by fsi.exe when incrementally adding definitions
let results, tcState =
(tcState, inputs)
Expand Down
28 changes: 0 additions & 28 deletions src/Compiler/Driver/fsc.fs
Original file line number Diff line number Diff line change
Expand Up @@ -166,9 +166,6 @@ let TypeCheck
inputs,
exiter: Exiter
) =
use _ =
Activity.instance.Start "typecheck_inputs" [| "assemblyName", assemblyName |]

try
if isNil inputs then
error (Error(FSComp.SR.fscNoImplementationFiles (), rangeStartup))
Expand Down Expand Up @@ -478,8 +475,6 @@ let main1
disposables: DisposablesTracker
) =

use mainActivity = new Activity("main")

// See Bug 735819
let lcidFromCodePage =
if
Expand Down Expand Up @@ -536,8 +531,6 @@ let main1

// Process command line, flags and collect filenames
let sourceFiles =
use parseActivity = Activity.instance.StartNoTags("determine_source_files")

// The ParseCompilerOptions function calls imperative function to process "real" args
// Rather than start processing, just collect names, then process them.
try
Expand Down Expand Up @@ -570,8 +563,6 @@ let main1

// If there's a problem building TcConfig, abort
let tcConfig =
use createConfigActivity = Activity.instance.StartNoTags("create_tc_config")

try
TcConfig.Create(tcConfigB, validate = false)
with e ->
Expand All @@ -596,14 +587,10 @@ let main1
let foundationalTcConfigP = TcConfigProvider.Constant tcConfig

let sysRes, otherRes, knownUnresolved =
use splitResolutionsActivity = Activity.instance.StartNoTags("split_resolutions")
TcAssemblyResolutions.SplitNonFoundationalResolutions(tcConfig)

// Import basic assemblies
let tcGlobals, frameworkTcImports =
use frameworkImportsActivity =
Activity.instance.StartNoTags("import_framework_references")

TcImports.BuildFrameworkTcImports(foundationalTcConfigP, sysRes, otherRes)
|> NodeCode.RunImmediateWithoutCancellation

Expand Down Expand Up @@ -656,9 +643,6 @@ let main1
ReportTime tcConfig "Import non-system references"

let tcImports =
use nonFrameworkImportsActivity =
Activity.instance.StartNoTags("import_non_framework_references")

TcImports.BuildNonFrameworkTcImports(tcConfigP, frameworkTcImports, otherRes, knownUnresolved, dependencyProvider)
|> NodeCode.RunImmediateWithoutCancellation

Expand All @@ -677,7 +661,6 @@ let main1
use unwindParsePhase = PushThreadBuildPhaseUntilUnwind BuildPhase.TypeCheck

let tcEnv0, openDecls0 =
use initialTcEnvActivity = Activity.instance.StartNoTags("get_initial_tc_env")
GetInitialTcEnv(assemblyName, rangeStartup, tcConfig, tcImports, tcGlobals)

// Type check the inputs
Expand Down Expand Up @@ -738,8 +721,6 @@ let main1OfAst
inputs: ParsedInput list
) =

use main1AstActivity = Activity.instance.StartNoTags("main1_of_ast")

let tryGetMetadataSnapshot = (fun _ -> None)

let directoryBuildingFrom = Directory.GetCurrentDirectory()
Expand Down Expand Up @@ -924,8 +905,6 @@ let main2
exiter: Exiter,
ilSourceDocs))
=
use main2Activity = Activity.instance.StartNoTags("main2")

if tcConfig.typeCheckOnly then
exiter.Exit 0

Expand Down Expand Up @@ -1033,7 +1012,6 @@ let main3
exiter: Exiter,
ilSourceDocs))
=
use main3Activity = Activity.instance.StartNoTags("main3")
// Encode the signature data
ReportTime tcConfig "Encode Interface Data"
let exportRemapping = MakeExportRemapping generatedCcu generatedCcu.Contents
Expand Down Expand Up @@ -1129,8 +1107,6 @@ let main4
exiter: Exiter,
ilSourceDocs))
=
use main4Activity = Activity.instance.StartNoTags("main4")

match tcImportsCapture with
| None -> ()
| Some f -> f tcImports
Expand Down Expand Up @@ -1233,8 +1209,6 @@ let main5
exiter: Exiter,
ilSourceDocs))
=
use main5Activity = Activity.instance.StartNoTags("main5")

use unwindBuildPhase = PushThreadBuildPhaseUntilUnwind BuildPhase.Output

// Static linking, if any
Expand Down Expand Up @@ -1266,8 +1240,6 @@ let main6
exiter: Exiter,
ilSourceDocs))
=
use main6Activity = Activity.instance.StartNoTags("main6")

ReportTime tcConfig "Write .NET Binary"

use unwindBuildPhase = PushThreadBuildPhaseUntilUnwind BuildPhase.Output
Expand Down
9 changes: 3 additions & 6 deletions src/Compiler/Facilities/BuildGraph.fs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ open System.Threading
open System.Threading.Tasks
open System.Diagnostics
open System.Globalization
open FSharp.Compiler.Diagnostics.Activity
open FSharp.Compiler.DiagnosticsLogger
open Internal.Utilities.Library

Expand Down Expand Up @@ -108,13 +107,11 @@ type NodeCodeBuilder() =
)

[<DebuggerHidden; DebuggerStepThrough>]
member _.Using(value: ActivityFacade, binder: ActivityFacade -> NodeCode<'U>) =
member _.Using(value: IDisposable, binder: IDisposable -> NodeCode<'U>) =
Node(
async {
try
return! binder value |> Async.AwaitNodeCode
finally
(value :> IDisposable).Dispose()
use _ = value
return! binder value |> Async.AwaitNodeCode
}
)

Expand Down
3 changes: 1 addition & 2 deletions src/Compiler/Facilities/BuildGraph.fsi
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ open System
open System.Diagnostics
open System.Threading
open System.Threading.Tasks
open FSharp.Compiler.Diagnostics.Activity
open FSharp.Compiler.DiagnosticsLogger
open Internal.Utilities.Library

Expand Down Expand Up @@ -49,7 +48,7 @@ type NodeCodeBuilder =
/// that a proper generic 'use' could be implemented but has not currently been necessary)
member Using: CompilationGlobalsScope * (CompilationGlobalsScope -> NodeCode<'T>) -> NodeCode<'T>

member Using: ActivityFacade * (ActivityFacade -> NodeCode<'T>) -> NodeCode<'T>
member Using: IDisposable * (IDisposable -> NodeCode<'T>) -> NodeCode<'T>

/// Specifies code that can be run as part of the build graph.
val node: NodeCodeBuilder
Expand Down
114 changes: 8 additions & 106 deletions src/Compiler/Facilities/Logger.fs
Original file line number Diff line number Diff line change
Expand Up @@ -6,113 +6,15 @@ open System
open System.Diagnostics
open System.Diagnostics.Tracing

module Activity =

type ActivityFacade(activity : Activity option) =
member this.AddTag key (value : #obj) = match activity with | Some activity -> activity.AddTag(key, value) |> ignore | None -> ()
member this.Perform action = match activity with | Some activity -> action activity | None -> ()
member this.Dispose() = match activity with | Some activity -> activity.Dispose() | None -> ()
interface IDisposable with
member this.Dispose() = this.Dispose()

let start (source : ActivitySource) (activityName : string) (tags : (string * #obj) seq) =
let activity = source.StartActivity(activityName) |> Option.ofObj
let facade = new ActivityFacade(activity)
for key, value in tags do
facade.AddTag key value
facade

let startNoTags (source : ActivitySource) (activityName : string) = start source activityName []

type ActivitySourceFacade(source : ActivitySource) =
member this.Start (name : string) (tags : (string * #obj) seq) = start source name tags
member this.StartNoTags name = startNoTags source name
member this.Name = source.Name
member this.Dispose() = source.Dispose()
interface IDisposable with
member this.Dispose() = this.Dispose()

let private activitySourceName = "fsc"
let private activitySource = new ActivitySource(activitySourceName)
let instance = new ActivitySourceFacade(activitySource)

type LogCompilerFunctionId =
| Service_ParseAndCheckFileInProject = 1
| Service_CheckOneFile = 2
| Service_IncrementalBuildersCache_BuildingNewCache = 3
| Service_IncrementalBuildersCache_GettingCache = 4
| CompileOps_TypeCheckOneInputAndFinishEventually = 5
| IncrementalBuild_CreateItemKeyStoreAndSemanticClassification = 6
| IncrementalBuild_TypeCheck = 7

/// This is for ETW tracing across FSharp.Compiler.
[<Sealed; EventSource(Name = "FSharpCompiler")>]
type FSharpCompilerEventSource() =
inherit EventSource()

static let instance = new FSharpCompilerEventSource()
static member Instance = instance

[<Event(1)>]
member this.Log(functionId: LogCompilerFunctionId) =
if this.IsEnabled() then this.WriteEvent(1, int functionId)

[<Event(2)>]
member this.LogMessage(message: string, functionId: LogCompilerFunctionId) =
if this.IsEnabled() then
this.WriteEvent(2, message, int functionId)

[<Event(3)>]
member this.BlockStart(functionId: LogCompilerFunctionId) =
if this.IsEnabled() then this.WriteEvent(3, int functionId)

[<Event(4)>]
member this.BlockStop(functionId: LogCompilerFunctionId) =
if this.IsEnabled() then this.WriteEvent(4, int functionId)

[<Event(5)>]
member this.BlockMessageStart(message: string, functionId: LogCompilerFunctionId) =
if this.IsEnabled() then
this.WriteEvent(5, message, int functionId)

[<Event(6)>]
member this.BlockMessageStop(message: string, functionId: LogCompilerFunctionId) =
if this.IsEnabled() then
this.WriteEvent(6, message, int functionId)

[<RequireQualifiedAccess>]
module Logger =

let Log functionId =
FSharpCompilerEventSource.Instance.Log(functionId)

let LogMessage message functionId =
FSharpCompilerEventSource.Instance.LogMessage(message, functionId)

let LogBlockStart functionId =
FSharpCompilerEventSource.Instance.BlockStart(functionId)

let LogBlockStop functionId =
FSharpCompilerEventSource.Instance.BlockStop(functionId)

let LogBlockMessageStart message functionId =
FSharpCompilerEventSource.Instance.BlockMessageStart(message, functionId)

let LogBlockMessageStop message functionId =
FSharpCompilerEventSource.Instance.BlockMessageStop(message, functionId)

let LogBlock functionId =
FSharpCompilerEventSource.Instance.BlockStart(functionId)
module Activity =

{ new IDisposable with
member _.Dispose() =
FSharpCompilerEventSource.Instance.BlockStop(functionId)
}
let private activitySource = new ActivitySource("fsc")

let LogBlockMessage message functionId =
FSharpCompilerEventSource.Instance.BlockMessageStart(message, functionId)
let Start name (tags:(string * #obj) seq) : IDisposable =
let act = activitySource.StartActivity(name)
for key,value in tags do
act.AddTag(key,value) |> ignore
act

{ new IDisposable with
member _.Dispose() =
FSharpCompilerEventSource.Instance.BlockMessageStop(message, functionId)
}
let StartNoTags name: IDisposable = activitySource.StartActivity(name)
Loading

0 comments on commit a776c86

Please sign in to comment.