-
Notifications
You must be signed in to change notification settings - Fork 66
/
ops_agent_test.go
2529 lines (2290 loc) · 106 KB
/
ops_agent_test.go
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
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//go:build integration_test
/*
Test for core functionality of the Ops Agent.
Can be run with Kokoro or "go test". For instructions, see the top of
gce_testing.go.
This test needs the following environment variables to be defined, in addition
to the ones mentioned at the top of gce_testing.go:
PLATFORMS: a comma-separated list of distros to test, e.g. "centos-7,centos-8".
The following variables are optional:
REPO_SUFFIX: If provided, what package repo suffix to install the ops agent from.
AGENT_PACKAGES_IN_GCS: If provided, a URL for a directory in GCS containing
.deb/.rpm/.goo files to install on the testing VMs.
REPO_SUFFIX_PREVIOUS: Used only by TestUpgradeOpsAgent, this specifies which
version of the Ops Agent to install first, before installing the version
from REPO_SUFFIX/AGENT_PACKAGES_IN_GCS. The default of "" means stable.
*/
package integration_test
import (
"context"
"encoding/json"
"fmt"
"log"
"os"
"path"
"regexp"
"strings"
"sync"
"testing"
"time"
"github.com/GoogleCloudPlatform/ops-agent/confgenerator"
"github.com/GoogleCloudPlatform/ops-agent/confgenerator/resourcedetector"
"github.com/GoogleCloudPlatform/ops-agent/integration_test/agents"
"github.com/GoogleCloudPlatform/ops-agent/integration_test/gce"
"github.com/GoogleCloudPlatform/ops-agent/integration_test/logging"
"github.com/GoogleCloudPlatform/ops-agent/integration_test/metadata"
"github.com/GoogleCloudPlatform/ops-agent/integration_test/util"
"google.golang.org/genproto/googleapis/api/metric"
"google.golang.org/genproto/googleapis/monitoring/v3"
"gopkg.in/yaml.v2"
cloudlogging "cloud.google.com/go/logging"
"github.com/google/uuid"
"go.uber.org/multierr"
"google.golang.org/protobuf/proto"
structpb "google.golang.org/protobuf/types/known/structpb"
)
func logPathForPlatform(platform string) string {
if gce.IsWindows(platform) {
return `C:\mylog`
}
return "/tmp/mylog"
}
func configPathForPlatform(platform string) string {
if gce.IsWindows(platform) {
return `C:\Program Files\Google\Cloud Operations\Ops Agent\config\config.yaml`
}
return "/etc/google-cloud-ops-agent/config.yaml"
}
func workDirForPlatform(platform string) string {
if gce.IsWindows(platform) {
return `C:\`
}
return "/tmp/"
}
func restartCommandForPlatform(platform string) string {
if gce.IsWindows(platform) {
return "Restart-Service google-cloud-ops-agent -Force"
}
// Return a command that works for both < 2.0.0 and >= 2.0.0 agents.
return "sudo service google-cloud-ops-agent restart || sudo systemctl restart google-cloud-ops-agent"
}
func systemLogTagForPlatform(platform string) string {
if gce.IsWindows(platform) {
return "windows_event_log"
}
return "syslog"
}
func logMessageQueryForPlatform(platform, message string) string {
if gce.IsWindows(platform) {
// On Windows, we have to look in the capital-M Message field. On linux
// it is lowercase-m message.
// Also, Fluent-Bit adds an extra newline to our payload, so we need to
// use ":" instead of "=" here.
return "jsonPayload.Message:" + message
}
return "jsonPayload.message=" + message
}
func metricsAgentProcessNamesForPlatform(platform string) []string {
if gce.IsWindows(platform) {
return []string{"google-cloud-metrics-agent_windows_amd64"}
}
return []string{"otelopscol", "collectd"}
}
func diagnosticsProcessNamesForPlatform(platform string) []string {
if gce.IsWindows(platform) {
return []string{"google-cloud-ops-agent-diagnostics"}
}
return []string{"google_cloud_ops_agent_diagnostics"}
}
func writeToWindowsEventLog(ctx context.Context, logger *log.Logger, vm *gce.VM, logName, payload string) error {
// If this is the first time we're trying to write to logName, we need to
// register a fake log source with New-EventLog.
// There's a problem: there's no way (that I can find) to check whether a
// particular log source is registered to write to logName: the closest I
// can get is checking whether a log source is registered to write
// *somewhere*. So the workaround is to make the log source's name unique
// per logName.
source := logName + "__ops_agent_test"
if _, err := gce.RunRemotely(ctx, logger, vm, "", fmt.Sprintf("if(![System.Diagnostics.EventLog]::SourceExists('%s')) { New-EventLog -LogName '%s' -Source '%s' }", source, logName, source)); err != nil {
return fmt.Errorf("writeToWindowsEventLog(logName=%q, payload=%q) failed to register new source %v: %v", logName, payload, source, err)
}
// Use a Powershell here-string to avoid most quoting issues.
if _, err := gce.RunRemotely(ctx, logger, vm, "", fmt.Sprintf("Write-EventLog -LogName '%s' -EventId 1 -Source '%s' -Message @'\n%s\n'@", logName, source, payload)); err != nil {
return fmt.Errorf("writeToWindowsEventLog(logName=%q, payload=%q) failed: %v", logName, payload, err)
}
return nil
}
// writeToSystemLog writes the given payload to the VM's normal log location.
// On Linux this is /var/log/syslog or /var/log/messages, depending on the
// distro.
// On Windows this is the "System" log within the event logging system.
func writeToSystemLog(ctx context.Context, logger *log.Logger, vm *gce.VM, payload string) error {
if gce.IsWindows(vm.Platform) {
return writeToWindowsEventLog(ctx, logger, vm, "System", payload)
}
line := payload + "\n"
location := gce.SyslogLocation(vm.Platform)
// Pass the content in on stdin and run "cat -" to tell cat to copy from stdin.
// This is to avoid having to quote the content correctly for the shell.
// "tee -a" will append to the file.
if _, err := gce.RunRemotely(ctx, logger, vm, line, fmt.Sprintf("cat - | sudo tee -a '%s' > /dev/null", location)); err != nil {
return fmt.Errorf("writeToSystemLog() failed to write %q to %s: %v", line, location, err)
}
return nil
}
type packageLocation struct {
// See description of AGENT_PACKAGES_IN_GCS at the top of this file.
// This setting takes precedence over repoSuffix.
packagesInGCS string
// Package repository suffix to install from. Setting this to ""
// means to install the latest stable release.
repoSuffix string
}
func locationFromEnvVars() packageLocation {
return packageLocation{
packagesInGCS: os.Getenv("AGENT_PACKAGES_IN_GCS"),
repoSuffix: os.Getenv("REPO_SUFFIX"),
}
}
// installOpsAgent installs the Ops Agent on the given VM. Preferentially
// chooses to install from location.packagesInGCS if that is set, otherwise
// falls back to location.repoSuffix.
func installOpsAgent(ctx context.Context, logger *logging.DirectoryLogger, vm *gce.VM, location packageLocation) error {
if location.packagesInGCS != "" {
return agents.InstallPackageFromGCS(ctx, logger, vm, location.packagesInGCS)
}
if gce.IsWindows(vm.Platform) {
suffix := location.repoSuffix
if suffix == "" {
suffix = "all"
}
runGoogetInstall := func() error {
_, err := gce.RunRemotely(ctx, logger.ToMainLog(), vm, "", fmt.Sprintf("googet -noconfirm install -sources https://packages.cloud.google.com/yuck/repos/google-cloud-ops-agent-windows-%s google-cloud-ops-agent", suffix))
return err
}
if err := agents.RunInstallFuncWithRetry(ctx, logger.ToMainLog(), vm, runGoogetInstall); err != nil {
return fmt.Errorf("installOpsAgent() failed to run googet: %v", err)
}
return nil
}
if _, err := gce.RunRemotely(ctx,
logger.ToMainLog(), vm, "", "curl -sSO https://dl.google.com/cloudagents/add-google-cloud-ops-agent-repo.sh"); err != nil {
return fmt.Errorf("installOpsAgent() failed to download repo script: %v", err)
}
runInstallScript := func() error {
_, err := gce.RunRemotely(ctx, logger.ToMainLog(), vm, "", "sudo REPO_SUFFIX="+location.repoSuffix+" bash -x add-google-cloud-ops-agent-repo.sh --also-install")
return err
}
if err := agents.RunInstallFuncWithRetry(ctx, logger.ToMainLog(), vm, runInstallScript); err != nil {
return fmt.Errorf("installOpsAgent() error running repo script: %v", err)
}
return nil
}
// setupOpsAgent installs the Ops Agent and installs the given config.
func setupOpsAgent(ctx context.Context, logger *logging.DirectoryLogger, vm *gce.VM, config string) error {
return setupOpsAgentFrom(ctx, logger, vm, config, locationFromEnvVars())
}
// restartOpsAgent restarts the Ops Agent and waits for it to become available.
func restartOpsAgent(ctx context.Context, logger *logging.DirectoryLogger, vm *gce.VM) error {
if _, err := gce.RunRemotely(ctx, logger.ToMainLog(), vm, "", restartCommandForPlatform(vm.Platform)); err != nil {
return fmt.Errorf("restartOpsAgent() failed to restart ops agent: %v", err)
}
// Give agents time to shut down. Fluent-Bit's default shutdown grace period
// is 5 seconds, so we should probably give it at least that long.
time.Sleep(10 * time.Second)
return nil
}
// setupOpsAgentFrom is an overload of setupOpsAgent that allows the callsite to
// decide which version of the agent gets installed.
func setupOpsAgentFrom(ctx context.Context, logger *logging.DirectoryLogger, vm *gce.VM, config string, location packageLocation) error {
if err := installOpsAgent(ctx, logger, vm, location); err != nil {
return err
}
startupDelay := 20 * time.Second
if len(config) > 0 {
if gce.IsWindows(vm.Platform) {
// Sleep to avoid some flaky errors when restarting the agent because the
// services have not fully started up yet.
time.Sleep(startupDelay)
}
if err := gce.UploadContent(ctx, logger, vm, strings.NewReader(config), util.ConfigPathForPlatform(vm.Platform)); err != nil {
return fmt.Errorf("setupOpsAgentFrom() failed to upload config file: %v", err)
}
if err := restartOpsAgent(ctx, logger, vm); err != nil {
return err
}
}
// Give agents time to start up.
time.Sleep(startupDelay)
return nil
}
func TestParseMultilineFileJava(t *testing.T) {
t.Parallel()
gce.RunForEachPlatform(t, func(t *testing.T, platform string) {
t.Parallel()
if gce.IsWindows(platform) {
t.SkipNow()
}
ctx, logger, vm := agents.CommonSetup(t, platform)
logPath := logPathForPlatform(vm.Platform)
config := fmt.Sprintf(`logging:
receivers:
files_1:
type: files
include_paths: [%s]
wildcard_refresh_interval: 30s
processors:
multiline_parser_1:
type: parse_multiline
match_any:
- type: language_exceptions
language: java
service:
pipelines:
p1:
receivers: [files_1]
processors: [multiline_parser_1]`, logPath)
//Below lines comes from 3 java exception stacktraces, thus expect 3 logEntries.
if err := gce.UploadContent(ctx, logger, vm, strings.NewReader(`Jul 09, 2015 3:23:29 PM com.google.devtools.search.cloud.feeder.MakeLog: RuntimeException: Run from this message!
at com.my.app.Object.do$a1(MakeLog.java:50)
at java.lang.Thing.call(Thing.java:10)
javax.servlet.ServletException: Something bad happened
at com.example.myproject.OpenSessionInViewFilter.doFilter(OpenSessionInViewFilter.java:60)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.example.myproject.ExceptionHandlerFilter.doFilter(ExceptionHandlerFilter.java:28)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.example.myproject.OutputBufferFilter.doFilter(OutputBufferFilter.java:33)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:388)
at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182)
at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:765)
at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:418)
at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
at org.mortbay.jetty.Server.handle(Server.java:326)
at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542)
at org.mortbay.jetty.HttpConnection$RequestHandler.content(HttpConnection.java:943)
at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:756)
at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:218)
at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404)
at org.mortbay.jetty.bio.SocketConnector$Connection.run(SocketConnector.java:228)
at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:582)
Caused by: com.example.myproject.MyProjectServletException
at com.example.myproject.MyServlet.doPost(MyServlet.java:169)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1166)
at com.example.myproject.OpenSessionInViewFilter.doFilter(OpenSessionInViewFilter.java:30)
... 27 common frames omitted
java.lang.RuntimeException: javax.mail.SendFailedException: Invalid Addresses;
nested exception is:
com.sun.mail.smtp.SMTPAddressFailedException: 550 5.7.1 <[REDACTED_EMAIL_ADDRESS]>... Relaying denied
at com.nethunt.crm.api.server.adminsync.AutomaticEmailFacade.sendWithSmtp(AutomaticEmailFacade.java:236)
at com.nethunt.crm.api.server.adminsync.AutomaticEmailFacade.sendSingleEmail(AutomaticEmailFacade.java:285)
at com.nethunt.crm.api.server.adminsync.AutomaticEmailFacade.lambda$sendSingleEmail$3(AutomaticEmailFacade.java:254)
at java.util.Optional.ifPresent(Optional.java:159)
at com.nethunt.crm.api.server.adminsync.AutomaticEmailFacade.sendSingleEmail(AutomaticEmailFacade.java:253)
at com.nethunt.crm.api.server.adminsync.AutomaticEmailFacade.sendSingleEmail(AutomaticEmailFacade.java:249)
at com.nethunt.crm.api.email.EmailSender.lambda$notifyPerson$0(EmailSender.java:80)
at com.nethunt.crm.api.util.ManagedExecutor.lambda$execute$0(ManagedExecutor.java:36)
at com.nethunt.crm.api.util.RequestContextActivator.lambda$withRequestContext$0(RequestContextActivator.java:36)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.base/java.lang.Thread.run(Thread.java:748)
Caused by: javax.mail.SendFailedException: Invalid Addresses;
nested exception is:
com.sun.mail.smtp.SMTPAddressFailedException: 550 5.7.1 <[REDACTED_EMAIL_ADDRESS]>... Relaying denied
at com.sun.mail.smtp.SMTPTransport.rcptTo(SMTPTransport.java:2064)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1286)
at com.nethunt.crm.api.server.adminsync.AutomaticEmailFacade.sendWithSmtp(AutomaticEmailFacade.java:229)
... 12 more
Caused by: com.sun.mail.smtp.SMTPAddressFailedException: 550 5.7.1 <[REDACTED_EMAIL_ADDRESS]>... Relaying denied
`), logPath); err != nil {
t.Fatalf("error writing dummy log lines for Java: %v", err)
}
if err := setupOpsAgent(ctx, logger, vm, config); err != nil {
t.Fatal(err)
}
if err := gce.WaitForLog(ctx, logger.ToMainLog(), vm, "files_1", time.Hour, `jsonPayload.message="Jul 09, 2015 3:23:29 PM com.google.devtools.search.cloud.feeder.MakeLog: RuntimeException: Run from this message!\n at com.my.app.Object.do$a1(MakeLog.java:50)\n at java.lang.Thing.call(Thing.java:10)\n"`); err != nil {
t.Error(err)
}
if err := gce.WaitForLog(ctx, logger.ToMainLog(), vm, "files_1", time.Hour, `jsonPayload.message="javax.servlet.ServletException: Something bad happened\n at com.example.myproject.OpenSessionInViewFilter.doFilter(OpenSessionInViewFilter.java:60)\n at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)\n at com.example.myproject.ExceptionHandlerFilter.doFilter(ExceptionHandlerFilter.java:28)\n at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)\n at com.example.myproject.OutputBufferFilter.doFilter(OutputBufferFilter.java:33)\n at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)\n at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:388)\n at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)\n at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182)\n at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:765)\n at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:418)\n at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)\n at org.mortbay.jetty.Server.handle(Server.java:326)\n at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542)\n at org.mortbay.jetty.HttpConnection$RequestHandler.content(HttpConnection.java:943)\n at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:756)\n at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:218)\n at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404)\n at org.mortbay.jetty.bio.SocketConnector$Connection.run(SocketConnector.java:228)\n at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:582)\nCaused by: com.example.myproject.MyProjectServletException\n at com.example.myproject.MyServlet.doPost(MyServlet.java:169)\n at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)\n at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)\n at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511)\n at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1166)\n at com.example.myproject.OpenSessionInViewFilter.doFilter(OpenSessionInViewFilter.java:30)\n ... 27 common frames omitted\n"`); err != nil {
t.Error(err)
}
})
}
func TestParseMultilineFileJavaPython(t *testing.T) {
t.Parallel()
gce.RunForEachPlatform(t, func(t *testing.T, platform string) {
t.Parallel()
if gce.IsWindows(platform) {
t.SkipNow()
}
ctx, logger, vm := agents.CommonSetup(t, platform)
logPath := logPathForPlatform(vm.Platform)
config := fmt.Sprintf(`logging:
receivers:
files_1:
type: files
include_paths: [%s]
wildcard_refresh_interval: 30s
processors:
multiline_parser_1:
type: parse_multiline
match_any:
- type: language_exceptions
language: java
- type: language_exceptions
language: python
service:
pipelines:
p1:
receivers: [files_1]
processors: [multiline_parser_1]`, logPath)
//Below lines comes from 3 java and 3 python exception stacktraces, thus expect 6 logEntries.
if err := gce.UploadContent(ctx, logger, vm, strings.NewReader(`Jul 09, 2015 3:23:29 PM com.google.devtools.search.cloud.feeder.MakeLog: RuntimeException: Run from this message!
at com.my.app.Object.do$a1(MakeLog.java:50)
at java.lang.Thing.call(Thing.java:10)
Traceback (most recent call last):
File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 1535, in __call__
rv = self.handle_exception(request, response, e)
File "/base/data/home/apps/s~nearfieldspy/1.378705245900539993/nearfieldspy.py", line 17, in start
return get()
File "/base/data/home/apps/s~nearfieldspy/1.378705245900539993/nearfieldspy.py", line 5, in get
raise Exception('spam', 'eggs')
Exception: ('spam', 'eggs')
javax.servlet.ServletException: Something bad happened
at com.example.myproject.OpenSessionInViewFilter.doFilter(OpenSessionInViewFilter.java:60)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.example.myproject.ExceptionHandlerFilter.doFilter(ExceptionHandlerFilter.java:28)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.example.myproject.OutputBufferFilter.doFilter(OutputBufferFilter.java:33)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:388)
at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182)
at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:765)
at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:418)
at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
at org.mortbay.jetty.Server.handle(Server.java:326)
at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542)
at org.mortbay.jetty.HttpConnection$RequestHandler.content(HttpConnection.java:943)
at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:756)
at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:218)
at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404)
at org.mortbay.jetty.bio.SocketConnector$Connection.run(SocketConnector.java:228)
at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:582)
Caused by: com.example.myproject.MyProjectServletException
at com.example.myproject.MyServlet.doPost(MyServlet.java:169)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1166)
at com.example.myproject.OpenSessionInViewFilter.doFilter(OpenSessionInViewFilter.java:30)
... 27 common frames omitted
java.lang.RuntimeException: javax.mail.SendFailedException: Invalid Addresses;
nested exception is:
com.sun.mail.smtp.SMTPAddressFailedException: 550 5.7.1 <[REDACTED_EMAIL_ADDRESS]>... Relaying denied
at com.nethunt.crm.api.server.adminsync.AutomaticEmailFacade.sendWithSmtp(AutomaticEmailFacade.java:236)
at com.nethunt.crm.api.server.adminsync.AutomaticEmailFacade.sendSingleEmail(AutomaticEmailFacade.java:285)
at com.nethunt.crm.api.server.adminsync.AutomaticEmailFacade.lambda$sendSingleEmail$3(AutomaticEmailFacade.java:254)
at java.util.Optional.ifPresent(Optional.java:159)
at com.nethunt.crm.api.server.adminsync.AutomaticEmailFacade.sendSingleEmail(AutomaticEmailFacade.java:253)
at com.nethunt.crm.api.server.adminsync.AutomaticEmailFacade.sendSingleEmail(AutomaticEmailFacade.java:249)
at com.nethunt.crm.api.email.EmailSender.lambda$notifyPerson$0(EmailSender.java:80)
at com.nethunt.crm.api.util.ManagedExecutor.lambda$execute$0(ManagedExecutor.java:36)
at com.nethunt.crm.api.util.RequestContextActivator.lambda$withRequestContext$0(RequestContextActivator.java:36)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.base/java.lang.Thread.run(Thread.java:748)
Caused by: javax.mail.SendFailedException: Invalid Addresses;
nested exception is:
com.sun.mail.smtp.SMTPAddressFailedException: 550 5.7.1 <[REDACTED_EMAIL_ADDRESS]>... Relaying denied
at com.sun.mail.smtp.SMTPTransport.rcptTo(SMTPTransport.java:2064)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1286)
at com.nethunt.crm.api.server.adminsync.AutomaticEmailFacade.sendWithSmtp(AutomaticEmailFacade.java:229)
... 12 more
Caused by: com.sun.mail.smtp.SMTPAddressFailedException: 550 5.7.1 <[REDACTED_EMAIL_ADDRESS]>... Relaying denied
Traceback (most recent call last):
File "/test/exception.py", line 21, in <module>
conn.request("GET", "/")
File "/usr/lib/python3.10/http/client.py", line 1282, in request
self._send_request(method, url, body, headers, encode_chunked)
File "/usr/lib/python3.10/http/client.py", line 1328, in _send_request
self.endheaders(body, encode_chunked=encode_chunked)
File "/usr/lib/python3.10/http/client.py", line 1277, in endheaders
self._send_output(message_body, encode_chunked=encode_chunked)
File "/usr/lib/python3.10/http/client.py", line 1037, in _send_output
self.send(msg)
File "/usr/lib/python3.10/http/client.py", line 975, in send
self.connect()
File "/usr/lib/python3.10/http/client.py", line 941, in connect
self.sock = self._create_connection(
File "/usr/lib/python3.10/socket.py", line 824, in create_connection
for res in getaddrinfo(host, port, 0, SOCK_STREAM):
File "/usr/lib/python3.10/socket.py", line 955, in getaddrinfo
for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno -2] Name or service not known
Traceback (most recent call last):
File "/usr/local/google/home/lujieduan/source/test/exception.py", line 11, in <module>
'2' + 2
TypeError: can only concatenate str (not "int") to str
`), logPath); err != nil {
t.Fatalf("error writing dummy log lines for Java + Python: %v", err)
}
if err := setupOpsAgent(ctx, logger, vm, config); err != nil {
t.Fatal(err)
}
// 1st one is Java
if err := gce.WaitForLog(ctx, logger.ToMainLog(), vm, "files_1", time.Hour, `jsonPayload.message="Jul 09, 2015 3:23:29 PM com.google.devtools.search.cloud.feeder.MakeLog: RuntimeException: Run from this message!\n at com.my.app.Object.do$a1(MakeLog.java:50)\n at java.lang.Thing.call(Thing.java:10)\n"`); err != nil {
t.Error(err)
}
// 2nd Python
if err := gce.WaitForLog(ctx, logger.ToMainLog(), vm, "files_1", time.Hour, `jsonPayload.message="Traceback (most recent call last):\n File \"/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py\", line 1535, in __call__\n rv = self.handle_exception(request, response, e)\n File \"/base/data/home/apps/s~nearfieldspy/1.378705245900539993/nearfieldspy.py\", line 17, in start\n return get()\n File \"/base/data/home/apps/s~nearfieldspy/1.378705245900539993/nearfieldspy.py\", line 5, in get\n raise Exception('spam', 'eggs')\nException: ('spam', 'eggs')\n"`); err != nil {
t.Error(err)
}
// 3rd Java
if err := gce.WaitForLog(ctx, logger.ToMainLog(), vm, "files_1", time.Hour, `jsonPayload.message="javax.servlet.ServletException: Something bad happened\n at com.example.myproject.OpenSessionInViewFilter.doFilter(OpenSessionInViewFilter.java:60)\n at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)\n at com.example.myproject.ExceptionHandlerFilter.doFilter(ExceptionHandlerFilter.java:28)\n at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)\n at com.example.myproject.OutputBufferFilter.doFilter(OutputBufferFilter.java:33)\n at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)\n at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:388)\n at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)\n at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182)\n at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:765)\n at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:418)\n at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)\n at org.mortbay.jetty.Server.handle(Server.java:326)\n at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542)\n at org.mortbay.jetty.HttpConnection$RequestHandler.content(HttpConnection.java:943)\n at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:756)\n at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:218)\n at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404)\n at org.mortbay.jetty.bio.SocketConnector$Connection.run(SocketConnector.java:228)\n at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:582)\nCaused by: com.example.myproject.MyProjectServletException\n at com.example.myproject.MyServlet.doPost(MyServlet.java:169)\n at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)\n at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)\n at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511)\n at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1166)\n at com.example.myproject.OpenSessionInViewFilter.doFilter(OpenSessionInViewFilter.java:30)\n ... 27 common frames omitted\n"`); err != nil {
t.Error(err)
}
// 4th Java
if err := gce.WaitForLog(ctx, logger.ToMainLog(), vm, "files_1", time.Hour, `jsonPayload.message="java.lang.RuntimeException: javax.mail.SendFailedException: Invalid Addresses;\n nested exception is:\ncom.sun.mail.smtp.SMTPAddressFailedException: 550 5.7.1 <[REDACTED_EMAIL_ADDRESS]>... Relaying denied\n at com.nethunt.crm.api.server.adminsync.AutomaticEmailFacade.sendWithSmtp(AutomaticEmailFacade.java:236)\n at com.nethunt.crm.api.server.adminsync.AutomaticEmailFacade.sendSingleEmail(AutomaticEmailFacade.java:285)\n at com.nethunt.crm.api.server.adminsync.AutomaticEmailFacade.lambda$sendSingleEmail$3(AutomaticEmailFacade.java:254)\n at java.util.Optional.ifPresent(Optional.java:159)\n at com.nethunt.crm.api.server.adminsync.AutomaticEmailFacade.sendSingleEmail(AutomaticEmailFacade.java:253)\n at com.nethunt.crm.api.server.adminsync.AutomaticEmailFacade.sendSingleEmail(AutomaticEmailFacade.java:249)\n at com.nethunt.crm.api.email.EmailSender.lambda$notifyPerson$0(EmailSender.java:80)\n at com.nethunt.crm.api.util.ManagedExecutor.lambda$execute$0(ManagedExecutor.java:36)\n at com.nethunt.crm.api.util.RequestContextActivator.lambda$withRequestContext$0(RequestContextActivator.java:36)\n at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)\n at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)\n at java.base/java.lang.Thread.run(Thread.java:748)\nCaused by: javax.mail.SendFailedException: Invalid Addresses;\n nested exception is:\ncom.sun.mail.smtp.SMTPAddressFailedException: 550 5.7.1 <[REDACTED_EMAIL_ADDRESS]>... Relaying denied\n at com.sun.mail.smtp.SMTPTransport.rcptTo(SMTPTransport.java:2064)\n at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1286)\n at com.nethunt.crm.api.server.adminsync.AutomaticEmailFacade.sendWithSmtp(AutomaticEmailFacade.java:229)\n ... 12 more\nCaused by: com.sun.mail.smtp.SMTPAddressFailedException: 550 5.7.1 <[REDACTED_EMAIL_ADDRESS]>... Relaying denied\n"`); err != nil {
t.Error(err)
}
// 5th Python
if err := gce.WaitForLog(ctx, logger.ToMainLog(), vm, "files_1", time.Hour, `jsonPayload.message="Traceback (most recent call last):\n File \"/test/exception.py\", line 21, in <module>\n conn.request(\"GET\", \"/\")\n File \"/usr/lib/python3.10/http/client.py\", line 1282, in request\n self._send_request(method, url, body, headers, encode_chunked)\n File \"/usr/lib/python3.10/http/client.py\", line 1328, in _send_request\n self.endheaders(body, encode_chunked=encode_chunked)\n File \"/usr/lib/python3.10/http/client.py\", line 1277, in endheaders\n self._send_output(message_body, encode_chunked=encode_chunked)\n File \"/usr/lib/python3.10/http/client.py\", line 1037, in _send_output\n self.send(msg)\n File \"/usr/lib/python3.10/http/client.py\", line 975, in send\n self.connect()\n File \"/usr/lib/python3.10/http/client.py\", line 941, in connect\n self.sock = self._create_connection(\n File \"/usr/lib/python3.10/socket.py\", line 824, in create_connection\n for res in getaddrinfo(host, port, 0, SOCK_STREAM):\n File \"/usr/lib/python3.10/socket.py\", line 955, in getaddrinfo\n for res in _socket.getaddrinfo(host, port, family, type, proto, flags):\nsocket.gaierror: [Errno -2] Name or service not known\n"`); err != nil {
t.Error(err)
}
// 6th Python
if err := gce.WaitForLog(ctx, logger.ToMainLog(), vm, "files_1", time.Hour, `jsonPayload.message="Traceback (most recent call last):\n File \"/usr/local/google/home/lujieduan/source/test/exception.py\", line 11, in <module>\n '2' + 2\nTypeError: can only concatenate str (not \"int\") to str\n"`); err != nil {
t.Error(err)
}
})
}
func TestParseMultilineFileGolangJavaPython(t *testing.T) {
t.Parallel()
gce.RunForEachPlatform(t, func(t *testing.T, platform string) {
t.Parallel()
if gce.IsWindows(platform) {
t.SkipNow()
}
ctx, logger, vm := agents.CommonSetup(t, platform)
logPath := logPathForPlatform(vm.Platform)
config := fmt.Sprintf(`logging:
receivers:
files_1:
type: files
include_paths: [%s]
wildcard_refresh_interval: 30s
processors:
multiline_parser_1:
type: parse_multiline
match_any:
- type: language_exceptions
language: go
- type: language_exceptions
language: java
- type: language_exceptions
language: python
service:
pipelines:
p1:
receivers: [files_1]
processors: [multiline_parser_1]`, logPath)
//Below lines comes from Go, Python and Java exception stacktraces.
if err := gce.UploadContent(ctx, logger, vm, strings.NewReader(`2019/01/15 07:48:05 http: panic serving [::1]:54143: test panic
goroutine 24 [running]:
net/http.(*conn).serve.func1(0xc00007eaa0)
/usr/local/go/src/net/http/server.go:1746 +0xd0
panic(0x12472a0, 0x12ece10)
/usr/local/go/src/runtime/panic.go:513 +0x1b9
main.doPanic(0x12f0ea0, 0xc00010e1c0, 0xc000104400)
/Users/ingvar/src/go/src/httppanic.go:8 +0x39
net/http.HandlerFunc.ServeHTTP(0x12be2e8, 0x12f0ea0, 0xc00010e1c0, 0xc000104400)
/usr/local/go/src/net/http/server.go:1964 +0x44
net/http.(*ServeMux).ServeHTTP(0x14a17a0, 0x12f0ea0, 0xc00010e1c0, 0xc000104400)
/usr/local/go/src/net/http/server.go:2361 +0x127
net/http.serverHandler.ServeHTTP(0xc000085040, 0x12f0ea0, 0xc00010e1c0, 0xc000104400)
/usr/local/go/src/net/http/server.go:2741 +0xab
net/http.(*conn).serve(0xc00007eaa0, 0x12f10a0, 0xc00008a780)
/usr/local/go/src/net/http/server.go:1847 +0x646
created by net/http.(*Server).Serve
/usr/local/go/src/net/http/server.go:2851 +0x2f5
Traceback (most recent call last):
File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 1535, in __call__
rv = self.handle_exception(request, response, e)
File "/base/data/home/apps/s~nearfieldspy/1.378705245900539993/nearfieldspy.py", line 17, in start
return get()
File "/base/data/home/apps/s~nearfieldspy/1.378705245900539993/nearfieldspy.py", line 5, in get
raise Exception('spam', 'eggs')
Exception: ('spam', 'eggs')
java.lang.RuntimeException: javax.mail.SendFailedException: Invalid Addresses;
nested exception is:
com.sun.mail.smtp.SMTPAddressFailedException: 550 5.7.1 <[REDACTED_EMAIL_ADDRESS]>... Relaying denied
at com.nethunt.crm.api.server.adminsync.AutomaticEmailFacade.sendWithSmtp(AutomaticEmailFacade.java:236)
at com.nethunt.crm.api.server.adminsync.AutomaticEmailFacade.sendSingleEmail(AutomaticEmailFacade.java:285)
at com.nethunt.crm.api.server.adminsync.AutomaticEmailFacade.lambda$sendSingleEmail$3(AutomaticEmailFacade.java:254)
at java.util.Optional.ifPresent(Optional.java:159)
at com.nethunt.crm.api.server.adminsync.AutomaticEmailFacade.sendSingleEmail(AutomaticEmailFacade.java:253)
at com.nethunt.crm.api.server.adminsync.AutomaticEmailFacade.sendSingleEmail(AutomaticEmailFacade.java:249)
at com.nethunt.crm.api.email.EmailSender.lambda$notifyPerson$0(EmailSender.java:80)
at com.nethunt.crm.api.util.ManagedExecutor.lambda$execute$0(ManagedExecutor.java:36)
at com.nethunt.crm.api.util.RequestContextActivator.lambda$withRequestContext$0(RequestContextActivator.java:36)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.base/java.lang.Thread.run(Thread.java:748)
Caused by: javax.mail.SendFailedException: Invalid Addresses;
nested exception is:
com.sun.mail.smtp.SMTPAddressFailedException: 550 5.7.1 <[REDACTED_EMAIL_ADDRESS]>... Relaying denied
at com.sun.mail.smtp.SMTPTransport.rcptTo(SMTPTransport.java:2064)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1286)
at com.nethunt.crm.api.server.adminsync.AutomaticEmailFacade.sendWithSmtp(AutomaticEmailFacade.java:229)
... 12 more
Caused by: com.sun.mail.smtp.SMTPAddressFailedException: 550 5.7.1 <[REDACTED_EMAIL_ADDRESS]>... Relaying denied
`), logPath); err != nil {
t.Fatalf("error writing dummy log lines for Go + Java + Python: %v", err)
}
if err := setupOpsAgent(ctx, logger, vm, config); err != nil {
t.Fatal(err)
}
// 1st one is Golang
if err := gce.WaitForLog(ctx, logger.ToMainLog(), vm, "files_1", time.Hour, `jsonPayload.message="2019/01/15 07:48:05 http: panic serving [::1]:54143: test panic\ngoroutine 24 [running]:\nnet/http.(*conn).serve.func1(0xc00007eaa0)\n /usr/local/go/src/net/http/server.go:1746 +0xd0\npanic(0x12472a0, 0x12ece10)\n /usr/local/go/src/runtime/panic.go:513 +0x1b9\nmain.doPanic(0x12f0ea0, 0xc00010e1c0, 0xc000104400)\n /Users/ingvar/src/go/src/httppanic.go:8 +0x39\nnet/http.HandlerFunc.ServeHTTP(0x12be2e8, 0x12f0ea0, 0xc00010e1c0, 0xc000104400)\n /usr/local/go/src/net/http/server.go:1964 +0x44\nnet/http.(*ServeMux).ServeHTTP(0x14a17a0, 0x12f0ea0, 0xc00010e1c0, 0xc000104400)\n /usr/local/go/src/net/http/server.go:2361 +0x127\nnet/http.serverHandler.ServeHTTP(0xc000085040, 0x12f0ea0, 0xc00010e1c0, 0xc000104400)\n /usr/local/go/src/net/http/server.go:2741 +0xab\nnet/http.(*conn).serve(0xc00007eaa0, 0x12f10a0, 0xc00008a780)\n /usr/local/go/src/net/http/server.go:1847 +0x646\ncreated by net/http.(*Server).Serve\n /usr/local/go/src/net/http/server.go:2851 +0x2f5\n"`); err != nil {
t.Error(err)
}
// 2nd Python
if err := gce.WaitForLog(ctx, logger.ToMainLog(), vm, "files_1", time.Hour, `jsonPayload.message="Traceback (most recent call last):\n File \"/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py\", line 1535, in __call__\n rv = self.handle_exception(request, response, e)\n File \"/base/data/home/apps/s~nearfieldspy/1.378705245900539993/nearfieldspy.py\", line 17, in start\n return get()\n File \"/base/data/home/apps/s~nearfieldspy/1.378705245900539993/nearfieldspy.py\", line 5, in get\n raise Exception('spam', 'eggs')\nException: ('spam', 'eggs')\n"`); err != nil {
t.Error(err)
}
// 3rd Java
if err := gce.WaitForLog(ctx, logger.ToMainLog(), vm, "files_1", time.Hour, `jsonPayload.message="java.lang.RuntimeException: javax.mail.SendFailedException: Invalid Addresses;\n nested exception is:\ncom.sun.mail.smtp.SMTPAddressFailedException: 550 5.7.1 <[REDACTED_EMAIL_ADDRESS]>... Relaying denied\n at com.nethunt.crm.api.server.adminsync.AutomaticEmailFacade.sendWithSmtp(AutomaticEmailFacade.java:236)\n at com.nethunt.crm.api.server.adminsync.AutomaticEmailFacade.sendSingleEmail(AutomaticEmailFacade.java:285)\n at com.nethunt.crm.api.server.adminsync.AutomaticEmailFacade.lambda$sendSingleEmail$3(AutomaticEmailFacade.java:254)\n at java.util.Optional.ifPresent(Optional.java:159)\n at com.nethunt.crm.api.server.adminsync.AutomaticEmailFacade.sendSingleEmail(AutomaticEmailFacade.java:253)\n at com.nethunt.crm.api.server.adminsync.AutomaticEmailFacade.sendSingleEmail(AutomaticEmailFacade.java:249)\n at com.nethunt.crm.api.email.EmailSender.lambda$notifyPerson$0(EmailSender.java:80)\n at com.nethunt.crm.api.util.ManagedExecutor.lambda$execute$0(ManagedExecutor.java:36)\n at com.nethunt.crm.api.util.RequestContextActivator.lambda$withRequestContext$0(RequestContextActivator.java:36)\n at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)\n at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)\n at java.base/java.lang.Thread.run(Thread.java:748)\nCaused by: javax.mail.SendFailedException: Invalid Addresses;\n nested exception is:\ncom.sun.mail.smtp.SMTPAddressFailedException: 550 5.7.1 <[REDACTED_EMAIL_ADDRESS]>... Relaying denied\n at com.sun.mail.smtp.SMTPTransport.rcptTo(SMTPTransport.java:2064)\n at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1286)\n at com.nethunt.crm.api.server.adminsync.AutomaticEmailFacade.sendWithSmtp(AutomaticEmailFacade.java:229)\n ... 12 more\nCaused by: com.sun.mail.smtp.SMTPAddressFailedException: 550 5.7.1 <[REDACTED_EMAIL_ADDRESS]>... Relaying denied\n"`); err != nil {
t.Error(err)
}
})
}
func TestParseMultilineFileMissingParser(t *testing.T) {
t.Parallel()
gce.RunForEachPlatform(t, func(t *testing.T, platform string) {
t.Parallel()
if gce.IsWindows(platform) {
t.SkipNow()
}
ctx, logger, vm := agents.CommonSetup(t, platform)
logPath := logPathForPlatform(vm.Platform)
// In the config file, only match for Golang exceptions
config := fmt.Sprintf(`logging:
receivers:
files_1:
type: files
include_paths: [%s]
wildcard_refresh_interval: 30s
processors:
multiline_parser_1:
type: parse_multiline
match_any:
- type: language_exceptions
language: go
service:
pipelines:
p1:
receivers: [files_1]
processors: [multiline_parser_1]`, logPath)
//Below lines comes from Go, Python and Java exception stacktraces.
if err := gce.UploadContent(ctx, logger, vm, strings.NewReader(`2019/01/15 07:48:05 http: panic serving [::1]:54143: test panic
goroutine 24 [running]:
net/http.(*conn).serve.func1(0xc00007eaa0)
/usr/local/go/src/net/http/server.go:1746 +0xd0
panic(0x12472a0, 0x12ece10)
/usr/local/go/src/runtime/panic.go:513 +0x1b9
main.doPanic(0x12f0ea0, 0xc00010e1c0, 0xc000104400)
/Users/ingvar/src/go/src/httppanic.go:8 +0x39
net/http.HandlerFunc.ServeHTTP(0x12be2e8, 0x12f0ea0, 0xc00010e1c0, 0xc000104400)
/usr/local/go/src/net/http/server.go:1964 +0x44
net/http.(*ServeMux).ServeHTTP(0x14a17a0, 0x12f0ea0, 0xc00010e1c0, 0xc000104400)
/usr/local/go/src/net/http/server.go:2361 +0x127
net/http.serverHandler.ServeHTTP(0xc000085040, 0x12f0ea0, 0xc00010e1c0, 0xc000104400)
/usr/local/go/src/net/http/server.go:2741 +0xab
net/http.(*conn).serve(0xc00007eaa0, 0x12f10a0, 0xc00008a780)
/usr/local/go/src/net/http/server.go:1847 +0x646
created by net/http.(*Server).Serve
/usr/local/go/src/net/http/server.go:2851 +0x2f5
Traceback (most recent call last):
File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 1535, in __call__
rv = self.handle_exception(request, response, e)
File "/base/data/home/apps/s~nearfieldspy/1.378705245900539993/nearfieldspy.py", line 17, in start
return get()
File "/base/data/home/apps/s~nearfieldspy/1.378705245900539993/nearfieldspy.py", line 5, in get
raise Exception('spam', 'eggs')
Exception: ('spam', 'eggs')
java.lang.RuntimeException: javax.mail.SendFailedException: Invalid Addresses;
nested exception is:
com.sun.mail.smtp.SMTPAddressFailedException: 550 5.7.1 <[REDACTED_EMAIL_ADDRESS]>... Relaying denied
at com.nethunt.crm.api.server.adminsync.AutomaticEmailFacade.sendWithSmtp(AutomaticEmailFacade.java:236)
at com.nethunt.crm.api.server.adminsync.AutomaticEmailFacade.sendSingleEmail(AutomaticEmailFacade.java:285)
at com.nethunt.crm.api.server.adminsync.AutomaticEmailFacade.lambda$sendSingleEmail$3(AutomaticEmailFacade.java:254)
at java.util.Optional.ifPresent(Optional.java:159)
at com.nethunt.crm.api.server.adminsync.AutomaticEmailFacade.sendSingleEmail(AutomaticEmailFacade.java:253)
at com.nethunt.crm.api.server.adminsync.AutomaticEmailFacade.sendSingleEmail(AutomaticEmailFacade.java:249)
at com.nethunt.crm.api.email.EmailSender.lambda$notifyPerson$0(EmailSender.java:80)
at com.nethunt.crm.api.util.ManagedExecutor.lambda$execute$0(ManagedExecutor.java:36)
at com.nethunt.crm.api.util.RequestContextActivator.lambda$withRequestContext$0(RequestContextActivator.java:36)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.base/java.lang.Thread.run(Thread.java:748)
Caused by: javax.mail.SendFailedException: Invalid Addresses;
nested exception is:
com.sun.mail.smtp.SMTPAddressFailedException: 550 5.7.1 <[REDACTED_EMAIL_ADDRESS]>... Relaying denied
at com.sun.mail.smtp.SMTPTransport.rcptTo(SMTPTransport.java:2064)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1286)
at com.nethunt.crm.api.server.adminsync.AutomaticEmailFacade.sendWithSmtp(AutomaticEmailFacade.java:229)
... 12 more
Caused by: com.sun.mail.smtp.SMTPAddressFailedException: 550 5.7.1 <[REDACTED_EMAIL_ADDRESS]>... Relaying denied
`), logPath); err != nil {
t.Fatalf("error writing dummy log lines for Go + Java + Python: %v", err)
}
if err := setupOpsAgent(ctx, logger, vm, config); err != nil {
t.Fatal(err)
}
// 1st one is Golang
if err := gce.WaitForLog(ctx, logger.ToMainLog(), vm, "files_1", time.Hour, `jsonPayload.message="2019/01/15 07:48:05 http: panic serving [::1]:54143: test panic\ngoroutine 24 [running]:\nnet/http.(*conn).serve.func1(0xc00007eaa0)\n /usr/local/go/src/net/http/server.go:1746 +0xd0\npanic(0x12472a0, 0x12ece10)\n /usr/local/go/src/runtime/panic.go:513 +0x1b9\nmain.doPanic(0x12f0ea0, 0xc00010e1c0, 0xc000104400)\n /Users/ingvar/src/go/src/httppanic.go:8 +0x39\nnet/http.HandlerFunc.ServeHTTP(0x12be2e8, 0x12f0ea0, 0xc00010e1c0, 0xc000104400)\n /usr/local/go/src/net/http/server.go:1964 +0x44\nnet/http.(*ServeMux).ServeHTTP(0x14a17a0, 0x12f0ea0, 0xc00010e1c0, 0xc000104400)\n /usr/local/go/src/net/http/server.go:2361 +0x127\nnet/http.serverHandler.ServeHTTP(0xc000085040, 0x12f0ea0, 0xc00010e1c0, 0xc000104400)\n /usr/local/go/src/net/http/server.go:2741 +0xab\nnet/http.(*conn).serve(0xc00007eaa0, 0x12f10a0, 0xc00008a780)\n /usr/local/go/src/net/http/server.go:1847 +0x646\ncreated by net/http.(*Server).Serve\n /usr/local/go/src/net/http/server.go:2851 +0x2f5\n"`); err != nil {
t.Error(err)
}
// 2nd one is Python - the golang parser will send those lines as single-line logs
if err := gce.WaitForLog(ctx, logger.ToMainLog(), vm, "files_1", time.Hour, `jsonPayload.message="Traceback (most recent call last):\n"`); err != nil {
t.Error(err)
}
if err := gce.WaitForLog(ctx, logger.ToMainLog(), vm, "files_1", time.Hour, `jsonPayload.message=" raise Exception('spam', 'eggs')\n"`); err != nil {
t.Error(err)
}
// 3rd one is Java - the golang parser will send those lines as single-line logs
if err := gce.WaitForLog(ctx, logger.ToMainLog(), vm, "files_1", time.Hour, `jsonPayload.message="java.lang.RuntimeException: javax.mail.SendFailedException: Invalid Addresses;\n"`); err != nil {
t.Error(err)
}
if err := gce.WaitForLog(ctx, logger.ToMainLog(), vm, "files_1", time.Hour, `jsonPayload.message="Caused by: com.sun.mail.smtp.SMTPAddressFailedException: 550 5.7.1 <[REDACTED_EMAIL_ADDRESS]>... Relaying denied\n"`); err != nil {
t.Error(err)
}
})
}
func TestCustomLogFile(t *testing.T) {
t.Parallel()
gce.RunForEachPlatform(t, func(t *testing.T, platform string) {
t.Parallel()
ctx, logger, vm := agents.CommonSetup(t, platform)
logPath := logPathForPlatform(vm.Platform)
config := fmt.Sprintf(`logging:
receivers:
mylog_source:
type: files
include_paths:
- %s
exporters:
google:
type: google_cloud_logging
processors:
my_exclude:
type: exclude_logs
match_any:
- jsonPayload.missing_field = "value"
- jsonPayload.message =~ "test pattern"
service:
pipelines:
my_pipeline:
receivers: [mylog_source]
processors: [my_exclude]
exporters: [google]
`, logPath)
if err := setupOpsAgent(ctx, logger, vm, config); err != nil {
t.Fatal(err)
}
if err := gce.UploadContent(ctx, logger, vm, strings.NewReader("abc test pattern xyz\n7654321\n"), logPath); err != nil {
t.Fatalf("error writing dummy log line: %v", err)
}
if err := gce.WaitForLog(ctx, logger.ToMainLog(), vm, "mylog_source", time.Hour, "jsonPayload.message=7654321"); err != nil {
t.Error(err)
}
time.Sleep(60 * time.Second)
_, err := gce.QueryLog(ctx, logger.ToMainLog(), vm, "mylog_source", time.Hour, `jsonPayload.message="abc test pattern xyz"`, 5)
if err == nil {
t.Error("expected log to be excluded but was included")
} else if !strings.Contains(err.Error(), "not found, exhausted retries") {
t.Fatalf("unexpected error: %v", err)
}
})
}
func TestCustomLogFormat(t *testing.T) {
t.Parallel()
gce.RunForEachPlatform(t, func(t *testing.T, platform string) {
t.Parallel()
ctx, logger, vm := agents.CommonSetup(t, platform)
logPath := logPathForPlatform(vm.Platform)
config := fmt.Sprintf(`logging:
receivers:
mylog_source:
type: files
include_paths:
- %s
exporters:
google:
type: google_cloud_logging
processors:
rfc5424:
type: parse_regex
regex: ^\<(?<pri>[0-9]{1,5})\>1 (?<time>[^ ]+) (?<host>[^ ]+) (?<ident>[^ ]+) (?<pid>[-0-9]+) (?<msgid>[^ ]+) (?<extradata>(\[(.*?)\]|-)) (?<message>.+)$
time_key: time
time_format: "%s"
service:
pipelines:
my_pipeline:
receivers: [mylog_source]
processors: [rfc5424]
exporters: [google]
`, logPath, "%Y-%m-%dT%H:%M:%S.%L%z")
if err := setupOpsAgent(ctx, logger, vm, config); err != nil {
t.Fatal(err)
}
// When not using UTC timestamps, the parsing with "%Y-%m-%dT%H:%M:%S.%L%z" doesn't work
// correctly in windows (b/218888265).
line := fmt.Sprintf("<13>1 %s %s my_app_id - - - qqqqrrrr\n", time.Now().UTC().Format(time.RFC3339Nano), vm.Name)
if err := gce.UploadContent(ctx, logger, vm, strings.NewReader(line), logPath); err != nil {
t.Fatalf("error writing dummy log line: %v", err)
}
if err := gce.WaitForLog(ctx, logger.ToMainLog(), vm, "mylog_source", time.Hour, "jsonPayload.message=qqqqrrrr AND jsonPayload.ident=my_app_id"); err != nil {
t.Error(err)
}
})
}
func TestHTTPRequestLog(t *testing.T) {
t.Parallel()
gce.RunForEachPlatform(t, func(t *testing.T, platform string) {
t.Parallel()
ctx, logger, vm := agents.CommonSetup(t, platform)
logPath := logPathForPlatform(vm.Platform)
config := fmt.Sprintf(`logging:
receivers:
mylog_source:
type: files
include_paths:
- %s
exporters:
google:
type: google_cloud_logging
processors:
json1:
type: parse_json
field: message
service:
pipelines:
my_pipeline:
receivers: [mylog_source]
processors: [json1]
exporters: [google]`, logPath)
if err := setupOpsAgent(ctx, logger, vm, config); err != nil {
t.Fatal(err)
}
// The HTTP request data that will be used in each log
httpRequestBody := map[string]interface{}{
"requestMethod": "GET",
"requestUrl": "https://cool.site.net",
"status": 200,
}
// Log with HTTP request data nested under "logging.googleapis.com/httpRequest".
const newHTTPRequestKey = confgenerator.HttpRequestKey
const newHTTPRequestLogId = "new_request_log"
newLogBody := map[string]interface{}{
"logId": newHTTPRequestLogId,
newHTTPRequestKey: httpRequestBody,
}
newLogBytes, err := json.Marshal(newLogBody)
if err != nil {
t.Fatalf("could not marshal new test log: %v", err)
}
// Log with HTTP request data nested under "logging.googleapis.com/http_request".
const oldHTTPRequestKey = "logging.googleapis.com/http_request"
const oldHTTPRequestLogId = "old_request_log"
oldLogBody := map[string]interface{}{
"logId": oldHTTPRequestLogId,
oldHTTPRequestKey: httpRequestBody,
}
oldLogBytes, err := json.Marshal(oldLogBody)
if err != nil {
t.Fatalf("could not marshal old test log: %v", err)
}
// Write both logs to log source file at the same time.
err = gce.UploadContent(
ctx,
logger,
vm,
strings.NewReader(fmt.Sprintf("%s\n%s\n", string(newLogBytes), string(oldLogBytes))),
logPath)
if err != nil {
t.Fatalf("error writing log line: %v", err)
}
queryLogById := func(logId string) (*cloudlogging.Entry, error) {
return gce.QueryLog(
ctx,
logger.ToMainLog(),
vm,
"mylog_source",
time.Hour,
fmt.Sprintf("jsonPayload.logId=%q", logId),
gce.QueryMaxAttempts)
}
isKeyInPayload := func(httpRequestKey string, entry *cloudlogging.Entry) bool {
payload := entry.Payload.(*structpb.Struct)
for k := range payload.GetFields() {
if k == httpRequestKey {
return true
}
}
return false
}
// Test that the new documented field, "logging.googleapis.com/httpRequest", will be
// parsed as expected by Fluent Bit.
t.Run("parse new HTTPRequest key", func(t *testing.T) {
t.Parallel()
entry, err := queryLogById(newHTTPRequestLogId)
if err != nil {
t.Fatalf("could not find written log with id %s: %v", newHTTPRequestLogId, err)
}
if entry.HTTPRequest == nil {
t.Fatal("expected log entry to have HTTPRequest field")
}
if isKeyInPayload(newHTTPRequestKey, entry) {
t.Fatalf("expected %s key to be stripped out of the payload", newHTTPRequestKey)
}
})
// Test that the old field, "logging.googleapis.com/http_request", is no longer
// parsed by Fluent Bit.
t.Run("don't parse old HTTPRequest key", func(t *testing.T) {
t.Parallel()
entry, err := queryLogById(oldHTTPRequestLogId)
if err != nil {
t.Fatalf("could not find written log with id %s: %v", oldHTTPRequestLogId, err)
}
if entry.HTTPRequest != nil {
t.Fatal("expected log entry not to have HTTPRequest field")
}
if !isKeyInPayload(oldHTTPRequestKey, entry) {
t.Fatalf("expected %s key to be present in payload", oldHTTPRequestKey)
}
})
})
}
func TestInvalidConfig(t *testing.T) {
t.Parallel()
gce.RunForEachPlatform(t, func(t *testing.T, platform string) {
t.Parallel()
ctx, logger, vm := agents.CommonSetup(t, platform)
// Sample bad config sourced from:
// https://github.com/GoogleCloudPlatform/ops-agent/blob/master/confgenerator/testdata/invalid/linux/logging-receiver_reserved_id_prefix/input.yaml
config := `logging:
receivers:
lib:receiver_1:
type: files
include_paths:
- /var/log/user-log
service:
pipelines:
default_pipeline:
receivers: [lib:receiver_1]
`
// Run install with an invalid config. We expect to see an error.
if err := setupOpsAgent(ctx, logger, vm, config); err == nil {
t.Fatal("Expected agent to reject bad config.")
}
})
}
func TestProcessorOrder(t *testing.T) {
// See b/194632049 and b/195105380. In that bug, the generated Fluent Bit
// config had mis-ordered filters: json2 came before json1 because "log"
// sorts before "message". The correct order is json1 then json2.
//
// Due to the bug, the log contents came through as a string, not as
// parsed JSON.
t.Parallel()
gce.RunForEachPlatform(t, func(t *testing.T, platform string) {
t.Parallel()
ctx, logger, vm := agents.CommonSetup(t, platform)