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
|
package debug
import (
"archive/tar"
"compress/gzip"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/hashicorp/consul/api"
"github.com/hashicorp/consul/command/flags"
multierror "github.com/hashicorp/go-multierror"
"github.com/mitchellh/cli"
)
const (
// debugInterval is the interval in which to capture dynamic information
// when running debug
debugInterval = 30 * time.Second
// debugDuration is the total duration that debug runs before being
// shut down
debugDuration = 2 * time.Minute
// debugDurationGrace is a period of time added to the specified
// duration to allow intervals to capture within that time
debugDurationGrace = 2 * time.Second
// debugMinInterval is the minimum a user can configure the interval
// to prevent accidental DOS
debugMinInterval = 5 * time.Second
// debugMinDuration is the minimum a user can configure the duration
// to ensure that all information can be collected in time
debugMinDuration = 10 * time.Second
// debugArchiveExtension is the extension for archive files
debugArchiveExtension = ".tar.gz"
// debugProtocolVersion is the version of the package that is
// generated. If this format changes interface, this version
// can be incremented so clients can selectively support packages
debugProtocolVersion = 1
)
func New(ui cli.Ui, shutdownCh <-chan struct{}) *cmd {
ui = &cli.PrefixedUi{
OutputPrefix: "==> ",
InfoPrefix: " ",
ErrorPrefix: "==> ",
Ui: ui,
}
c := &cmd{UI: ui, shutdownCh: shutdownCh}
c.init()
return c
}
type cmd struct {
UI cli.Ui
flags *flag.FlagSet
http *flags.HTTPFlags
help string
shutdownCh <-chan struct{}
// flags
interval time.Duration
duration time.Duration
output string
archive bool
capture []string
client *api.Client
// validateTiming can be used to skip validation of interval, duration. This
// is primarily useful for testing
validateTiming bool
index *debugIndex
}
// debugIndex is used to manage the summary of all data recorded
// during the debug, to be written to json at the end of the run
// and stored at the root. Each attribute corresponds to a file or files.
type debugIndex struct {
// Version of the debug package
Version int
// Version of the target Consul agent
AgentVersion string
Interval string
Duration string
Targets []string
}
func (c *cmd) init() {
c.flags = flag.NewFlagSet("", flag.ContinueOnError)
defaultFilename := fmt.Sprintf("consul-debug-%d", time.Now().Unix())
c.flags.Var((*flags.AppendSliceValue)(&c.capture), "capture",
fmt.Sprintf("One or more types of information to capture. This can be used "+
"to capture a subset of information, and defaults to capturing "+
"everything available. Possible information for capture: %s. "+
"This can be repeated multiple times.", strings.Join(c.defaultTargets(), ", ")))
c.flags.DurationVar(&c.interval, "interval", debugInterval,
fmt.Sprintf("The interval in which to capture dynamic information such as "+
"telemetry, and profiling. Defaults to %s.", debugInterval))
c.flags.DurationVar(&c.duration, "duration", debugDuration,
fmt.Sprintf("The total time to record information. "+
"Defaults to %s.", debugDuration))
c.flags.BoolVar(&c.archive, "archive", true, "Boolean value for if the files "+
"should be archived and compressed. Setting this to false will skip the "+
"archive step and leave the directory of information on the current path.")
c.flags.StringVar(&c.output, "output", defaultFilename, "The path "+
"to the compressed archive that will be created with the "+
"information after collection.")
c.http = &flags.HTTPFlags{}
flags.Merge(c.flags, c.http.ClientFlags())
c.help = flags.Usage(help, c.flags)
c.validateTiming = true
}
func (c *cmd) Run(args []string) int {
if err := c.flags.Parse(args); err != nil {
c.UI.Error(fmt.Sprintf("Error parsing flags: %s", err))
return 1
}
if len(c.flags.Args()) > 0 {
c.UI.Error("debug: Too many arguments provided, expected 0")
return 1
}
// Connect to the agent
client, err := c.http.APIClient()
if err != nil {
c.UI.Error(fmt.Sprintf("Error connecting to Consul agent: %s", err))
return 1
}
c.client = client
version, err := c.prepare()
if err != nil {
c.UI.Error(fmt.Sprintf("Capture validation failed: %v", err))
return 1
}
archiveName := c.output
// Show the user the final file path if archiving
if c.archive {
archiveName = archiveName + debugArchiveExtension
}
c.UI.Output("Starting debugger and capturing static information...")
// Output metadata about target agent
c.UI.Info(fmt.Sprintf(" Agent Version: '%s'", version))
c.UI.Info(fmt.Sprintf(" Interval: '%s'", c.interval))
c.UI.Info(fmt.Sprintf(" Duration: '%s'", c.duration))
c.UI.Info(fmt.Sprintf(" Output: '%s'", archiveName))
c.UI.Info(fmt.Sprintf(" Capture: '%s'", strings.Join(c.capture, ", ")))
// Record some information for the index at the root of the archive
index := &debugIndex{
Version: debugProtocolVersion,
AgentVersion: version,
Interval: c.interval.String(),
Duration: c.duration.String(),
Targets: c.capture,
}
// Add the extra grace period to ensure
// all intervals will be captured within the time allotted
c.duration = c.duration + debugDurationGrace
// Capture static information from the target agent
err = c.captureStatic()
if err != nil {
c.UI.Warn(fmt.Sprintf("Static capture failed: %v", err))
}
// Capture dynamic information from the target agent, blocking for duration
if c.configuredTarget("metrics") || c.configuredTarget("logs") || c.configuredTarget("pprof") {
err = c.captureDynamic()
if err != nil {
c.UI.Error(fmt.Sprintf("Error encountered during collection: %v", err))
}
}
// Write the index document
idxMarshalled, err := json.MarshalIndent(index, "", "\t")
if err != nil {
c.UI.Error(fmt.Sprintf("Error marshalling index document: %v", err))
return 1
}
err = ioutil.WriteFile(fmt.Sprintf("%s/index.json", c.output), idxMarshalled, 0644)
if err != nil {
c.UI.Error(fmt.Sprintf("Error creating index document: %v", err))
return 1
}
// Archive the data if configured to
if c.archive {
err = c.createArchive()
if err != nil {
c.UI.Warn(fmt.Sprintf("Archive creation failed: %v", err))
return 1
}
}
c.UI.Info(fmt.Sprintf("Saved debug archive: %s", archiveName))
return 0
}
// prepare validates agent settings against targets and prepares the environment for capturing
func (c *cmd) prepare() (version string, err error) {
// Ensure realistic duration and intervals exists
if c.validateTiming {
if c.duration < debugMinDuration {
return "", fmt.Errorf("duration must be longer than %s", debugMinDuration)
}
if c.interval < debugMinInterval {
return "", fmt.Errorf("interval must be longer than %s", debugMinDuration)
}
if c.duration < c.interval {
return "", fmt.Errorf("duration (%s) must be longer than interval (%s)", c.duration, c.interval)
}
}
// Retrieve and process agent information necessary to validate
self, err := c.client.Agent().Self()
if err != nil {
return "", fmt.Errorf("error querying target agent: %s. verify connectivity and agent address", err)
}
version, ok := self["Config"]["Version"].(string)
if !ok {
return "", fmt.Errorf("agent response did not contain version key")
}
debugEnabled, ok := self["DebugConfig"]["EnableDebug"].(bool)
if !ok {
return version, fmt.Errorf("agent response did not contain debug key")
}
// If none are specified we will collect information from
// all by default
if len(c.capture) == 0 {
c.capture = c.defaultTargets()
}
if !debugEnabled && c.configuredTarget("pprof") {
cs := c.capture
for i := 0; i < len(cs); i++ {
if cs[i] == "pprof" {
c.capture = append(cs[:i], cs[i+1:]...)
i--
}
}
c.UI.Warn("[WARN] Unable to capture pprof. Set enable_debug to true on target agent to enable profiling.")
}
for _, t := range c.capture {
if !c.allowedTarget(t) {
return version, fmt.Errorf("target not found: %s", t)
}
}
if _, err := os.Stat(c.output); os.IsNotExist(err) {
err := os.MkdirAll(c.output, 0755)
if err != nil {
return version, fmt.Errorf("could not create output directory: %s", err)
}
} else {
return version, fmt.Errorf("output directory already exists: %s", c.output)
}
return version, nil
}
// captureStatic captures static target information and writes it
// to the output path
func (c *cmd) captureStatic() error {
// Collect errors via multierror as we want to gracefully
// fail if an API is inacessible
var errors error
// Collect the named outputs here
outputs := make(map[string]interface{})
// Capture host information
if c.configuredTarget("host") {
host, err := c.client.Agent().Host()
if err != nil {
errors = multierror.Append(errors, err)
}
outputs["host"] = host
}
// Capture agent information
if c.configuredTarget("agent") {
agent, err := c.client.Agent().Self()
if err != nil {
errors = multierror.Append(errors, err)
}
outputs["agent"] = agent
}
// Capture cluster members information, including WAN
if c.configuredTarget("cluster") {
members, err := c.client.Agent().Members(true)
if err != nil {
errors = multierror.Append(errors, err)
}
outputs["cluster"] = members
}
// Write all outputs to disk as JSON
for output, v := range outputs {
marshaled, err := json.MarshalIndent(v, "", "\t")
if err != nil {
errors = multierror.Append(errors, err)
}
err = ioutil.WriteFile(fmt.Sprintf("%s/%s.json", c.output, output), marshaled, 0644)
if err != nil {
errors = multierror.Append(errors, err)
}
}
return errors
}
// captureDynamic blocks for the duration of the command
// specified by the duration flag, capturing the dynamic
// targets at the interval specified
func (c *cmd) captureDynamic() error {
successChan := make(chan int64)
errCh := make(chan error)
durationChn := time.After(c.duration)
intervalCount := 0
c.UI.Output(fmt.Sprintf("Beginning capture interval %s (%d)", time.Now().Local().String(), intervalCount))
// We'll wait for all of the targets configured to be
// captured before continuing
var wg sync.WaitGroup
capture := func() {
timestamp := time.Now().Local().Unix()
// Make the directory that will store all captured data
// for this interval
timestampDir := fmt.Sprintf("%s/%d", c.output, timestamp)
err := os.MkdirAll(timestampDir, 0755)
if err != nil {
errCh <- err
}
// Capture metrics
if c.configuredTarget("metrics") {
wg.Add(1)
go func() {
metrics, err := c.client.Agent().Metrics()
if err != nil {
errCh <- err
}
marshaled, err := json.MarshalIndent(metrics, "", "\t")
if err != nil {
errCh <- err
}
err = ioutil.WriteFile(fmt.Sprintf("%s/%s.json", timestampDir, "metrics"), marshaled, 0644)
if err != nil {
errCh <- err
}
// We need to sleep for the configured interval in the case
// of metrics being the only target captured. When it is,
// the waitgroup would return on Wait() and repeat without
// waiting for the interval.
time.Sleep(c.interval)
wg.Done()
}()
}
// Capture pprof
if c.configuredTarget("pprof") {
wg.Add(1)
go func() {
// We need to capture profiles and traces at the same time
// and block for both of them
var wgProf sync.WaitGroup
heap, err := c.client.Debug().Heap()
if err != nil {
errCh <- err
}
err = ioutil.WriteFile(fmt.Sprintf("%s/heap.prof", timestampDir), heap, 0644)
if err != nil {
errCh <- err
}
// Capture a profile/trace with a minimum of 1s
s := c.interval.Seconds()
if s < 1 {
s = 1
}
wgProf.Add(1)
go func() {
prof, err := c.client.Debug().Profile(int(s))
if err != nil {
errCh <- err
}
err = ioutil.WriteFile(fmt.Sprintf("%s/profile.prof", timestampDir), prof, 0644)
if err != nil {
errCh <- err
}
wgProf.Done()
}()
wgProf.Add(1)
go func() {
trace, err := c.client.Debug().Trace(int(s))
if err != nil {
errCh <- err
}
err = ioutil.WriteFile(fmt.Sprintf("%s/trace.out", timestampDir), trace, 0644)
if err != nil {
errCh <- err
}
wgProf.Done()
}()
gr, err := c.client.Debug().Goroutine()
if err != nil {
errCh <- err
}
err = ioutil.WriteFile(fmt.Sprintf("%s/goroutine.prof", timestampDir), gr, 0644)
if err != nil {
errCh <- err
}
wgProf.Wait()
wg.Done()
}()
}
// Capture logs
if c.configuredTarget("logs") {
wg.Add(1)
go func() {
endLogChn := make(chan struct{})
logCh, err := c.client.Agent().Monitor("DEBUG", endLogChn, nil)
if err != nil {
errCh <- err
}
// Close the log stream
defer close(endLogChn)
// Create the log file for writing
f, err := os.Create(fmt.Sprintf("%s/%s", timestampDir, "consul.log"))
if err != nil {
errCh <- err
}
defer f.Close()
intervalChn := time.After(c.interval)
OUTER:
for {
select {
case log := <-logCh:
// Append the line to the file
if _, err = f.WriteString(log + "\n"); err != nil {
errCh <- err
break OUTER
}
// Stop collecting the logs after the interval specified
case <-intervalChn:
break OUTER
}
}
wg.Done()
}()
}
// Wait for all captures to complete
wg.Wait()
// Send down the timestamp for UI output
successChan <- timestamp
}
go capture()
for {
select {
case t := <-successChan:
intervalCount++
c.UI.Output(fmt.Sprintf("Capture successful %s (%d)", time.Unix(t, 0).Local().String(), intervalCount))
go capture()
case e := <-errCh:
c.UI.Error(fmt.Sprintf("Capture failure %s", e))
case <-durationChn:
return nil
case <-c.shutdownCh:
return errors.New("stopping collection due to shutdown signal")
}
}
}
// allowedTarget returns a boolean if the target is able to be captured
func (c *cmd) allowedTarget(target string) bool {
for _, dt := range c.defaultTargets() {
if dt == target {
return true
}
}
return false
}
// configuredTarget returns a boolean if the target is configured to be
// captured in the command
func (c *cmd) configuredTarget(target string) bool {
for _, dt := range c.capture {
if dt == target {
return true
}
}
return false
}
// createArchive walks the files in the temporary directory
// and creates a tar file that is gzipped with the contents
func (c *cmd) createArchive() error {
path := c.output + debugArchiveExtension
tempName, err := c.createArchiveTemp(path)
if err != nil {
return err
}
if err := os.Rename(tempName, path); err != nil {
return err
}
// fsync the dir to make the rename stick
if err := syncParentDir(path); err != nil {
return err
}
// Remove directory that has been archived
if err := os.RemoveAll(c.output); err != nil {
return fmt.Errorf("failed to remove archived directory: %s", err)
}
return nil
}
func syncParentDir(name string) error {
f, err := os.Open(filepath.Dir(name))
if err != nil {
return err
}
defer f.Close()
return f.Sync()
}
func (c *cmd) createArchiveTemp(path string) (tempName string, err error) {
dir := filepath.Dir(path)
name := filepath.Base(path)
f, err := ioutil.TempFile(dir, name+".tmp")
if err != nil {
return "", fmt.Errorf("failed to create compressed temp archive: %s", err)
}
g := gzip.NewWriter(f)
t := tar.NewWriter(g)
tempName = f.Name()
cleanup := func(err error) (string, error) {
_ = t.Close()
_ = g.Close()
_ = f.Close()
_ = os.Remove(tempName)
return "", err
}
err = filepath.Walk(c.output, func(file string, fi os.FileInfo, err error) error {
if err != nil {
return fmt.Errorf("failed to walk filepath for archive: %s", err)
}
header, err := tar.FileInfoHeader(fi, fi.Name())
if err != nil {
return fmt.Errorf("failed to create compressed archive header: %s", err)
}
header.Name = filepath.Join(filepath.Base(c.output), strings.TrimPrefix(file, c.output))
if err := t.WriteHeader(header); err != nil {
return fmt.Errorf("failed to write compressed archive header: %s", err)
}
// Only copy files
if !fi.Mode().IsRegular() {
return nil
}
f, err := os.Open(file)
if err != nil {
return fmt.Errorf("failed to open target files for archive: %s", err)
}
if _, err := io.Copy(t, f); err != nil {
return fmt.Errorf("failed to copy files for archive: %s", err)
}
f.Close()
return nil
})
if err != nil {
return cleanup(fmt.Errorf("failed to walk output path for archive: %s", err))
}
// Explicitly close things in the correct order (tar then gzip) so we
// know if they worked.
if err := t.Close(); err != nil {
return cleanup(err)
}
if err := g.Close(); err != nil {
return cleanup(err)
}
// Guarantee that the contents of the temp file are flushed to disk.
if err := f.Sync(); err != nil {
return cleanup(err)
}
// Close the temp file and go back to the wrapper function for the rest.
if err := f.Close(); err != nil {
return cleanup(err)
}
return tempName, nil
}
// defaultTargets specifies the list of all targets that
// will be captured by default
func (c *cmd) defaultTargets() []string {
return append(c.dynamicTargets(), c.staticTargets()...)
}
// dynamicTargets returns all the supported targets
// that are retrieved at the interval specified
func (c *cmd) dynamicTargets() []string {
return []string{"metrics", "logs", "pprof"}
}
// staticTargets returns all the supported targets
// that are retrieved at the start of the command execution
func (c *cmd) staticTargets() []string {
return []string{"host", "agent", "cluster"}
}
func (c *cmd) Synopsis() string {
return synopsis
}
func (c *cmd) Help() string {
return c.help
}
const synopsis = "Records a debugging archive for operators"
const help = `
Usage: consul debug [options]
Monitors a Consul agent for the specified period of time, recording
information about the agent, cluster, and environment to an archive
written to the specified path.
If ACLs are enabled, an 'operator:read' token must be supplied in order
to perform this operation.
To create a debug archive in the current directory for the default
duration and interval, capturing all information available:
$ consul debug
The command stores captured data at the configured output path
through the duration, and will archive the data at the same
path if interrupted.
Flags can be used to customize the duration and interval of the
operation. Duration is the total time to capture data for from the target
agent and interval controls how often dynamic data such as metrics
are scraped.
$ consul debug -interval=20s -duration=1m
The capture flag can be specified multiple times to limit information
retrieved.
$ consul debug -capture metrics -capture agent
By default, the archive containing the debugging information is
saved to the current directory as a .tar.gz file. The
output path can be specified, as well as an option to disable
archiving, leaving the directory intact.
$ consul debug -output=/foo/bar/my-debugging -archive=false
Note: Information collected by this command has the potential
to be highly sensitive. Sensitive material such as ACL tokens and
other commonly secret material are redacted automatically, but we
strongly recommend review of the data within the archive prior to
transmitting it.
For a full list of options and examples, please see the Consul
documentation.
`
|