@@ -6,11 +6,15 @@ import (
66 "fmt"
77 "os"
88 "path/filepath"
9+ "time"
910
1011 "agent-metadata-action/internal/client"
1112 "agent-metadata-action/internal/config"
1213 "agent-metadata-action/internal/loader"
14+ "agent-metadata-action/internal/logging"
1315 "agent-metadata-action/internal/models"
16+
17+ "github.com/newrelic/go-agent/v3/newrelic"
1418)
1519
1620// metadataClient interface for testing
@@ -24,22 +28,89 @@ var createMetadataClientFunc = func(baseURL, token string) metadataClient {
2428 return client .NewInstrumentationClient (baseURL , token )
2529}
2630
31+ // initNewRelic initializes the New Relic application
32+ // Returns nil if APM_CONTROL_NR_LICENSE_KEY is not set (silent no-op mode)
33+ func initNewRelic () * newrelic.Application {
34+ licenseKey := config .GetNRAgentLicenseKey ()
35+ if licenseKey == "" {
36+ _ , _ = fmt .Fprintln (os .Stderr , "::warn::Failed to init New Relic - missing license key" )
37+ return nil
38+ }
39+
40+ // Hardcode staging environment
41+ err := config .SetNRAgentHost ()
42+ if err != nil {
43+ _ , _ = fmt .Fprintf (os .Stderr , "::warn::Failed to init New Relic, missing host: %v\n " , err )
44+ return nil
45+ }
46+ fmt .Println ("::notice::Using New Relic staging environment" )
47+
48+ app , err := newrelic .NewApplication (
49+ newrelic .ConfigAppName ("agent-metadata-action" ),
50+ newrelic .ConfigLicense (licenseKey ),
51+ newrelic .ConfigDebugLogger (os .Stdout ),
52+ newrelic .ConfigDistributedTracerEnabled (true ),
53+ newrelic .ConfigAppLogForwardingEnabled (true ),
54+ newrelic .ConfigFromEnvironment (), // This reads NEW_RELIC_HOST
55+ newrelic .ConfigLabels (map [string ]string {
56+ "team" : "APM Control Team" ,
57+ }),
58+ )
59+
60+ if err != nil {
61+ _ , _ = fmt .Fprintf (os .Stderr , "::warn::Failed to init New Relic: %v\n " , err )
62+ return nil
63+ }
64+
65+ fmt .Println ("::notice::New Relic APM enabled - waiting for connection..." )
66+
67+ // Wait for the app to connect (max 10 seconds)
68+ if err := app .WaitForConnection (10 * time .Second ); err != nil {
69+ fmt .Printf ("::warn::New Relic connection timeout: %v - will try to send data anyway\n " , err )
70+ } else {
71+ fmt .Println ("::notice::New Relic connected successfully" )
72+ }
73+
74+ return app
75+ }
76+
2777func main () {
28- if err := run (); err != nil {
78+ nrApp := initNewRelic ()
79+
80+ if err := run (nrApp ); err != nil {
2981 _ , _ = fmt .Fprintf (os .Stderr , "::error::%v\n " , err )
3082 os .Exit (1 )
3183 }
84+
85+ if nrApp != nil {
86+ fmt .Println ("::notice::Shutting down New Relic - waiting up to 15 seconds to send data..." )
87+ nrApp .Shutdown (15 * time .Second )
88+ fmt .Println ("::notice::New Relic shutdown complete" )
89+ }
3290}
3391
34- func run () error {
92+ func run (nrApp * newrelic.Application ) error {
93+ // Create context
94+ ctx := context .Background ()
95+
96+ // Start transaction if New Relic is enabled
97+ if nrApp != nil {
98+ txn := nrApp .StartTransaction ("agent-metadata-action" )
99+ defer txn .End ()
100+
101+ // Add transaction to context for logging
102+ ctx = newrelic .NewContext (ctx , txn )
103+ logging .Debug (ctx , "New Relic transaction started" )
104+ defer logging .Debug (ctx , "New Relic transaction ended" )
105+ }
106+
35107 // Validate required environment and setup
36- workspace , token , err := validateEnvironment ()
108+ workspace , token , err := validateEnvironment (ctx )
37109 if err != nil {
38110 return err
39111 }
40112
41113 // Create metadataClient
42- ctx := context .Background ()
43114 metadataClient := createMetadataClientFunc (config .GetMetadataURL (), token )
44115
45116 // Determine which flow to execute
@@ -54,7 +125,7 @@ func run() error {
54125}
55126
56127// validateEnvironment checks required environment variables and workspace
57- func validateEnvironment () (workspace string , token string , err error ) {
128+ func validateEnvironment (ctx context. Context ) (workspace string , token string , err error ) {
58129 workspace = config .GetWorkspace ()
59130 if workspace == "" {
60131 return "" , "" , fmt .Errorf ("GITHUB_WORKSPACE is required but not set" )
@@ -69,13 +140,13 @@ func validateEnvironment() (workspace string, token string, err error) {
69140 return "" , "" , fmt .Errorf ("NEWRELIC_TOKEN is required but not set" )
70141 }
71142
72- fmt . Println ( "::notice:: Environment validated successfully" )
143+ logging . Notice ( ctx , " Environment validated successfully" )
73144 return workspace , token , nil
74145}
75146
76147// runAgentFlow handles the agent repository workflow
77148func runAgentFlow (ctx context.Context , client metadataClient , workspace , agentType , agentVersion string ) error {
78- fmt . Println ( "::debug:: Running agent repository flow" )
149+ logging . Debug ( ctx , " Running agent repository flow" )
79150
80151 // Check for .fleetControl directory
81152 fleetControlPath := filepath .Join (workspace , config .GetRootFolderForAgentRepo ())
@@ -88,15 +159,15 @@ func runAgentFlow(ctx context.Context, client metadataClient, workspace, agentTy
88159 if err != nil {
89160 return fmt .Errorf ("failed to read configuration definitions: %w" , err )
90161 }
91- fmt . Printf ( "::notice:: Loaded %d configuration definitions\n " , len (configs ))
162+ logging . Noticef ( ctx , " Loaded %d configuration definitions" , len (configs ))
92163
93164 // Load agent control definitions (optional)
94165 agentControl , err := loader .ReadAgentControlDefinitions (workspace )
95166 if err != nil {
96- fmt . Printf ( "::warn:: Unable to load agent control definitions: %v - continuing without them\n " , err )
167+ logging . Warnf ( ctx , " Unable to load agent control definitions: %v - continuing without them" , err )
97168 agentControl = nil
98169 } else {
99- fmt . Printf ( "::notice:: Loaded %d agent control definitions\n " , len (agentControl ))
170+ logging . Noticef ( ctx , " Loaded %d agent control definitions" , len (agentControl ))
100171 }
101172
102173 // Build metadata
@@ -113,13 +184,13 @@ func runAgentFlow(ctx context.Context, client metadataClient, workspace, agentTy
113184 return fmt .Errorf ("failed to send metadata for %s: %w" , agentType , err )
114185 }
115186
116- fmt . Printf ( "::notice:: Successfully sent metadata for %s version %s\n " , agentType , agentVersion )
187+ logging . Noticef ( ctx , " Successfully sent metadata for %s version %s" , agentType , agentVersion )
117188 return nil
118189}
119190
120191// runDocsFlow handles the documentation repository workflow
121192func runDocsFlow (ctx context.Context , client metadataClient ) error {
122- fmt . Println ( "::debug:: Running documentation flow" )
193+ logging . Debug ( ctx , " Running documentation flow" )
123194
124195 // Load metadata from changed MDX files
125196 metadataList , err := loader .LoadMetadataForDocs ()
@@ -128,23 +199,23 @@ func runDocsFlow(ctx context.Context, client metadataClient) error {
128199 }
129200
130201 if len (metadataList ) == 0 {
131- fmt . Println ( "::notice:: No metadata changes detected" )
202+ logging . Notice ( ctx , " No metadata changes detected" )
132203 return nil
133204 }
134205
135- fmt . Printf ( "::notice:: Processing %d metadata entries\n " , len (metadataList ))
206+ logging . Noticef ( ctx , " Processing %d metadata entries" , len (metadataList ))
136207
137208 // Send each metadata entry separately
138209 successCount := 0
139210 for _ , entry := range metadataList {
140211 if err := sendDocsMetadata (ctx , client , entry ); err != nil {
141- fmt . Printf ( "::warn:: Failed to send metadata for %s: %v\n " , entry .AgentType , err )
212+ logging . Warnf ( ctx , " Failed to send metadata for %s: %v" , entry .AgentType , err )
142213 continue
143214 }
144215 successCount ++
145216 }
146217
147- fmt . Printf ( "::notice:: Successfully sent %d of %d metadata entries\n " , successCount , len (metadataList ))
218+ logging . Noticef ( ctx , " Successfully sent %d of %d metadata entries" , successCount , len (metadataList ))
148219 return nil
149220}
150221
@@ -162,7 +233,7 @@ func sendDocsMetadata(ctx context.Context, client metadataClient, entry loader.M
162233 return err
163234 }
164235
165- fmt . Printf ( "::notice:: Sent metadata for %s version %s\n " , entry .AgentType , version )
236+ logging . Noticef ( ctx , " Sent metadata for %s version %s" , entry .AgentType , version )
166237 return nil
167238}
168239
0 commit comments