-
Notifications
You must be signed in to change notification settings - Fork 158
Expand file tree
/
Copy pathBuild.Steps.cs
More file actions
2892 lines (2561 loc) · 137 KB
/
Build.Steps.cs
File metadata and controls
2892 lines (2561 loc) · 137 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using CodeGenerators;
using ICSharpCode.SharpZipLib.Zip;
using LogParsing;
using Mono.Cecil;
using Nuke.Common;
using Nuke.Common.IO;
using Nuke.Common.ProjectModel;
using Nuke.Common.Tooling;
using Nuke.Common.Tools.DotNet;
using Nuke.Common.Tools.MSBuild;
using Nuke.Common.Tools.NuGet;
using Nuke.Common.Utilities.Collections;
using static Nuke.Common.EnvironmentInfo;
using static Nuke.Common.IO.CompressionTasks;
using static Nuke.Common.IO.FileSystemTasks;
using static Nuke.Common.IO.PathConstruction;
using static Nuke.Common.Tools.DotNet.DotNetTasks;
using static Nuke.Common.Tools.MSBuild.MSBuildTasks;
using Logger = Serilog.Log;
// #pragma warning disable SA1306
// #pragma warning disable SA1134
// #pragma warning disable SA1111
// #pragma warning disable SA1400
// #pragma warning disable SA1401
partial class Build
{
[Solution("Datadog.Trace.sln")] readonly Solution Solution;
[Solution("Datadog.Trace.Samples.g.sln")] readonly Solution SamplesSolution;
AbsolutePath TracerDirectory => RootDirectory / "tracer";
AbsolutePath SharedDirectory => RootDirectory / "shared";
AbsolutePath ProfilerDirectory => RootDirectory / "profiler";
AbsolutePath MsBuildProject => TracerDirectory / "Datadog.Trace.proj";
AbsolutePath BuildArtifactsDirectory => RootDirectory / "artifacts";
AbsolutePath OutputDirectory => TracerDirectory / "bin";
AbsolutePath SymbolsDirectory => OutputDirectory / "symbols";
AbsolutePath ArtifactsDirectory => Artifacts ?? (OutputDirectory / "artifacts");
AbsolutePath WindowsTracerHomeZip => ArtifactsDirectory / "windows-tracer-home.zip";
AbsolutePath WindowsSymbolsZip => ArtifactsDirectory / "windows-native-symbols.zip";
AbsolutePath OsxTracerHomeZip => ArtifactsDirectory / "macOS-tracer-home.zip";
AbsolutePath BuildDataDirectory => BuildArtifactsDirectory / "build_data";
AbsolutePath MsbuildDebugPath => TestLogsDirectory / "msbuild";
AbsolutePath TestLogsDirectory => BuildDataDirectory / "logs";
AbsolutePath ToolSourceDirectory => ToolSource ?? (OutputDirectory / "runnerTool");
AbsolutePath ToolInstallDirectory => ToolDestination ?? (ToolSourceDirectory / "install");
AbsolutePath MonitoringHomeDirectory => MonitoringHome ?? (SharedDirectory / "bin" / "monitoring-home");
[Solution("profiler/src/Demos/Datadog.Demos.sln")] readonly Solution ProfilerSamplesSolution;
[Solution("Datadog.Profiler.sln")] readonly Solution ProfilerSolution;
AbsolutePath ProfilerMsBuildProject => ProfilerDirectory / "src" / "ProfilerEngine" / "Datadog.Profiler.Native.Windows" / "Datadog.Profiler.Native.Windows.WithTests.proj";
AbsolutePath ProfilerOutputDirectory => RootDirectory / "profiler" / "_build";
AbsolutePath ProfilerBuildDataDirectory => ProfilerDirectory / "build_data";
AbsolutePath ProfilerTestLogsDirectory => ProfilerBuildDataDirectory / "logs";
AbsolutePath NativeBuildDirectory => RootDirectory / "obj";
const string LibDdwafVersion = "1.30.0";
string[] OlderLibDdwafVersions = { "1.3.0", "1.10.0", "1.14.0", "1.16.0", "1.23.0" };
AbsolutePath LibDdwafDirectory(string libDdwafVersion = null) => (NugetPackageDirectory ?? RootDirectory / "packages") / $"libddwaf.{libDdwafVersion ?? LibDdwafVersion}";
AbsolutePath SourceDirectory => TracerDirectory / "src";
AbsolutePath BuildDirectory => TracerDirectory / "build";
AbsolutePath TestsDirectory => TracerDirectory / "test";
AbsolutePath BundleHomeDirectory => Solution.GetProject(Projects.DatadogTraceBundle).Directory / "home";
AbsolutePath DatadogTraceDirectory => Solution.GetProject(Projects.DatadogTrace).Directory;
AbsolutePath BenchmarkHomeDirectory => Solution.GetProject(Projects.DatadogTraceBenchmarkDotNet).Directory / "home";
readonly TargetFramework[] AppTrimmingTFMs = { TargetFramework.NETCOREAPP3_1, TargetFramework.NET6_0 };
AbsolutePath SharedTestsDirectory => SharedDirectory / "test";
AbsolutePath TempDirectory => (AbsolutePath)(IsWin ? Path.GetTempPath() : "/tmp/");
readonly string[] WindowsArchitectureFolders = { "win-x86", "win-x64" };
Project NativeTracerProject => Solution.GetProject(Projects.ClrProfilerNative);
Project NativeTracerTestsProject => Solution.GetProject(Projects.NativeTracerNativeTests);
Project NativeLoaderProject => Solution.GetProject(Projects.NativeLoader);
Project NativeLoaderTestsProject => Solution.GetProject(Projects.NativeLoaderNativeTests);
[LazyPathExecutable(name: "cmake")] readonly Lazy<Tool> CMake;
[LazyPathExecutable(name: "make")] readonly Lazy<Tool> Make;
[LazyPathExecutable(name: "tar")] readonly Lazy<Tool> Tar;
[LazyPathExecutable(name: "nfpm")] readonly Lazy<Tool> Nfpm;
[LazyPathExecutable(name: "cmd")] readonly Lazy<Tool> Cmd;
[LazyPathExecutable(name: "chmod")] readonly Lazy<Tool> Chmod;
[LazyPathExecutable(name: "objcopy")] readonly Lazy<Tool> ExtractDebugInfo;
[LazyPathExecutable(name: "strip")] readonly Lazy<Tool> StripBinary;
[LazyPathExecutable(name: "ln")] readonly Lazy<Tool> HardLinkUtil;
[LazyPathExecutable(name: "cppcheck")] readonly Lazy<Tool> CppCheck;
[LazyPathExecutable(name: "run-clang-tidy")] readonly Lazy<Tool> RunClangTidy;
[LazyPathExecutable(name: "patchelf")] readonly Lazy<Tool> PatchElf;
[LazyPathExecutable(name: "nm")] readonly Lazy<Tool> Nm;
//OSX Tools
readonly string[] OsxArchs = { "arm64", "x86_64" };
[LazyPathExecutable(name: "otool")] readonly Lazy<Tool> OTool;
[LazyPathExecutable(name: "lipo")] readonly Lazy<Tool> Lipo;
bool IsGitlab => !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("CI_JOB_ID"));
IEnumerable<MSBuildTargetPlatform> ArchitecturesForPlatformForTracer
{
get
{
if (TargetPlatform == MSBuildTargetPlatform.x64)
{
if (ForceARM64BuildInWindows)
{
return new[] { MSBuildTargetPlatform.x64, MSBuildTargetPlatform.x86, ARM64ECTargetPlatform };
}
else
{
return new[] { MSBuildTargetPlatform.x64, MSBuildTargetPlatform.x86 };
}
}
else if (TargetPlatform == ARM64TargetPlatform)
{
return new[] { MSBuildTargetPlatform.x64, MSBuildTargetPlatform.x86, ARM64ECTargetPlatform };
}
else if (TargetPlatform == MSBuildTargetPlatform.x86)
{
return new[] { MSBuildTargetPlatform.x86 };
}
return new[] { TargetPlatform };
}
}
IEnumerable<MSBuildTargetPlatform> ArchitecturesForPlatformForProfiler
{
get
{
if (TargetPlatform == MSBuildTargetPlatform.x64)
{
return new[] { MSBuildTargetPlatform.x64, MSBuildTargetPlatform.x86 };
}
else if (TargetPlatform == MSBuildTargetPlatform.x86)
{
return new[] { MSBuildTargetPlatform.x86 };
}
return new[] { TargetPlatform };
}
}
bool IsArm64 => RuntimeInformation.ProcessArchitecture == Architecture.Arm64;
string UnixArchitectureIdentifier => IsArm64 ? "arm64" : TargetPlatform.ToString();
IEnumerable<string> LinuxPackageTypes => IsAlpine ? new[] { "tar" } : new[] { "deb", "rpm", "tar" };
IEnumerable<Project> ProjectsToPack => new[]
{
Solution.GetProject(Projects.DatadogTraceManual),
Solution.GetProject(Projects.DatadogTraceOpenTracing),
Solution.GetProject(Projects.DatadogTraceAnnotations),
Solution.GetProject(Projects.DatadogTraceTrimming),
};
Project[] ParallelIntegrationTests => new[]
{
Solution.GetProject(Projects.TraceIntegrationTests),
};
Project[] ClrProfilerIntegrationTests
=> IsOsx
? new[] { Solution.GetProject(Projects.ClrProfilerIntegrationTests), Solution.GetProject(Projects.AppSecIntegrationTests), Solution.GetProject(Projects.DdTraceIntegrationTests) }
: new[] { Solution.GetProject(Projects.ClrProfilerIntegrationTests), Solution.GetProject(Projects.AppSecIntegrationTests), Solution.GetProject(Projects.DdTraceIntegrationTests), Solution.GetProject(Projects.DdDotnetIntegrationTests) };
TargetFramework[] TestingFrameworks => GetTestingFrameworks(Platform, IsArm64);
TargetFramework[] GetTestingFrameworks(PlatformFamily platform, bool isArm64 = false) => (platform, isArm64, IncludeAllTestFrameworks || RequiresThoroughTesting()) switch
{
// we only support linux-arm64 on .NET 5+, so we run a different subset of the TFMs for ARM64
(PlatformFamily.Linux, true, true) => new[] { TargetFramework.NET5_0, TargetFramework.NET6_0, TargetFramework.NET7_0, TargetFramework.NET8_0, TargetFramework.NET9_0, TargetFramework.NET10_0, },
(PlatformFamily.Linux, true, false) => new[] { TargetFramework.NET5_0, TargetFramework.NET6_0, TargetFramework.NET9_0, TargetFramework.NET10_0, },
// Don't test 2.1 for now, as the build is broken on master. If/when that's resolved, re-enable
(PlatformFamily.Windows, _, true) => new[] { TargetFramework.NET48, TargetFramework.NETCOREAPP3_0, TargetFramework.NETCOREAPP3_1, TargetFramework.NET5_0, TargetFramework.NET6_0, TargetFramework.NET7_0, TargetFramework.NET8_0, TargetFramework.NET9_0, TargetFramework.NET10_0, },
(PlatformFamily.Windows, _, false) => new[] { TargetFramework.NET48, TargetFramework.NETCOREAPP3_1, TargetFramework.NET9_0, TargetFramework.NET10_0, },
// Everything else e.g. MaxOS, linux-x64 etc
// Same as Windows just without the .NET FX
(_, _, true) => new[] { TargetFramework.NETCOREAPP3_0, TargetFramework.NETCOREAPP3_1, TargetFramework.NET5_0, TargetFramework.NET6_0, TargetFramework.NET7_0, TargetFramework.NET8_0, TargetFramework.NET9_0, TargetFramework.NET10_0, },
(_, _, false) => new[] { TargetFramework.NETCOREAPP3_1, TargetFramework.NET9_0, TargetFramework.NET10_0, },
};
string ReleaseBranchForCurrentVersion() => new Version(Version).Major switch
{
LatestMajorVersion => "origin/master",
var major => $"origin/release/{major}.x",
};
bool RequiresThoroughTesting()
{
if (IsLocalBuild)
{
// we should always run all tests locally
return true;
}
var baseBranch = string.IsNullOrEmpty(TargetBranch) ? ReleaseBranchForCurrentVersion() : $"origin/{TargetBranch}";
if (IsGitBaseBranch(baseBranch))
{
// do a full run on the main branch
return true;
}
var gitChangedFiles = GetGitChangedFiles(baseBranch);
var integrationChangedFiles = TargetFrameworks
.SelectMany(tfm => new[]
{
// Changes to the definitions (new integrations etc)
$"tracer/src/Datadog.Trace/Generated/{tfm}/Datadog.Trace.SourceGenerators/Datadog.Trace.SourceGenerators.InstrumentationDefinitions.InstrumentationDefinitionsGenerator",
$"tracer/src/Datadog.Trace/Generated/{tfm}/Datadog.Trace.SourceGenerators/AspectsDefinitionsGenerator",
})
.Concat(new [] {
// Changes to the integrations themselves, e.g. change in behaviour
"tracer/src/Datadog.Trace/ClrProfiler/AutoInstrumentation",
"tracer/src/Datadog.Trace/Iast/Aspects"
})
.ToList();
var hasIntegrationChanges = gitChangedFiles.Any(s => integrationChangedFiles.Any(s.Contains));
var snapshotChangeCount = gitChangedFiles.Count(s => s.EndsWith("verified.txt"));
// If the integrations have changed, we should play it safe and test all the frameworks
// If a lot of snapshots have changed, we should play it safe
return hasIntegrationChanges || (snapshotChangeCount > 100);
}
readonly IEnumerable<TargetFramework> TargetFrameworks = new[]
{
TargetFramework.NET461,
TargetFramework.NETSTANDARD2_0,
TargetFramework.NETCOREAPP3_1,
TargetFramework.NET6_0,
};
Target CreateRequiredDirectories => _ => _
.Unlisted()
.Executes(() =>
{
EnsureExistingDirectory(MonitoringHomeDirectory);
EnsureExistingDirectory(ArtifactsDirectory);
EnsureExistingDirectory(BuildDataDirectory);
EnsureExistingDirectory(ProfilerBuildDataDirectory);
EnsureExistingDirectory(SymbolsDirectory);
EnsureExistingDirectory(BuildArtifactsDirectory / "publish");
});
Target Restore => _ => _
.After(Clean)
.Unlisted()
.Executes(() =>
{
if (FastDevLoop)
{
return;
}
if (IsWin)
{
NuGetTasks.NuGetRestore(s => s
.SetTargetPath(Solution)
.SetVerbosity(NuGetVerbosity.Normal)
.SetProcessLogOutput(!IsServerBuild)
.When(!string.IsNullOrEmpty(NugetPackageDirectory), o =>
o.SetPackagesDirectory(NugetPackageDirectory)));
}
else
{
DotNetRestore(s => s
.SetProjectFile(Solution)
.SetVerbosity(DotNetVerbosity.Minimal)
.SetProperty("configuration", BuildConfiguration.ToString())
.When(!string.IsNullOrEmpty(NugetPackageDirectory), o =>
o.SetPackageDirectory(NugetPackageDirectory)));
}
});
Target CompileTracerNativeSrcWindows => _ => _
.Unlisted()
.After(CompileManagedLoader)
.OnlyWhenStatic(() => IsWin)
.Executes(() =>
{
// If we're building for x64, build for x86 too
var platforms = ArchitecturesForPlatformForTracer;
Logger.Information($"Running in GitLab? {IsGitlab}");
// Can't use dotnet msbuild, as needs to use the VS version of MSBuild
// Build native tracer assets
MSBuild(s => s
.SetTargetPath(MsBuildProject)
.SetConfiguration(BuildConfiguration)
.SetMSBuildPath()
.SetTargets("BuildCppSrc")
.DisableRestore()
// Gitlab has issues with memory usage...
.SetMaxCpuCount(IsGitlab ? 1 : null)
.CombineWith(platforms, (m, platform) => m
.SetTargetPlatform(platform)));
});
Target CompileTracerNativeSrcLinux => _ => _
.Unlisted()
.After(CompileManagedLoader)
.OnlyWhenStatic(() => IsLinux)
.Executes(() =>
{
EnsureExistingDirectory(NativeBuildDirectory);
CMake.Value(
arguments: $"-DCMAKE_CXX_COMPILER=clang++ -DCMAKE_C_COMPILER=clang -B {NativeBuildDirectory} -S {RootDirectory} -DCMAKE_BUILD_TYPE={BuildConfiguration}");
CMake.Value(
arguments: $"--build {NativeBuildDirectory} --parallel {Environment.ProcessorCount} --target {FileNames.NativeTracer}");
});
Target CompileTracerNativeTestsLinux => _ => _
.Unlisted()
.After(CompileManagedLoader)
.OnlyWhenStatic(() => IsLinux)
.Executes(() =>
{
EnsureExistingDirectory(NativeBuildDirectory);
CMake.Value(
arguments: $"-DCMAKE_CXX_COMPILER=clang++ -DCMAKE_C_COMPILER=clang -B {NativeBuildDirectory} -S {RootDirectory} -DCMAKE_BUILD_TYPE={BuildConfiguration}");
CMake.Value(
arguments: $"--build {NativeBuildDirectory} --parallel {Environment.ProcessorCount} --target {FileNames.NativeTracerTests}");
});
Target CompileNativeSrcMacOs => _ => _
.Unlisted()
.After(CompileManagedLoader)
.OnlyWhenStatic(() => IsOsx)
.Executes(() =>
{
DeleteDirectory(NativeTracerProject.Directory / "build");
var finalArchs = string.Join(';', OsxArchs);
var buildDirectory = NativeBuildDirectory + "_" + finalArchs.Replace(';', '_');
EnsureExistingDirectory(buildDirectory);
var envVariables = new Dictionary<string, string>
{
["HOME"] = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),
["PATH"] = Environment.GetEnvironmentVariable("PATH"),
["CMAKE_OSX_ARCHITECTURES"] = finalArchs,
["CMAKE_MAKE_PROGRAM"] = "make",
["CMAKE_CXX_COMPILER"] = "clang++",
["CMAKE_C_COMPILER"] = "clang",
};
// Build native
CMake.Value(
arguments: $"-B {buildDirectory} -S {RootDirectory} -DCMAKE_BUILD_TYPE={BuildConfiguration}",
environmentVariables: envVariables);
CMake.Value(
arguments: $"--build {buildDirectory} --parallel {Environment.ProcessorCount} --target {FileNames.NativeTracer}",
environmentVariables: envVariables);
var sourceFile = NativeTracerProject.Directory / "build" / "bin" / $"{NativeTracerProject.Name}.dylib";
// Check section with the manager loader
var output = OTool.Value(arguments: $"-s binary dll {sourceFile}", logOutput: false);
var outputCount = output.Select(o => o.Type == OutputType.Std).Count();
if (outputCount < 1000)
{
throw new ApplicationException("Managed loader section doesn't have the enough size > 1000");
}
foreach (var arch in finalArchs.Split(';'))
{
// Check the architecture of the build
output = Lipo.Value(arguments: $"-archs {sourceFile}", logOutput: false);
var strOutput = string.Join('\n', output.Where(o => o.Type == OutputType.Std).Select(o => o.Text));
if (!strOutput.Contains(arch, StringComparison.OrdinalIgnoreCase))
{
throw new ApplicationException($"Invalid architecture, expected: '{arch}', actual: '{strOutput}'");
}
}
});
Target CompileTracerNativeSrc => _ => _
.Unlisted()
.Description("Compiles the native tracer assets")
.DependsOn(CompileTracerNativeSrcWindows)
.DependsOn(CompileNativeSrcMacOs)
.DependsOn(CompileTracerNativeSrcLinux)
.After(CompileManagedSrc);
Target CompileTracerNativeTests => _ => _
.Unlisted()
.Description("Compiles the native tracer tests assets")
.DependsOn(CompileTracerNativeTestsWindows)
.DependsOn(CompileTracerNativeTestsLinux);
Target CppCheckNativeSrcUnix => _ => _
.Unlisted()
.OnlyWhenStatic(() => IsLinux || IsOsx)
.Executes(() =>
{
var (arch, ext) = GetUnixArchitectureAndExtension();
CppCheck.Value(arguments: $"--inconclusive --project={NativeTracerProject.Path} --output-file={BuildDataDirectory}/{NativeTracerProject.Name}-cppcheck-{arch}.xml --xml --enable=all --suppress=\"noExplicitConstructor\" --suppress=\"cstyleCast\" --suppress=\"duplicateBreak\" --suppress=\"unreadVariable\" --suppress=\"functionConst\" --suppress=\"funcArgNamesDifferent\" --suppress=\"variableScope\" --suppress=\"useStlAlgorithm\" --suppress=\"functionStatic\" --suppress=\"initializerList\" --suppress=\"redundantAssignment\" --suppress=\"redundantInitialization\" --suppress=\"shadowVariable\" --suppress=\"constParameter\" --suppress=\"unusedPrivateFunction\" --suppress=\"unusedFunction\" --suppress=\"missingInclude\" --suppress=\"unmatchedSuppression\" --suppress=\"knownConditionTrueFalse\"");
CppCheck.Value(arguments: $"--inconclusive --project={NativeTracerProject.Path} --output-file={BuildDataDirectory}/{NativeTracerProject.Name}-cppcheck-{arch}.txt --enable=all --suppress=\"noExplicitConstructor\" --suppress=\"cstyleCast\" --suppress=\"duplicateBreak\" --suppress=\"unreadVariable\" --suppress=\"functionConst\" --suppress=\"funcArgNamesDifferent\" --suppress=\"variableScope\" --suppress=\"useStlAlgorithm\" --suppress=\"functionStatic\" --suppress=\"initializerList\" --suppress=\"redundantAssignment\" --suppress=\"redundantInitialization\" --suppress=\"shadowVariable\" --suppress=\"constParameter\" --suppress=\"unusedPrivateFunction\" --suppress=\"unusedFunction\" --suppress=\"missingInclude\" --suppress=\"unmatchedSuppression\" --suppress=\"knownConditionTrueFalse\"");
});
Target CppCheckNativeSrc => _ => _
.Unlisted()
.Description("Runs CppCheck over the native tracer project")
.DependsOn(CppCheckNativeSrcUnix);
Target CompileManagedLoader => _ => _
.Unlisted()
.Description("Compiles the managed loader (which is required by the native loader)")
.After(CreateRequiredDirectories)
.After(Restore)
.Executes(() =>
{
DotnetBuild(new[] { Solution.GetProject(Projects.ManagedLoader).Path }, noRestore: false, noDependencies: false);
});
Target CompileManagedSrc => _ => _
.Unlisted()
.Description("Compiles the managed code in the src directory")
.After(CreateRequiredDirectories)
.After(Restore)
.After(CompileManagedLoader)
.Executes(() =>
{
// Removes previously generated files
// This is mostly to avoid forgetting to remove deprecated files (class name change or path change)
if (IsWin)
{
EnsureCleanDirectory(DatadogTraceDirectory / "Generated");
}
var include = TracerDirectory.GlobFiles(
"src/**/*.csproj"
);
var exclude = TracerDirectory.GlobFiles(
"src/Datadog.Trace.Bundle/Datadog.Trace.Bundle.csproj", // no code, used to generate nuget package
"src/Datadog.AzureFunctions/Datadog.AzureFunctions.csproj", // no code, used to generate nuget package
"src/Datadog.Trace.Tools.Runner/*.csproj",
"src/**/Datadog.InstrumentedAssembly*.csproj",
"src/Datadog.AutoInstrumentation.Generator/*.csproj",
$"src/{Projects.ManagedLoader}/*.csproj"
);
var toBuild = include.Except(exclude);
DotnetBuild(toBuild, noDependencies: false);
var nativeGeneratedFilesOutputPath = NativeTracerProject.Directory / "Generated";
CallSitesGenerator.GenerateCallSites(TargetFrameworks, tfm => DatadogTraceDirectory / "bin" / BuildConfiguration / tfm / Projects.DatadogTrace + ".dll", nativeGeneratedFilesOutputPath);
CallTargetsGenerator.GenerateCallTargets(TargetFrameworks, tfm => DatadogTraceDirectory / "bin" / BuildConfiguration / tfm / Projects.DatadogTrace + ".dll", nativeGeneratedFilesOutputPath, Version, BuildDirectory);
});
Target CompileTracerNativeTestsWindows => _ => _
.Unlisted()
.OnlyWhenStatic(() => IsWin)
.Executes(() =>
{
// If we're building for x64, build for x86 too
var platforms =
Equals(TargetPlatform, MSBuildTargetPlatform.x64)
? new[] { MSBuildTargetPlatform.x64, MSBuildTargetPlatform.x86 }
: new[] { MSBuildTargetPlatform.x86 };
// Can't use dotnet msbuild, as needs to use the VS version of MSBuild
MSBuild(s => s
.SetTargetPath(MsBuildProject)
.SetConfiguration(BuildConfiguration)
.SetMSBuildPath()
.SetTargets("BuildCppTests")
.DisableRestore()
.SetMaxCpuCount(null)
.CombineWith(platforms, (m, platform) => m
.SetTargetPlatform(platform)));
});
Target DownloadLibDdwaf => _ => _.Unlisted().After(CreateRequiredDirectories).Executes(() => DownloadWafVersion());
async Task DownloadWafVersion(string libddwafVersion = null, string uncompressFolderTarget = null)
{
var libDdwafUri = new Uri(
$"https://www.nuget.org/api/v2/package/libddwaf/{libddwafVersion ?? LibDdwafVersion}"
);
var libDdwafZip = TempDirectory / "libddwaf.zip";
using var client = new HttpClient();
const int maxRetries = 5;
const int timeoutSeconds = 15;
for (int attempt = 1; attempt <= maxRetries; attempt++)
{
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(timeoutSeconds));
try
{
Console.WriteLine($"Attempt {attempt}: Downloading {libDdwafUri}...");
var response = await client.GetAsync(libDdwafUri, cts.Token);
response.EnsureSuccessStatusCode();
await using var file = File.Create(libDdwafZip);
await using var stream = await response.Content.ReadAsStreamAsync(cts.Token);
await stream.CopyToAsync(file, cts.Token);
Console.WriteLine($"Download succeeded on attempt {attempt}.");
break; // Exit loop on success
}
catch (OperationCanceledException) when (cts.IsCancellationRequested)
{
Console.WriteLine($"Attempt {attempt} timed out after {timeoutSeconds} seconds.");
}
catch (HttpRequestException ex)
{
Console.WriteLine($"Attempt {attempt} failed: {ex.Message}");
}
if (attempt == maxRetries)
{
throw new Exception($"Failed to download {libDdwafUri} after {maxRetries} attempts.");
}
// Exponential backoff before retrying
await Task.Delay(TimeSpan.FromSeconds(2 * attempt));
}
uncompressFolderTarget ??= LibDdwafDirectory(libddwafVersion);
Console.WriteLine($"{libDdwafZip} downloaded. Extracting to {uncompressFolderTarget}...");
UncompressZipQuiet(libDdwafZip, uncompressFolderTarget);
}
Target CopyLibDdwaf => _ => _
.Unlisted()
.After(Clean)
.After(DownloadLibDdwaf)
.Executes(() =>
{
if (IsWin)
{
foreach (var architecture in WindowsArchitectureFolders)
{
var source = LibDdwafDirectory() / "runtimes" / architecture / "native" / "ddwaf.dll";
var dest = MonitoringHomeDirectory / architecture;
CopyFileToDirectory(source, dest, FileExistsPolicy.Overwrite);
}
}
else if (IsLinux)
{
var (sourceArch, ext) = GetLibDdWafUnixArchitectureAndExtension();
var (destArch, _) = GetUnixArchitectureAndExtension();
var ddwafFileName = $"libddwaf.{ext}";
var source = LibDdwafDirectory() / "runtimes" / sourceArch / "native" / ddwafFileName;
var dest = MonitoringHomeDirectory / destArch;
CopyFileToDirectory(source, dest, FileExistsPolicy.Overwrite);
}
else if (IsOsx)
{
var (sourceArch, ext) = GetLibDdWafUnixArchitectureAndExtension();
var ddwafFileName = $"libddwaf.{ext}";
var source = LibDdwafDirectory() / "runtimes" / sourceArch / "native" / ddwafFileName;
var dest = MonitoringHomeDirectory / "osx";
CopyFileToDirectory(source, dest, FileExistsPolicy.Overwrite);
}
});
Target DownloadLibDatadog => _ => _
.Unlisted()
.After(CreateRequiredDirectories)
.Executes(async () =>
{
if (IsLinux || IsOsx)
{
if (!Directory.Exists(NativeBuildDirectory))
{
CMake.Value(
arguments: $"-DCMAKE_CXX_COMPILER=clang++ -DCMAKE_C_COMPILER=clang -B {NativeBuildDirectory} -S {RootDirectory}");
}
// In CI, the folder might already exist. Which means that CMake was already configured
// and libdatadog artifact (correct one) was already downloaded.
// So just reuse it.
}
else if (IsWin)
{
var vcpkgExePath = await GetVcpkg();
var vcpkgRoot = Environment.GetEnvironmentVariable("VCPKG_ROOT") ?? Directory.GetParent(vcpkgExePath).FullName;
var vcpkg = ToolResolver.GetLocalTool(vcpkgExePath);
foreach (var arch in new[] { MSBuildTargetPlatform.x64, MSBuildTargetPlatform.x86 })
{
var triplet = $"{arch}-windows";
// note that the following are all quoted when entered into the vcpkg call itself
// this is necessary to support cases where we have a space in the folder name
var installRoot = $@"{BuildArtifactsDirectory}\deps\vcpkg\{triplet}";
var downloads = $@"{BuildArtifactsDirectory}\obj\vcpkg\downloads";
var packages = $@"{BuildArtifactsDirectory}\obj\vcpkg\packages";
var buildTrees = $@"{BuildArtifactsDirectory}\obj\vcpkg\buildtrees";
const int maxRetries = 3;
for (int attempt = 1; attempt <= maxRetries; attempt++)
{
try
{
Logger.Information($"Attempt {attempt}: Running vcpkg install for {triplet}...");
// This big line is the same generated by VS when installing libdatadog while building the profiler
vcpkg($@"install --x-wait-for-lock --triplet ""{triplet}"" --vcpkg-root ""{vcpkgRoot}"" ""--x-manifest-root={RootDirectory}"" ""--x-install-root={installRoot}"" --downloads-root ""{downloads}"" --x-packages-root ""{packages}"" --x-buildtrees-root ""{buildTrees}"" --clean-after-build");
Logger.Information($"vcpkg install succeeded on attempt {attempt}.");
break; // Exit loop on success
}
catch (Exception ex)
{
Logger.Warning($"Attempt {attempt} failed: {ex.Message}");
if (attempt == maxRetries)
{
throw;
}
// Exponential backoff before retrying
var delaySeconds = 5 * attempt;
Logger.Information($"Waiting {delaySeconds} seconds before retry...");
await Task.Delay(TimeSpan.FromSeconds(delaySeconds));
}
}
}
}
});
Target CopyLibDatadog => _ => _
.Unlisted()
.After(DownloadLibDatadog)
.Executes(() =>
{
if (IsWin)
{
var vcpkgDepsFolder = BuildArtifactsDirectory / "deps" / "vcpkg";
foreach (var architecture in new[] { MSBuildTargetPlatform.x64, MSBuildTargetPlatform.x86 })
{
var source = vcpkgDepsFolder / $"{architecture}-windows" / $"{architecture}-windows";
if (BuildConfiguration == Configuration.Debug)
{
source /= "debug";
}
var dllFile = source / "bin" / "datadog_profiling_ffi.dll";
var dest = MonitoringHomeDirectory / $"win-{architecture}";
CopyFileToDirectory(dllFile, dest, FileExistsPolicy.Overwrite);
var pdbFile = source / "bin" / "datadog_profiling_ffi.pdb";
dest = SymbolsDirectory / $"win-{architecture}";
CopyFileToDirectory(pdbFile, dest, FileExistsPolicy.Overwrite);
}
}
else if (IsLinux)
{
var (destArch, ext) = GetUnixArchitectureAndExtension();
var libdatadogFileName = $"libdatadog_profiling.{ext}";
var source = NativeBuildDirectory / "libdatadog-install" / "lib" / libdatadogFileName;
var dest = MonitoringHomeDirectory / destArch;
CopyFileToDirectory(source, dest, FileExistsPolicy.Overwrite);
}
else if (IsOsx)
{
var libdatadogFileName = $"libdatadog_profiling.dylib";
var source = NativeBuildDirectory / "libdatadog-install" / "lib" / libdatadogFileName;
var dest = MonitoringHomeDirectory / "osx";
CopyFileToDirectory(source, dest, FileExistsPolicy.Overwrite);
}
});
Target CopyNativeFilesForTests => _ => _
.Unlisted()
.After(Clean, BuildTracerHome)
.Before(RunIntegrationTests, RunManagedUnitTests)
.Executes(() =>
{
// Copy the native files to all the test projects for simplicity.
var testProjects = Solution.GetProjects("*Tests")
.Where(p => p.SolutionFolder.Name == "test"
&& p.Path.ToString().EndsWith(".csproj")); // exclude native test projects
foreach(var projectName in testProjects)
{
Logger.Information("Copying native files for project {ProjectName}", projectName);
var project = Solution.GetProject(projectName);
var testDir = project!.Directory;
var frameworks = project.GetTargetFrameworks();
if (Framework is not null)
{
frameworks = frameworks.Where(x=> x == Framework).ToList();
}
var testBinFolder = testDir / "bin" / BuildConfiguration;
var (ext, source, libdatadog) = Platform switch
{
PlatformFamily.Windows => ("dll", MonitoringHomeDirectory / $"win-{TargetPlatform}", "datadog_profiling_ffi.dll"),
PlatformFamily.Linux => ("so", MonitoringHomeDirectory / GetUnixArchitectureAndExtension().Arch, "libdatadog_profiling.so"),
PlatformFamily.OSX => ("dylib", MonitoringHomeDirectory / "osx", "libdatadog_profiling.dylib"),
_ => throw new NotSupportedException($"Unsupported platform: {Platform}")
};
var libs = new[]
{
(libdatadog, $"LibDatadog.{ext}"),
($"Datadog.Tracer.Native.{ext}", $"Datadog.Tracer.Native.{ext}"),
};
foreach (var framework in frameworks)
{
foreach (var lib in libs)
{
var dest = testBinFolder / framework / lib.Item2;
CopyFile(source / lib.Item1, dest, FileExistsPolicy.Overwrite);
}
}
}
});
Target CopyNativeFilesForAppSecUnitTests => _ => _
.Unlisted()
.After(Clean)
.After(DownloadLibDdwaf)
.Executes(async () =>
{
var project = Solution.GetProject(Projects.AppSecUnitTests);
var testDir = project.Directory;
var frameworks = project.GetTargetFrameworks();
var testBinFolder = testDir / "bin" / BuildConfiguration;
// dotnet test runs under x86 for net461, even on x64 platforms
// so copy both, just to be safe
if (IsWin)
{
foreach (var olderLibDdwafVersion in OlderLibDdwafVersions)
{
var oldVersionTempPath = TempDirectory / $"libddwaf.{olderLibDdwafVersion}";
await DownloadWafVersion(olderLibDdwafVersion, oldVersionTempPath);
foreach (var arch in WindowsArchitectureFolders)
{
var oldVersionPath = oldVersionTempPath / "runtimes" / arch / "native" / "ddwaf.dll";
var source = MonitoringHomeDirectory / arch;
foreach (var framework in frameworks)
{
var dest = testBinFolder / framework / arch;
CopyDirectoryRecursively(source, dest, DirectoryExistsPolicy.Merge, FileExistsPolicy.Overwrite);
CopyFile(oldVersionPath, dest / $"ddwaf-{olderLibDdwafVersion}.dll", FileExistsPolicy.Overwrite);
}
}
}
}
else
{
var (arch, _) = GetUnixArchitectureAndExtension();
var (archWaf, ext) = GetLibDdWafUnixArchitectureAndExtension();
foreach (var olderLibDdwafVersion in OlderLibDdwafVersions)
{
var patchedArchWaf = (IsOsx && olderLibDdwafVersion == "1.3.0") ? archWaf + "-x64" : archWaf;
var oldVersionTempPath = TempDirectory / $"libddwaf.{olderLibDdwafVersion}";
var oldVersionPath = oldVersionTempPath / "runtimes" / patchedArchWaf / "native" / $"libddwaf.{ext}";
await DownloadWafVersion(olderLibDdwafVersion, oldVersionTempPath);
{
foreach (var framework in frameworks)
{
// We have to copy into the _root_ test bin folder here, not the arch sub-folder.
// This is because these tests try to load the WAF.
// Loading the WAF requires using the native tracer as a proxy, which means either
// - The native tracer must be loaded first, so it can rewrite the PInvoke calls
// - The native tracer must be side-by-side with the running dll
// As this is a managed-only unit test, the native tracer _must_ be in the root folder
// For simplicity, we just copy all the native dlls there
var dest = testBinFolder / framework;
// use the files from the monitoring native folder
CopyDirectoryRecursively(MonitoringHomeDirectory / (IsOsx ? "osx" : arch), dest, DirectoryExistsPolicy.Merge, FileExistsPolicy.Overwrite);
CopyFile(oldVersionPath, dest / $"libddwaf-{olderLibDdwafVersion}.{ext}", FileExistsPolicy.Overwrite);
}
}
}
}
});
Target PublishManagedTracer => _ => _
.Unlisted()
.After(CompileManagedSrc)
.Executes(() =>
{
var targetFrameworks = IsWin
? TargetFrameworks
: TargetFrameworks.Where(framework => !framework.ToString().StartsWith("net4"));
try
{
// Publish Datadog.Trace.MSBuild which includes Datadog.Trace
DotNetPublish(s => s
.SetProject(Solution.GetProject(Projects.DatadogTraceMsBuild))
.SetConfiguration(BuildConfiguration)
.SetTargetPlatformAnyCPU()
.EnableNoBuild()
.EnableNoRestore()
.CombineWith(targetFrameworks, (p, framework) => p
.SetFramework(framework)
.SetOutput(MonitoringHomeDirectory / framework)
.SetProcessEnvironmentVariable("MSBUILDDEBUGPATH", MsbuildDebugPath))
);
}
catch
{
// Print tail of MSBuild failure notes, if any, then rethrow
MSBuildLogHelper.DumpMsBuildChildFailures(MsbuildDebugPath);
throw;
}
});
Target PublishManagedTracerR2R => _ => _
.Unlisted()
.After(CompileManagedSrc)
.Executes(() =>
{
var targetFramework = TargetFramework.NET6_0;
// Needed as we need to restore with the RuntimeIdentifier
DotNetRestore(s => s
.SetProjectFile(Solution.GetProject(Projects.DatadogTraceMsBuild))
.SetPublishReadyToRun(true)
.SetRuntime(RuntimeIdentifier)
);
DotNetPublish(s => s
.SetProject(Solution.GetProject(Projects.DatadogTraceMsBuild))
.SetConfiguration(BuildConfiguration)
.SetTargetPlatformAnyCPU()
.SetPublishReadyToRun(true)
.SetRuntime(RuntimeIdentifier)
.SetSelfContained(false)
.SetFramework(targetFramework)
.SetOutput(MonitoringHomeDirectory / targetFramework)
);
});
Target PublishNativeSymbolsWindows => _ => _
.Unlisted()
.OnlyWhenStatic(() => IsWin)
.After(CompileTracerNativeSrc, PublishManagedTracer)
.Executes(() =>
{
foreach (var architecture in ArchitecturesForPlatformForTracer)
{
var source = NativeTracerProject.Directory / "bin" / BuildConfiguration / architecture.ToString() /
$"{NativeTracerProject.Name}.pdb";
var dest = SymbolsDirectory / $"win-{architecture}" / Path.GetFileName(source);
CopyFile(source, dest, FileExistsPolicy.Overwrite);
}
});
Target PublishDdDotnetSymbolsWindows => _ => _
.Unlisted()
.OnlyWhenStatic(() => IsWin)
.After(BuildDdDotnet, PublishManagedTracer)
.Executes(() =>
{
var source = ArtifactsDirectory / "dd-dotnet" / "win-x64" / "dd-dotnet.pdb";
var dest = SymbolsDirectory / "dd-dotnet-win-x64" / "dd-dotnet.pdb";
CopyFile(source, dest, FileExistsPolicy.Overwrite);
});
Target PublishNativeTracerWindows => _ => _
.Unlisted()
.OnlyWhenStatic(() => IsWin)
.After(CompileTracerNativeSrc, PublishManagedTracer)
.Executes(() =>
{
foreach (var architecture in ArchitecturesForPlatformForTracer)
{
// Copy native tracer assets
var source = NativeTracerProject.Directory / "bin" / BuildConfiguration / architecture.ToString() /
$"{NativeTracerProject.Name}.dll";
var dest = MonitoringHomeDirectory / $"win-{architecture}";
CopyFileToDirectory(source, dest, FileExistsPolicy.Overwrite);
}
});
Target PublishNativeTracerUnix => _ => _
.Unlisted()
.OnlyWhenStatic(() => IsLinux)
.After(CompileTracerNativeSrc, PublishManagedTracer)
.Executes(() =>
{
var (arch, extension) = GetUnixArchitectureAndExtension();
// Copy Native file
CopyFileToDirectory(
NativeTracerProject.Directory / "build" / "bin" / $"{NativeTracerProject.Name}.{extension}",
MonitoringHomeDirectory / arch,
FileExistsPolicy.Overwrite);
});
Target PublishNativeTracerOsx => _ => _
.Unlisted()
.OnlyWhenStatic(() => IsOsx)
.After(CompileTracerNativeSrc, PublishManagedTracer)
.Executes(() =>
{
// Copy the universal binary to the output folder
CopyFileToDirectory(
NativeTracerProject.Directory / "build" / "bin" / $"{NativeTracerProject.Name}.dylib",
MonitoringHomeDirectory / "osx",
FileExistsPolicy.Overwrite,
true);
});
Target PublishNativeTracer => _ => _
.Unlisted()
.DependsOn(PublishNativeTracerWindows)
.DependsOn(PublishNativeTracerUnix)
.DependsOn(PublishNativeTracerOsx);
Target BuildFleetInstaller => _ => _
.Unlisted()
.Description("Builds and publishes the fleet installer binary files")
.After(Clean, Restore, CompileManagedSrc)
.Before(SignDlls)
.OnlyWhenStatic(() => IsWin)
.Executes(() =>
{
// Build the fleet installer project
var project = SourceDirectory / "Datadog.FleetInstaller" / "Datadog.FleetInstaller.csproj";
var tfms = Solution.GetProject(project).GetTargetFrameworks();
// we should only have a single tfm for fleet installer
if (tfms.Count != 1)
{
throw new ApplicationException("Fleet installer should only have a single target framework but found: " + string.Join(", ", tfms));
}
var publishFolder = ArtifactsDirectory / "Datadog.FleetInstaller";
DotNetPublish(s => s
.SetProject(project)
.SetConfiguration(BuildConfiguration)
.SetOutput(publishFolder)
.CombineWith(tfms, (p, tfm) => p.SetFramework(tfm)));
});
Target PublishFleetInstaller => _ => _
.Unlisted()
.Description("Publishes the fleet installer binary files as a zip")
.DependsOn(BuildFleetInstaller)
.After(SignDlls)
.OnlyWhenStatic(() => IsWin)
.Executes(() =>
{
var publishFolder = ArtifactsDirectory / "Datadog.FleetInstaller";
CompressZip(publishFolder, ArtifactsDirectory / "fleet-installer.zip", fileMode: FileMode.Create);
});
Target BuildMsi => _ => _
.Unlisted()
.Description("Builds the .msi files from the repo")
.After(BuildTracerHome, BuildProfilerHome, BuildNativeLoader, BuildDdDotnet)
.OnlyWhenStatic(() => IsWin)
.Executes(() =>
{
// We don't produce an x86-only MSI any more
var architectures = ArchitecturesForPlatformForTracer.Where(x => x != MSBuildTargetPlatform.x86);
MSBuild(s => s
.SetTargetPath(SharedDirectory / "src" / "msi-installer" / "WindowsInstaller.wixproj")
.SetConfiguration(BuildConfiguration)
.SetMSBuildPath()