diff --git a/documentation/content/de/books/handbook/dtrace/_index.adoc b/documentation/content/de/books/handbook/dtrace/_index.adoc index 52806dce8f..0ad5483e4d 100644 --- a/documentation/content/de/books/handbook/dtrace/_index.adoc +++ b/documentation/content/de/books/handbook/dtrace/_index.adoc @@ -1,238 +1,238 @@ --- title: Kapitel 24. DTrace part: Teil III. Systemadministration prev: books/handbook/cutting-edge next: books/handbook/usb-device-mode --- [[dtrace]] = DTrace :doctype: book :toc: macro :toclevels: 1 :icons: font :sectnums: :sectnumlevels: 6 :source-highlighter: rouge :experimental: :skip-front-matter: :table-caption: Tabelle :figure-caption: Abbildung :example-caption: Beispiel :xrefstyle: basic :relfileprefix: ../ :outfilesuffix: :sectnumoffset: 24 ifeval::["{backend}" == "html5"] :imagesdir: ../../../images/books/handbook/dtrace/ endif::[] ifeval::["{backend}" == "pdf"] :imagesdir: ../../../../static/images/books/handbook/dtrace/ endif::[] ifeval::["{backend}" == "epub3"] :imagesdir: ../../../../static/images/books/handbook/dtrace/ endif::[] include::shared/authors.adoc[] include::shared/releases.adoc[] include::shared/de/mailing-lists.adoc[] include::shared/de/teams.adoc[] include::shared/de/urls.adoc[] toc::[] [[dtrace-synopsis]] == Überblick DTrace, auch bekannt als Dynamic Tracing, wurde von Sun(TM) als ein Werkzeug zur Analyse von Performance-Problemen in Produktiv- und Entwicklungssystemen entwickelt. Zusätzlich zur Diagnose von Performance-Problemen kann DTrace auch verwendet werden, um bei der Untersuchung und Behebung von unerwartetem Verhalten im FreeBSD-Kernel und den Anwenderprogrammen zu helfen. DTrace ist ein bemerkenswertes Werkzeug zur Profilerstellung, mit einer beeindruckenden Palette von Eigenschaften zur Diagnose von Systemereignissen. Es kann auch dazu verwendet werden, bestehende Skripte ablaufen zu lassen, um einen Nutzen aus deren Möglichkeiten zu ziehen. Nutzer können mittels der Programmiersprache D von DTrace ihre eigenen Hilfsmittel schreiben, was es ermöglicht, die eigenen Profile nach Ihren Bedürfnissen anzupassen. Die DTrace-Implementierung in FreeBSD bietet experimentelle Unterstützung für DTrace im Userland. Userland DTrace erlaubt es Anwendern, function boundary tracing für Anwendungsprogramme über den `pid`-Provider hinweg vorzunehmen und um statische Sonden in Anwendungsprogramme für die spätere Aufzeichnung einzufügen. Manche Ports, wie beispielsweise package:databases/postgresql12-server[] und package:lang/php74[] besitzen eine DTrace-Option, um statische Sonden zu aktivieren. Eine offizielle Anleitung für DTrace wird vom Illumos Projekt im http://dtrace.org/guide[DTrace Guide] bereitgestellt. Nachdem Sie dieses Kapitel gelesen haben, werden Sie Folgendes wissen: * Was DTrace ist und welche Funktionen es zur Verfügung stellt. * Unterschiede zwischen der Solaris(TM) DTrace Implementierung und derjenigen, die FreeBSD bereitstellt. * Wie man DTrace auf FreeBSD aktiviert und verwendet. Bevor Sie dieses Kapitel lesen, sollten Sie: * UNIX(R) und FreeBSD Grundlagen verstehen (crossref:basics[basics,Grundlagen des FreeBSD Betriebssystems]). * Vertraut sein mit Sicherheitsaspekten und wie diese FreeBSD betreffen (crossref:security[security,Sicherheit]). [WARNING] ==== Diese Funktion ist als experimentell anzusehen. Manche Einstellungen enthalten möglicherweise nicht alle Funktionalitäten, andere Teile könnten gar nicht laufen. Mit der Zeit, wenn diese Funktion als für den Produktivbetrieb geeignet erscheint, wird auch diese Dokumentation geändert, um diesem Umstand gerecht zu werden. ==== [[dtrace-implementation]] == Unterschiede in der Implementierung Obwohl DTrace in FreeBSD sehr ähnlich zu dem in Solaris(TM) ist, existieren doch Unterschiede. Der Hauptunterschied besteht darin, dass in FreeBSD DTrace als eine Menge von Kernelmodulen implementiert ist und DTrace nicht verwendet werden kann, bis diese Module geladen wurden. Um alle nötigen Module zu laden, geben Sie ein: [source,shell] .... # kldload dtraceall .... Beginnend mit FreeBSD 10.0-RELEASE werden die Module automatisch geladen, sobald `dtrace` aufgerufen wird. FreeBSD verwendet die Kerneloption `DDB_CTF`, um die Unterstützung im Kernel für das Laden von CTF-Daten aus Kernelmodulen und dem Kernel selbst zu ermöglichen. CTF ist das Compact C Type Format von Solaris(TM), welches eine reduzierte Form von Debug-Informationen kapselt, ähnlich zu DWARF und den antiken Stabs. Diese CTF-Daten werden dem Binärcode von den `ctfconvert` und `ctfmerge` Befehlen den Werkzeugen zum Bauen des Systems hinzugefügt. Das `ctfconvert`-Dienstprogramm parst die vom Compiler erstellten DWARFELF Debug-Abschnitte und `ctfmerge` vereint CTFELF-Abschnitte aus Objekten, entweder in ausführbare Dateien oder Shared-Libraries. Einige Provider in FreeBSD unterscheiden sich von der Solaris(TM)-Implementierung. Am deutlichsten wird das beim `dtmalloc`-Provider, welcher das Aufzeichnen von `malloc()` nach Typen im FreeBSD-Kernel ermöglicht. Manche der Provider in Solaris(TM) wie `cpc` und `mib` sind in FreeBSD nicht vorhanden. Diese können in zukünftigen FreeBSD-Versionen auftauchen. Weiterhin sind manche der Provider in beiden Betriebssystemen nicht zueinander kompatibel, in dem Sinne daß deren Sonden unterschiedliche Argumenttypen aufweisen. Dadurch können D-Skripte, die unter Solaris(TM) geschrieben wurden, evtl. unter FreeBSD funktionieren oder auch nicht, umgekehrt ist das genauso. In FreeBSD darf DTrace wegen unterschiedlicher Sicherheitskonzepte nur von `root` verwendet werden. Solaris(TM) besitzt ein paar Audit-Funktionen auf den unteren Ebenen, die noch nicht in FreeBSD implementiert sind. Deshalb kann nur `root` auf [.filename]#/dev/dtrace/dtrace# zugreifen. Zum Schluss muss noch erwähnt werden, dass die DTrace-Software unter die CDDL Lizenz fällt. Die `Common Development and Distribution License` wird von FreeBSD mitgeliefert, sehen Sie sich dazu [.filename]#/usr/src/cddl/contrib/opensolaris/OPENSOLARIS.LICENSE# an, oder lesen Sie die Online-Version unter http://opensource.org/licenses/CDDL-1.0[http://opensource.org/licenses/CDDL-1.0]. Während der FreeBSD-Kernel mit den DTrace-Optionen immer noch BSD-lizenziert ist, tritt die CDDL in Kraft, wenn Module in Binärform vertrieben werden oder die Binärdateien geladen werden. [[dtrace-enable]] == Die DTrace Unterstützung aktivieren In FreeBSD 9.2 und 10.0 ist die Unterstützung von DTrace im [.filename]#GENERIC#-Kernel bereits eingebaut. Nutzer von früheren Versionen sollten die folgenden Zeilen in eine eigene Kernelkonfigurationsdatei einfügen und den Kernel mittels der Anleitung in crossref:kernelconfig[kernelconfig,Konfiguration des FreeBSD-Kernels] neu übersetzen: [.programlisting] .... options KDTRACE_HOOKS options DDB_CTF makeoptions DEBUG=-g makeoptions WITH_CTF=1 .... Besitzer der AMD64-Architektur werden wahrscheinlich noch die folgende Zeile zur Kernelkonfigurationsdatei hinzufügen: [.programlisting] .... options KDTRACE_FRAME .... Diese Option liefert die Unterstützung für die FBT-Eigenschaft. DTrace wird auch ohne diese Option funktionieren; jedoch wird dann Function Boundary Tracing nur eingeschränkt unterstützt. Sobald FreeBSD in den neuen Kernel gebootet oder die DTrace-Kernelmodule mittels `kldload dtraceall` geladen wurden, benötigt das System Unterstützung für die Korn-Shell, da DTrace mehrere Dienstprogramme enthält, die in `ksh` implementiert sind. Vergewissern Sie sich, dass das Paket oder der Port package:shells/ksh93[] installiert ist. Es ist auch möglich, diese Werkzeuge unter package:shells/pdksh[] oder package:shells/mksh[] laufen zu lassen. -Zum Schluss sollten Sie noch den aktuellen DTrace-Werkzeugsatz beschaffen. Die DTrace-Werkzeugsammlung enthält gebrauchsfertige Skripte, um Systeminformationen zu sammeln. Es gibt Skripte zum Überprüfen von offenen Dateien, Speicher- und CPU-Gebrauch und noch viel mehr. FreeBSD 10 installiert ein paar dieser Skripte in [.filename]#/usr/shared/dtrace#. Für andere FreeBSD-Versionen oder um die volle DTrace-Werkzeugsammlung zu installieren, verwenden Sie den package:sysutils/DTraceToolkit[] Port oder das Paket. +Zum Schluss sollten Sie noch den aktuellen DTrace-Werkzeugsatz beschaffen. Die DTrace-Werkzeugsammlung enthält gebrauchsfertige Skripte, um Systeminformationen zu sammeln. Es gibt Skripte zum Überprüfen von offenen Dateien, Speicher- und CPU-Gebrauch und noch viel mehr. FreeBSD 10 installiert ein paar dieser Skripte in [.filename]#/usr/shared/dtrace#. Für andere FreeBSD-Versionen oder um die volle DTrace-Werkzeugsammlung zu installieren, verwenden Sie den package:sysutils/dtrace-toolkit[] Port oder das Paket. [NOTE] ==== Die Skripte in [.filename]#/usr/shared/dtrace# wurden speziell für FreeBSD portiert. Nicht alle Skripte in der DTrace-Werkzeugsammlung werden in FreeBSD unverändert funktionieren und manche Skript benötigen einigen Aufwand, damit diese auf FreeBSD funktionieren. ==== Der DTrace-Werkzeugsatz beinhaltet viele Skripte in der speziellen Sprache von DTrace. Diese Sprache wird die D-Sprache genannt und ist sehr ähnlich zu C++. Eine detaillierte Beschreibung dieser Sprache würde den Rahmen dieses Dokuments sprengen. Im http://www.dtrace.org/guide[Illumos Dynamic Tracing Guide] wird diese Sprache ausführlich beschrieben. [[dtrace-using]] == DTrace verwenden DTrace-Skripte bestehen aus einer Liste von einer oder mehreren _Sonden_ oder Instrumentationspunkten, an denen jede Sonde mit einer Aktion verknüpft ist. Jedesmal, wenn die Bedingung für eine Sonde zutrifft, wird die verknüpfte Aktion ausgeführt. Beispielsweise könnte eine Aktion ausgeführt werden, wenn eine Datei geöffnet, ein Prozess gestartet oder eine Codezeile ausgeführt wird. Die Aktion könnte die Protokollierung von Informationen sein oder die Änderung von Kontextvariablen. Das Lesen und Schreiben von Kontextvariablen erlaubt es den Sonden, Informationen auszutauschen und kooperativ die Korrelation bestimmter Ereignisse zu analysieren. Um alle Sonden anzuzeigen, kann der Administrator nun den folgenden Befehl eingeben: [source,shell] .... # dtrace -l | more .... Jede Sonde besitzt eine `ID`, einen `PROVIDER` (dtrace oder fbt), ein `MODULE` und einen `FUNCTION NAME`. Lesen Sie man:dtrace[1] für weitere Informationen zu diesem Kommando. Die Beispiele in diesem Abschnitt geben einen Überblick, wie man zwei dieser voll funktionsfähigen Skripte aus der DTrace-Werkzeugsammlung verwendet: die Skripte [.filename]#hotkernel# und [.filename]#procsystime#. Das [.filename]#hotkernel# Skript wurde entworfen, um zu identifizieren, welche Funktion die meiste Kernelzeit beansprucht. Es wird es Ausgaben ähnlich der Folgenden produzieren: [source,shell] .... # cd /usr/local/share/dtrace-toolkit # ./hotkernel Sampling... Hit Ctrl-C to end. .... Verwenden Sie wie angegeben die Tastenkombination kbd:[Ctrl+C] drücken, um den Prozess zu stoppen. Nach dem Abbruch wird das Skript eine Liste von Kernelfunktionen und Zeitmessungen ausgeben, aufsteigend sortiert nach den Zeiten: [source,shell] .... kernel`_thread_lock_flags 2 0.0% 0xc1097063 2 0.0% kernel`sched_userret 2 0.0% kernel`kern_select 2 0.0% kernel`generic_copyin 3 0.0% kernel`_mtx_assert 3 0.0% kernel`vm_fault 3 0.0% kernel`sopoll_generic 3 0.0% kernel`fixup_filename 4 0.0% kernel`_isitmyx 4 0.0% kernel`find_instance 4 0.0% kernel`_mtx_unlock_flags 5 0.0% kernel`syscall 5 0.0% kernel`DELAY 5 0.0% 0xc108a253 6 0.0% kernel`witness_lock 7 0.0% kernel`read_aux_data_no_wait 7 0.0% kernel`Xint0x80_syscall 7 0.0% kernel`witness_checkorder 7 0.0% kernel`sse2_pagezero 8 0.0% kernel`strncmp 9 0.0% kernel`spinlock_exit 10 0.0% kernel`_mtx_lock_flags 11 0.0% kernel`witness_unlock 15 0.0% kernel`sched_idletd 137 0.3% 0xc10981a5 42139 99.3% .... Dieses Skript funktioniert auch mit Kernelmodulen. Um diese Eigenschaft zu verwenden, starten Sie das Skript mit `-m`: [source,shell] .... # ./hotkernel -m Sampling... Hit Ctrl-C to end. ^C MODULE COUNT PCNT 0xc107882e 1 0.0% 0xc10e6aa4 1 0.0% 0xc1076983 1 0.0% 0xc109708a 1 0.0% 0xc1075a5d 1 0.0% 0xc1077325 1 0.0% 0xc108a245 1 0.0% 0xc107730d 1 0.0% 0xc1097063 2 0.0% 0xc108a253 73 0.0% kernel 874 0.4% 0xc10981a5 213781 99.6% .... Das [.filename]#procsystime# Skript fängt die Systemaufruf-Zeiten für eine gegebene Prozess-ID (PID) oder einen Prozessnamen ab und gibt diese aus. Im folgenden Beispiel wurde eine neue Instanz von [.filename]#/bin/csh# erzeugt. Dann wurde [.filename]#procsystime# ausgeführt und verbleibt so, während ein paar Befehle in die andere Instanz von `csh` eingegeben werden. Dies sind die Ergebnisse dieses Versuchs: [source,shell] .... # ./procsystime -n csh Tracing... Hit Ctrl-C to end... ^C Elapsed Times for processes csh, SYSCALL TIME (ns) getpid 6131 sigreturn 8121 close 19127 fcntl 19959 dup 26955 setpgid 28070 stat 31899 setitimer 40938 wait4 62717 sigaction 67372 sigprocmask 119091 gettimeofday 183710 write 263242 execve 492547 ioctl 770073 vfork 3258923 sigsuspend 6985124 read 3988049784 .... Wie aus der Ausgabe ersichtlich ist, verbraucht der `read()`-Systemaufruf die meiste Zeit in Nanosekunden, während der Systemaufruf `getpid()` hingegen am schnellsten läuft. diff --git a/documentation/content/en/books/handbook/dtrace/_index.adoc b/documentation/content/en/books/handbook/dtrace/_index.adoc index 24c95a8467..d68411983c 100644 --- a/documentation/content/en/books/handbook/dtrace/_index.adoc +++ b/documentation/content/en/books/handbook/dtrace/_index.adoc @@ -1,231 +1,231 @@ --- title: Chapter 25. DTrace part: Part III. System Administration prev: books/handbook/cutting-edge next: books/handbook/usb-device-mode description: This chapter explains how to use DTrace in FreeBSD tags: ["DTrace", "features", "guide", "tutorial", "kldload"] --- [[dtrace]] = DTrace :doctype: book :toc: macro :toclevels: 1 :icons: font :sectnums: :sectnumlevels: 6 :source-highlighter: rouge :experimental: :skip-front-matter: :xrefstyle: basic :relfileprefix: ../ :outfilesuffix: :sectnumoffset: 25 ifeval::["{backend}" == "html5"] :imagesdir: ../../../../images/books/handbook/dtrace/ endif::[] ifeval::["{backend}" == "pdf"] :imagesdir: ../../../../static/images/books/handbook/dtrace/ endif::[] ifeval::["{backend}" == "epub3"] :imagesdir: ../../../../static/images/books/handbook/dtrace/ endif::[] include::shared/authors.adoc[] include::shared/releases.adoc[] include::shared/en/mailing-lists.adoc[] include::shared/en/teams.adoc[] include::shared/en/urls.adoc[] toc::[] [[dtrace-synopsis]] == Synopsis DTrace, also known as Dynamic Tracing, was developed by Sun(TM) as a tool for locating performance bottlenecks in production and pre-production systems. In addition to diagnosing performance problems, DTrace can be used to help investigate and debug unexpected behavior in both the FreeBSD kernel and in userland programs. DTrace is a remarkable profiling tool, with an impressive array of features for diagnosing system issues. It may also be used to run pre-written scripts to take advantage of its capabilities. Users can author their own utilities using the DTrace D Language, allowing them to customize their profiling based on specific needs. The FreeBSD implementation provides full support for kernel DTrace and experimental support for userland DTrace. Userland DTrace allows users to perform function boundary tracing for userland programs using the `pid` provider, and to insert static probes into userland programs for later tracing. Some ports, such as package:databases/postgresql12-server[] and package:lang/php74[] have a DTrace option to enable static probes. The official guide to DTrace is maintained by the Illumos project at http://dtrace.org/guide[DTrace Guide]. After reading this chapter, you will know: * What DTrace is and what features it provides. * Differences between the Solaris(TM) DTrace implementation and the one provided by FreeBSD. * How to enable and use DTrace on FreeBSD. Before reading this chapter, you should: * Understand UNIX(R) and FreeBSD basics (crossref:basics[basics,FreeBSD Basics]). * Have some familiarity with security and how it pertains to FreeBSD (crossref:security[security,Security]). [[dtrace-implementation]] == Implementation Differences While the DTrace in FreeBSD is similar to that found in Solaris(TM), differences do exist. The primary difference is that in FreeBSD, DTrace is implemented as a set of kernel modules and DTrace can not be used until the modules are loaded. To load all of the necessary modules: [source,shell] .... # kldload dtraceall .... Beginning with FreeBSD 10.0-RELEASE, the modules are automatically loaded when `dtrace` is run. FreeBSD uses the `DDB_CTF` kernel option to enable support for loading `CTF` data from kernel modules and the kernel itself. `CTF` is the Solaris(TM) Compact C Type Format which encapsulates a reduced form of debugging information similar to `DWARF` and the venerable stabs. `CTF` data is added to binaries by the `ctfconvert` and `ctfmerge` build tools. The `ctfconvert` utility parses `DWARF``ELF` debug sections created by the compiler and `ctfmerge` merges `CTF``ELF` sections from objects into either executables or shared libraries. Some different providers exist for FreeBSD than for Solaris(TM). Most notable is the `dtmalloc` provider, which allows tracing `malloc()` by type in the FreeBSD kernel. Some of the providers found in Solaris(TM), such as `cpc` and `mib`, are not present in FreeBSD. These may appear in future versions of FreeBSD. Moreover, some of the providers available in both operating systems are not compatible, in the sense that their probes have different argument types. Thus, `D` scripts written on Solaris(TM) may or may not work unmodified on FreeBSD, and vice versa. Due to security differences, only `root` may use DTrace on FreeBSD. Solaris(TM) has a few low level security checks which do not yet exist in FreeBSD. As such, the [.filename]#/dev/dtrace/dtrace# is strictly limited to `root`. DTrace falls under the Common Development and Distribution License (`CDDL`) license. To view this license on FreeBSD, see [.filename]#/usr/src/cddl/contrib/opensolaris/OPENSOLARIS.LICENSE# or view it online at http://opensource.org/licenses/CDDL-1.0[http://opensource.org/licenses/CDDL-1.0]. While a FreeBSD kernel with DTrace support is `BSD` licensed, the `CDDL` is used when the modules are distributed in binary form or the binaries are loaded. [[dtrace-enable]] == Enabling DTrace Support In FreeBSD 9.2 and 10.0, DTrace support is built into the [.filename]#GENERIC# kernel. Users of earlier versions of FreeBSD or who prefer to statically compile in DTrace support should add the following lines to a custom kernel configuration file and recompile the kernel using the instructions in crossref:kernelconfig[kernelconfig,Configuring the FreeBSD Kernel]: [.programlisting] .... options KDTRACE_HOOKS options DDB_CTF makeoptions DEBUG=-g makeoptions WITH_CTF=1 .... Users of the AMD64 architecture should also add this line: [.programlisting] .... options KDTRACE_FRAME .... This option provides support for `FBT`. While DTrace will work without this option, there will be limited support for function boundary tracing. Once the FreeBSD system has rebooted into the new kernel, or the DTrace kernel modules have been loaded using `kldload dtraceall`, the system will need support for the Korn shell as the DTrace Toolkit has several utilities written in `ksh`. Make sure that the package:shells/ksh93[] package or port is installed. It is also possible to run these tools under package:shells/pdksh[] or package:shells/mksh[]. -Finally, install the current DTrace Toolkit, a collection of ready-made scripts for collecting system information. There are scripts to check open files, memory, `CPU` usage, and a lot more. FreeBSD 10 installs a few of these scripts into [.filename]#/usr/share/dtrace#. On other FreeBSD versions, or to install the full DTrace Toolkit, use the package:sysutils/DTraceToolkit[] package or port. +Finally, install the current DTrace Toolkit, a collection of ready-made scripts for collecting system information. There are scripts to check open files, memory, `CPU` usage, and a lot more. FreeBSD 10 installs a few of these scripts into [.filename]#/usr/share/dtrace#. On other FreeBSD versions, or to install the full DTrace Toolkit, use the package:sysutils/dtrace-toolkit[] package or port. [NOTE] ==== The scripts found in [.filename]#/usr/share/dtrace# have been specifically ported to FreeBSD. Not all of the scripts found in the DTrace Toolkit will work as-is on FreeBSD and some scripts may require some effort in order for them to work on FreeBSD. ==== The DTrace Toolkit includes many scripts in the special language of DTrace. This language is called the D language and it is very similar to C++. An in depth discussion of the language is beyond the scope of this document. It is covered extensively in the http://www.dtrace.org/guide[Illumos Dynamic Tracing Guide]. [[dtrace-using]] == Using DTrace DTrace scripts consist of a list of one or more _probes_, or instrumentation points, where each probe is associated with an action. Whenever the condition for a probe is met, the associated action is executed. For example, an action may occur when a file is opened, a process is started, or a line of code is executed. The action might be to log some information or to modify context variables. The reading and writing of context variables allows probes to share information and to cooperatively analyze the correlation of different events. To view all probes, the administrator can execute the following command: [source,shell] .... # dtrace -l | more .... Each probe has an `ID`, a `PROVIDER` (dtrace or fbt), a `MODULE`, and a `FUNCTION NAME`. Refer to man:dtrace[1] for more information about this command. The examples in this section provide an overview of how to use two of the fully supported scripts from the DTrace Toolkit: the [.filename]#hotkernel# and [.filename]#procsystime# scripts. The [.filename]#hotkernel# script is designed to identify which function is using the most kernel time. It will produce output similar to the following: [source,shell] .... # cd /usr/local/share/dtrace-toolkit # ./hotkernel Sampling... Hit Ctrl-C to end. .... As instructed, use the kbd:[Ctrl+C] key combination to stop the process. Upon termination, the script will display a list of kernel functions and timing information, sorting the output in increasing order of time: [source,shell] .... kernel`_thread_lock_flags 2 0.0% 0xc1097063 2 0.0% kernel`sched_userret 2 0.0% kernel`kern_select 2 0.0% kernel`generic_copyin 3 0.0% kernel`_mtx_assert 3 0.0% kernel`vm_fault 3 0.0% kernel`sopoll_generic 3 0.0% kernel`fixup_filename 4 0.0% kernel`_isitmyx 4 0.0% kernel`find_instance 4 0.0% kernel`_mtx_unlock_flags 5 0.0% kernel`syscall 5 0.0% kernel`DELAY 5 0.0% 0xc108a253 6 0.0% kernel`witness_lock 7 0.0% kernel`read_aux_data_no_wait 7 0.0% kernel`Xint0x80_syscall 7 0.0% kernel`witness_checkorder 7 0.0% kernel`sse2_pagezero 8 0.0% kernel`strncmp 9 0.0% kernel`spinlock_exit 10 0.0% kernel`_mtx_lock_flags 11 0.0% kernel`witness_unlock 15 0.0% kernel`sched_idletd 137 0.3% 0xc10981a5 42139 99.3% .... This script will also work with kernel modules. To use this feature, run the script with `-m`: [source,shell] .... # ./hotkernel -m Sampling... Hit Ctrl-C to end. ^C MODULE COUNT PCNT 0xc107882e 1 0.0% 0xc10e6aa4 1 0.0% 0xc1076983 1 0.0% 0xc109708a 1 0.0% 0xc1075a5d 1 0.0% 0xc1077325 1 0.0% 0xc108a245 1 0.0% 0xc107730d 1 0.0% 0xc1097063 2 0.0% 0xc108a253 73 0.0% kernel 874 0.4% 0xc10981a5 213781 99.6% .... The [.filename]#procsystime# script captures and prints the system call time usage for a given process `ID` (`PID`) or process name. In the following example, a new instance of [.filename]#/bin/csh# was spawned. Then, [.filename]#procsystime# was executed and remained waiting while a few commands were typed on the other incarnation of `csh`. These are the results of this test: [source,shell] .... # ./procsystime -n csh Tracing... Hit Ctrl-C to end... ^C Elapsed Times for processes csh, SYSCALL TIME (ns) getpid 6131 sigreturn 8121 close 19127 fcntl 19959 dup 26955 setpgid 28070 stat 31899 setitimer 40938 wait4 62717 sigaction 67372 sigprocmask 119091 gettimeofday 183710 write 263242 execve 492547 ioctl 770073 vfork 3258923 sigsuspend 6985124 read 3988049784 .... As shown, the `read()` system call used the most time in nanoseconds while the `getpid()` system call used the least amount of time. diff --git a/documentation/content/mn/books/handbook/dtrace/_index.adoc b/documentation/content/mn/books/handbook/dtrace/_index.adoc index e8d9439e88..519ddd2018 100644 --- a/documentation/content/mn/books/handbook/dtrace/_index.adoc +++ b/documentation/content/mn/books/handbook/dtrace/_index.adoc @@ -1,263 +1,263 @@ --- title: Бүлэг 26. DTrace part: хэсэг III. Системийн Удирдлага prev: books/handbook/cutting-edge next: books/handbook/partiv --- [[dtrace]] = DTrace :doctype: book :toc: macro :toclevels: 1 :icons: font :sectnums: :sectnumlevels: 6 :source-highlighter: rouge :experimental: :skip-front-matter: :toc-title: Гарчиг :table-caption: Хүснэгт :figure-caption: Зураг :example-caption: Жишээ :xrefstyle: basic :relfileprefix: ../ :outfilesuffix: :sectnumoffset: 26 ifeval::["{backend}" == "html5"] :imagesdir: ../../../images/books/handbook/dtrace/ endif::[] ifeval::["{backend}" == "pdf"] :imagesdir: ../../../../static/images/books/handbook/dtrace/ endif::[] ifeval::["{backend}" == "epub3"] :imagesdir: ../../../../static/images/books/handbook/dtrace/ endif::[] include::shared/authors.adoc[] include::shared/releases.adoc[] include::shared/mn/mailing-lists.adoc[] include::shared/mn/teams.adoc[] include::shared/mn/urls.adoc[] toc::[] [[dtrace-synopsis]] == Ерөнхий агуулга DTrace буюу Dynamic Tracing (Динамик Мөрдөлт) нь үйлдвэрлэлд ашиглаж байгаа болон ашиглахын өмнөх системүүдэд үйл ажиллагааны саад тотгоруудыг олоход зориулагдсан Sun(TM)-с хөгжүүлсэн хэрэгсэл юм. Энэ нь ямар ч тохиолдолд дибаг хийгч хэрэгсэл биш боловч үйл ажиллагаа болон бусад асуудлуудыг цаг тухайд нь олох системийн анализ хийхэд зориулагдсан хэрэгсэл юм. DTrace нь системийн асуудлуудыг оношлоход зориулагдсан сэтгэл хөдлөм боломжуудтай гайхамшигтай профиль хийгч хэрэгсэл юм. Энэ нь өөрийн боломжуудыг ашиглахын тулд өмнө нь бичигдсэн скриптүүдийг ажиллуулж бас болдог. Хэрэглэгчид нь тусгай зориулалтаар өөрсдийн профиль хийлтийг өөрчлөх боломжтой DTrace D хэлийг ашиглан бүр өөрсдийн хэрэгслүүдийг зохиож болох юм. Энэ бүлгийг уншсаны дараа, та дараах зүйлсийг мэдэх болно: * DTrace гэж юу болох ямар ямар боломжуудаар хангадаг талаар. * Solaris(TM)-ийн DTrace шийдэл болон FreeBSD-д байгаа хоёрын хоорондын ялгаанууд. * FreeBSD дээр DTrace-ийг хэрхэн идэвхжүүлж ашиглах талаар. Энэ бүлгийг уншихаасаа өмнө та дараах зүйлсийг гүйцэтгэх хэрэгтэй: * UNIX(R) болон FreeBSD-ийн үндсүүдийг (crossref:basics[basics,Юниксийн үндэс]) ойлгох. * Цөмийн тохиргоо/эмхэтгэлтийн (crossref:kernelconfig[kernelconfig,FreeBSD цөмийг тохируулах нь]) үндсийг мэддэг байх. * Аюулгүй байдлын талаар болон энэ нь FreeBSD-д хэрхэн хамааралтай байх талаар зарим ойлголттой байх (crossref:security[security,Аюулгүй байдал]). * FreeBSD эхийг хэрхэн авч дахин бүтээх талаар ойлгох (crossref:cutting-edge[updating-upgrading,FreeBSD-г шинэчилж сайжруулах нь]). [WARNING] ==== Энэ боломж нь туршилтын гэж тооцогддог. Зарим тохиргоонууд ажиллагааны хувьд дутуу, зарим хэсэг нь ерөөсөө ажиллахгүй байж болох юм. Цагийн явцад энэ боломж нь үйлдвэрлэлд ашиглагдахад бэлэн гэж тооцогдох бөгөөд энэ баримт нь тэр тохиолдолд таарахаар өөрчлөгдөх болно. ==== [[dtrace-implementation]] == Шийдлийн ялгаанууд FreeBSD дээрх DTrace нь Solaris(TM)-д байдагтай маш төстэй боловч цааш үргэлжлүүлэхээсээ өмнө тайлбарлах ёстой ялгаанууд байдаг. Хэрэглэгчдийн мэдрэх үндсэн ялгаа нь FreeBSD дээр DTrace нь тусгайлан идэвхжүүлэх ёстой байдаг. DTrace нь зөв ажиллахын тулд идэвхжүүлсэн байх ёстой цөмийн тохиргоонууд болон модулиуд байдаг. Эдгээрийг дараа тайлбарлах болно. CTF өгөгдлийг цөмийн модуль болон цөмөөс өөрөөс нь дуудахад зориулсан дэмжлэгийг идэвхжүүлэх цөмийн `DDB_CTF` тохиргоо байдаг. CTF нь Solaris(TM)-ийн Compact C Type буюу Шахмал C Төрөл бөгөөд DWARF болон venerable stab-уудтай (хүндтэй хатгалтууд) адил дибаг мэдээллийн багасгасан хэлбэрийг агуулдаг. Энэ CTF өгөгдөл нь `ctfconvert` болон `ctfmerge` гэсэн бүтээх хэрэгслүүдээр хоёртын файлуудад нэмэгддэг. `ctfconvert` хэрэгсэл нь эмхэтгэгчийн үүсгэсэн DWARFELF дибаг хэсгүүдийг задлан ялгаж `ctfmerge` нь обьектуудын CTFELF хэсгүүдийг ажилладаг файлууд юм уу эсвэл хуваалцсан сангууд руу нийлүүлдэг. Цөм болон FreeBSD бүтээлтэд зориулж үүнийг хэрхэн идэвхжүүлэх талаар дэлгэрэнгүй тайлбар удахгүй бичигдэх болно. Solaris(TM)-д байдгаас өөр хангагчид FreeBSD-д байдаг. Хамгийн алдартай нь `dtmalloc` хангагч бөгөөд FreeBSD цөмд `malloc()`-ийг төрлөөр нь мөрдөх боломжийг бүрдүүлдэг. Зөвхөн `root` DTrace-ийг FreeBSD дээр ашиглаж болно. Энэ нь аюулгүй байдлын ялгаатай холбоотой бөгөөд FreeBSD-д байдаггүй хэдэн доод түвшний аюулгүй байдлын шалгалтууд Solaris(TM)-д байдаг. Тийм болохоор [.filename]#/dev/dtrace/dtrace# нь зөвхөн `root` хэрэглэгчээр хатуу хязгаарлагдсан байдаг. Төгсгөлд нь DTrace програм хангамж нь Sun(TM)-ий CDDL лицензийн доор байдаг. `Common Development and Distribution License` буюу Нийтлэг Хөгжүүлэлт ба Түгээлтийн Лиценз нь FreeBSD-тэй цуг ирдэг бөгөөд [.filename]#/usr/src/cddl/contrib/opensolaris/OPENSOLARIS.LICENSE# юм уу эсвэл онлайн хэлбэрээр http://www.opensolaris.org/os/licensing[http://www.opensolaris.org/os/licensing] хаягаас харж болно. Энэ лиценз нь DTrace тохиргоотой FreeBSD цөм нь BSD лицензтэй хэвээр гэсэн үг боловч модулиуд нь хоёртын хэлбэрээр түгээгдэх үед юм уу эсвэл хоёртын файлууд дуудагдсан үед CDDL нь хүчин төгөлдөр болдог. [[dtrace-enable]] == DTrace дэмжлэгийг идэвхжүүлэх DTrace-д зориулсан дэмжлэгийг идэвхжүүлэхийн тулд дараах мөрүүдийг цөмийн тохиргооны файлд нэмнэ: [.programlisting] .... options KDTRACE_HOOKS options DDB_CTF .... [NOTE] ==== AMD64 архитектурын хэрэглэгчид өөрсдийн цөмийн тохиргооны файлдаа дараах мөрийг нэмэхийг хүсэх болно: [.programlisting] .... options KDTRACE_FRAME .... Энэ тохиргоо нь FBT боломжид зориулсан дэмжлэгийг хангадаг. DTrace нь энэ тохиргоогүйгээр ажилладаг боловч функцийн хязгаарын мөрдөлтөд зориулсан дэмжлэг хязгаарлагдмал байх болно. ==== Бүх эх CTF тохиргоонуудтай дахин бүтээгдэж суулгагдсан байх ёстой. Ингэхийн тул FreeBSD-ийн эхийг доорх тушаалуудыг ашиглан дахин бүтээнэ: [source,shell] .... # cd /usr/src # make WITH_CTF=1 kernel .... Системийг дахин ачаалах хэрэгтэй. Дахин ачаалж шинэ цөмийг санах ойд дуудагдсаны дараа Korn бүрхүүлийн дэмжлэгийг нэмэх хэрэгтэй. DTrace хэрэгслүүд нь `ksh` дээр бичигдсэн хэд хэдэн хэрэгслүүдтэй болохоор энэ нь хэрэгтэй юм. package:shells/ksh93[]-г суулгах хэрэгтэй. Эдгээр хэрэгслүүдийг package:shells/pdksh[] эсвэл package:shells/mksh[] дээр ажиллуулж бас болно. -Төгсгөлд нь одоогийн DTrace хэрэгслүүдийг олж авах хэрэгтэй. Хэрэв FreeBSD 10 бол DTrace хэрэгслүүдийг [.filename]#/usr/shared/dtrace# байрлалаас олж болно. Үгүй бол DTrace хэрэгслүүдийг package:sysutils/DTraceToolkit[] портоос суулгаж болно. +Төгсгөлд нь одоогийн DTrace хэрэгслүүдийг олж авах хэрэгтэй. Хэрэв FreeBSD 10 бол DTrace хэрэгслүүдийг [.filename]#/usr/shared/dtrace# байрлалаас олж болно. Үгүй бол DTrace хэрэгслүүдийг package:sysutils/dtrace-toolkit[] портоос суулгаж болно. [[dtrace-using]] == DTrace-г ашиглах DTrace боломжийг ашиглахаас өмнө DTrace төхөөрөмж байх хэрэгтэй. Төхөөрөмжийг дуудахын тулд дараах тушаалыг ажиллуулна: [source,shell] .... # kldload dtraceall .... DTrace дэмжлэг одоо боломжтой болсон байх ёстой. Бүх шалгалтыг харахын тулд администратор дараах тушаалыг одоо ажиллуулж болно: [source,shell] .... # dtrace -l | more .... Дэлгэцийн буфферийг түргэн дүүргэх болохоор бүх гаралтыг `more` хэрэгсэл рүү дамжуулдаг. Энд хүрэхэд DTrace-ийг ажиллаж байна гэж үзнэ. Одоо уг хэрэгслийг шалгаж үзэх цаг боллоо. Уг хэрэгсэл нь системийн мэдээллийг цуглуулахын тулд DTrace-тэй цуг ажиллуулж болох ашиглахад бэлэн скриптүүдийн цуглуулга юм. Нээлттэй файлууд, санах ой,CPU-ийн хэрэглээ болон өөр олон зүйлсийг шалгах скриптүүд байдаг. Скриптүүдийг дараах тушаалаар задалж болно: [source,shell] .... # gunzip -c DTraceToolkit* | tar xvf - .... `cd` ашиглан тэр сан руу өөрчилж жижиг үсгээр бичигдсэн нэртэй бүх файлууд дээр ажиллуулах зөвшөөрлүүдийг `755` руу өөрчлөх хэрэгтэй. Эдгээр бүх скриптүүдийн агуулгад өөрчлөлт хийх хэрэгтэй болно. [.filename]#/usr/bin/ksh# гэснийг [.filename]#/usr/local/bin/ksh# болгох ёстой бөгөөд [.filename]#/usr/bin/sh#-ийг [.filename]#/bin/sh# болгон ашиглахаар, төгсгөлд нь [.filename]#/usr/bin/perl#-г [.filename]#/usr/local/bin/perl# болгон ашиглахаар болгож өөрчлөх хэрэгтэй. [IMPORTANT] ==== FreeBSD дээрх DTrace дэмжлэг нь _бүрэн бус_ бөгөөд _туршилтын_ гэдгийг уншигчид сануулах нь ухаалаг болох юм. Эдгээр скриптүүдийн олонхи нь ажиллахгүй бөгөөд тэдгээр нь хэтэрхий Solaris(TM)-д тусгайлан зориулсан эсвэл одоо дэмжигдээгүй байгаа шалгалтуудыг ашигладаг. ==== Үүнийг бичиж байх үед DTrace хэрэгслийн зөвхөн хоёр скрипт FreeBSD дээр бүрэн дэмжигдсэн: эдгээр нь [.filename]#hotkernel# болон [.filename]#procsystime# скриптүүд юм. Эдгээр хоёрыг бид энэ бүлгийн дараагийн хэсгүүдэд авч үзэх болно. [.filename]#hotkernel# нь аль функц цөмийн ихэнх хугацааг ашиглаж байгааг илрүүлэхээр хийгдсэн. Хэвийнээр ажиллуулахад энэ нь дараахтай төстэй гаралтыг харуулах болно: [source,shell] .... # cd /usr/shared/dtrace/toolkit # ./hotkernel Sampling... Hit Ctrl-C to end. .... Системийн администратор процессийг зогсоохын тулд kbd:[Ctrl+C] товчлуурын хослолыг ашиглах ёстой. Зогсоосны дараа скрипт нь цөмийн функцуудын жагсаалт болон хугацааны мэдээллийг харуулах бөгөөд гаралтыг хугацааны ихэссэн дарааллаар эрэмбэлж харуулна: [source,shell] .... kernel`_thread_lock_flags 2 0.0% 0xc1097063 2 0.0% kernel`sched_userret 2 0.0% kernel`kern_select 2 0.0% kernel`generic_copyin 3 0.0% kernel`_mtx_assert 3 0.0% kernel`vm_fault 3 0.0% kernel`sopoll_generic 3 0.0% kernel`fixup_filename 4 0.0% kernel`_isitmyx 4 0.0% kernel`find_instance 4 0.0% kernel`_mtx_unlock_flags 5 0.0% kernel`syscall 5 0.0% kernel`DELAY 5 0.0% 0xc108a253 6 0.0% kernel`witness_lock 7 0.0% kernel`read_aux_data_no_wait 7 0.0% kernel`Xint0x80_syscall 7 0.0% kernel`witness_checkorder 7 0.0% kernel`sse2_pagezero 8 0.0% kernel`strncmp 9 0.0% kernel`spinlock_exit 10 0.0% kernel`_mtx_lock_flags 11 0.0% kernel`witness_unlock 15 0.0% kernel`sched_idletd 137 0.3% 0xc10981a5 42139 99.3% .... Энэ скрипт нь цөмийн модулиудтай бас ажилладаг. Энэ боломжийг ашиглахын тулд скриптийг `-m` өгөгдөлтэй ажиллуулах хэрэгтэй: [source,shell] .... # ./hotkernel -m Sampling... Hit Ctrl-C to end. ^C MODULE COUNT PCNT 0xc107882e 1 0.0% 0xc10e6aa4 1 0.0% 0xc1076983 1 0.0% 0xc109708a 1 0.0% 0xc1075a5d 1 0.0% 0xc1077325 1 0.0% 0xc108a245 1 0.0% 0xc107730d 1 0.0% 0xc1097063 2 0.0% 0xc108a253 73 0.0% kernel 874 0.4% 0xc10981a5 213781 99.6% .... [.filename]#procsystime# скрипт нь өгөгдсөн PID эсвэл процессийн хувьд системийн дуудлагын цагийн хэрэглээг авч хэвлэн харуулдаг. Дараах жишээн дээр [.filename]#/bin/csh#-ийн шинэ хуулбар ажиллуулсан. [.filename]#procsystime#-ийг ажиллуулсан бөгөөд өөр нэг `csh` дээр цөөн хэдэн тушаалыг бичтэл энэ нь хүлээх горимд орсон. Энэ тестийн үр дүн энд байна: [source,shell] .... # ./procsystime -n csh Tracing... Hit Ctrl-C to end... ^C Elapsed Times for processes csh, SYSCALL TIME (ns) getpid 6131 sigreturn 8121 close 19127 fcntl 19959 dup 26955 setpgid 28070 stat 31899 setitimer 40938 wait4 62717 sigaction 67372 sigprocmask 119091 gettimeofday 183710 write 263242 execve 492547 ioctl 770073 vfork 3258923 sigsuspend 6985124 read 3988049784 .... Энд үзүүлснээр `read()` системийн дуудлага ихэнх цагийг, `getpid()` системийн дуудлага хамгийн бага хугацааг ашигласныг наносекундаар харуулж байна. [[dtrace-language]] == D хэл DTrace хэрэгсэл нь DTrace-ийн тусгай хэл дээр байдаг олон скриптүүдийг агуулдаг. Энэ хэл нь Sun(TM)-ийн баримтаар "D хэл" гэгддэг бөгөөд C++ хэлтэй тун төстэй юм. Энэ хэлний талаарх гүнзгий хэлэлцүүлэг нь энэ баримтаас хүрээнээс гадна юм. Энэ нь http://wikis.oracle.com/display/DTrace/Documentation[http://wikis.oracle.com/display/DTrace/Documentation] хаяг дээр дэлгэрэнгүй хэлэлцэгдсэн байдаг. diff --git a/documentation/content/nl/books/handbook/dtrace/_index.adoc b/documentation/content/nl/books/handbook/dtrace/_index.adoc index b51b1a7fd1..661159cec3 100644 --- a/documentation/content/nl/books/handbook/dtrace/_index.adoc +++ b/documentation/content/nl/books/handbook/dtrace/_index.adoc @@ -1,263 +1,263 @@ --- title: Hoofdstuk 25. DTrace part: Deel III. Systeembeheer prev: books/handbook/cutting-edge next: books/handbook/partiv --- [[dtrace]] = DTrace :doctype: book :toc: macro :toclevels: 1 :icons: font :sectnums: :sectnumlevels: 6 :source-highlighter: rouge :experimental: :skip-front-matter: :toc-title: Inhoudsopgave :table-caption: Tabel :figure-caption: Afbeelding :example-caption: Voorbeeld :xrefstyle: basic :relfileprefix: ../ :outfilesuffix: :sectnumoffset: 25 ifeval::["{backend}" == "html5"] :imagesdir: ../../../images/books/handbook/dtrace/ endif::[] ifeval::["{backend}" == "pdf"] :imagesdir: ../../../../static/images/books/handbook/dtrace/ endif::[] ifeval::["{backend}" == "epub3"] :imagesdir: ../../../../static/images/books/handbook/dtrace/ endif::[] include::shared/authors.adoc[] include::shared/releases.adoc[] include::shared/nl/mailing-lists.adoc[] include::shared/nl/teams.adoc[] include::shared/nl/urls.adoc[] toc::[] [[dtrace-synopsis]] == Overzicht DTrace, ook bekend als Dynamic Tracing, was ontwikkeld door Sun(TM) als een gereedschap om prestatie-bottlenecks in productie- en preproductiesystemen op te sporen. Het is in geen enkel opzicht een debug-gereedschap, maar een gereedschap voor real-time analyse om prestatie- en andere zaken op te sporen. DTrace is een opmerkelijk profileringsgereedschap, met een indrukwekkende verzameling mogelijkheden om systeemzaken te diagnosticeren. Het kan ook worden gebruikt om vooraf geschreven scripts te draaien om zo voordeel te halen uit de mogelijkheden. Gebruikers kunnen zelfs hun eigen middelen schrijven door gebruik te maken van de DTrace D Language, wat ze in staat stelt om hun profilering aan te passen aan hun specifieke behoeften. Na het lezen van dit hoofdstuk weet u: * Wat DTrace is en welke mogelijkheden het biedt. * De verschillen tussen de DTrace-implementatie van Solaris(TM) en degene die door FreeBSD wordt aangeboden. * Hoe DTrace op FreeBSD aan te zetten en te gebruiken. Voordat u dit hoofdstuk leest, dient u: * De beginselen van UNIX(R) en FreeBSD te begrijpen (crossref:basics[basics,UNIX® beginselen]). * Bekend te zijn met de beginselen van kernelconfiguratie en -compilatie (crossref:kernelconfig[kernelconfig,De FreeBSD-kernel instellen]). * Wat bekendheid te hebben met beveiliging en hoe het zich verhoudt tot FreeBSD (crossref:security[security,Beveiliging]). * Te begrijpen hoe de broncode van FreeBSD te verkrijgen en te herbouwen (crossref:cutting-edge[updating-upgrading,FreeBSD updaten en upgraden]). [WARNING] ==== Deze mogelijkheid wordt als experimenteel beschouwd. Van sommige opties kan er functionaliteit ontbreken, andere delen kunnen in het geheel niet werken. In de loop der tijd zal deze mogelijkheid als productierijp worden beschouwd en zal deze documentatie worden aangepast om die situatie te representeren. ==== [[dtrace-implementation]] == Implementatieverschillen Hoewel DTrace in FreeBSD erg lijkt op degene die in Solaris(TM) zit, zijn er verschillen die uitgelegd moeten worden voordat er verder wordt gegaan. Het primaire verschil dat gebruikers zullen zien is dat DTrace specifiek moet worden aangezet op FreeBSD. Er zijn kernelopties en modulen die aangezet moeten worden om DTrace juist te laten werken. Deze zullen later worden uitgelegd. Er is een kerneloptie `DDB_CTF` die gebruikt wordt om ondersteuning voor het laden van CTF-gegevens van kernelmodulen en de kernel zelf. CTF is het Compact C Type Format van Solaris(TM) welke een beperkte vorm van debuginformatie bevat die vergelijkbaar is met DWARF en de befaamde stabs. Deze CTF-gegevens worden door de bouwmiddelen `ctfconvert` en `ctfmerge` aan de binairen toegevoegd. Het hulpmiddel `ctfconvert` parseert DWARFELF-debug-secties die door de compiler zijn aangemaakt en `ctfmerge` voegt CTFELF-secties van objecten samen in hun executables of gedeelde bibliotheken. Meer informatie over hoe dit voor de bouw van de kernel en FreeBSD aan te zetten komt eraan. Sommige aanbieders voor FreeBSD verschillen van die voor Solaris(TM). De meest opmerkelijke is de aanbieder `dtmalloc`, welke het volgen van `malloc()` op soort in de FreeBSD-kernel toestaat. Alleen `root` mag DTrace op FreeBSD gebruiken. Dit heeft te maken met beveiligingsverschillen, Solaris(TM) heeft enkele beveiligingscontroles op laag niveau die nog niet bestaan in FreeBSD. Hierom is [.filename]#/dev/dtrace/dtrace# strikt beperkt tot `root`. Tenslotte valt de DTrace-software onder de CDDL-licentie van Sun(TM). De `Common Development and Distribution License` wordt bij FreeBSD geleverd, zie [.filename]#/usr/src/cddl/contrib/opensolaris/OPENSOLARIS.LICENSE# of bekijk het online op http://www.opensolaris.org/os/licensing[http://www.opensolaris.org/os/licensing]. Deze licentie houdt in dat een FreeBSD-kernel met de DTrace-opties nog steeds onder de BSD-licentie valt; de CDDL komt echter op de proppen wanneer de modulen in binaire vorm worden verspreid, of wanneer de binairen zijn geladen. [[dtrace-enable]] == Ondersteuning voor DTrace aanzetten Voeg de volgende regels toe aan het kernelinstellingenbestand om ondersteuning voor DTrace aan te zetten: [.programlisting] .... options KDTRACE_HOOKS options DDB_CTF .... [NOTE] ==== Gebruikers van de AMD64-architectuur zullen de volgende regel aan hun kernelinstellingenbestand willen toevoegen: [.programlisting] .... options KDTRACE_FRAME .... Deze optie biedt ondersteuning voor de mogelijkheid FBT. DTrace zal zonder deze optie werken; er zal echter beperkte ondersteuning zijn voor het volgen van functiegrenzen. ==== Alle broncode moet herbouwd en geherinstalleerd worden met de CTF-opties. Om deze taak te volbrengen, wordt de FreeBSD-broncode herbouwd met: [source,shell] .... # cd /usr/src # make WITH_CTF=1 kernel .... Het systeem moet opnieuw gestart worden. Nadat opnieuw is opgestart en de nieuwe kernel in het geheugen is geladen, dient ondersteuning voor de Korn-shell te worden toegevoegd. Dit is nodig omdat de verschillende hulpmiddelen van DTraceToolkit in `ksh` zijn geschreven. Installeer package:shells/ksh93[]. Het is ook mogelijk om deze hulpmiddelen in package:shells/pdksh[] of package:shells/mksh[] te draaien. -Als laatste dient de huidige DTraceToolkit verkregen te worden. Indien u FreeBSD 10 draait, vindt u de DTraceToolkit in [.filename]#/usr/shared/dtrace#. In andere gevallen kunt u de DTraceToolkit installeren via de port package:sysutils/DTraceToolkit[]. +Als laatste dient de huidige DTraceToolkit verkregen te worden. Indien u FreeBSD 10 draait, vindt u de DTraceToolkit in [.filename]#/usr/shared/dtrace#. In andere gevallen kunt u de DTraceToolkit installeren via de port package:sysutils/dtrace-toolkit[]. [[dtrace-using]] == DTrace gebruiken Voordat er gebruik wordt gemaakt van de functionaliteit van DTrace, moet het DTrace-apparaat bestaan. Geef het volgende commando om het apparaat te laten: [source,shell] .... # kldload dtraceall .... Ondersteuning van DTrace zou nu beschikbaar moeten zijn. De beheerder kan het volgende commando uitvoeren om alle sondes te bekijken: [source,shell] .... # dtrace -l | more .... Alle uitvoer wordt aan het hulpmiddel `more` doorgegeven omdat het snel de schermbuffer zal laten overstromen. DTrace kan nu als werkend worden beschouwd. Het is nu tijd om de gereedschapskist te bekijken. De gereedschapskist is een verzameling van kant-en-klare scripts die met DTrace gedraaid kunnen worden om informatie over het systeem te verzamelen. Er zijn scripts om open bestanden, geheugen, CPU-gebruik, en nog veel meer te controleren. Pak de scripts uit met het volgende commando: [source,shell] .... # gunzip -c DTraceToolkit* | tar xvf - .... Ga naar die map met `cd` en zet de uitvoerpermissies voor alle bestanden waarvan de naam uit kleine letters bestaat, op `755`. De inhoud van al deze scripts moet veranderd worden. Degenen die naar [.filename]#/usr/bin/ksh# verwijzen dienen naar [.filename]#/usr/local/bin/ksh# te verwijzen, de anderen die [.filename]#/usr/bin/sh# gebruiken dienen gewijzigd te worden om [.filename]#/bin/sh# te gebruiken, en tenslotte dienen degenen die [.filename]#/usr/bin/perl# gebruiken veranderd te worden om [.filename]#/usr/local/bin/perl# te gebruiken. [IMPORTANT] ==== Op dit moment is het voorzichtig om de lezer eraan te herinneren dat de ondersteuning voor DTrace in FreeBSD _niet compleet_ en _experimenteel_ is. Veel van deze scripts zullen niet werken omdat ze of te Solaris(TM)-specifiek zijn of omdat ze sondes gebruiken die momenteel niet ondersteund worden. ==== Op het moment van schrijven worden slechts twee scripts van de DTrace Toolkit volledig ondersteund in FreeBSD: de scripts [.filename]#hotkernel# en [.filename]#procsystime#. Dit zijn de twee die we in de volgende gedeelten van deze sectie zullen bekijken. De [.filename]#hotkernel# is ontworpen om te identificeren welke functie de meeste kerneltijd gebruikt. Als het normaal gedraaid wordt, zal het uitvoer die op de volgende lijkt produceren: [source,shell] .... # cd /usr/shared/dtrace/toolkit # ./hotkernel Sampling... Hit Ctrl-C to end. .... De systeembeheerder moet de toetsencombinatie kbd:[Ctrl+C] gebruiken om het proces te stoppen. Nadat het gestopt is, zal het script een lijst van kernelfuncties en timinginformatie weergeven, waarbij de uitvoer in volgorde van toenemende tijd is gesorteerd: [source,shell] .... kernel`_thread_lock_flags 2 0.0% 0xc1097063 2 0.0% kernel`sched_userret 2 0.0% kernel`kern_select 2 0.0% kernel`generic_copyin 3 0.0% kernel`_mtx_assert 3 0.0% kernel`vm_fault 3 0.0% kernel`sopoll_generic 3 0.0% kernel`fixup_filename 4 0.0% kernel`_isitmyx 4 0.0% kernel`find_instance 4 0.0% kernel`_mtx_unlock_flags 5 0.0% kernel`syscall 5 0.0% kernel`DELAY 5 0.0% 0xc108a253 6 0.0% kernel`witness_lock 7 0.0% kernel`read_aux_data_no_wait 7 0.0% kernel`Xint0x80_syscall 7 0.0% kernel`witness_checkorder 7 0.0% kernel`sse2_pagezero 8 0.0% kernel`strncmp 9 0.0% kernel`spinlock_exit 10 0.0% kernel`_mtx_lock_flags 11 0.0% kernel`witness_unlock 15 0.0% kernel`sched_idletd 137 0.3% 0xc10981a5 42139 99.3% .... Het script werkt ook met kernelmodules. Draai het script met de vlag `-m` om deze mogelijkheid te gebruiken: [source,shell] .... # ./hotkernel -m Sampling... Hit Ctrl-C to end. ^C MODULE COUNT PCNT 0xc107882e 1 0.0% 0xc10e6aa4 1 0.0% 0xc1076983 1 0.0% 0xc109708a 1 0.0% 0xc1075a5d 1 0.0% 0xc1077325 1 0.0% 0xc108a245 1 0.0% 0xc107730d 1 0.0% 0xc1097063 2 0.0% 0xc108a253 73 0.0% kernel 874 0.4% 0xc10981a5 213781 99.6% .... Het script [.filename]#procsystime# vangt en beeldt het tijdsgebruik van systeemaanroepen af voor een gegeven PID of procesnaam. In het volgende voorbeeld wordt er een nieuwe instantie van [.filename]#/bin/csh# gedraaid. Het [.filename]#procsystime# werd uitgevoerd en bleef wachten terwijl er enkele commando's op de andere instantie van `csh` werden getypt. Dit zijn de resultaten van deze test: [source,shell] .... # ./procsystime -n csh Tracing... Hit Ctrl-C to end... ^C Elapsed Times for processes csh, SYSCALL TIME (ns) getpid 6131 sigreturn 8121 close 19127 fcntl 19959 dup 26955 setpgid 28070 stat 31899 setitimer 40938 wait4 62717 sigaction 67372 sigprocmask 119091 gettimeofday 183710 write 263242 execve 492547 ioctl 770073 vfork 3258923 sigsuspend 6985124 read 3988049784 .... Zoals te zien is, lijkt de systeemaanroep `read()` de meeste tijd in nanoseconden te gebruiken en gebruikte de systeemaanroep `getpid()` de minste hoeveelheid tijd. [[dtrace-language]] == De taal D De DTrace-gereedschapskist bevat vele scripts in de speciale taal van DTrace. Deze taal wordt "de taal D" genoemd door de documentatie van Sun(TM), en lijkt sterk op C++. Een diepgaande discussie over de taal valt buiten het bereik van dit document. Het wordt uitgebreid behandeld op http://wikis.oracle.com/display/DTrace/Documentation[http://wikis.oracle.com/display/DTrace/Documentation]. diff --git a/documentation/content/pl/books/handbook/dtrace/_index.adoc b/documentation/content/pl/books/handbook/dtrace/_index.adoc index b5a10b3301..e78b0404d7 100644 --- a/documentation/content/pl/books/handbook/dtrace/_index.adoc +++ b/documentation/content/pl/books/handbook/dtrace/_index.adoc @@ -1,233 +1,233 @@ --- title: Rozdział 25. DTrace part: Część III. Administracja systemem prev: books/handbook/cutting-edge next: books/handbook/usb-device-mode --- [[dtrace]] = DTrace :doctype: book :toc: macro :toclevels: 1 :icons: font :sectnums: :sectnumlevels: 6 :source-highlighter: rouge :experimental: :skip-front-matter: :toc-title: Spis treści :table-caption: Tabela :figure-caption: Rysunek :example-caption: Przykład :xrefstyle: basic :relfileprefix: ../ :outfilesuffix: :sectnumoffset: 25 ifeval::["{backend}" == "html5"] :imagesdir: ../../../images/books/handbook/dtrace/ endif::[] ifeval::["{backend}" == "pdf"] :imagesdir: ../../../../static/images/books/handbook/dtrace/ endif::[] ifeval::["{backend}" == "epub3"] :imagesdir: ../../../../static/images/books/handbook/dtrace/ endif::[] include::shared/authors.adoc[] include::shared/releases.adoc[] include::shared/pl/mailing-lists.adoc[] include::shared/pl/urls.adoc[] include::shared/pl/teams.adoc[] toc::[] [[dtrace-synopsis]] == Synopsis DTrace, also known as Dynamic Tracing, was developed by Sun(TM) as a tool for locating performance bottlenecks in production and pre-production systems. In addition to diagnosing performance problems, DTrace can be used to help investigate and debug unexpected behavior in both the FreeBSD kernel and in userland programs. DTrace is a remarkable profiling tool, with an impressive array of features for diagnosing system issues. It may also be used to run pre-written scripts to take advantage of its capabilities. Users can author their own utilities using the DTrace D Language, allowing them to customize their profiling based on specific needs. The FreeBSD implementation provides full support for kernel DTrace and experimental support for userland DTrace. Userland DTrace allows users to perform function boundary tracing for userland programs using the `pid` provider, and to insert static probes into userland programs for later tracing. Some ports, such as package:databases/postgresql12-server[] and package:lang/php74[] have a DTrace option to enable static probes. The official guide to DTrace is maintained by the Illumos project at http://dtrace.org/guide[DTrace Guide]. After reading this chapter, you will know: * What DTrace is and what features it provides. * Differences between the Solaris(TM) DTrace implementation and the one provided by FreeBSD. * How to enable and use DTrace on FreeBSD. Before reading this chapter, you should: * Understand UNIX(R) and FreeBSD basics (crossref:basics[basics,FreeBSD Basics]). * Have some familiarity with security and how it pertains to FreeBSD (crossref:security[security,Security]). [[dtrace-implementation]] == Implementation Differences While the DTrace in FreeBSD is similar to that found in Solaris(TM), differences do exist. The primary difference is that in FreeBSD, DTrace is implemented as a set of kernel modules and DTrace can not be used until the modules are loaded. To load all of the necessary modules: [source,shell] .... # kldload dtraceall .... Beginning with FreeBSD 10.0-RELEASE, the modules are automatically loaded when `dtrace` is run. FreeBSD uses the `DDB_CTF` kernel option to enable support for loading `CTF` data from kernel modules and the kernel itself. `CTF` is the Solaris(TM) Compact C Type Format which encapsulates a reduced form of debugging information similar to `DWARF` and the venerable stabs. `CTF` data is added to binaries by the `ctfconvert` and `ctfmerge` build tools. The `ctfconvert` utility parses `DWARF``ELF` debug sections created by the compiler and `ctfmerge` merges `CTF``ELF` sections from objects into either executables or shared libraries. Some different providers exist for FreeBSD than for Solaris(TM). Most notable is the `dtmalloc` provider, which allows tracing `malloc()` by type in the FreeBSD kernel. Some of the providers found in Solaris(TM), such as `cpc` and `mib`, are not present in FreeBSD. These may appear in future versions of FreeBSD. Moreover, some of the providers available in both operating systems are not compatible, in the sense that their probes have different argument types. Thus, `D` scripts written on Solaris(TM) may or may not work unmodified on FreeBSD, and vice versa. Due to security differences, only `root` may use DTrace on FreeBSD. Solaris(TM) has a few low level security checks which do not yet exist in FreeBSD. As such, the [.filename]#/dev/dtrace/dtrace# is strictly limited to `root`. DTrace falls under the Common Development and Distribution License (`CDDL`) license. To view this license on FreeBSD, see [.filename]#/usr/src/cddl/contrib/opensolaris/OPENSOLARIS.LICENSE# or view it online at http://opensource.org/licenses/CDDL-1.0[http://opensource.org/licenses/CDDL-1.0]. While a FreeBSD kernel with DTrace support is `BSD` licensed, the `CDDL` is used when the modules are distributed in binary form or the binaries are loaded. [[dtrace-enable]] == Enabling DTrace Support In FreeBSD 9.2 and 10.0, DTrace support is built into the [.filename]#GENERIC# kernel. Users of earlier versions of FreeBSD or who prefer to statically compile in DTrace support should add the following lines to a custom kernel configuration file and recompile the kernel using the instructions in crossref:kernelconfig[kernelconfig,Configuring the FreeBSD Kernel]: [.programlisting] .... options KDTRACE_HOOKS options DDB_CTF makeoptions DEBUG=-g makeoptions WITH_CTF=1 .... Users of the AMD64 architecture should also add this line: [.programlisting] .... options KDTRACE_FRAME .... This option provides support for `FBT`. While DTrace will work without this option, there will be limited support for function boundary tracing. Once the FreeBSD system has rebooted into the new kernel, or the DTrace kernel modules have been loaded using `kldload dtraceall`, the system will need support for the Korn shell as the DTrace Toolkit has several utilities written in `ksh`. Make sure that the package:shells/ksh93[] package or port is installed. It is also possible to run these tools under package:shells/pdksh[] or package:shells/mksh[]. -Finally, install the current DTrace Toolkit, a collection of ready-made scripts for collecting system information. There are scripts to check open files, memory, `CPU` usage, and a lot more. FreeBSD 10 installs a few of these scripts into [.filename]#/usr/shared/dtrace#. On other FreeBSD versions, or to install the full DTrace Toolkit, use the package:sysutils/DTraceToolkit[] package or port. +Finally, install the current DTrace Toolkit, a collection of ready-made scripts for collecting system information. There are scripts to check open files, memory, `CPU` usage, and a lot more. FreeBSD 10 installs a few of these scripts into [.filename]#/usr/shared/dtrace#. On other FreeBSD versions, or to install the full DTrace Toolkit, use the package:sysutils/dtrace-toolkit[] package or port. [NOTE] ==== The scripts found in [.filename]#/usr/shared/dtrace# have been specifically ported to FreeBSD. Not all of the scripts found in the DTrace Toolkit will work as-is on FreeBSD and some scripts may require some effort in order for them to work on FreeBSD. ==== The DTrace Toolkit includes many scripts in the special language of DTrace. This language is called the D language and it is very similar to C++. An in depth discussion of the language is beyond the scope of this document. It is covered extensively in the http://www.dtrace.org/guide[Illumos Dynamic Tracing Guide]. [[dtrace-using]] == Using DTrace DTrace scripts consist of a list of one or more _probes_, or instrumentation points, where each probe is associated with an action. Whenever the condition for a probe is met, the associated action is executed. For example, an action may occur when a file is opened, a process is started, or a line of code is executed. The action might be to log some information or to modify context variables. The reading and writing of context variables allows probes to share information and to cooperatively analyze the correlation of different events. To view all probes, the administrator can execute the following command: [source,shell] .... # dtrace -l | more .... Each probe has an `ID`, a `PROVIDER` (dtrace or fbt), a `MODULE`, and a `FUNCTION NAME`. Refer to man:dtrace[1] for more information about this command. The examples in this section provide an overview of how to use two of the fully supported scripts from the DTrace Toolkit: the [.filename]#hotkernel# and [.filename]#procsystime# scripts. The [.filename]#hotkernel# script is designed to identify which function is using the most kernel time. It will produce output similar to the following: [source,shell] .... # cd /usr/local/share/dtrace-toolkit # ./hotkernel Sampling... Hit Ctrl-C to end. .... As instructed, use the kbd:[Ctrl+C] key combination to stop the process. Upon termination, the script will display a list of kernel functions and timing information, sorting the output in increasing order of time: [source,shell] .... kernel`_thread_lock_flags 2 0.0% 0xc1097063 2 0.0% kernel`sched_userret 2 0.0% kernel`kern_select 2 0.0% kernel`generic_copyin 3 0.0% kernel`_mtx_assert 3 0.0% kernel`vm_fault 3 0.0% kernel`sopoll_generic 3 0.0% kernel`fixup_filename 4 0.0% kernel`_isitmyx 4 0.0% kernel`find_instance 4 0.0% kernel`_mtx_unlock_flags 5 0.0% kernel`syscall 5 0.0% kernel`DELAY 5 0.0% 0xc108a253 6 0.0% kernel`witness_lock 7 0.0% kernel`read_aux_data_no_wait 7 0.0% kernel`Xint0x80_syscall 7 0.0% kernel`witness_checkorder 7 0.0% kernel`sse2_pagezero 8 0.0% kernel`strncmp 9 0.0% kernel`spinlock_exit 10 0.0% kernel`_mtx_lock_flags 11 0.0% kernel`witness_unlock 15 0.0% kernel`sched_idletd 137 0.3% 0xc10981a5 42139 99.3% .... This script will also work with kernel modules. To use this feature, run the script with `-m`: [source,shell] .... # ./hotkernel -m Sampling... Hit Ctrl-C to end. ^C MODULE COUNT PCNT 0xc107882e 1 0.0% 0xc10e6aa4 1 0.0% 0xc1076983 1 0.0% 0xc109708a 1 0.0% 0xc1075a5d 1 0.0% 0xc1077325 1 0.0% 0xc108a245 1 0.0% 0xc107730d 1 0.0% 0xc1097063 2 0.0% 0xc108a253 73 0.0% kernel 874 0.4% 0xc10981a5 213781 99.6% .... The [.filename]#procsystime# script captures and prints the system call time usage for a given process `ID` (`PID`) or process name. In the following example, a new instance of [.filename]#/bin/csh# was spawned. Then, [.filename]#procsystime# was executed and remained waiting while a few commands were typed on the other incarnation of `csh`. These are the results of this test: [source,shell] .... # ./procsystime -n csh Tracing... Hit Ctrl-C to end... ^C Elapsed Times for processes csh, SYSCALL TIME (ns) getpid 6131 sigreturn 8121 close 19127 fcntl 19959 dup 26955 setpgid 28070 stat 31899 setitimer 40938 wait4 62717 sigaction 67372 sigprocmask 119091 gettimeofday 183710 write 263242 execve 492547 ioctl 770073 vfork 3258923 sigsuspend 6985124 read 3988049784 .... As shown, the `read()` system call used the most time in nanoseconds while the `getpid()` system call used the least amount of time. diff --git a/documentation/content/pt-br/books/handbook/dtrace/_index.adoc b/documentation/content/pt-br/books/handbook/dtrace/_index.adoc index f6523be992..b14e208973 100644 --- a/documentation/content/pt-br/books/handbook/dtrace/_index.adoc +++ b/documentation/content/pt-br/books/handbook/dtrace/_index.adoc @@ -1,233 +1,233 @@ --- title: Chapter 24. DTrace part: Parte III. Administração do Sistema prev: books/handbook/cutting-edge next: books/handbook/usb-device-mode --- [[dtrace]] = DTrace :doctype: book :toc: macro :toclevels: 1 :icons: font :sectnums: :sectnumlevels: 6 :source-highlighter: rouge :experimental: :skip-front-matter: :toc-title: Índice :table-caption: Tabela :figure-caption: Figura :example-caption: Exemplo :xrefstyle: basic :relfileprefix: ../ :outfilesuffix: :sectnumoffset: 24 ifeval::["{backend}" == "html5"] :imagesdir: ../../../images/books/handbook/dtrace/ endif::[] ifeval::["{backend}" == "pdf"] :imagesdir: ../../../../static/images/books/handbook/dtrace/ endif::[] ifeval::["{backend}" == "epub3"] :imagesdir: ../../../../static/images/books/handbook/dtrace/ endif::[] include::shared/authors.adoc[] include::shared/releases.adoc[] include::shared/pt-br/mailing-lists.adoc[] include::shared/pt-br/teams.adoc[] include::shared/pt-br/urls.adoc[] toc::[] [[dtrace-synopsis]] == Sinopse O DTrace, também conhecido como Dynamic Tracing, foi desenvolvido pela Sun(TM) como uma ferramenta para localizar gargalos de desempenho em sistemas de produção e pré-produção. Além de diagnosticar problemas de desempenho, o DTrace pode ser usado para ajudar a investigar e depurar comportamentos inesperados no kernel do FreeBSD e em programas da userland. O DTrace é uma ferramenta de criação de perfil notável, com uma impressionante variedade de recursos para diagnosticar problemas do sistema. Ele também pode ser usado para executar scripts pré-escritos para aproveitar seus recursos. Os usuários podem criar seus próprios utilitários usando a DTrace D Language, permitindo que eles personalizem seus perfis com base em necessidades específicas. A implementação do FreeBSD fornece suporte completo para o DTrace do kernel e suporte experimental para o DTrace da userland. O Userland DTrace permite que os usuários executem o rastreio de limite de função para programas de área de trabalho usando o provedor `pid` e insiram investigações estáticas em programas da userland para rastreamento posterior. Alguns ports, como package:databases/postgresql12-server[] e package:lang/php74[], possuem uma opção do DTrace para ativar testes estáticos. O guia oficial do DTrace é mantido pelo projeto Illumos no http://dtrace.org/guide[Guia do DTrace]. Depois de ler este capítulo, você saberá: * O que é o DTrace e quais recursos ele fornece. * Diferenças entre a implementação do DTrace Solaris(TM) e a fornecida pelo FreeBSD. * Como ativar e usar o DTrace no FreeBSD. Antes de ler este capítulo, você deve: * Entender os fundamentos do UNIX(TM) e do FreeBSD (crossref:basics[basics, Fundamentos do FreeBSD]). * Ter alguma familiaridade com segurança e como ela está presente no FreeBSD (crossref:security[security, Segurança]). [[dtrace-implementation]] == Diferenças de Implementação Embora o DTrace no FreeBSD seja semelhante ao encontrado no Solaris(TM), existem diferenças. A principal diferença é que no FreeBSD, o DTrace é implementado como um conjunto de módulos do kernel e o DTrace não pode ser usado até que os módulos sejam carregados. Para carregar todos os módulos necessários: [source,shell] .... # kldload dtraceall .... Começando com o FreeBSD 10.0-RELEASE, os módulos são carregados automaticamente quando o `dtrace` é executado. O FreeBSD usa a opção do kernel `DDB_CTF` para ativar o suporte para carregar dados CTF dos módulos do kernel e do próprio kernel. O CTF é o Solaris(TM) Compact C Type Format, que encapsula uma forma reduzida de informações de depuração semelhantes ao DWARF e aos veneráveis stabs. Os dados do CTF são adicionados aos binários pelas ferramentas de compilação `ctfconvert` e `ctfmerge`. O utilitário `ctfconvert` analisa as seções de depuração do DWARFELF criadas pelo compilador e o `ctfmerge` mescla as seções do ELF do CTF dos objetos em executáveis ou bibliotecas compartilhadas. Alguns provedores diferentes existem para o FreeBSD não para o Solaris(TM). O mais notável é o provedor `dtmalloc`, que permite rastrear `malloc()` por tipo no kernel do FreeBSD. Alguns dos provedores encontrados no Solaris(TM), como `cpc` e `mib`, não estão presentes no FreeBSD. Estes podem aparecer em futuras versões do FreeBSD. Além disso, alguns dos provedores disponíveis em ambos os sistemas operacionais não são compatíveis, no sentido de que suas sondas têm tipos de argumentos diferentes. Assim, os scripts D escritos em Solaris(TM) podem ou não funcionar sem modificações no FreeBSD, e vice-versa. Devido as diferenças de segurança, somente o `root` pode usar o DTrace no FreeBSD. O Solaris(TM) possui algumas verificações de segurança de baixo nível que ainda não existem no FreeBSD. Como tal, o [.filename]#/dev/dtrace/dtrace# é estritamente limitado ao `root`. O DTrace se enquadra na licença Common Development and Distribution License (CDDL). Para ver esta licença no FreeBSD, consulte [.filename]#/usr/src/cddl/contrib/opensolaris/OPENSOLARIS.LICENSE# ou acesse on-line em http://opensource.org/licenses/CDDL-1.0[http://opensource.org/licenses/CDDL-1.0]. Enquanto um kernel do FreeBSD com suporte a DTrace é licenciado sob BSD, o CDDL é usado quando os módulos são distribuídos em formato binário ou quando os binários são carregados. [[dtrace-enable]] == Ativando o Suporte do DTrace No FreeBSD 9.2 e 10.0, o suporte do DTrace está embutido no kernel [.filename]#GENERIC#. Usuários de versões anteriores do FreeBSD ou que preferem compilar estaticamente o suporte do DTrace devem adicionar as seguintes linhas a um arquivo de configuração de kernel personalizado e recompilar o kernel usando as instruções em crossref:kernelconfig[kernelconfig, Configurando o kernel do FreeBSD]: [.programlisting] .... options KDTRACE_HOOKS options DDB_CTF makeoptions DEBUG=-g makeoptions WITH_CTF=1 .... Os usuários da arquitetura AMD64 também devem adicionar esta linha: [.programlisting] .... options KDTRACE_FRAME .... Esta opção fornece suporte para FBT. Embora o DTrace funcione sem essa opção, haverá suporte limitado para o rastreamento de limite de função. Uma vez que o sistema FreeBSD foi reinicializado no novo kernel, ou os módulos de kernel do DTrace foram carregados usando `kldload dtraceall`, o sistema precisará de suporte para o shell Korn, pois o DTrace Toolkit possui vários utilitários escritos em `ksh`. Certifique-se de que o pacote ou port package:shells/ksh93[] esteja instalado. Também é possível rodar estas ferramentas com package:shells/pdksh[] ou package:shells/mksh[]. -Por fim, instale o DTrace Toolkit atual, uma coleção de scripts prontos para coletar informações do sistema. Existem scripts para verificar arquivos abertos, memória, uso de CPU e muito mais. O FreeBSD 10 instala alguns desses scripts em [.filename]#/usr/shared/dtrace#. Em outras versões do FreeBSD, ou para instalar o DTrace Toolkit completo, use o pacote ou port package:sysutils/DTraceToolkit[]. +Por fim, instale o DTrace Toolkit atual, uma coleção de scripts prontos para coletar informações do sistema. Existem scripts para verificar arquivos abertos, memória, uso de CPU e muito mais. O FreeBSD 10 instala alguns desses scripts em [.filename]#/usr/shared/dtrace#. Em outras versões do FreeBSD, ou para instalar o DTrace Toolkit completo, use o pacote ou port package:sysutils/dtrace-toolkit[]. [NOTE] ==== Os scripts encontrados em [.filename]#/usr/shared/dtrace# foram especificamente portados para o FreeBSD. Nem todos os scripts encontrados no DTrace Toolkit funcionarão no FreeBSD e alguns scripts podem exigir algum esforço para que funcionem no FreeBSD. ==== O DTrace Toolkit inclui muitos scripts no idioma especial do DTrace. Esta linguagem é chamada de linguagem D e é muito semelhante ao C++. Uma discussão aprofundada da linguagem está além do escopo deste documento. Ele é abordado extensivamente no http://www.dtrace.org/guide[Illumos Dynamic Tracing Guide]. [[dtrace-using]] == Usando o DTrace Os scripts do DTrace consistem em uma lista de um ou mais testes _probes_, ou pontos de instrumentação, em que cada teste é associado a uma ação. Sempre que a condição de uma sonda é atendida, a ação associada é executada. Por exemplo, uma ação pode ocorrer quando um arquivo é aberto, um processo é iniciado ou uma linha de código é executada. A ação pode ser registrar algumas informações ou modificar variáveis de contexto. A leitura e a escrita de variáveis de contexto permitem que os probes compartilhem informações e analisem cooperativa-mente a correlação de diferentes eventos. Para ver todos os probes, o administrador pode executar o seguinte comando: [source,shell] .... # dtrace -l | more .... Cada probe possui um `ID`, um `PROVIDER` (dtrace ou fbt), um `MODULE` e um `FUNCTION NAME`. Consulte man:dtrace[1] para obter maiores informações sobre este comando. Os exemplos nesta seção fornecem uma visão geral de como usar dois dos scripts totalmente suportados dos scripts do DTrace Toolkit: o [.filename]#hotkernel# e [.filename]#procsystime#. O script [.filename]#hotkernel# é projetado para identificar qual função está usando a maior parte do tempo do kernel. Ele produzirá uma saída semelhante à seguinte: [source,shell] .... # cd /usr/local/share/dtrace-toolkit # ./hotkernel Sampling... Hit Ctrl-C to end. .... Conforme instruído, use a combinação de teclas kbd:[Ctrl+C] para interromper o processo. Após o término, o script exibirá uma lista de funções do kernel e informações de tempo, classificando a saída em ordem crescente de tempo: [source,shell] .... kernel`_thread_lock_flags 2 0.0% 0xc1097063 2 0.0% kernel`sched_userret 2 0.0% kernel`kern_select 2 0.0% kernel`generic_copyin 3 0.0% kernel`_mtx_assert 3 0.0% kernel`vm_fault 3 0.0% kernel`sopoll_generic 3 0.0% kernel`fixup_filename 4 0.0% kernel`_isitmyx 4 0.0% kernel`find_instance 4 0.0% kernel`_mtx_unlock_flags 5 0.0% kernel`syscall 5 0.0% kernel`DELAY 5 0.0% 0xc108a253 6 0.0% kernel`witness_lock 7 0.0% kernel`read_aux_data_no_wait 7 0.0% kernel`Xint0x80_syscall 7 0.0% kernel`witness_checkorder 7 0.0% kernel`sse2_pagezero 8 0.0% kernel`strncmp 9 0.0% kernel`spinlock_exit 10 0.0% kernel`_mtx_lock_flags 11 0.0% kernel`witness_unlock 15 0.0% kernel`sched_idletd 137 0.3% 0xc10981a5 42139 99.3% .... Este script também funcionará com módulos do kernel. Para usar este recurso, execute o script com `-m`: [source,shell] .... # ./hotkernel -m Sampling... Hit Ctrl-C to end. ^C MODULE COUNT PCNT 0xc107882e 1 0.0% 0xc10e6aa4 1 0.0% 0xc1076983 1 0.0% 0xc109708a 1 0.0% 0xc1075a5d 1 0.0% 0xc1077325 1 0.0% 0xc108a245 1 0.0% 0xc107730d 1 0.0% 0xc1097063 2 0.0% 0xc108a253 73 0.0% kernel 874 0.4% 0xc10981a5 213781 99.6% .... O script [.filename]#procsystime# captura e imprime o uso do tempo de chamada do sistema para um determinado processo ID (PID) ou nome do processo. No exemplo a seguir, uma nova instância de [.filename]#/bin/csh# foi gerada. Então, [.filename]#procsystime# foi executado e permaneceu aguardando enquanto alguns comandos foram digitados na outra instância do `csh`. Estes são os resultados deste teste: [source,shell] .... # ./procsystime -n csh Tracing... Hit Ctrl-C to end... ^C Elapsed Times for processes csh, SYSCALL TIME (ns) getpid 6131 sigreturn 8121 close 19127 fcntl 19959 dup 26955 setpgid 28070 stat 31899 setitimer 40938 wait4 62717 sigaction 67372 sigprocmask 119091 gettimeofday 183710 write 263242 execve 492547 ioctl 770073 vfork 3258923 sigsuspend 6985124 read 3988049784 .... Como mostrado, a chamada de sistema `read()` usou a maior parte do tempo em nanossegundos enquanto a chamada de sistema `getpid()` usou a menor quantidade de tempo. diff --git a/documentation/content/zh-tw/books/handbook/dtrace/_index.adoc b/documentation/content/zh-tw/books/handbook/dtrace/_index.adoc index 70f8e2e5ee..811a2e4525 100644 --- a/documentation/content/zh-tw/books/handbook/dtrace/_index.adoc +++ b/documentation/content/zh-tw/books/handbook/dtrace/_index.adoc @@ -1,233 +1,233 @@ --- title: 章 24. DTrace part: 部 III. 系統管理 prev: books/handbook/cutting-edge next: books/handbook/usb-device-mode --- [[dtrace]] = DTrace :doctype: book :toc: macro :toclevels: 1 :icons: font :sectnums: :sectnumlevels: 6 :source-highlighter: rouge :experimental: :skip-front-matter: :toc-title: 目录 :table-caption: 表 :figure-caption: 图 :example-caption: 例 :xrefstyle: basic :relfileprefix: ../ :outfilesuffix: :sectnumoffset: 24 ifeval::["{backend}" == "html5"] :imagesdir: ../../../images/books/handbook/dtrace/ endif::[] ifeval::["{backend}" == "pdf"] :imagesdir: ../../../../static/images/books/handbook/dtrace/ endif::[] ifeval::["{backend}" == "epub3"] :imagesdir: ../../../../static/images/books/handbook/dtrace/ endif::[] include::shared/authors.adoc[] include::shared/releases.adoc[] include::shared/zh-tw/mailing-lists.adoc[] include::shared/zh-tw/urls.adoc[] include::shared/zh-tw/teams.adoc[] toc::[] [[dtrace-synopsis]] == 概述 DTrace, also known as Dynamic Tracing, was developed by Sun(TM) as a tool for locating performance bottlenecks in production and pre-production systems. In addition to diagnosing performance problems, DTrace can be used to help investigate and debug unexpected behavior in both the FreeBSD kernel and in userland programs. DTrace is a remarkable profiling tool, with an impressive array of features for diagnosing system issues. It may also be used to run pre-written scripts to take advantage of its capabilities. Users can author their own utilities using the DTrace D Language, allowing them to customize their profiling based on specific needs. The FreeBSD implementation provides full support for kernel DTrace and experimental support for userland DTrace. Userland DTrace allows users to perform function boundary tracing for userland programs using the `pid` provider, and to insert static probes into userland programs for later tracing. Some ports, such as package:databases/postgres-server[] and package:lang/php56[] have a DTrace option to enable static probes. FreeBSD 10.0-RELEASE has reasonably good userland DTrace support, but it is not considered production ready. In particular, it is possible to crash traced programs. The official guide to DTrace is maintained by the Illumos project at http://dtrace.org/guide[DTrace Guide]. 讀完這章,您將了解: * What DTrace is and what features it provides. * Differences between the Solaris(TM) DTrace implementation and the one provided by FreeBSD. * How to enable and use DTrace on FreeBSD. 在開始閱讀這章之前,您需要: * 了解 UNIX(TM) 及 FreeBSD 基礎 (crossref:basics[basics,FreeBSD 基礎])。 * Have some familiarity with security and how it pertains to FreeBSD (crossref:security[security,安全性]). [[dtrace-implementation]] == 實作差異 While the DTrace in FreeBSD is similar to that found in Solaris(TM), differences do exist. The primary difference is that in FreeBSD, DTrace is implemented as a set of kernel modules and DTrace can not be used until the modules are loaded. To load all of the necessary modules: [source,shell] .... # kldload dtraceall .... Beginning with FreeBSD 10.0-RELEASE, the modules are automatically loaded when `dtrace` is run. FreeBSD uses the `DDB_CTF` kernel option to enable support for loading CTF data from kernel modules and the kernel itself. CTF is the Solaris(TM) Compact C Type Format which encapsulates a reduced form of debugging information similar to DWARF and the venerable stabs. CTF data is added to binaries by the `ctfconvert` and `ctfmerge` build tools. The `ctfconvert` utility parses DWARFELF debug sections created by the compiler and `ctfmerge` merges CTFELF sections from objects into either executables or shared libraries. Some different providers exist for FreeBSD than for Solaris(TM). Most notable is the `dtmalloc` provider, which allows tracing `malloc()` by type in the FreeBSD kernel. Some of the providers found in Solaris(TM), such as `cpc` and `mib`, are not present in FreeBSD. These may appear in future versions of FreeBSD. Moreover, some of the providers available in both operating systems are not compatible, in the sense that their probes have different argument types. Thus, D scripts written on Solaris(TM) may or may not work unmodified on FreeBSD, and vice versa. Due to security differences, only `root` may use DTrace on FreeBSD. Solaris(TM) has a few low level security checks which do not yet exist in FreeBSD. As such, the [.filename]#/dev/dtrace/dtrace# is strictly limited to `root`. DTrace falls under the Common Development and Distribution License (CDDL) license. To view this license on FreeBSD, see [.filename]#/usr/src/cddl/contrib/opensolaris/OPENSOLARIS.LICENSE# or view it online at http://opensource.org/licenses/CDDL-1.0[http://opensource.org/licenses/CDDL-1.0]. While a FreeBSD kernel with DTrace support is BSD licensed, the CDDL is used when the modules are distributed in binary form or the binaries are loaded. [[dtrace-enable]] == 開啟 DTrace 支援 In FreeBSD 9.2 and 10.0, DTrace support is built into the [.filename]#GENERIC# kernel. Users of earlier versions of FreeBSD or who prefer to statically compile in DTrace support should add the following lines to a custom kernel configuration file and recompile the kernel using the instructions in crossref:kernelconfig[kernelconfig,設定 FreeBSD 核心]: [.programlisting] .... options KDTRACE_HOOKS options DDB_CTF makeoptions DEBUG=-g makeoptions WITH_CTF=1 .... Users of the AMD64 architecture should also add this line: [.programlisting] .... options KDTRACE_FRAME .... This option provides support for FBT. While DTrace will work without this option, there will be limited support for function boundary tracing. Once the FreeBSD system has rebooted into the new kernel, or the DTrace kernel modules have been loaded using `kldload dtraceall`, the system will need support for the Korn shell as the DTrace Toolkit has several utilities written in `ksh`. Make sure that the package:shells/ksh93[] package or port is installed. It is also possible to run these tools under package:shells/pdksh[] or package:shells/mksh[]. -Finally, install the current DTrace Toolkit, a collection of ready-made scripts for collecting system information. There are scripts to check open files, memory, CPU usage, and a lot more. FreeBSD 10 installs a few of these scripts into [.filename]#/usr/shared/dtrace#. On other FreeBSD versions, or to install the full DTrace Toolkit, use the package:sysutils/DTraceToolkit[] package or port. +Finally, install the current DTrace Toolkit, a collection of ready-made scripts for collecting system information. There are scripts to check open files, memory, CPU usage, and a lot more. FreeBSD 10 installs a few of these scripts into [.filename]#/usr/shared/dtrace#. On other FreeBSD versions, or to install the full DTrace Toolkit, use the package:sysutils/dtrace-toolkit[] package or port. [NOTE] ==== The scripts found in [.filename]#/usr/shared/dtrace# have been specifically ported to FreeBSD. Not all of the scripts found in the DTrace Toolkit will work as-is on FreeBSD and some scripts may require some effort in order for them to work on FreeBSD. ==== The DTrace Toolkit includes many scripts in the special language of DTrace. This language is called the D language and it is very similar to C++. An in depth discussion of the language is beyond the scope of this document. It is covered extensively in the http://www.dtrace.org/guide[Illumos Dynamic Tracing Guide]. [[dtrace-using]] == 使用 DTrace DTrace scripts consist of a list of one or more _probes_, or instrumentation points, where each probe is associated with an action. Whenever the condition for a probe is met, the associated action is executed. For example, an action may occur when a file is opened, a process is started, or a line of code is executed. The action might be to log some information or to modify context variables. The reading and writing of context variables allows probes to share information and to cooperatively analyze the correlation of different events. To view all probes, the administrator can execute the following command: [source,shell] .... # dtrace -l | more .... Each probe has an `ID`, a `PROVIDER` (dtrace or fbt), a `MODULE`, and a `FUNCTION NAME`. Refer to man:dtrace[1] for more information about this command. The examples in this section provide an overview of how to use two of the fully supported scripts from the DTrace Toolkit: the [.filename]#hotkernel# and [.filename]#procsystime# scripts. The [.filename]#hotkernel# script is designed to identify which function is using the most kernel time. It will produce output similar to the following: [source,shell] .... # cd /usr/shared/dtrace/toolkit # ./hotkernel Sampling... Hit Ctrl-C to end. .... As instructed, use the kbd:[Ctrl+C] key combination to stop the process. Upon termination, the script will display a list of kernel functions and timing information, sorting the output in increasing order of time: [source,shell] .... kernel`_thread_lock_flags 2 0.0% 0xc1097063 2 0.0% kernel`sched_userret 2 0.0% kernel`kern_select 2 0.0% kernel`generic_copyin 3 0.0% kernel`_mtx_assert 3 0.0% kernel`vm_fault 3 0.0% kernel`sopoll_generic 3 0.0% kernel`fixup_filename 4 0.0% kernel`_isitmyx 4 0.0% kernel`find_instance 4 0.0% kernel`_mtx_unlock_flags 5 0.0% kernel`syscall 5 0.0% kernel`DELAY 5 0.0% 0xc108a253 6 0.0% kernel`witness_lock 7 0.0% kernel`read_aux_data_no_wait 7 0.0% kernel`Xint0x80_syscall 7 0.0% kernel`witness_checkorder 7 0.0% kernel`sse2_pagezero 8 0.0% kernel`strncmp 9 0.0% kernel`spinlock_exit 10 0.0% kernel`_mtx_lock_flags 11 0.0% kernel`witness_unlock 15 0.0% kernel`sched_idletd 137 0.3% 0xc10981a5 42139 99.3% .... This script will also work with kernel modules. To use this feature, run the script with `-m`: [source,shell] .... # ./hotkernel -m Sampling... Hit Ctrl-C to end. ^C MODULE COUNT PCNT 0xc107882e 1 0.0% 0xc10e6aa4 1 0.0% 0xc1076983 1 0.0% 0xc109708a 1 0.0% 0xc1075a5d 1 0.0% 0xc1077325 1 0.0% 0xc108a245 1 0.0% 0xc107730d 1 0.0% 0xc1097063 2 0.0% 0xc108a253 73 0.0% kernel 874 0.4% 0xc10981a5 213781 99.6% .... The [.filename]#procsystime# script captures and prints the system call time usage for a given process ID (PID) or process name. In the following example, a new instance of [.filename]#/bin/csh# was spawned. Then, [.filename]#procsystime# was executed and remained waiting while a few commands were typed on the other incarnation of `csh`. These are the results of this test: [source,shell] .... # ./procsystime -n csh Tracing... Hit Ctrl-C to end... ^C Elapsed Times for processes csh, SYSCALL TIME (ns) getpid 6131 sigreturn 8121 close 19127 fcntl 19959 dup 26955 setpgid 28070 stat 31899 setitimer 40938 wait4 62717 sigaction 67372 sigprocmask 119091 gettimeofday 183710 write 263242 execve 492547 ioctl 770073 vfork 3258923 sigsuspend 6985124 read 3988049784 .... As shown, the `read()` system call used the most time in nanoseconds while the `getpid()` system call used the least amount of time.