Diagnostics 诊断

Introduction 介绍Profiling 分析Tracing 跟踪Debugging 调试Runtime statistics and events 运行时统计信息和事件
Execution tracer 执行跟踪器
GODEBUG go的调试器
 

Introduction

The Go ecosystem provides a large suite of APIs and tools to diagnose logic and performance problems in Go programs. This page summarizes the available tools and helps Go users pick the right one for their specific problem.

Diagnostics solutions can be categorized into the following groups:

  • Profiling: Profiling tools analyze the complexity and costs of a Go program such as its memory usage and frequently called functions to identify the expensive sections of a Go program.
  • Tracing: Tracing is a way to instrument code to analyze latency throughout the lifecycle of a call or user request. Traces provide an overview of how much latency each component contributes to the overall latency in a system. Traces can span multiple Go processes.
  • Debugging: Debugging allows us to pause a Go program and examine its execution. Program state and flow can be verified with debugging.
  • Runtime statistics and events: Collection and analysis of runtime stats and events provides a high-level overview of the health of Go programs. Spikes/dips of metrics helps us to identify changes in throughput, utilization, and performance.

Note: Some diagnostics tools may interfere with each other. For example, precise memory profiling skews CPU profiles and goroutine blocking profiling affects scheduler trace. Use tools in isolation to get more precise info.

Profiling

Profiling is useful for identifying expensive or frequently called sections of code. The Go runtime provides profiling data in the format expected by the pprof visualization tool. The profiling data can be collected during testing via go test or endpoints made available from the net/http/pprof package. Users need to collect the profiling data and use pprof tools to filter and visualize the top code paths.

Predefined profiles provided by the runtime/pprof package:

  • cpu: CPU profile determines where a program spends its time while actively consuming CPU cycles (as opposed to while sleeping or waiting for I/O).
  • heap: Heap profile reports memory allocation samples; used to monitor current and historical memory usage, and to check for memory leaks.
  • threadcreate: Thread creation profile reports the sections of the program that lead the creation of new OS threads.
  • goroutine: Goroutine profile reports the stack traces of all current goroutines.
  • block: Block profile shows where goroutines block waiting on synchronization primitives (including timer channels). Block profile is not enabled by default; use runtime.SetBlockProfileRate to enable it.
  • mutex: Mutex profile reports the lock contentions. When you think your CPU is not fully utilized due to a mutex contention, use this profile. Mutex profile is not enabled by default, see runtime.SetMutexProfileFraction to enable it.

What other profilers can I use to profile Go programs?

On Linux, perf tools can be used for profiling Go programs. Perf can profile and unwind cgo/SWIG code and kernel, so it can be useful to get insights into native/kernel performance bottlenecks. On macOS, Instrumentssuite can be used profile Go programs.

Can I profile my production services?

Yes. It is safe to profile programs in production, but enabling some profiles (e.g. the CPU profile) adds cost. You should expect to see performance downgrade. The performance penalty can be estimated by measuring the overhead of the profiler before turning it on in production.

You may want to periodically profile your production services. Especially in a system with many replicas of a single process, selecting a random replica periodically is a safe option. Select a production process, profile it for X seconds for every Y seconds and save the results for visualization and analysis; then repeat periodically. Results may be manually and/or automatically reviewed to find problems. Collection of profiles can interfere with each other, so it is recommended to collect only a single profile at a time.

What are the best ways to visualize the profiling data?

The Go tools provide text, graph, and callgrind visualization of the profile data using go tool pprof. Read Profiling Go programs to see them in action.


Listing of the most expensive calls as text.


Visualization of the most expensive calls as a graph.

Weblist view displays the expensive parts of the source line by line in an HTML page. In the following example, 530ms is spent in the runtime.concatstrings and cost of each line is presented in the listing.


Visualization of the most expensive calls as weblist.

Another way to visualize profile data is a flame graph. Flame graphs allow you to move in a specific ancestry path, so you can zoom in/out of specific sections of code. The upstream pprof has support for flame graphs.


Flame graphs offers visualization to spot the most expensive code-paths.

Am I restricted to the built-in profiles?

Additionally to what is provided by the runtime, Go users can create their custom profiles via pprof.Profile and use the existing tools to examine them.

Can I serve the profiler handlers (/debug/pprof/...) on a different path and port?

Yes. The net/http/pprof package registers its handlers to the default mux by default, but you can also register them yourself by using the handlers exported from the package.

For example, the following example will serve the pprof.Profile handler on :7777 at /custom_debug_path/profile:

package mainimport ("log""net/http""net/http/pprof"
)func main() {mux := http.NewServeMux()mux.HandleFunc("/custom_debug_path/profile", pprof.Profile)log.Fatal(http.ListenAndServe(":7777", mux))
}

Tracing

Tracing is a way to instrument code to analyze latency throughout the lifecycle of a chain of calls. Go providesgolang.org/x/net/trace package as a minimal tracing backend per Go node and provides a minimal instrumentation library with a simple dashboard. Go also provides an execution tracer to trace the runtime events within an interval.

Tracing enables us to:

  • Instrument and analyze application latency in a Go process.
  • Measure the cost of specific calls in a long chain of calls.
  • Figure out the utilization and performance improvements. Bottlenecks are not always obvious without tracing data.

In monolithic systems, it's relatively easy to collect diagnostic data from the building blocks of a program. All modules live within one process and share common resources to report logs, errors, and other diagnostic information. Once your system grows beyond a single process and starts to become distributed, it becomes harder to follow a call starting from the front-end web server to all of its back-ends until a response is returned back to the user. This is where distributed tracing plays a big role to instrument and analyze your production systems.

Distributed tracing is a way to instrument code to analyze latency throughout the lifecycle of a user request. When a system is distributed and when conventional profiling and debugging tools don’t scale, you might want to use distributed tracing tools to analyze the performance of your user requests and RPCs.

Distributed tracing enables us to:

  • Instrument and profile application latency in a large system.
  • Track all RPCs within the lifecycle of a user request and see integration issues that are only visible in production.
  • Figure out performance improvements that can be applied to our systems. Many bottlenecks are not obvious before the collection of tracing data.

The Go ecosystem provides various distributed tracing libraries per tracing system and backend-agnostic ones.

Is there a way to automatically intercept each function call and create traces?

Go doesn’t provide a way to automatically intercept every function call and create trace spans. You need to manually instrument your code to create, end, and annotate spans.

How should I propagate trace headers in Go libraries?

You can propagate trace identifiers and tags in the context.Context. There is no canonical trace key or common representation of trace headers in the industry yet. Each tracing provider is responsible for providing propagation utilities in their Go libraries.

What other low-level events from the standard library or runtime can be included in a trace?

The standard library and runtime are trying to expose several additional APIs to notify on low level internal events. For example, httptrace.ClientTrace provides APIs to follow low-level events in the life cycle of an outgoing request. There is an ongoing effort to retrieve low-level runtime events from the runtime execution tracer and allow users to define and record their user events.

Debugging

Debugging is the process of identifying why a program misbehaves. Debuggers allow us to understand a program’s execution flow and current state. There are several styles of debugging; this section will only focus on attaching a debugger to a program and core dump debugging.

Go users mostly use the following debuggers:

  • Delve: Delve is a debugger for the Go programming language. It has support for Go’s runtime concepts and built-in types. Delve is trying to be a fully featured reliable debugger for Go programs.
  • GDB: Go provides GDB support via the standard Go compiler and Gccgo. The stack management, threading, and runtime contain aspects that differ enough from the execution model GDB expects that they can confuse the debugger, even when the program is compiled with gccgo. Even though GDB can be used to debug Go programs, it is not ideal and may create confusion.

How well do debuggers work with Go programs?

The gc compiler performs optimizations such as function inlining and variable registerization. These optimizations sometimes make debugging with debuggers harder. There is an ongoing effort to improve the quality of the DWARF information generated for optimized binaries. Until those improvements are available, we recommend disabling optimizations when building the code being debugged. The following command builds a package with no compiler optimizations:

$ go build -gcflags=all="-N -l"

As part of the improvement effort, Go 1.10 introduced a new compiler flag -dwarflocationlists. The flag causes the compiler to add location lists that helps debuggers work with optimized binaries. The following command builds a package with optimizations but with the DWARF location lists:

$ go build -gcflags="-dwarflocationlists=true"

What’s the recommended debugger user interface?

Even though both delve and gdb provides CLIs, most editor integrations and IDEs provides debugging-specific user interfaces.

Is it possible to do postmortem debugging with Go programs?

A core dump file is a file that contains the memory dump of a running process and its process status. It is primarily used for post-mortem debugging of a program and to understand its state while it is still running. These two cases make debugging of core dumps a good diagnostic aid to postmortem and analyze production services. It is possible to obtain core files from Go programs and use delve or gdb to debug, see the core dump debuggingpage for a step-by-step guide.

Runtime statistics and events

The runtime provides stats and reporting of internal events for users to diagnose performance and utilization problems at the runtime level.

Users can monitor these stats to better understand the overall health and performance of Go programs. Some frequently monitored stats and states:

  • runtime.ReadMemStats reports the metrics related to heap allocation and garbage collection. Memory stats are useful for monitoring how much memory resources a process is consuming, whether the process can utilize memory well, and to catch memory leaks.
  • debug.ReadGCStats reads statistics about garbage collection. It is useful to see how much of the resources are spent on GC pauses. It also reports a timeline of garbage collector pauses and pause time percentiles.
  • debug.Stack returns the current stack trace. Stack trace is useful to see how many goroutines are currently running, what they are doing, and whether they are blocked or not.
  • debug.WriteHeapDump suspends the execution of all goroutines and allows you to dump the heap to a file. A heap dump is a snapshot of a Go process' memory at a given time. It contains all allocated objects as well as goroutines, finalizers, and more.
  • runtime.NumGoroutine returns the number of current goroutines. The value can be monitored to see whether enough goroutines are utilized, or to detect goroutine leaks.

Execution tracer

Go comes with a runtime execution tracer to capture a wide range of runtime events. Scheduling, syscall, garbage collections, heap size, and other events are collected by runtime and available for visualization by the go tool trace. Execution tracer is a tool to detect latency and utilization problems. You can examine how well the CPU is utilized, and when networking or syscalls are a cause of preemption for the goroutines.

Tracer is useful to:

  • Understand how your goroutines execute.
  • Understand some of the core runtime events such as GC runs.
  • Identify poorly parallelized execution.

However, it is not great for identifying hot spots such as analyzing the cause of excessive memory or CPU usage. Use profiling tools instead first to address them.

Above, the go tool trace visualization shows the execution started fine, and then it became serialized. It suggests that there might be lock contention for a shared resource that creates a bottleneck.

See go tool trace to collect and analyze runtime traces.

GODEBUG

Runtime also emits events and information if GODEBUG environmental variable is set accordingly.

  • GODEBUG=gctrace=1 prints garbage collector events at each collection, summarizing the amount of memory collected and the length of the pause.
  • GODEBUG=schedtrace=X prints scheduling events every X milliseconds.

转载于:https://www.cnblogs.com/kaid/p/9698404.html

05 Diagnostics 诊断相关推荐

  1. SAP UI5 应用开发教程之四十二 - SAP UI5 自带的 Diagnostics 诊断工具使用方法介绍

    一套适合 SAP UI5 初学者循序渐进的学习教程 教程目录 SAP UI5 本地开发环境的搭建 SAP UI5 应用开发教程之一:Hello World SAP UI5 应用开发教程之二:SAP U ...

  2. prophet Diagnostics诊断

    例子代码 https://github.com/lilihongjava/prophet_demo/tree/master/diagnostics # encoding: utf-8 import p ...

  3. 05 数据分析 - 诊断性分析方法

    诊断性分析: 根据业务逻辑,通过数据寻找引起最终结果的原因和可以改变未来结果的方法 分析目的 解决问题 坏的结果 -> 产生问题的原因和解决的方案 发现机会 好的结果 -> 在机会出现的时 ...

  4. spss多因素方差分析

    多因素方差分析 多因素方差分析是对一个独立变量是否受一个或多个因素或变量影响而进行的方差分析.SPSS调用"Univariate"过程,检验不同水平组合之间因变量均数,由于受不同因 ...

  5. 生产力工具:shell 与 Bash 脚本

    生产力工具:shell 与 Bash 脚本 作者:吴甜甜 个人博客网站: wutiantian.github.io 微信公众号: 吴甜甜的博客 注意:本文只是我个人总结的学习笔记,不适合0基础人士观看 ...

  6. MATLAB-fsolve函数帮助文档翻译与补充

    fsolve 解非线性方程组 非线性系统解算器 解决指定的问题 F(x)= 0 对于x, F(x)是一个返回向量值的函数. x是一个向量或者一个矩阵;看矩阵参数. 语法: x = fsolve(fun ...

  7. 深度丨AI挑战人类情感!机器人写诗出书背后透露了什么?

    继在围棋人机大战中,顶级人类选手完败给人工智能后,人工智能机器人就不断刷爆人们的眼球.地震中机器人6秒写新闻稿.医院里"人工智能"医生0.05秒诊断一起病例.工程现场机器人给排水管 ...

  8. linux系统中查看己设置iptables规则

    1.iptables -L 查看filter表的iptables规则,包括所有的链.filter表包含INPUT.OUTPUT.FORWARD三个规则链. 说明:-L是--list的简写,作用是列出规 ...

  9. ie网络集合代理无法启动_网络故障诊断70例!经典老文了!

    1.故障现象:网络适配器(网卡)设置与计算机资源有冲突. 分析.排除:通过调整网卡资源中的IRQ和I/O值来避开与计算机其它资源的冲突.有些情况还需要通过设置主板的跳线来调整与其它资源的冲突. 2.故 ...

最新文章

  1. Twitter团队最新研究:快速高效的可扩展图神经网络SIGN
  2. NBT封面:纳米孔基因组测序快速临床诊断细菌性下呼吸道感染
  3. sqlserver在linux数据备份,SQLServer数据库之sqlserver for linux自动备份数据库脚本
  4. QTreeWidget 读取windows注册表
  5. python散点图拟合曲线-Python解决最小二乘法拟合并绘制散点图
  6. boost::shared_ptr shared_from_this
  7. python批量生成文件夹_python实现批量获取指定文件夹下的所有文件的厂
  8. 科大星云诗社动态20210531
  9. macbook不能进系统 备份数据_外卖骑手,困在系统里;绩效考核与奖惩激励,不能困在数据里...
  10. GridView 激发了未处理的事件“RowEditing”
  11. [CF/AT]各大网站网赛 体验部部长第一季度工作报告
  12. spark on yarn 部署问题
  13. Bootstrap3 表单静态控件
  14. git 小乌龟 配置_Git-Bash和TortoiseGit小乌龟客户端配置记录
  15. .net mysql 工作流_一个适合于.NET Core的超轻量级工作流引擎:Workflow-Core
  16. leetcode第一刷_Count and Say
  17. access统计各职务人数_东莞各阶段学生人数统计|终于知道为什么在东莞总是学位紧缺了...
  18. esp8266教程:esp8266使用mqtt连接百度智能云
  19. 智利车厘子的尺寸说明,给大家扫盲
  20. 怎样正确的维护使用电脑

热门文章

  1. 13-3 14 NFS
  2. 例子:倒计时按钮可用
  3. SQL Server 存储过程的应用
  4. 三个免费图片网站:特别适合场景图
  5. 好物推荐:notion想同步什么东西,直接在这里写就可以,不用再发消息,真棒
  6. 一个有趣的观察:关于内向和外向
  7. 几何着色器与细分(镶嵌)着色器
  8. UNITY 模型与动画优化选项
  9. 毁掉云计算项目的三个“好办法”
  10. 破天荒第一遭 安全公司因玩忽职守被客户告上法庭