├── CODE_OF_CONDUCT.md ├── LICENSE ├── README.md ├── bcc ├── README.md └── trace-open.py ├── dns ├── 4-times-close.pcap ├── README.md ├── images │ ├── Dockerfile │ ├── README.md │ ├── dnsmasq.conf │ └── resolv.conf.dnsmasq ├── ping.pcap └── web.pcap ├── flamegraph ├── README.md ├── cpu-mysql-updated.svg ├── jbd2.svg └── ksoftirqd.svg ├── high-iowait-process ├── Dockerfile ├── Makefile ├── README.md ├── app-fix1.c ├── app-fix2.c └── app.c ├── images └── intro.jpg ├── io-cached ├── Dockerfile ├── Makefile ├── README.md ├── app-cached.c └── app.c ├── io-latency ├── Dockerfile ├── Makefile ├── README.md └── app.py ├── logging-app ├── Dockerfile ├── Makefile ├── README.md └── app.py ├── mem-leak ├── Dockerfile ├── Makefile ├── README.md ├── app-fix.c ├── app-no-calloc.c └── app.c ├── mysql-slow ├── Dockerfile ├── Dockerfile.dataservice ├── Dockerfile.mysql ├── Makefile ├── README.md ├── app.py ├── dataservice.py ├── mysqld.cnf └── tables.sql ├── nat ├── Dockerfile ├── Dockerfile.80 ├── Makefile ├── README.md ├── default.80.conf ├── default.conf ├── dropwatch.stp └── nginx.conf ├── network-latency ├── Dockerfile ├── Makefile ├── README.md ├── default.conf └── nginx.conf ├── nginx-high-cpu ├── Dockerfile.nginx ├── Dockerfile.php-fpm ├── Makefile ├── README.md ├── app │ ├── 404.html │ ├── index.php │ ├── ok.php │ └── phpinfo.php ├── nginx.conf └── php-fpm.d │ └── www.conf ├── nginx-short-process ├── Dockerfile.nginx ├── Dockerfile.php-fpm ├── Makefile ├── README.md ├── app │ ├── 404.html │ ├── index.php │ ├── ok.php │ └── phpinfo.php ├── nginx.conf └── php-fpm.d │ └── www.conf ├── nginx-throughput ├── Dockerfile.nginx ├── Dockerfile.php-fpm ├── Makefile ├── README.md ├── app │ ├── 404.html │ └── index.php ├── init.sh ├── nginx.conf ├── nginx.svg └── php-fpm.d │ └── www.conf ├── packet-drop ├── Dockerfile ├── Makefile ├── README.md └── start.sh ├── redis-slow ├── Dockerfile ├── Dockerfile.redis ├── Makefile ├── README.md ├── app.py └── redis.conf ├── short-lived-process ├── Dockerfile ├── Makefile ├── README.md └── app.c └── tomcat ├── Dockerfile ├── Dockerfile.jre11 ├── Makefile ├── README.md └── index.jsp /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, sex characteristics, gender identity and expression, 9 | level of experience, education, socio-economic status, nationality, personal 10 | appearance, race, religion, or sexual identity and orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at feiskyer@gmail.com. All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 72 | 73 | [homepage]: https://www.contributor-covenant.org 74 | 75 | For answers to common questions about this code of conduct, see 76 | https://www.contributor-covenant.org/faq 77 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Pengfei Ni 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 《Linux 性能优化实战》案例 2 | 3 | 极客时间专栏《[Linux 性能优化实战](https://time.geekbang.org/column/intro/140)》案例源码。 4 | 5 | ![introduction](images/intro.jpg) 6 | 7 | ## 部分案例列表 8 | 9 | * [应用程序 CPU 使用率过高案例](nginx-high-cpu/README.md) 10 | * [用户 CPU 使用率过高案例](nginx-short-process/README.md) 11 | * [短时进程案例](short-lived-process/README.md) 12 | * [iowait 使用率过高案例](high-iowait-process/README.md) 13 | * [未利用系统缓存导致 I/O 缓慢案例](io-cached/README.md) 14 | * [内存泄漏案例](mem-leak/README.md) 15 | * [狂打日志案例](logging-app/README.md) 16 | * [I/O延迟案例](io-latency/README.md) 17 | * [MySQL 案例](mysql-slow/README.md) 18 | * [Redis 延迟案例](redis-slow/README.md) 19 | * [DNS 案例](dns/README.md) 20 | * [网络延迟案例](network-latency/README.md) 21 | * [NAT 案例](nat/README.md) 22 | * [Docker 运行 Tomcat 案例](tomcat/README.md) 23 | * [火焰图](flamegraph/README.md) 24 | 25 | ## 依赖环境 26 | 27 | 所有案例的编译运行都需要预先安装 Docker 以及必要的编译工具。以 Ubuntu 18.04 为例,可以运行以下命令来安装它们: 28 | 29 | ```sh 30 | sudo apt-get install docker.io build-essential 31 | ``` 32 | 33 | -------------------------------------------------------------------------------- /bcc/README.md: -------------------------------------------------------------------------------- 1 | # BCC 案例 2 | 3 | **《[Linux 性能优化实战](https://time.geekbang.org/column/intro/140)》第 51 篇案例。** 4 | 5 | 主要内容: 6 | 7 | * trace-open.py:使用 BCC 动态跟踪系统调用 `do_sys_open`。 8 | -------------------------------------------------------------------------------- /bcc/trace-open.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | from bcc import BPF 3 | 4 | # define BPF program 5 | prog = """ 6 | #include 7 | #include 8 | #include 9 | // define output data structure in C 10 | struct data_t { 11 | u32 pid; 12 | u64 ts; 13 | char comm[TASK_COMM_LEN]; 14 | char fname[NAME_MAX]; 15 | }; 16 | BPF_PERF_OUTPUT(events); 17 | int hello(struct pt_regs *ctx, int dfd, const char __user *filename, int flags){ 18 | struct data_t data = {}; 19 | data.pid = bpf_get_current_pid_tgid(); 20 | data.ts = bpf_ktime_get_ns(); 21 | if (bpf_get_current_comm(&data.comm, sizeof(data.comm)) == 0) { 22 | bpf_probe_read(&data.fname, sizeof(data.fname), (void *)filename); 23 | } 24 | events.perf_submit(ctx, &data, sizeof(data)); 25 | return 0; 26 | } 27 | """ 28 | 29 | # load BPF program 30 | b = BPF(text=prog) 31 | # attach kprobe do_sys_open. 32 | b.attach_kprobe(event="do_sys_open", fn_name="hello") 33 | 34 | # print header 35 | print("%-18s %-16s %-6s %-16s" % ("TIME(s)", "COMM", "PID", "FILE")) 36 | 37 | 38 | # process event 39 | start = 0 40 | def print_event(cpu, data, size): 41 | global start 42 | event = b["events"].event(data) 43 | if start == 0: 44 | start = event.ts 45 | time_s = (float(event.ts - start)) / 1000000000 46 | print("%-18.9f %-16s %-6d %-16s" % (time_s, event.comm, event.pid, event.fname)) 47 | 48 | 49 | # loop with callback to print_event 50 | b["events"].open_perf_buffer(print_event) 51 | while 1: 52 | try: 53 | b.perf_buffer_poll() 54 | except KeyboardInterrupt: 55 | exit() 56 | -------------------------------------------------------------------------------- /dns/4-times-close.pcap: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/feiskyer/linux-perf-examples/8e8cd6ce4061d7499db9f95fe399156228f8322b/dns/4-times-close.pcap -------------------------------------------------------------------------------- /dns/README.md: -------------------------------------------------------------------------------- 1 | # DNS 案例 2 | 3 | **《[Linux 性能优化实战](https://time.geekbang.org/column/intro/140)》第 37 篇案例。** 4 | 5 | 包括一个用于 DNS 案例的 Docker 镜像和三个使用 tcpdump 预先抓取的网络包(pcap 格式,也直接在 Wireshark 中分析)。 6 | 7 | -------------------------------------------------------------------------------- /dns/images/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM ubuntu 2 | 3 | RUN apt-get update && \ 4 | apt-get install -y dnsutils net-tools iproute2 inetutils-ping curl dnsmasq && \ 5 | apt-get clean 6 | 7 | ADD dnsmasq.conf /etc/dnsmasq.conf 8 | ADD resolv.conf.dnsmasq /etc/resolv.conf.dnsmasq 9 | 10 | -------------------------------------------------------------------------------- /dns/images/README.md: -------------------------------------------------------------------------------- 1 | # dnsutils 2 | 3 | 预先安装 dig 和 nslookup 的镜像,用于排查 DNS 问题。 4 | 5 | ```sh 6 | $ docker run --rm -it feisky/dnsutils 7 | root@47ff2889e585:/# 8 | 9 | # continue play with nslookup or dig 10 | ``` 11 | -------------------------------------------------------------------------------- /dns/images/dnsmasq.conf: -------------------------------------------------------------------------------- 1 | # Configuration file for dnsmasq. 2 | # 3 | # Format is one option per line, legal options are the same 4 | # as the long options legal on the command line. See 5 | # "/usr/sbin/dnsmasq --help" or "man 8 dnsmasq" for details. 6 | 7 | # Listen on this specific port instead of the standard DNS port 8 | # (53). Setting this to zero completely disables DNS function, 9 | # leaving only DHCP and/or TFTP. 10 | #port=5353 11 | 12 | # The following two options make you a better netizen, since they 13 | # tell dnsmasq to filter out queries which the public DNS cannot 14 | # answer, and which load the servers (especially the root servers) 15 | # unnecessarily. If you have a dial-on-demand link they also stop 16 | # these requests from bringing up the link unnecessarily. 17 | 18 | # Never forward plain names (without a dot or domain part) 19 | #domain-needed 20 | # Never forward addresses in the non-routed address spaces. 21 | #bogus-priv 22 | 23 | # Uncomment these to enable DNSSEC validation and caching: 24 | # (Requires dnsmasq to be built with DNSSEC option.) 25 | #conf-file=%%PREFIX%%/share/dnsmasq/trust-anchors.conf 26 | #dnssec 27 | 28 | # Replies which are not DNSSEC signed may be legitimate, because the domain 29 | # is unsigned, or may be forgeries. Setting this option tells dnsmasq to 30 | # check that an unsigned reply is OK, by finding a secure proof that a DS 31 | # record somewhere between the root and the domain does not exist. 32 | # The cost of setting this is that even queries in unsigned domains will need 33 | # one or more extra DNS queries to verify. 34 | #dnssec-check-unsigned 35 | 36 | # Uncomment this to filter useless windows-originated DNS requests 37 | # which can trigger dial-on-demand links needlessly. 38 | # Note that (amongst other things) this blocks all SRV requests, 39 | # so don't use it if you use eg Kerberos, SIP, XMMP or Google-talk. 40 | # This option only affects forwarding, SRV records originating for 41 | # dnsmasq (via srv-host= lines) are not suppressed by it. 42 | #filterwin2k 43 | 44 | # Change this line if you want dns to get its upstream servers from 45 | # somewhere other that /etc/resolv.conf 46 | resolv-file=/etc/resolv.conf.dnsmasq 47 | 48 | # By default, dnsmasq will send queries to any of the upstream 49 | # servers it knows about and tries to favour servers to are known 50 | # to be up. Uncommenting this forces dnsmasq to try each query 51 | # with each server strictly in the order they appear in 52 | # /etc/resolv.conf 53 | #strict-order 54 | 55 | # If you don't want dnsmasq to read /etc/resolv.conf or any other 56 | # file, getting its servers from this file instead (see below), then 57 | # uncomment this. 58 | #no-resolv 59 | 60 | # If you don't want dnsmasq to poll /etc/resolv.conf or other resolv 61 | # files for changes and re-read them then uncomment this. 62 | #no-poll 63 | 64 | # Add other name servers here, with domain specs if they are for 65 | # non-public domains. 66 | #server=/localnet/192.168.0.1 67 | 68 | # Example of routing PTR queries to nameservers: this will send all 69 | # address->name queries for 192.168.3/24 to nameserver 10.1.2.3 70 | #server=/3.168.192.in-addr.arpa/10.1.2.3 71 | 72 | # Add local-only domains here, queries in these domains are answered 73 | # from /etc/hosts or DHCP only. 74 | #local=/localnet/ 75 | 76 | # Add domains which you want to force to an IP address here. 77 | # The example below send any host in double-click.net to a local 78 | # web-server. 79 | #address=/double-click.net/127.0.0.1 80 | 81 | # --address (and --server) work with IPv6 addresses too. 82 | #address=/www.thekelleys.org.uk/fe80::20d:60ff:fe36:f83 83 | 84 | # Add the IPs of all queries to yahoo.com, google.com, and their 85 | # subdomains to the vpn and search ipsets: 86 | #ipset=/yahoo.com/google.com/vpn,search 87 | 88 | # You can control how dnsmasq talks to a server: this forces 89 | # queries to 10.1.2.3 to be routed via eth1 90 | # server=10.1.2.3@eth1 91 | 92 | # and this sets the source (ie local) address used to talk to 93 | # 10.1.2.3 to 192.168.1.1 port 55 (there must be an interface with that 94 | # IP on the machine, obviously). 95 | # server=10.1.2.3@192.168.1.1#55 96 | 97 | # If you want dnsmasq to change uid and gid to something other 98 | # than the default, edit the following lines. 99 | #user= 100 | #group= 101 | 102 | # If you want dnsmasq to listen for DHCP and DNS requests only on 103 | # specified interfaces (and the loopback) give the name of the 104 | # interface (eg eth0) here. 105 | # Repeat the line for more than one interface. 106 | #interface= 107 | # Or you can specify which interface _not_ to listen on 108 | #except-interface= 109 | # Or which to listen on by address (remember to include 127.0.0.1 if 110 | # you use this.) 111 | #listen-address= 112 | # If you want dnsmasq to provide only DNS service on an interface, 113 | # configure it as shown above, and then use the following line to 114 | # disable DHCP and TFTP on it. 115 | #no-dhcp-interface= 116 | 117 | # On systems which support it, dnsmasq binds the wildcard address, 118 | # even when it is listening on only some interfaces. It then discards 119 | # requests that it shouldn't reply to. This has the advantage of 120 | # working even when interfaces come and go and change address. If you 121 | # want dnsmasq to really bind only the interfaces it is listening on, 122 | # uncomment this option. About the only time you may need this is when 123 | # running another nameserver on the same machine. 124 | #bind-interfaces 125 | 126 | # If you don't want dnsmasq to read /etc/hosts, uncomment the 127 | # following line. 128 | #no-hosts 129 | # or if you want it to read another file, as well as /etc/hosts, use 130 | # this. 131 | #addn-hosts=/etc/banner_add_hosts 132 | 133 | # Set this (and domain: see below) if you want to have a domain 134 | # automatically added to simple names in a hosts-file. 135 | #expand-hosts 136 | 137 | # Set the domain for dnsmasq. this is optional, but if it is set, it 138 | # does the following things. 139 | # 1) Allows DHCP hosts to have fully qualified domain names, as long 140 | # as the domain part matches this setting. 141 | # 2) Sets the "domain" DHCP option thereby potentially setting the 142 | # domain of all systems configured by DHCP 143 | # 3) Provides the domain part for "expand-hosts" 144 | #domain=thekelleys.org.uk 145 | 146 | # Set a different domain for a particular subnet 147 | #domain=wireless.thekelleys.org.uk,192.168.2.0/24 148 | 149 | # Same idea, but range rather then subnet 150 | #domain=reserved.thekelleys.org.uk,192.68.3.100,192.168.3.200 151 | 152 | # Uncomment this to enable the integrated DHCP server, you need 153 | # to supply the range of addresses available for lease and optionally 154 | # a lease time. If you have more than one network, you will need to 155 | # repeat this for each network on which you want to supply DHCP 156 | # service. 157 | #dhcp-range=192.168.0.50,192.168.0.150,12h 158 | 159 | # This is an example of a DHCP range where the netmask is given. This 160 | # is needed for networks we reach the dnsmasq DHCP server via a relay 161 | # agent. If you don't know what a DHCP relay agent is, you probably 162 | # don't need to worry about this. 163 | #dhcp-range=192.168.0.50,192.168.0.150,255.255.255.0,12h 164 | 165 | # This is an example of a DHCP range which sets a tag, so that 166 | # some DHCP options may be set only for this network. 167 | #dhcp-range=set:red,192.168.0.50,192.168.0.150 168 | 169 | # Use this DHCP range only when the tag "green" is set. 170 | #dhcp-range=tag:green,192.168.0.50,192.168.0.150,12h 171 | 172 | # Specify a subnet which can't be used for dynamic address allocation, 173 | # is available for hosts with matching --dhcp-host lines. Note that 174 | # dhcp-host declarations will be ignored unless there is a dhcp-range 175 | # of some type for the subnet in question. 176 | # In this case the netmask is implied (it comes from the network 177 | # configuration on the machine running dnsmasq) it is possible to give 178 | # an explicit netmask instead. 179 | #dhcp-range=192.168.0.0,static 180 | 181 | # Enable DHCPv6. Note that the prefix-length does not need to be specified 182 | # and defaults to 64 if missing/ 183 | #dhcp-range=1234::2, 1234::500, 64, 12h 184 | 185 | # Do Router Advertisements, BUT NOT DHCP for this subnet. 186 | #dhcp-range=1234::, ra-only 187 | 188 | # Do Router Advertisements, BUT NOT DHCP for this subnet, also try and 189 | # add names to the DNS for the IPv6 address of SLAAC-configured dual-stack 190 | # hosts. Use the DHCPv4 lease to derive the name, network segment and 191 | # MAC address and assume that the host will also have an 192 | # IPv6 address calculated using the SLAAC algorithm. 193 | #dhcp-range=1234::, ra-names 194 | 195 | # Do Router Advertisements, BUT NOT DHCP for this subnet. 196 | # Set the lifetime to 46 hours. (Note: minimum lifetime is 2 hours.) 197 | #dhcp-range=1234::, ra-only, 48h 198 | 199 | # Do DHCP and Router Advertisements for this subnet. Set the A bit in the RA 200 | # so that clients can use SLAAC addresses as well as DHCP ones. 201 | #dhcp-range=1234::2, 1234::500, slaac 202 | 203 | # Do Router Advertisements and stateless DHCP for this subnet. Clients will 204 | # not get addresses from DHCP, but they will get other configuration information. 205 | # They will use SLAAC for addresses. 206 | #dhcp-range=1234::, ra-stateless 207 | 208 | # Do stateless DHCP, SLAAC, and generate DNS names for SLAAC addresses 209 | # from DHCPv4 leases. 210 | #dhcp-range=1234::, ra-stateless, ra-names 211 | 212 | # Do router advertisements for all subnets where we're doing DHCPv6 213 | # Unless overridden by ra-stateless, ra-names, et al, the router 214 | # advertisements will have the M and O bits set, so that the clients 215 | # get addresses and configuration from DHCPv6, and the A bit reset, so the 216 | # clients don't use SLAAC addresses. 217 | #enable-ra 218 | 219 | # Supply parameters for specified hosts using DHCP. There are lots 220 | # of valid alternatives, so we will give examples of each. Note that 221 | # IP addresses DO NOT have to be in the range given above, they just 222 | # need to be on the same network. The order of the parameters in these 223 | # do not matter, it's permissible to give name, address and MAC in any 224 | # order. 225 | 226 | # Always allocate the host with Ethernet address 11:22:33:44:55:66 227 | # The IP address 192.168.0.60 228 | #dhcp-host=11:22:33:44:55:66,192.168.0.60 229 | 230 | # Always set the name of the host with hardware address 231 | # 11:22:33:44:55:66 to be "fred" 232 | #dhcp-host=11:22:33:44:55:66,fred 233 | 234 | # Always give the host with Ethernet address 11:22:33:44:55:66 235 | # the name fred and IP address 192.168.0.60 and lease time 45 minutes 236 | #dhcp-host=11:22:33:44:55:66,fred,192.168.0.60,45m 237 | 238 | # Give a host with Ethernet address 11:22:33:44:55:66 or 239 | # 12:34:56:78:90:12 the IP address 192.168.0.60. Dnsmasq will assume 240 | # that these two Ethernet interfaces will never be in use at the same 241 | # time, and give the IP address to the second, even if it is already 242 | # in use by the first. Useful for laptops with wired and wireless 243 | # addresses. 244 | #dhcp-host=11:22:33:44:55:66,12:34:56:78:90:12,192.168.0.60 245 | 246 | # Give the machine which says its name is "bert" IP address 247 | # 192.168.0.70 and an infinite lease 248 | #dhcp-host=bert,192.168.0.70,infinite 249 | 250 | # Always give the host with client identifier 01:02:02:04 251 | # the IP address 192.168.0.60 252 | #dhcp-host=id:01:02:02:04,192.168.0.60 253 | 254 | # Always give the InfiniBand interface with hardware address 255 | # 80:00:00:48:fe:80:00:00:00:00:00:00:f4:52:14:03:00:28:05:81 the 256 | # ip address 192.168.0.61. The client id is derived from the prefix 257 | # ff:00:00:00:00:00:02:00:00:02:c9:00 and the last 8 pairs of 258 | # hex digits of the hardware address. 259 | #dhcp-host=id:ff:00:00:00:00:00:02:00:00:02:c9:00:f4:52:14:03:00:28:05:81,192.168.0.61 260 | 261 | # Always give the host with client identifier "marjorie" 262 | # the IP address 192.168.0.60 263 | #dhcp-host=id:marjorie,192.168.0.60 264 | 265 | # Enable the address given for "judge" in /etc/hosts 266 | # to be given to a machine presenting the name "judge" when 267 | # it asks for a DHCP lease. 268 | #dhcp-host=judge 269 | 270 | # Never offer DHCP service to a machine whose Ethernet 271 | # address is 11:22:33:44:55:66 272 | #dhcp-host=11:22:33:44:55:66,ignore 273 | 274 | # Ignore any client-id presented by the machine with Ethernet 275 | # address 11:22:33:44:55:66. This is useful to prevent a machine 276 | # being treated differently when running under different OS's or 277 | # between PXE boot and OS boot. 278 | #dhcp-host=11:22:33:44:55:66,id:* 279 | 280 | # Send extra options which are tagged as "red" to 281 | # the machine with Ethernet address 11:22:33:44:55:66 282 | #dhcp-host=11:22:33:44:55:66,set:red 283 | 284 | # Send extra options which are tagged as "red" to 285 | # any machine with Ethernet address starting 11:22:33: 286 | #dhcp-host=11:22:33:*:*:*,set:red 287 | 288 | # Give a fixed IPv6 address and name to client with 289 | # DUID 00:01:00:01:16:d2:83:fc:92:d4:19:e2:d8:b2 290 | # Note the MAC addresses CANNOT be used to identify DHCPv6 clients. 291 | # Note also that the [] around the IPv6 address are obligatory. 292 | #dhcp-host=id:00:01:00:01:16:d2:83:fc:92:d4:19:e2:d8:b2, fred, [1234::5] 293 | 294 | # Ignore any clients which are not specified in dhcp-host lines 295 | # or /etc/ethers. Equivalent to ISC "deny unknown-clients". 296 | # This relies on the special "known" tag which is set when 297 | # a host is matched. 298 | #dhcp-ignore=tag:!known 299 | 300 | # Send extra options which are tagged as "red" to any machine whose 301 | # DHCP vendorclass string includes the substring "Linux" 302 | #dhcp-vendorclass=set:red,Linux 303 | 304 | # Send extra options which are tagged as "red" to any machine one 305 | # of whose DHCP userclass strings includes the substring "accounts" 306 | #dhcp-userclass=set:red,accounts 307 | 308 | # Send extra options which are tagged as "red" to any machine whose 309 | # MAC address matches the pattern. 310 | #dhcp-mac=set:red,00:60:8C:*:*:* 311 | 312 | # If this line is uncommented, dnsmasq will read /etc/ethers and act 313 | # on the ethernet-address/IP pairs found there just as if they had 314 | # been given as --dhcp-host options. Useful if you keep 315 | # MAC-address/host mappings there for other purposes. 316 | #read-ethers 317 | 318 | # Send options to hosts which ask for a DHCP lease. 319 | # See RFC 2132 for details of available options. 320 | # Common options can be given to dnsmasq by name: 321 | # run "dnsmasq --help dhcp" to get a list. 322 | # Note that all the common settings, such as netmask and 323 | # broadcast address, DNS server and default route, are given 324 | # sane defaults by dnsmasq. You very likely will not need 325 | # any dhcp-options. If you use Windows clients and Samba, there 326 | # are some options which are recommended, they are detailed at the 327 | # end of this section. 328 | 329 | # Override the default route supplied by dnsmasq, which assumes the 330 | # router is the same machine as the one running dnsmasq. 331 | #dhcp-option=3,1.2.3.4 332 | 333 | # Do the same thing, but using the option name 334 | #dhcp-option=option:router,1.2.3.4 335 | 336 | # Override the default route supplied by dnsmasq and send no default 337 | # route at all. Note that this only works for the options sent by 338 | # default (1, 3, 6, 12, 28) the same line will send a zero-length option 339 | # for all other option numbers. 340 | #dhcp-option=3 341 | 342 | # Set the NTP time server addresses to 192.168.0.4 and 10.10.0.5 343 | #dhcp-option=option:ntp-server,192.168.0.4,10.10.0.5 344 | 345 | # Send DHCPv6 option. Note [] around IPv6 addresses. 346 | #dhcp-option=option6:dns-server,[1234::77],[1234::88] 347 | 348 | # Send DHCPv6 option for namservers as the machine running 349 | # dnsmasq and another. 350 | #dhcp-option=option6:dns-server,[::],[1234::88] 351 | 352 | # Ask client to poll for option changes every six hours. (RFC4242) 353 | #dhcp-option=option6:information-refresh-time,6h 354 | 355 | # Set option 58 client renewal time (T1). Defaults to half of the 356 | # lease time if not specified. (RFC2132) 357 | #dhcp-option=option:T1,1m 358 | 359 | # Set option 59 rebinding time (T2). Defaults to 7/8 of the 360 | # lease time if not specified. (RFC2132) 361 | #dhcp-option=option:T2,2m 362 | 363 | # Set the NTP time server address to be the same machine as 364 | # is running dnsmasq 365 | #dhcp-option=42,0.0.0.0 366 | 367 | # Set the NIS domain name to "welly" 368 | #dhcp-option=40,welly 369 | 370 | # Set the default time-to-live to 50 371 | #dhcp-option=23,50 372 | 373 | # Set the "all subnets are local" flag 374 | #dhcp-option=27,1 375 | 376 | # Send the etherboot magic flag and then etherboot options (a string). 377 | #dhcp-option=128,e4:45:74:68:00:00 378 | #dhcp-option=129,NIC=eepro100 379 | 380 | # Specify an option which will only be sent to the "red" network 381 | # (see dhcp-range for the declaration of the "red" network) 382 | # Note that the tag: part must precede the option: part. 383 | #dhcp-option = tag:red, option:ntp-server, 192.168.1.1 384 | 385 | # The following DHCP options set up dnsmasq in the same way as is specified 386 | # for the ISC dhcpcd in 387 | # http://www.samba.org/samba/ftp/docs/textdocs/DHCP-Server-Configuration.txt 388 | # adapted for a typical dnsmasq installation where the host running 389 | # dnsmasq is also the host running samba. 390 | # you may want to uncomment some or all of them if you use 391 | # Windows clients and Samba. 392 | #dhcp-option=19,0 # option ip-forwarding off 393 | #dhcp-option=44,0.0.0.0 # set netbios-over-TCP/IP nameserver(s) aka WINS server(s) 394 | #dhcp-option=45,0.0.0.0 # netbios datagram distribution server 395 | #dhcp-option=46,8 # netbios node type 396 | 397 | # Send an empty WPAD option. This may be REQUIRED to get windows 7 to behave. 398 | #dhcp-option=252,"\n" 399 | 400 | # Send RFC-3397 DNS domain search DHCP option. WARNING: Your DHCP client 401 | # probably doesn't support this...... 402 | #dhcp-option=option:domain-search,eng.apple.com,marketing.apple.com 403 | 404 | # Send RFC-3442 classless static routes (note the netmask encoding) 405 | #dhcp-option=121,192.168.1.0/24,1.2.3.4,10.0.0.0/8,5.6.7.8 406 | 407 | # Send vendor-class specific options encapsulated in DHCP option 43. 408 | # The meaning of the options is defined by the vendor-class so 409 | # options are sent only when the client supplied vendor class 410 | # matches the class given here. (A substring match is OK, so "MSFT" 411 | # matches "MSFT" and "MSFT 5.0"). This example sets the 412 | # mtftp address to 0.0.0.0 for PXEClients. 413 | #dhcp-option=vendor:PXEClient,1,0.0.0.0 414 | 415 | # Send microsoft-specific option to tell windows to release the DHCP lease 416 | # when it shuts down. Note the "i" flag, to tell dnsmasq to send the 417 | # value as a four-byte integer - that's what microsoft wants. See 418 | # http://technet2.microsoft.com/WindowsServer/en/library/a70f1bb7-d2d4-49f0-96d6-4b7414ecfaae1033.mspx?mfr=true 419 | #dhcp-option=vendor:MSFT,2,1i 420 | 421 | # Send the Encapsulated-vendor-class ID needed by some configurations of 422 | # Etherboot to allow is to recognise the DHCP server. 423 | #dhcp-option=vendor:Etherboot,60,"Etherboot" 424 | 425 | # Send options to PXELinux. Note that we need to send the options even 426 | # though they don't appear in the parameter request list, so we need 427 | # to use dhcp-option-force here. 428 | # See http://syslinux.zytor.com/pxe.php#special for details. 429 | # Magic number - needed before anything else is recognised 430 | #dhcp-option-force=208,f1:00:74:7e 431 | # Configuration file name 432 | #dhcp-option-force=209,configs/common 433 | # Path prefix 434 | #dhcp-option-force=210,/tftpboot/pxelinux/files/ 435 | # Reboot time. (Note 'i' to send 32-bit value) 436 | #dhcp-option-force=211,30i 437 | 438 | # Set the boot filename for netboot/PXE. You will only need 439 | # this if you want to boot machines over the network and you will need 440 | # a TFTP server; either dnsmasq's built-in TFTP server or an 441 | # external one. (See below for how to enable the TFTP server.) 442 | #dhcp-boot=pxelinux.0 443 | 444 | # The same as above, but use custom tftp-server instead machine running dnsmasq 445 | #dhcp-boot=pxelinux,server.name,192.168.1.100 446 | 447 | # Boot for iPXE. The idea is to send two different 448 | # filenames, the first loads iPXE, and the second tells iPXE what to 449 | # load. The dhcp-match sets the ipxe tag for requests from iPXE. 450 | #dhcp-boot=undionly.kpxe 451 | #dhcp-match=set:ipxe,175 # iPXE sends a 175 option. 452 | #dhcp-boot=tag:ipxe,http://boot.ipxe.org/demo/boot.php 453 | 454 | # Encapsulated options for iPXE. All the options are 455 | # encapsulated within option 175 456 | #dhcp-option=encap:175, 1, 5b # priority code 457 | #dhcp-option=encap:175, 176, 1b # no-proxydhcp 458 | #dhcp-option=encap:175, 177, string # bus-id 459 | #dhcp-option=encap:175, 189, 1b # BIOS drive code 460 | #dhcp-option=encap:175, 190, user # iSCSI username 461 | #dhcp-option=encap:175, 191, pass # iSCSI password 462 | 463 | # Test for the architecture of a netboot client. PXE clients are 464 | # supposed to send their architecture as option 93. (See RFC 4578) 465 | #dhcp-match=peecees, option:client-arch, 0 #x86-32 466 | #dhcp-match=itanics, option:client-arch, 2 #IA64 467 | #dhcp-match=hammers, option:client-arch, 6 #x86-64 468 | #dhcp-match=mactels, option:client-arch, 7 #EFI x86-64 469 | 470 | # Do real PXE, rather than just booting a single file, this is an 471 | # alternative to dhcp-boot. 472 | #pxe-prompt="What system shall I netboot?" 473 | # or with timeout before first available action is taken: 474 | #pxe-prompt="Press F8 for menu.", 60 475 | 476 | # Available boot services. for PXE. 477 | #pxe-service=x86PC, "Boot from local disk" 478 | 479 | # Loads /pxelinux.0 from dnsmasq TFTP server. 480 | #pxe-service=x86PC, "Install Linux", pxelinux 481 | 482 | # Loads /pxelinux.0 from TFTP server at 1.2.3.4. 483 | # Beware this fails on old PXE ROMS. 484 | #pxe-service=x86PC, "Install Linux", pxelinux, 1.2.3.4 485 | 486 | # Use bootserver on network, found my multicast or broadcast. 487 | #pxe-service=x86PC, "Install windows from RIS server", 1 488 | 489 | # Use bootserver at a known IP address. 490 | #pxe-service=x86PC, "Install windows from RIS server", 1, 1.2.3.4 491 | 492 | # If you have multicast-FTP available, 493 | # information for that can be passed in a similar way using options 1 494 | # to 5. See page 19 of 495 | # http://download.intel.com/design/archives/wfm/downloads/pxespec.pdf 496 | 497 | 498 | # Enable dnsmasq's built-in TFTP server 499 | #enable-tftp 500 | 501 | # Set the root directory for files available via FTP. 502 | #tftp-root=/var/ftpd 503 | 504 | # Do not abort if the tftp-root is unavailable 505 | #tftp-no-fail 506 | 507 | # Make the TFTP server more secure: with this set, only files owned by 508 | # the user dnsmasq is running as will be send over the net. 509 | #tftp-secure 510 | 511 | # This option stops dnsmasq from negotiating a larger blocksize for TFTP 512 | # transfers. It will slow things down, but may rescue some broken TFTP 513 | # clients. 514 | #tftp-no-blocksize 515 | 516 | # Set the boot file name only when the "red" tag is set. 517 | #dhcp-boot=tag:red,pxelinux.red-net 518 | 519 | # An example of dhcp-boot with an external TFTP server: the name and IP 520 | # address of the server are given after the filename. 521 | # Can fail with old PXE ROMS. Overridden by --pxe-service. 522 | #dhcp-boot=/var/ftpd/pxelinux.0,boothost,192.168.0.3 523 | 524 | # If there are multiple external tftp servers having a same name 525 | # (using /etc/hosts) then that name can be specified as the 526 | # tftp_servername (the third option to dhcp-boot) and in that 527 | # case dnsmasq resolves this name and returns the resultant IP 528 | # addresses in round robin fashion. This facility can be used to 529 | # load balance the tftp load among a set of servers. 530 | #dhcp-boot=/var/ftpd/pxelinux.0,boothost,tftp_server_name 531 | 532 | # Set the limit on DHCP leases, the default is 150 533 | #dhcp-lease-max=150 534 | 535 | # The DHCP server needs somewhere on disk to keep its lease database. 536 | # This defaults to a sane location, but if you want to change it, use 537 | # the line below. 538 | #dhcp-leasefile=/var/lib/misc/dnsmasq.leases 539 | 540 | # Set the DHCP server to authoritative mode. In this mode it will barge in 541 | # and take over the lease for any client which broadcasts on the network, 542 | # whether it has a record of the lease or not. This avoids long timeouts 543 | # when a machine wakes up on a new network. DO NOT enable this if there's 544 | # the slightest chance that you might end up accidentally configuring a DHCP 545 | # server for your campus/company accidentally. The ISC server uses 546 | # the same option, and this URL provides more information: 547 | # http://www.isc.org/files/auth.html 548 | #dhcp-authoritative 549 | 550 | # Run an executable when a DHCP lease is created or destroyed. 551 | # The arguments sent to the script are "add" or "del", 552 | # then the MAC address, the IP address and finally the hostname 553 | # if there is one. 554 | #dhcp-script=/bin/echo 555 | 556 | # Set the cachesize here. 557 | cache-size=150 558 | 559 | # If you want to disable negative caching, uncomment this. 560 | #no-negcache 561 | 562 | # Normally responses which come from /etc/hosts and the DHCP lease 563 | # file have Time-To-Live set as zero, which conventionally means 564 | # do not cache further. If you are happy to trade lower load on the 565 | # server for potentially stale date, you can set a time-to-live (in 566 | # seconds) here. 567 | #local-ttl= 568 | 569 | # If you want dnsmasq to detect attempts by Verisign to send queries 570 | # to unregistered .com and .net hosts to its sitefinder service and 571 | # have dnsmasq instead return the correct NXDOMAIN response, uncomment 572 | # this line. You can add similar lines to do the same for other 573 | # registries which have implemented wildcard A records. 574 | #bogus-nxdomain=64.94.110.11 575 | 576 | # If you want to fix up DNS results from upstream servers, use the 577 | # alias option. This only works for IPv4. 578 | # This alias makes a result of 1.2.3.4 appear as 5.6.7.8 579 | #alias=1.2.3.4,5.6.7.8 580 | # and this maps 1.2.3.x to 5.6.7.x 581 | #alias=1.2.3.0,5.6.7.0,255.255.255.0 582 | # and this maps 192.168.0.10->192.168.0.40 to 10.0.0.10->10.0.0.40 583 | #alias=192.168.0.10-192.168.0.40,10.0.0.0,255.255.255.0 584 | 585 | # Change these lines if you want dnsmasq to serve MX records. 586 | 587 | # Return an MX record named "maildomain.com" with target 588 | # servermachine.com and preference 50 589 | #mx-host=maildomain.com,servermachine.com,50 590 | 591 | # Set the default target for MX records created using the localmx option. 592 | #mx-target=servermachine.com 593 | 594 | # Return an MX record pointing to the mx-target for all local 595 | # machines. 596 | #localmx 597 | 598 | # Return an MX record pointing to itself for all local machines. 599 | #selfmx 600 | 601 | # Change the following lines if you want dnsmasq to serve SRV 602 | # records. These are useful if you want to serve ldap requests for 603 | # Active Directory and other windows-originated DNS requests. 604 | # See RFC 2782. 605 | # You may add multiple srv-host lines. 606 | # The fields are ,,,, 607 | # If the domain part if missing from the name (so that is just has the 608 | # service and protocol sections) then the domain given by the domain= 609 | # config option is used. (Note that expand-hosts does not need to be 610 | # set for this to work.) 611 | 612 | # A SRV record sending LDAP for the example.com domain to 613 | # ldapserver.example.com port 389 614 | #srv-host=_ldap._tcp.example.com,ldapserver.example.com,389 615 | 616 | # A SRV record sending LDAP for the example.com domain to 617 | # ldapserver.example.com port 389 (using domain=) 618 | #domain=example.com 619 | #srv-host=_ldap._tcp,ldapserver.example.com,389 620 | 621 | # Two SRV records for LDAP, each with different priorities 622 | #srv-host=_ldap._tcp.example.com,ldapserver.example.com,389,1 623 | #srv-host=_ldap._tcp.example.com,ldapserver.example.com,389,2 624 | 625 | # A SRV record indicating that there is no LDAP server for the domain 626 | # example.com 627 | #srv-host=_ldap._tcp.example.com 628 | 629 | # The following line shows how to make dnsmasq serve an arbitrary PTR 630 | # record. This is useful for DNS-SD. (Note that the 631 | # domain-name expansion done for SRV records _does_not 632 | # occur for PTR records.) 633 | #ptr-record=_http._tcp.dns-sd-services,"New Employee Page._http._tcp.dns-sd-services" 634 | 635 | # Change the following lines to enable dnsmasq to serve TXT records. 636 | # These are used for things like SPF and zeroconf. (Note that the 637 | # domain-name expansion done for SRV records _does_not 638 | # occur for TXT records.) 639 | 640 | #Example SPF. 641 | #txt-record=example.com,"v=spf1 a -all" 642 | 643 | #Example zeroconf 644 | #txt-record=_http._tcp.example.com,name=value,paper=A4 645 | 646 | # Provide an alias for a "local" DNS name. Note that this _only_ works 647 | # for targets which are names from DHCP or /etc/hosts. Give host 648 | # "bert" another name, bertrand 649 | #cname=bertand,bert 650 | 651 | # For debugging purposes, log each DNS query as it passes through 652 | # dnsmasq. 653 | #log-queries 654 | 655 | # Log lots of extra information about DHCP transactions. 656 | #log-dhcp 657 | 658 | # Include another lot of configuration options. 659 | #conf-file=/etc/dnsmasq.more.conf 660 | #conf-dir=/etc/dnsmasq.d 661 | 662 | # Include all the files in a directory except those ending in .bak 663 | #conf-dir=/etc/dnsmasq.d,.bak 664 | 665 | # Include all files in a directory which end in .conf 666 | #conf-dir=/etc/dnsmasq.d/,*.conf 667 | -------------------------------------------------------------------------------- /dns/images/resolv.conf.dnsmasq: -------------------------------------------------------------------------------- 1 | nameserver 8.8.8.8 2 | -------------------------------------------------------------------------------- /dns/ping.pcap: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/feiskyer/linux-perf-examples/8e8cd6ce4061d7499db9f95fe399156228f8322b/dns/ping.pcap -------------------------------------------------------------------------------- /dns/web.pcap: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/feiskyer/linux-perf-examples/8e8cd6ce4061d7499db9f95fe399156228f8322b/dns/web.pcap -------------------------------------------------------------------------------- /flamegraph/README.md: -------------------------------------------------------------------------------- 1 | # 火焰图 2 | 3 | [火焰图](http://www.brendangregg.com/flamegraphs.html) 可以以矢量图的方式动态展示通过 perf、systemtap、bpftrace 等各种工具获取的性能剖析数据。 4 | 5 | ## 使用方法 6 | 7 | ```sh 8 | # 下载工具 9 | $ git clone https://github.com/brendangregg/FlameGraph 10 | $ cd FlameGraph 11 | 12 | # 使用perf记录性能数据 13 | $ perf record -a -g -- sleep 30 14 | 15 | # 生成火焰图 16 | $ perf script -i perf.data | ./stackcollapse-perf.pl --all | ./flamegraph.pl > ksoftirqd.svg 17 | ``` 18 | 19 | ## 示例火焰图 20 | 21 | **MySQL 火焰图** 22 | 23 | ![MySQL 火焰图](cpu-mysql-updated.svg) 24 | 25 | 26 | 27 | **ksoftirqd 火焰图** 28 | 29 | ![ksoftirqd 火焰图](ksoftirqd.svg) 30 | 31 | 32 | 33 | **jbd2 火焰图** 34 | 35 | ![jbd2 火焰图](jbd2.svg) -------------------------------------------------------------------------------- /flamegraph/jbd2.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 23 | 337 | 338 | Flame Graph 339 | 340 | Reset Zoom 341 | Search 342 | 343 | 344 | 345 | blk_account_io_start (6 samples, 8.96%) 346 | blk_account_.. 347 | 348 | 349 | mempool_alloc_slab (2 samples, 2.99%) 350 | me.. 351 | 352 | 353 | __schedule (16 samples, 23.88%) 354 | __schedule 355 | 356 | 357 | mempool_alloc (1 samples, 1.49%) 358 | 359 | 360 | 361 | kthread (67 samples, 100.00%) 362 | kthread 363 | 364 | 365 | submit_bio (35 samples, 52.24%) 366 | submit_bio 367 | 368 | 369 | read_hv_clock_tsc (2 samples, 2.99%) 370 | re.. 371 | 372 | 373 | ext4_journal_commit_callback (67 samples, 100.00%) 374 | ext4_journal_commit_callback 375 | 376 | 377 | wbt_wait (1 samples, 1.49%) 378 | 379 | 380 | 381 | _cond_resched (18 samples, 26.87%) 382 | _cond_resched 383 | 384 | 385 | blk_integrity_merge_bio (1 samples, 1.49%) 386 | 387 | 388 | 389 | jbd2/sda1-8 (67 samples, 100.00%) 390 | jbd2/sda1-8 391 | 392 | 393 | blk_mq_queue_tag_busy_iter (1 samples, 1.49%) 394 | 395 | 396 | 397 | mempool_alloc (3 samples, 4.48%) 398 | mempo.. 399 | 400 | 401 | mod_delayed_work_on (7 samples, 10.45%) 402 | mod_delayed_wor.. 403 | 404 | 405 | finish_task_switch (16 samples, 23.88%) 406 | finish_task_switch 407 | 408 | 409 | kmem_cache_alloc (2 samples, 2.99%) 410 | km.. 411 | 412 | 413 | part_in_flight (1 samples, 1.49%) 414 | 415 | 416 | 417 | kjournald2 (67 samples, 100.00%) 418 | kjournald2 419 | 420 | 421 | blk_queue_split (2 samples, 2.99%) 422 | bl.. 423 | 424 | 425 | ext4_process_freed_data (67 samples, 100.00%) 426 | ext4_process_freed_data 427 | 428 | 429 | __slab_alloc (2 samples, 2.99%) 430 | __.. 431 | 432 | 433 | bio_init (1 samples, 1.49%) 434 | 435 | 436 | 437 | percpu_counter_add_batch (1 samples, 1.49%) 438 | 439 | 440 | 441 | generic_make_request (35 samples, 52.24%) 442 | generic_make_request 443 | 444 | 445 | kthread_blkcg (1 samples, 1.49%) 446 | 447 | 448 | 449 | bio_chain (5 samples, 7.46%) 450 | bio_chain 451 | 452 | 453 | ktime_get (2 samples, 2.99%) 454 | kt.. 455 | 456 | 457 | blk_mq_bio_list_merge (1 samples, 1.49%) 458 | 459 | 460 | 461 | blk_mq_in_flight (1 samples, 1.49%) 462 | 463 | 464 | 465 | blk_mq_check_inflight (1 samples, 1.49%) 466 | 467 | 468 | 469 | blk_mq_run_hw_queue (7 samples, 10.45%) 470 | blk_mq_run_hw_q.. 471 | 472 | 473 | generic_make_request_checks (2 samples, 2.99%) 474 | ge.. 475 | 476 | 477 | next_bio (45 samples, 67.16%) 478 | next_bio 479 | 480 | 481 | blk_mq_bio_to_request (7 samples, 10.45%) 482 | blk_mq_bio_to_r.. 483 | 484 | 485 | __blkdev_issue_discard (65 samples, 97.01%) 486 | __blkdev_issue_discard 487 | 488 | 489 | kblockd_mod_delayed_work_on (7 samples, 10.45%) 490 | kblockd_mod_del.. 491 | 492 | 493 | part_round_stats (1 samples, 1.49%) 494 | 495 | 496 | 497 | blk_init_request_from_bio (1 samples, 1.49%) 498 | 499 | 500 | 501 | __blk_mq_sched_bio_merge (2 samples, 2.99%) 502 | __.. 503 | 504 | 505 | blk_mq_make_request (32 samples, 47.76%) 506 | blk_mq_make_request 507 | 508 | 509 | __blk_mq_delay_run_hw_queue (7 samples, 10.45%) 510 | __blk_mq_delay_.. 511 | 512 | 513 | blk_mq_sched_insert_request (7 samples, 10.45%) 514 | blk_mq_sched_in.. 515 | 516 | 517 | jbd2_journal_commit_transaction (67 samples, 100.00%) 518 | jbd2_journal_commit_transaction 519 | 520 | 521 | blk_mq_get_request (7 samples, 10.45%) 522 | blk_mq_get_requ.. 523 | 524 | 525 | ret_from_fork (67 samples, 100.00%) 526 | ret_from_fork 527 | 528 | 529 | all (67 samples, 100%) 530 | 531 | 532 | 533 | bio_alloc_bioset (4 samples, 5.97%) 534 | bio_all.. 535 | 536 | 537 | 538 | -------------------------------------------------------------------------------- /high-iowait-process/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM ubuntu 2 | 3 | LABEL maintainer="feiskyer@gmail.com" 4 | 5 | ADD app /app 6 | 7 | CMD ["/app"] 8 | -------------------------------------------------------------------------------- /high-iowait-process/Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: build 2 | build: 3 | gcc -o app app.c 4 | docker build -t feisky/app:iowait -f Dockerfile . 5 | gcc -o app app-fix1.c 6 | docker build -t feisky/app:iowait-fix1 -f Dockerfile . 7 | gcc -o app app-fix2.c 8 | docker build -t feisky/app:iowait-fix2 -f Dockerfile . 9 | 10 | .PHONY: push 11 | push: 12 | docker push feisky/app:iowait 13 | docker push feisky/app:iowait-fix1 14 | docker push feisky/app:iowait-fix2 15 | 16 | .PHONY: run 17 | run: 18 | docker run --privileged --name=app -itd feisky/app:iowait 19 | 20 | .PHONY: run-fix1 21 | run-fix1: 22 | docker run --privileged --name=app -itd feisky/app:iowait-fix1 23 | 24 | .PHONY: run-fix2 25 | run-fix2: 26 | docker run --privileged --name=app -itd feisky/app:iowait-fix2 27 | 28 | .PHONY: clean 29 | clean: 30 | rm -f app 31 | docker rm -f app || echo "Container app already deleted." 32 | -------------------------------------------------------------------------------- /high-iowait-process/README.md: -------------------------------------------------------------------------------- 1 | # iowait 使用率过高案例 2 | 3 | **《[Linux 性能优化实战](https://time.geekbang.org/column/intro/140)》第 07 和 08 篇案例。** 4 | 5 | 案例场景为多个子进程读取磁盘导致以下两种现象: 6 | 7 | * 系统的 iowait 使用率和平均负载过高 8 | * 大量僵尸进程 9 | 10 | ## 构建 Docker 镜像 11 | 12 | ```sh 13 | make build 14 | ``` 15 | 16 | ## 运行案例应用 17 | 18 | ```sh 19 | make run 20 | ``` 21 | 22 | 默认的运行命令为 `docker run --privileged --name=app -itd feisky/app:iowait`。 23 | 24 | 你还可以通过以下三个选项来修改磁盘读取的行为: 25 | 26 | * `-d` 设置要读取的磁盘,默认前缀为 `/dev/sd` 或者 `/dev/xvd` 的磁盘 27 | * `-s` 设置每次读取的数据量大小,单位为字节,默认为 67108864(也就是 64MB) 28 | * `-c` 设置每个子进程读取的次数,默认为 20 次,也就是读取 20*64MB 数据后子进程退出 29 | 30 | 这些选项的使用方法为: 31 | 32 | ```sh 33 | docker run --privileged --name=app -itd feisky/app:iowait /app -d /dev/sdb -s 67108864 -c 20 34 | ``` 35 | 36 | 案例运行后,你可以执行 `docker logs app` 查看它的日志,正常情况下,可以看到如下的输出: 37 | 38 | ```sh 39 | Reading data from disk /dev/sdb with buffer size 67108864 and count 20 40 | ``` 41 | 42 | ## 停止应用 43 | 44 | ```sh 45 | make clean 46 | ``` 47 | -------------------------------------------------------------------------------- /high-iowait-process/app-fix1.c: -------------------------------------------------------------------------------- 1 | #define _GNU_SOURCE 2 | #define BUF_SIZE 64 * 1024 * 1024 3 | #define BUF_COUNT 20 4 | 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | 19 | char *select_disk() 20 | { 21 | DIR *dirptr = opendir("/dev/"); 22 | if (dirptr == NULL) 23 | { 24 | perror("Failed to open dir"); 25 | return NULL; 26 | } 27 | 28 | struct dirent *entry; 29 | char *result = (char *)calloc(512, sizeof(char)); 30 | const char *sd_prefix = "sd"; 31 | const char *xvd_prefix = "xvd"; 32 | while (entry = readdir(dirptr)) 33 | { 34 | if (strncmp(sd_prefix, entry->d_name, 2) == 0 || strncmp(xvd_prefix, entry->d_name, 3) == 0) 35 | { 36 | snprintf(result, 512 * sizeof(char), "/dev/%s", entry->d_name); 37 | closedir(dirptr); 38 | return result; 39 | } 40 | } 41 | closedir(dirptr); 42 | 43 | dirptr = opendir("/dev/mapper/"); 44 | if (dirptr == NULL) 45 | { 46 | perror("Failed to open dir"); 47 | return NULL; 48 | } 49 | while (entry = readdir(dirptr)) 50 | { 51 | if (strncmp(".", entry->d_name, 1) != 0) 52 | { 53 | snprintf(result, 512 * sizeof(char), "/dev/mapper/%s", entry->d_name); 54 | closedir(dirptr); 55 | return result; 56 | } 57 | } 58 | closedir(dirptr); 59 | free(result); 60 | return NULL; 61 | } 62 | 63 | long int get_value(char *str) 64 | { 65 | char *endptr = NULL; 66 | long int value = strtol(str, &endptr, 10); 67 | if ((errno == ERANGE && (value == LONG_MAX || value == LONG_MIN)) || (errno != 0 && value == 0)) 68 | { 69 | perror("strtol"); 70 | return -1; 71 | } 72 | 73 | if (endptr == str) 74 | { 75 | perror("not number"); 76 | return -1; 77 | } 78 | 79 | if (value <= 0) 80 | { 81 | perror("not positive number"); 82 | return -1; 83 | } 84 | 85 | return value; 86 | } 87 | 88 | void sub_process(const char *disk, size_t buffer_size, size_t count) 89 | { 90 | int fd = open(disk, O_RDONLY | O_LARGEFILE, 0755); 91 | if (fd < 0) 92 | { 93 | perror("failed to open disk"); 94 | _exit(1); 95 | } 96 | 97 | unsigned char *buf; 98 | posix_memalign((void **)&buf, 512, buffer_size); 99 | int read_bytes = 0; 100 | while (read_bytes < count * buffer_size) 101 | { 102 | int ret = read(fd, buf, buffer_size); 103 | if (ret < 0) 104 | { 105 | perror("failed to read contents"); 106 | close(fd); 107 | free(buf); 108 | _exit(1); 109 | } 110 | read_bytes += ret; 111 | } 112 | 113 | out: 114 | close(fd); 115 | free(buf); 116 | _exit(0); 117 | } 118 | 119 | int main(int argc, char **argv) 120 | { 121 | int status = 0; 122 | int c = 0; 123 | char *disk = NULL; 124 | char *size = NULL; 125 | char *count = NULL; 126 | 127 | while ((c = getopt(argc, argv, "d:s:c:")) != -1) 128 | { 129 | switch (c) 130 | { 131 | case 'd': 132 | disk = optarg; 133 | break; 134 | case 's': 135 | size = optarg; 136 | break; 137 | case 'c': 138 | count = optarg; 139 | break; 140 | case '?': 141 | printf("Illegal option: -%c\n", isprint(optopt) ? optopt : '#'); 142 | _exit(1); 143 | default: 144 | _exit(1); 145 | } 146 | } 147 | 148 | if (disk == NULL) 149 | { 150 | disk = select_disk(); 151 | } 152 | if (disk == NULL) 153 | { 154 | _exit(1); 155 | } 156 | 157 | long int buffer_size = BUF_SIZE; 158 | long int buffer_count = BUF_COUNT; 159 | if (size != NULL) 160 | { 161 | buffer_size = get_value(size); 162 | if (buffer_size < 0) 163 | { 164 | exit(1); 165 | } 166 | } 167 | if (count != NULL) 168 | { 169 | buffer_count = get_value(count); 170 | if (buffer_count < 0) 171 | { 172 | exit(1); 173 | } 174 | } 175 | 176 | printf("Reading data from disk %s with buffer size %ld and count %ld\n", disk, buffer_size, buffer_count); 177 | 178 | int i = 0; 179 | for (;;) 180 | { 181 | for (i = 0; i < 2; i++) 182 | { 183 | if (fork() == 0) 184 | { 185 | sub_process(disk, buffer_size, buffer_count); 186 | } 187 | } 188 | sleep(5); 189 | } 190 | 191 | while (wait(&status) > 0); 192 | return 0; 193 | } 194 | -------------------------------------------------------------------------------- /high-iowait-process/app-fix2.c: -------------------------------------------------------------------------------- 1 | #define _GNU_SOURCE 2 | #define BUF_SIZE 64 * 1024 * 1024 3 | #define BUF_COUNT 20 4 | 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | 19 | char *select_disk() 20 | { 21 | DIR *dirptr = opendir("/dev/"); 22 | if (dirptr == NULL) 23 | { 24 | perror("Failed to open dir"); 25 | return NULL; 26 | } 27 | 28 | struct dirent *entry; 29 | char *result = (char *)calloc(512, sizeof(char)); 30 | const char *sd_prefix = "sd"; 31 | const char *xvd_prefix = "xvd"; 32 | while (entry = readdir(dirptr)) 33 | { 34 | if (strncmp(sd_prefix, entry->d_name, 2) == 0 || strncmp(xvd_prefix, entry->d_name, 3) == 0) 35 | { 36 | snprintf(result, 512 * sizeof(char), "/dev/%s", entry->d_name); 37 | closedir(dirptr); 38 | return result; 39 | } 40 | } 41 | closedir(dirptr); 42 | 43 | dirptr = opendir("/dev/mapper/"); 44 | if (dirptr == NULL) 45 | { 46 | perror("Failed to open dir"); 47 | return NULL; 48 | } 49 | while (entry = readdir(dirptr)) 50 | { 51 | if (strncmp(".", entry->d_name, 1) != 0) 52 | { 53 | snprintf(result, 512 * sizeof(char), "/dev/mapper/%s", entry->d_name); 54 | closedir(dirptr); 55 | return result; 56 | } 57 | } 58 | closedir(dirptr); 59 | 60 | free(result); 61 | return NULL; 62 | } 63 | 64 | long int get_value(char *str) 65 | { 66 | char *endptr = NULL; 67 | long int value = strtol(str, &endptr, 10); 68 | if ((errno == ERANGE && (value == LONG_MAX || value == LONG_MIN)) || (errno != 0 && value == 0)) 69 | { 70 | perror("strtol"); 71 | return -1; 72 | } 73 | 74 | if (endptr == str) 75 | { 76 | perror("not number"); 77 | return -1; 78 | } 79 | 80 | if (value <= 0) 81 | { 82 | perror("not positive number"); 83 | return -1; 84 | } 85 | 86 | return value; 87 | } 88 | 89 | void sub_process(const char *disk, size_t buffer_size, size_t count) 90 | { 91 | int fd = open(disk, O_RDONLY | O_LARGEFILE, 0755); 92 | if (fd < 0) 93 | { 94 | perror("failed to open disk"); 95 | _exit(1); 96 | } 97 | 98 | unsigned char *buf; 99 | posix_memalign((void **)&buf, 512, buffer_size); 100 | int read_bytes = 0; 101 | while (read_bytes < count * buffer_size) 102 | { 103 | int ret = read(fd, buf, buffer_size); 104 | if (ret < 0) 105 | { 106 | perror("failed to read contents"); 107 | close(fd); 108 | free(buf); 109 | _exit(1); 110 | } 111 | read_bytes += ret; 112 | } 113 | 114 | out: 115 | close(fd); 116 | free(buf); 117 | _exit(0); 118 | } 119 | 120 | int main(int argc, char **argv) 121 | { 122 | int status = 0; 123 | int c = 0; 124 | char *disk = NULL; 125 | char *size = NULL; 126 | char *count = NULL; 127 | 128 | while ((c = getopt(argc, argv, "d:s:c:")) != -1) 129 | { 130 | switch (c) 131 | { 132 | case 'd': 133 | disk = optarg; 134 | break; 135 | case 's': 136 | size = optarg; 137 | break; 138 | case 'c': 139 | count = optarg; 140 | break; 141 | case '?': 142 | printf("Illegal option: -%c\n", isprint(optopt) ? optopt : '#'); 143 | _exit(1); 144 | default: 145 | _exit(1); 146 | } 147 | } 148 | 149 | if (disk == NULL) 150 | { 151 | disk = select_disk(); 152 | } 153 | if (disk == NULL) 154 | { 155 | _exit(1); 156 | } 157 | 158 | long int buffer_size = BUF_SIZE; 159 | long int buffer_count = BUF_COUNT; 160 | if (size != NULL) 161 | { 162 | buffer_size = get_value(size); 163 | if (buffer_size < 0) 164 | { 165 | exit(1); 166 | } 167 | } 168 | if (count != NULL) 169 | { 170 | buffer_count = get_value(count); 171 | if (buffer_count < 0) 172 | { 173 | exit(1); 174 | } 175 | } 176 | 177 | printf("Reading data from disk %s with buffer size %ld and count %ld\n", disk, buffer_size, buffer_count); 178 | 179 | int i = 0; 180 | for (;;) 181 | { 182 | for (i = 0; i < 2; i++) 183 | { 184 | if (fork() == 0) 185 | { 186 | sub_process(disk, buffer_size, buffer_count); 187 | } 188 | } 189 | 190 | while (wait(&status) > 0); 191 | sleep(5); 192 | } 193 | 194 | return 0; 195 | } 196 | -------------------------------------------------------------------------------- /high-iowait-process/app.c: -------------------------------------------------------------------------------- 1 | #define _GNU_SOURCE 2 | #define BUF_SIZE 64 * 1024 * 1024 3 | #define BUF_COUNT 20 4 | 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | 19 | char *select_disk() 20 | { 21 | DIR *dirptr = opendir("/dev/"); 22 | if (dirptr == NULL) 23 | { 24 | perror("Failed to open dir"); 25 | return NULL; 26 | } 27 | 28 | struct dirent *entry; 29 | char *result = (char *)calloc(512, sizeof(char)); 30 | const char *sd_prefix = "sd"; 31 | const char *xvd_prefix = "xvd"; 32 | while (entry = readdir(dirptr)) 33 | { 34 | if (strncmp(sd_prefix, entry->d_name, 2) == 0 || strncmp(xvd_prefix, entry->d_name, 3) == 0) 35 | { 36 | snprintf(result, 512 * sizeof(char), "/dev/%s", entry->d_name); 37 | closedir(dirptr); 38 | return result; 39 | } 40 | } 41 | 42 | closedir(dirptr); 43 | 44 | dirptr = opendir("/dev/mapper/"); 45 | if (dirptr == NULL) 46 | { 47 | perror("Failed to open dir"); 48 | return NULL; 49 | } 50 | while (entry = readdir(dirptr)) 51 | { 52 | if (strncmp(".", entry->d_name, 1) != 0) 53 | { 54 | snprintf(result, 512 * sizeof(char), "/dev/mapper/%s", entry->d_name); 55 | closedir(dirptr); 56 | return result; 57 | } 58 | } 59 | closedir(dirptr); 60 | free(result); 61 | return NULL; 62 | } 63 | 64 | long int get_value(char *str) 65 | { 66 | char *endptr = NULL; 67 | long int value = strtol(str, &endptr, 10); 68 | if ((errno == ERANGE && (value == LONG_MAX || value == LONG_MIN)) || (errno != 0 && value == 0)) 69 | { 70 | perror("strtol"); 71 | return -1; 72 | } 73 | 74 | if (endptr == str) 75 | { 76 | perror("not number"); 77 | return -1; 78 | } 79 | 80 | if (value <= 0) 81 | { 82 | perror("not positive number"); 83 | return -1; 84 | } 85 | 86 | return value; 87 | } 88 | 89 | void sub_process(const char *disk, size_t buffer_size, size_t count) 90 | { 91 | int fd = open(disk, O_RDONLY | O_DIRECT | O_LARGEFILE, 0755); 92 | if (fd < 0) 93 | { 94 | perror("failed to open disk"); 95 | _exit(1); 96 | } 97 | 98 | unsigned char *buf; 99 | posix_memalign((void **)&buf, 512, buffer_size); 100 | size_t read_bytes = 0; 101 | while (read_bytes < count * buffer_size) 102 | { 103 | size_t ret = read(fd, buf, buffer_size); 104 | if (ret < 0) 105 | { 106 | perror("failed to read contents"); 107 | close(fd); 108 | free(buf); 109 | _exit(1); 110 | } 111 | read_bytes += ret; 112 | } 113 | 114 | close(fd); 115 | free(buf); 116 | _exit(0); 117 | } 118 | 119 | int main(int argc, char **argv) 120 | { 121 | int status = 0; 122 | int c = 0; 123 | char *disk = NULL; 124 | char *size = NULL; 125 | char *count = NULL; 126 | 127 | while ((c = getopt(argc, argv, "d:s:c:")) != -1) 128 | { 129 | switch (c) 130 | { 131 | case 'd': 132 | disk = optarg; 133 | break; 134 | case 's': 135 | size = optarg; 136 | break; 137 | case 'c': 138 | count = optarg; 139 | break; 140 | case '?': 141 | printf("Illegal option: -%c\n", isprint(optopt) ? optopt : '#'); 142 | _exit(1); 143 | default: 144 | _exit(1); 145 | } 146 | } 147 | 148 | if (disk == NULL) 149 | { 150 | disk = select_disk(); 151 | } 152 | if (disk == NULL) 153 | { 154 | _exit(1); 155 | } 156 | 157 | long int buffer_size = BUF_SIZE; 158 | long int buffer_count = BUF_COUNT; 159 | if (size != NULL) 160 | { 161 | buffer_size = get_value(size); 162 | if (buffer_size < 0) 163 | { 164 | exit(1); 165 | } 166 | } 167 | if (count != NULL) 168 | { 169 | buffer_count = get_value(count); 170 | if (buffer_count < 0) 171 | { 172 | exit(1); 173 | } 174 | } 175 | 176 | printf("Reading data from disk %s with buffer size %ld and count %ld\n", disk, buffer_size, buffer_count); 177 | 178 | int i = 0; 179 | for (;;) 180 | { 181 | for (i = 0; i < 2; i++) 182 | { 183 | if (fork() == 0) 184 | { 185 | sub_process(disk, buffer_size, buffer_count); 186 | } 187 | } 188 | sleep(5); 189 | } 190 | 191 | while (wait(&status) > 0); 192 | return 0; 193 | } 194 | -------------------------------------------------------------------------------- /images/intro.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/feiskyer/linux-perf-examples/8e8cd6ce4061d7499db9f95fe399156228f8322b/images/intro.jpg -------------------------------------------------------------------------------- /io-cached/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM ubuntu 2 | 3 | LABEL maintainer="feiskyer@gmail.com" 4 | 5 | ADD app /app 6 | ADD app.c /app.c 7 | 8 | CMD ["/app"] 9 | -------------------------------------------------------------------------------- /io-cached/Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: build 2 | build: 3 | gcc -o app app.c 4 | docker build -t feisky/app:io-direct -f Dockerfile . 5 | gcc -o app app-cached.c 6 | docker build -t feisky/app:io-cached -f Dockerfile . 7 | 8 | .PHONY: push 9 | push: 10 | docker push feisky/app:io-direct 11 | docker push feisky/app:io-cached 12 | 13 | .PHONY: run 14 | run: 15 | docker run --privileged --name=app -itd feisky/app:io-direct 16 | 17 | .PHONY: clean 18 | clean: 19 | rm -f app 20 | docker rm -f app || echo "Container app already deleted." 21 | -------------------------------------------------------------------------------- /io-cached/README.md: -------------------------------------------------------------------------------- 1 | # 直接 I/O 案例 2 | 3 | **《[Linux 性能优化实战](https://time.geekbang.org/column/intro/140)》第 17 篇案例。** 4 | 5 | 案例场景为进程以固定间隔时间读取磁盘导致以下两种现象: 6 | 7 | * 直接 I/O 导致文件读取缓慢的问题 8 | * 缓存命中次数与 I/O 大小不匹配的问题 9 | 10 | ## 构建 Docker 镜像 11 | 12 | ```sh 13 | make build 14 | ``` 15 | 16 | 默认的运行命令为 `docker run --privileged --name=app -itd feisky/app:io-direct`。 17 | 18 | 你还可以通过以下两个个选项来修改磁盘读取的行为: 19 | 20 | * `-d` 设置要读取的磁盘,默认前缀为 `/dev/sd` 或者 `/dev/xvd` 的磁盘 21 | * `-s` 设置每次读取的数据量大小,单位为字节,默认为 33554432(也就是 32MB) 22 | 23 | 这些选项的使用方法为: 24 | 25 | ```sh 26 | docker run --privileged --name=app -itd feisky/app:io-direct /app -d /dev/sdb -s 33554432 27 | ``` 28 | 29 | 案例运行后,你可以执行 `docker logs app` 查看它的日志,正常情况下,可以看到如下的输出: 30 | 31 | ```sh 32 | Reading data from disk /dev/sdb with buffer size 33554432 33 | ``` 34 | 35 | ## 运行案例应用 36 | 37 | ```sh 38 | make run 39 | ``` 40 | 41 | ## 停止应用 42 | 43 | ```sh 44 | make clean 45 | ``` 46 | -------------------------------------------------------------------------------- /io-cached/app-cached.c: -------------------------------------------------------------------------------- 1 | #define _GNU_SOURCE 2 | #define BUF_SIZE 32 * 1024 * 1024 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | 18 | char *select_disk() 19 | { 20 | DIR *dirptr = opendir("/dev/"); 21 | if (dirptr == NULL) 22 | { 23 | perror("Failed to open dir"); 24 | return NULL; 25 | } 26 | 27 | struct dirent *entry; 28 | char *result = (char *)calloc(512, sizeof(char)); 29 | const char *sd_prefix = "sd"; 30 | const char *xvd_prefix = "xvd"; 31 | while (entry = readdir(dirptr)) 32 | { 33 | if (strncmp(sd_prefix, entry->d_name, 2) == 0 || strncmp(xvd_prefix, entry->d_name, 3) == 0) 34 | { 35 | snprintf(result, 512 * sizeof(char), "/dev/%s", entry->d_name); 36 | return result; 37 | } 38 | } 39 | 40 | free(result); 41 | return NULL; 42 | } 43 | 44 | long int get_value(char *str) 45 | { 46 | char *endptr = NULL; 47 | long int value = strtol(str, &endptr, 10); 48 | if ((errno == ERANGE && (value == LONG_MAX || value == LONG_MIN)) || (errno != 0 && value == 0)) 49 | { 50 | perror("strtol"); 51 | return -1; 52 | } 53 | 54 | if (endptr == str) 55 | { 56 | perror("not number"); 57 | return -1; 58 | } 59 | 60 | if (value <= 0) 61 | { 62 | perror("not positive number"); 63 | return -1; 64 | } 65 | 66 | return value; 67 | } 68 | 69 | void app(const char *disk, long int buffer_size) 70 | { 71 | int flags = O_RDONLY | O_LARGEFILE; 72 | int fd = open(disk, flags, 0755); 73 | if (fd < 0) 74 | { 75 | perror("failed to open disk"); 76 | _exit(1); 77 | } 78 | 79 | unsigned char *buf; 80 | struct timeval start, end; 81 | posix_memalign((void **)&buf, 512, buffer_size); 82 | int read_bytes = 0; 83 | gettimeofday(&start, NULL); 84 | while (read_bytes < buffer_size) 85 | { 86 | int ret = read(fd, buf, buffer_size); 87 | if (ret < 0) 88 | { 89 | perror("failed to read contents"); 90 | close(fd); 91 | free(buf); 92 | _exit(1); 93 | } 94 | read_bytes += ret; 95 | } 96 | 97 | gettimeofday(&end, NULL); 98 | double total_time = (end.tv_sec - start.tv_sec) + (end.tv_usec - start.tv_usec) / 1000000.0; 99 | printf("Time used: %f s to read %ld bytes\n", total_time, buffer_size); 100 | close(fd); 101 | free(buf); 102 | } 103 | 104 | int main(int argc, char **argv) 105 | { 106 | int status = 0; 107 | int c = 0; 108 | char *disk = NULL; 109 | char *size = NULL; 110 | 111 | while ((c = getopt(argc, argv, "d:s:")) != -1) 112 | { 113 | switch (c) 114 | { 115 | case 'd': 116 | disk = optarg; 117 | break; 118 | case 's': 119 | size = optarg; 120 | break; 121 | case '?': 122 | printf("Illegal option: -%c\n", isprint(optopt) ? optopt : '#'); 123 | break; 124 | default: 125 | _exit(1); 126 | } 127 | } 128 | 129 | if (disk == NULL) 130 | { 131 | disk = select_disk(); 132 | } 133 | if (disk == NULL) 134 | { 135 | _exit(1); 136 | } 137 | 138 | long int buffer_size = BUF_SIZE; 139 | if (size != NULL) 140 | { 141 | buffer_size = get_value(size); 142 | if (buffer_size < 0) 143 | { 144 | exit(1); 145 | } 146 | } 147 | 148 | printf("Reading data from disk %s with buffer size %ld\n", disk, buffer_size); 149 | 150 | for (;;) 151 | { 152 | app(disk, buffer_size); 153 | sleep(1); 154 | } 155 | 156 | return 0; 157 | } -------------------------------------------------------------------------------- /io-cached/app.c: -------------------------------------------------------------------------------- 1 | #define _GNU_SOURCE 2 | #define BUF_SIZE 32 * 1024 * 1024 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | 18 | char *select_disk() 19 | { 20 | DIR *dirptr = opendir("/dev/"); 21 | if (dirptr == NULL) 22 | { 23 | perror("Failed to open dir"); 24 | return NULL; 25 | } 26 | 27 | struct dirent *entry; 28 | char *result = (char *)calloc(512, sizeof(char)); 29 | const char *sd_prefix = "sd"; 30 | const char *xvd_prefix = "xvd"; 31 | while (entry = readdir(dirptr)) 32 | { 33 | if (strncmp(sd_prefix, entry->d_name, 2) == 0 || strncmp(xvd_prefix, entry->d_name, 3) == 0) 34 | { 35 | snprintf(result, 512 * sizeof(char), "/dev/%s", entry->d_name); 36 | return result; 37 | } 38 | } 39 | 40 | free(result); 41 | return NULL; 42 | } 43 | 44 | long int get_value(char *str) 45 | { 46 | char *endptr = NULL; 47 | long int value = strtol(str, &endptr, 10); 48 | if ((errno == ERANGE && (value == LONG_MAX || value == LONG_MIN)) || (errno != 0 && value == 0)) 49 | { 50 | perror("strtol"); 51 | return -1; 52 | } 53 | 54 | if (endptr == str) 55 | { 56 | perror("not number"); 57 | return -1; 58 | } 59 | 60 | if (value <= 0) 61 | { 62 | perror("not positive number"); 63 | return -1; 64 | } 65 | 66 | return value; 67 | } 68 | 69 | void app(const char *disk, long int buffer_size) 70 | { 71 | int flags = O_RDONLY | O_LARGEFILE | O_DIRECT; 72 | int fd = open(disk, flags, 0755); 73 | if (fd < 0) 74 | { 75 | perror("failed to open disk"); 76 | _exit(1); 77 | } 78 | 79 | unsigned char *buf; 80 | struct timeval start, end; 81 | posix_memalign((void **)&buf, 512, buffer_size); 82 | int read_bytes = 0; 83 | gettimeofday(&start, NULL); 84 | while (read_bytes < buffer_size) 85 | { 86 | int ret = read(fd, buf, buffer_size); 87 | if (ret < 0) 88 | { 89 | perror("failed to read contents"); 90 | close(fd); 91 | free(buf); 92 | _exit(1); 93 | } 94 | read_bytes += ret; 95 | } 96 | 97 | gettimeofday(&end, NULL); 98 | double total_time = (end.tv_sec - start.tv_sec) + (end.tv_usec - start.tv_usec) / 1000000.0; 99 | printf("Time used: %f s to read %ld bytes\n", total_time, buffer_size); 100 | close(fd); 101 | free(buf); 102 | } 103 | 104 | int main(int argc, char **argv) 105 | { 106 | int status = 0; 107 | int c = 0; 108 | char *disk = NULL; 109 | char *size = NULL; 110 | 111 | while ((c = getopt(argc, argv, "d:s:")) != -1) 112 | { 113 | switch (c) 114 | { 115 | case 'd': 116 | disk = optarg; 117 | break; 118 | case 's': 119 | size = optarg; 120 | break; 121 | case '?': 122 | printf("Illegal option: -%c\n", isprint(optopt) ? optopt : '#'); 123 | break; 124 | default: 125 | _exit(1); 126 | } 127 | } 128 | 129 | if (disk == NULL) 130 | { 131 | disk = select_disk(); 132 | } 133 | if (disk == NULL) 134 | { 135 | _exit(1); 136 | } 137 | 138 | long int buffer_size = BUF_SIZE; 139 | if (size != NULL) 140 | { 141 | buffer_size = get_value(size); 142 | if (buffer_size < 0) 143 | { 144 | exit(1); 145 | } 146 | } 147 | 148 | printf("Reading data from disk %s with buffer size %ld\n", disk, buffer_size); 149 | 150 | for (;;) 151 | { 152 | app(disk, buffer_size); 153 | sleep(1); 154 | } 155 | 156 | return 0; 157 | } -------------------------------------------------------------------------------- /io-latency/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM python:alpine 2 | 3 | LABEL maintainer="feiskyer@gmail.com" 4 | 5 | RUN pip install flask 6 | 7 | EXPOSE 80 8 | ADD app.py /app.py 9 | 10 | CMD ["python", "/app.py"] 11 | -------------------------------------------------------------------------------- /io-latency/Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: run 2 | run: 3 | docker run --name=app -p 10000:80 -itd feisky/word-pop 4 | 5 | 6 | .PHONY: build 7 | build: 8 | docker build -t feisky/word-pop -f Dockerfile . 9 | 10 | 11 | .PHONY: push 12 | push: 13 | docker push feisky/word-pop 14 | 15 | 16 | .PHONY: clean 17 | clean: 18 | docker rm -f app || echo "Container app already deleted." 19 | -------------------------------------------------------------------------------- /io-latency/README.md: -------------------------------------------------------------------------------- 1 | # 应用程序I/O延迟案例 2 | 3 | **《[Linux 性能优化实战](https://time.geekbang.org/column/intro/140)》第 27 篇案例。** 4 | 5 | 案例场景: 6 | 7 | * 简单的 flask app,提供一个测试单词热度的 api。该接口会生成一批文章并分别保存到一个文件中,再逐个读取这些文件来统计目标的单词是否出现在文章中 8 | * 应用程序接口的性能并不让人满意,I/O 延迟过大 9 | 10 | ## 构建 Docker 镜像 11 | 12 | ```sh 13 | make build 14 | ``` 15 | 16 | ## 运行案例应用 17 | 18 | ```sh 19 | make run 20 | ``` 21 | 22 | 运行后,访问 `http:///popularity/` 就可以测试单词的热度。 23 | 24 | ## 停止应用 25 | 26 | ```sh 27 | make clean 28 | ``` 29 | -------------------------------------------------------------------------------- /io-latency/app.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: UTF-8 -*- 3 | 4 | import os 5 | import uuid 6 | import random 7 | import shutil 8 | from concurrent.futures import ThreadPoolExecutor 9 | from flask import Flask, jsonify 10 | 11 | app = Flask(__name__) 12 | 13 | 14 | def validate(word, sentence): 15 | return word in sentence 16 | 17 | 18 | def generate_article(): 19 | s_nouns = [ 20 | "A dude", "My mom", "The king", "Some guy", "A cat with rabies", 21 | "A sloth", "Your homie", "This cool guy my gardener met yesterday", 22 | "Superman" 23 | ] 24 | p_nouns = [ 25 | "These dudes", "Both of my moms", "All the kings of the world", 26 | "Some guys", "All of a cattery's cats", 27 | "The multitude of sloths living under your bed", "Your homies", 28 | "Like, these, like, all these people", "Supermen" 29 | ] 30 | s_verbs = [ 31 | "eats", "kicks", "gives", "treats", "meets with", "creates", "hacks", 32 | "configures", "spies on", "retards", "meows on", "flees from", 33 | "tries to automate", "explodes" 34 | ] 35 | infinitives = [ 36 | "to make a pie.", "for no apparent reason.", 37 | "because the sky is green.", "for a disease.", 38 | "to be able to make toast explode.", "to know more about archeology." 39 | ] 40 | sentence = '{} {} {} {}'.format( 41 | random.choice(s_nouns), random.choice(s_verbs), 42 | random.choice(s_nouns).lower() or random.choice(p_nouns).lower(), 43 | random.choice(infinitives)) 44 | return '\n'.join([sentence for i in range(50000)]) 45 | 46 | 47 | @app.route('/') 48 | def hello_world(): 49 | return 'hello world' 50 | 51 | 52 | @app.route("/popularity/") 53 | def word_popularity(word): 54 | dir_path = '/tmp/{}'.format(uuid.uuid1()) 55 | count = 0 56 | sample_size = 1000 57 | 58 | def save_to_file(file_name, content): 59 | with open(file_name, 'w') as f: 60 | f.write(content) 61 | 62 | try: 63 | # initial directory firstly 64 | os.mkdir(dir_path) 65 | 66 | # save article to files 67 | for i in range(sample_size): 68 | file_name = '{}/{}.txt'.format(dir_path, i) 69 | article = generate_article() 70 | save_to_file(file_name, article) 71 | 72 | # count word popularity 73 | for root, dirs, files in os.walk(dir_path): 74 | for file_name in files: 75 | with open('{}/{}'.format(dir_path, file_name)) as f: 76 | if validate(word, f.read()): 77 | count += 1 78 | finally: 79 | # clean files 80 | shutil.rmtree(dir_path, ignore_errors=True) 81 | 82 | return jsonify({'popularity': count / sample_size * 100, 'word': word}) 83 | 84 | 85 | @app.route("/popular/") 86 | def word_popular(word): 87 | count = 0 88 | sample_size = 1000 89 | articles = [] 90 | 91 | try: 92 | for i in range(sample_size): 93 | articles.append(generate_article()) 94 | 95 | for article in articles: 96 | if validate(word, article): 97 | count += 1 98 | finally: 99 | pass 100 | 101 | return jsonify({'popularity': count / sample_size * 100, 'word': word}) 102 | 103 | 104 | if __name__ == '__main__': 105 | app.run(debug=True, host='0.0.0.0', port=80) 106 | -------------------------------------------------------------------------------- /logging-app/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM python:alpine 2 | 3 | LABEL maintainer="feiskyer@gmail.com" 4 | 5 | ADD app.py /app.py 6 | 7 | CMD ["python", "/app.py"] 8 | -------------------------------------------------------------------------------- /logging-app/Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: run 2 | run: 3 | docker run -v /tmp:/tmp --name=app -itd feisky/logapp 4 | 5 | 6 | .PHONY: build 7 | build: 8 | docker build -t feisky/logapp -f Dockerfile . 9 | 10 | 11 | .PHONY: push 12 | push: 13 | docker push feisky/logapp 14 | 15 | 16 | .PHONY: clean 17 | clean: 18 | docker rm -f app || echo "Container app already deleted." 19 | -------------------------------------------------------------------------------- /logging-app/README.md: -------------------------------------------------------------------------------- 1 | # 应用程序狂打日志案例 2 | 3 | **《[Linux 性能优化实战](https://time.geekbang.org/column/intro/140)》第 26 篇案例。** 4 | 5 | 案例场景: 6 | 7 | * 应用程序疯狂打印日志导致磁盘 I/O 瓶颈 8 | * 等待 I/O 的 CPU 使用率(iowait%)过高 9 | 10 | ## 构建 Docker 镜像 11 | 12 | ```sh 13 | make build 14 | ``` 15 | 16 | ## 运行案例应用 17 | 18 | ```sh 19 | make run 20 | ``` 21 | 22 | ## 停止应用 23 | 24 | ```sh 25 | make clean 26 | ``` 27 | -------------------------------------------------------------------------------- /logging-app/app.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: UTF-8 -*- 3 | 4 | import logging 5 | import random 6 | import string 7 | import signal 8 | import time 9 | 10 | from logging.handlers import RotatingFileHandler 11 | 12 | logger = logging.getLogger(__name__) 13 | logger.setLevel(level=logging.INFO) 14 | rHandler = RotatingFileHandler( 15 | "/tmp/logtest.txt", maxBytes=1024 * 1024 * 1024, backupCount=1) 16 | rHandler.setLevel(logging.INFO) 17 | formatter = logging.Formatter( 18 | '%(asctime)s - %(name)s - %(levelname)s - %(message)s') 19 | rHandler.setFormatter(formatter) 20 | logger.addHandler(rHandler) 21 | 22 | 23 | def set_logging_info(signal_num, frame): 24 | '''Set loging level to INFO when receives SIGUSR1''' 25 | logger.setLevel(logging.INFO) 26 | 27 | 28 | def set_logging_warning(signal_num, frame): 29 | '''Set loging level to WARNING when receives SIGUSR2''' 30 | logger.setLevel(logging.WARNING) 31 | 32 | 33 | def get_message(N): 34 | '''Get message for logging''' 35 | return N * ''.join( 36 | random.choices(string.ascii_uppercase + string.digits, k=1)) 37 | 38 | 39 | def write_log(size): 40 | '''Write logs to file''' 41 | message = get_message(size) 42 | while True: 43 | logger.info(message) 44 | time.sleep(0.1) 45 | 46 | 47 | signal.signal(signal.SIGUSR1, set_logging_info) 48 | signal.signal(signal.SIGUSR2, set_logging_warning) 49 | 50 | if __name__ == '__main__': 51 | msg_size = 300 * 1024 * 1024 52 | write_log(msg_size) 53 | -------------------------------------------------------------------------------- /mem-leak/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM ubuntu 2 | 3 | LABEL maintainer="feiskyer@gmail.com" 4 | 5 | ADD app /app 6 | ADD app.c /app.c 7 | 8 | CMD ["/app"] 9 | -------------------------------------------------------------------------------- /mem-leak/Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: build 2 | build: 3 | gcc -o app app.c -pthread 4 | docker build -t feisky/app:mem-leak -f Dockerfile . 5 | gcc -o app app-fix.c -pthread 6 | docker build -t feisky/app:mem-leak-fix -f Dockerfile . 7 | 8 | .PHONY: push 9 | push: 10 | docker push feisky/app:mem-leak 11 | docker push feisky/app:mem-leak-fix 12 | 13 | .PHONY: run 14 | run: 15 | docker run --name=app -itd feisky/app:mem-leak 16 | 17 | .PHONY: clean 18 | clean: 19 | rm -f app 20 | docker rm -f app || echo "Container app already deleted." 21 | -------------------------------------------------------------------------------- /mem-leak/README.md: -------------------------------------------------------------------------------- 1 | # 内存泄漏案例 2 | 3 | **《[Linux 性能优化实战](https://time.geekbang.org/column/intro/140)》第 18 篇案例。** 4 | 5 | 案例场景: 6 | 7 | * 应用程序存在内存泄漏 8 | * memleak 工具无法获得应用程序调用栈 9 | 10 | ## 构建 Docker 镜像 11 | 12 | ```sh 13 | make build 14 | ``` 15 | 16 | ## 运行案例应用 17 | 18 | ```sh 19 | make run 20 | ``` 21 | 22 | ## 停止应用 23 | 24 | ```sh 25 | make clean 26 | ``` 27 | -------------------------------------------------------------------------------- /mem-leak/app-fix.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | long long *fibonacci(long long *n0, long long *n1) 7 | { 8 | //分配1024个长整数空间方便观测内存的变化情况 9 | long long *v = (long long *) calloc(1024, sizeof(long long)); 10 | *v = *n0 + *n1; 11 | return v; 12 | } 13 | 14 | void *child(void *arg) 15 | { 16 | long long n0 = 0; 17 | long long n1 = 1; 18 | long long *v = NULL; 19 | int n = 2; 20 | for (n = 2; n > 0; n++) { 21 | v = fibonacci(&n0, &n1); 22 | n0 = n1; 23 | n1 = *v; 24 | free(v); 25 | printf("%dth => %lld\n", n, n1); 26 | sleep(1); 27 | } 28 | } 29 | 30 | 31 | int main(void) 32 | { 33 | pthread_t tid; 34 | pthread_create(&tid, NULL, child, NULL); 35 | pthread_join(tid, NULL); 36 | printf("main thread exit\n"); 37 | return 0; 38 | } 39 | -------------------------------------------------------------------------------- /mem-leak/app-no-calloc.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | long long fibonacci(long long n0, long long n1) 7 | { 8 | return n0 + n1; 9 | } 10 | 11 | void *child(void *arg) 12 | { 13 | long long n0 = 0; 14 | long long n1 = 1; 15 | long long v = 0; 16 | int n = 2; 17 | for (n = 2; n > 0; n++) { 18 | v = fibonacci(n0, n1); 19 | n0 = n1; 20 | n1 = v; 21 | printf("%dth => %lld\n", n, v); 22 | sleep(1); 23 | } 24 | } 25 | 26 | 27 | int main(void) 28 | { 29 | pthread_t tid; 30 | pthread_create(&tid, NULL, child, NULL); 31 | pthread_join(tid, NULL); 32 | printf("main thread exit\n"); 33 | return 0; 34 | } -------------------------------------------------------------------------------- /mem-leak/app.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | long long *fibonacci(long long *n0, long long *n1) 7 | { 8 | //分配1024个长整数空间方便观测内存的变化情况 9 | long long *v = (long long *) calloc(1024, sizeof(long long)); 10 | *v = *n0 + *n1; 11 | return v; 12 | } 13 | 14 | void *child(void *arg) 15 | { 16 | long long n0 = 0; 17 | long long n1 = 1; 18 | long long *v = NULL; 19 | int n = 2; 20 | for (n = 2; n > 0; n++) { 21 | v = fibonacci(&n0, &n1); 22 | n0 = n1; 23 | n1 = *v; 24 | printf("%dth => %lld\n", n, *v); 25 | sleep(1); 26 | } 27 | } 28 | 29 | 30 | int main(void) 31 | { 32 | pthread_t tid; 33 | pthread_create(&tid, NULL, child, NULL); 34 | pthread_join(tid, NULL); 35 | printf("main thread exit\n"); 36 | return 0; 37 | } -------------------------------------------------------------------------------- /mysql-slow/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM python:3.6 2 | 3 | LABEL maintainer="feiskyer@gmail.com" 4 | 5 | RUN pip install flask PyMySQL 6 | 7 | EXPOSE 80 8 | ADD app.py /app.py 9 | 10 | CMD ["python", "/app.py"] 11 | -------------------------------------------------------------------------------- /mysql-slow/Dockerfile.dataservice: -------------------------------------------------------------------------------- 1 | FROM python:3.6 2 | 3 | LABEL maintainer="feiskyer@gmail.com" 4 | 5 | ADD dataservice.py /dataservice.py 6 | 7 | CMD ["python", "/dataservice.py"] 8 | -------------------------------------------------------------------------------- /mysql-slow/Dockerfile.mysql: -------------------------------------------------------------------------------- 1 | FROM mysql:5.6 2 | 3 | LABEL maintainer="feiskyer@gmail.com" 4 | 5 | ENV MYSQL_ALLOW_EMPTY_PASSWORD=1 6 | ADD mysqld.cnf /etc/mysql/mysql.conf.d/mysqld.cnf 7 | 8 | CMD ["mysqld", "--log_bin=on", "--sync_binlog=1"] 9 | -------------------------------------------------------------------------------- /mysql-slow/Makefile: -------------------------------------------------------------------------------- 1 | DATA_NUM ?= 10000 2 | 3 | .PHONY: run 4 | run: mysql dataservice 5 | docker run --name=app --network=container:mysql -itd feisky/mysql-slow 6 | 7 | .PHONY: dataservice 8 | dataservice: 9 | docker run --name=dataservice -itd --privileged feisky/mysql-dataservice 10 | 11 | 12 | .PHONY: mysql 13 | mysql: 14 | docker run --name=mysql -itd -p 10000:80 -m 800m feisky/mysql:5.6 15 | 16 | 17 | .PHONY: init 18 | init: 19 | docker exec -i mysql mysql -uroot -P3306 < tables.sql 20 | curl http://127.0.0.1:10000/db/insert/products/$(DATA_NUM) 21 | 22 | 23 | .PHONY: build 24 | build: 25 | docker build -t feisky/mysql-slow -f Dockerfile . 26 | docker build -t feisky/mysql:5.6 -f Dockerfile.mysql . 27 | docker build -t feisky/mysql-dataservice -f Dockerfile.dataservice . 28 | 29 | 30 | .PHONY: test 31 | test: 32 | curl http://127.0.0.1:10000/products/geektime 33 | 34 | 35 | .PHONY: push 36 | push: 37 | docker push feisky/mysql-slow 38 | docker push feisky/mysql:5.6 39 | docker push feisky/mysql-dataservice 40 | 41 | 42 | .PHONY: clean 43 | clean: 44 | docker rm -f app mysql dataservice || echo "Containers already deleted." 45 | -------------------------------------------------------------------------------- /mysql-slow/README.md: -------------------------------------------------------------------------------- 1 | # MySQL 慢查询案例 2 | 3 | **《[Linux 性能优化实战](https://time.geekbang.org/column/intro/140)》第 28 篇案例。** 4 | 5 | 案例场景: 6 | 7 | * MySQL 查询特别慢,一个简单的查询需要 15 秒 8 | * 系统 CPU 使用率中的 iowait% 特别高 9 | * 磁盘 I/O 使用率接近 100% 10 | 11 | 这个案例总共由三个容器组成,包括一个 MySQL 数据库应用、一个商品搜索应用以及一个数据处理的应用。其中,商品搜索应用以 HTTP 的形式提供了一个接口: 12 | 13 | - `/`:返回 `Index Page`; 14 | - `/db/insert/products/`:插入指定数量的商品信息; 15 | - `/products/`:查询指定商品的信息并返回处理时间。 16 | 17 | ## 构建 Docker 镜像 18 | 19 | ```sh 20 | make build 21 | ``` 22 | 23 | ## 运行案例应用 24 | 25 | ```sh 26 | make run 27 | ``` 28 | 29 | ## 停止应用 30 | 31 | ```sh 32 | make clean 33 | ``` 34 | -------------------------------------------------------------------------------- /mysql-slow/app.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: UTF-8 -*- 3 | import pymysql 4 | import random 5 | import string 6 | import time 7 | from flask import Flask 8 | 9 | config = { 10 | "host": "127.0.0.1", 11 | "user": "root", 12 | "port": 3306, 13 | "password": "", 14 | "database": "test" 15 | } 16 | 17 | 18 | app = Flask(__name__) 19 | 20 | 21 | @app.route('/') 22 | def index(): 23 | return 'Index Page' 24 | 25 | 26 | @app.route("/sleep/") 27 | def sleep(num): 28 | time.sleep(int(num)) 29 | return "sleep " + num + "\n" 30 | 31 | 32 | @app.route('/db//count') 33 | def select(table): 34 | db = pymysql.connect(**config) 35 | cursor = db.cursor() 36 | sql = "SELECT count(*) FROM " + table 37 | cursor.execute(sql) 38 | data = cursor.fetchone() 39 | return str(data[0]) + "\n" 40 | 41 | 42 | @app.route('/products/') 43 | def products(product): 44 | start = time.time() 45 | db = pymysql.connect(**config) 46 | cursor = db.cursor() 47 | sql = "select * from products where productName='%s'" % product 48 | cursor.execute(sql) 49 | data = cursor.fetchall() 50 | elapsed = (time.time() - start) 51 | return "Got data: " + str(data) + " in " + str(elapsed) + " sec \n" 52 | 53 | 54 | @app.route('/db/insert/products/') 55 | def insert_products(num): 56 | values = [] 57 | i = 0 58 | while i < int(num): 59 | i += 1 60 | productCode = ''.join(random.choices( 61 | string.ascii_letters + string.digits, k=10240)) 62 | productName = ''.join(random.choices( 63 | string.ascii_letters + string.digits, k=10240)) 64 | productLine = ''.join(random.choices( 65 | string.ascii_letters + string.digits, k=10240)) 66 | productScale = ''.join(random.choices( 67 | string.ascii_letters + string.digits, k=10240)) 68 | productVendor = ''.join(random.choices( 69 | string.ascii_letters + string.digits, k=10240)) 70 | productDescription = ''.join(random.sample( 71 | string.ascii_letters + string.digits, 8)) 72 | quantityInStock = random.randint(1, 1000) 73 | buyPrice = random.uniform(1.0, 10000.0) 74 | MSRP = random.uniform(10.0, 20000.0) 75 | 76 | value = (i, productCode, productName, productLine, productScale, 77 | productVendor, productDescription, quantityInStock, buyPrice, MSRP) 78 | values.append(value) 79 | 80 | db = pymysql.connect(**config) 81 | cursor = db.cursor() 82 | sql = "INSERT INTO products (id, productCode, productName, productLine, productScale, productVendor, productDescription, quantityInStock, buyPrice, MSRP) VALUES ( %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)" 83 | cursor.executemany(sql, values) 84 | db.commit() 85 | cursor.close() 86 | return 'insert ' + num + ' lines' + "\n" 87 | 88 | 89 | if __name__ == '__main__': 90 | app.run(host='0.0.0.0', debug=True, port=80) 91 | -------------------------------------------------------------------------------- /mysql-slow/dataservice.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: UTF-8 -*- 3 | import time 4 | filename = "/tmp/dataservice" 5 | 6 | 7 | def write(): 8 | with open(filename, "w+") as f: 9 | f.write("data") 10 | 11 | 12 | def read(): 13 | with open(filename) as f: 14 | return f.read() 15 | 16 | 17 | def clean_cache(): 18 | with open("/proc/sys/vm/drop_caches", "w") as f: 19 | f.write("1") 20 | 21 | if __name__ == "__main__": 22 | while True: 23 | write() 24 | clean_cache() 25 | read() 26 | time.sleep(3) 27 | -------------------------------------------------------------------------------- /mysql-slow/mysqld.cnf: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved. 2 | # 3 | # This program is free software; you can redistribute it and/or modify 4 | # it under the terms of the GNU General Public License as published by 5 | # the Free Software Foundation; version 2 of the License. 6 | # 7 | # This program is distributed in the hope that it will be useful, 8 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 9 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 10 | # GNU General Public License for more details. 11 | # 12 | # You should have received a copy of the GNU General Public License 13 | # along with this program; if not, write to the Free Software 14 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 15 | 16 | # 17 | # The MySQL Server configuration file. 18 | # 19 | # For explanations see 20 | # http://dev.mysql.com/doc/mysql/en/server-system-variables.html 21 | 22 | [mysqld] 23 | pid-file = /var/run/mysqld/mysqld.pid 24 | socket = /var/run/mysqld/mysqld.sock 25 | datadir = /var/lib/mysql 26 | performance_schema = OFF 27 | #log-error = /var/log/mysql/error.log 28 | # Disabling symbolic-links is recommended to prevent assorted security risks 29 | symbolic-links=0 30 | innodb_flush_log_at_trx_commit = 1 31 | innodb_buffer_pool_size = 5242880 32 | max_heap_table_size = 1048576 33 | tmp_table_size = 1048576 34 | slow_query_log = ON 35 | innodb_file_per_table = ON 36 | innodb_file_format = barracuda -------------------------------------------------------------------------------- /mysql-slow/tables.sql: -------------------------------------------------------------------------------- 1 | CREATE DATABASE IF NOT EXISTS `test`; 2 | USE `test`; 3 | 4 | DROP TABLE IF EXISTS `products`; 5 | CREATE TABLE `products` ( 6 | `id` int(11) NOT NULL, 7 | `productCode` text NOT NULL DEFAULT '' COMMENT '产品代码', 8 | `productName` text NOT NULL COMMENT '产品名称', 9 | `productLine` text NOT NULL COMMENT '产品线', 10 | `productScale` text NOT NULL, 11 | `productVendor` text NOT NULL, 12 | `productDescription` text NOT NULL, 13 | `quantityInStock` smallint(6) NOT NULL COMMENT '库存', 14 | `buyPrice` decimal(10,2) NOT NULL COMMENT '价格', 15 | `MSRP` decimal(10,2) NOT NULL COMMENT '建议零售价', 16 | PRIMARY KEY (`id`) 17 | ) ENGINE=MyISAM DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC; -------------------------------------------------------------------------------- /nat/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM nginx 2 | 3 | LABEL maintainer="feiskyer@gmail.com" 4 | 5 | ADD default.conf /etc/nginx/conf.d/default.conf 6 | ADD nginx.conf /etc/nginx/nginx.conf 7 | 8 | CMD ["/bin/sh", "-c", "echo 1000 > /proc/sys/net/netfilter/nf_conntrack_max && nginx -g \"daemon off;\""] 9 | -------------------------------------------------------------------------------- /nat/Dockerfile.80: -------------------------------------------------------------------------------- 1 | FROM nginx 2 | 3 | LABEL maintainer="feiskyer@gmail.com" 4 | 5 | ADD default.80.conf /etc/nginx/conf.d/default.conf 6 | ADD nginx.conf /etc/nginx/nginx.conf 7 | 8 | CMD ["/bin/sh", "-c", "echo 10485760 > /proc/sys/net/netfilter/nf_conntrack_max && nginx -g \"daemon off;\""] 9 | -------------------------------------------------------------------------------- /nat/Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: run 2 | run: 3 | docker run --name nginx --privileged -p 8080:8080 -itd feisky/nginx:nat 4 | 5 | .PHONY: host-network 6 | host-network: 7 | docker run --name nginx-hostnet --privileged --network=host -itd feisky/nginx:80 8 | 9 | .PHONY: build 10 | build: 11 | docker build -t feisky/nginx:nat -f Dockerfile . 12 | docker build -t feisky/nginx:80 -f Dockerfile.80 . 13 | 14 | .PHONY: push 15 | push: 16 | docker push feisky/nginx:nat 17 | docker push feisky/nginx:80 18 | 19 | .PHONY: clean 20 | clean: 21 | docker rm -f nginx nginx-hostnet || echo "Containers already deleted." 22 | -------------------------------------------------------------------------------- /nat/README.md: -------------------------------------------------------------------------------- 1 | # 网络地址转换(NAT)案例 2 | 3 | **《[Linux 性能优化实战](https://time.geekbang.org/column/intro/140)》第 41、42 篇案例。** 4 | 5 | 案例场景: 6 | 7 | * Nginx 并发连接数因 NAT 降低,延迟增大 8 | 9 | ## 构建 Docker 镜像 10 | 11 | ```sh 12 | make build 13 | ``` 14 | 15 | ## 运行案例应用 16 | 17 | ```sh 18 | make run 19 | ``` 20 | 21 | ## 停止应用 22 | 23 | ```sh 24 | make clean 25 | ``` 26 | -------------------------------------------------------------------------------- /nat/default.80.conf: -------------------------------------------------------------------------------- 1 | server { 2 | listen 80; 3 | server_name localhost; 4 | 5 | #charset koi8-r; 6 | #access_log /var/log/nginx/host.access.log main; 7 | 8 | location / { 9 | root /usr/share/nginx/html; 10 | index index.html index.htm; 11 | } 12 | 13 | #error_page 404 /404.html; 14 | 15 | # redirect server error pages to the static page /50x.html 16 | # 17 | error_page 500 502 503 504 /50x.html; 18 | location = /50x.html { 19 | root /usr/share/nginx/html; 20 | } 21 | 22 | # proxy the PHP scripts to Apache listening on 127.0.0.1:80 23 | # 24 | #location ~ \.php$ { 25 | # proxy_pass http://127.0.0.1; 26 | #} 27 | 28 | # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000 29 | # 30 | #location ~ \.php$ { 31 | # root html; 32 | # fastcgi_pass 127.0.0.1:9000; 33 | # fastcgi_index index.php; 34 | # fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name; 35 | # include fastcgi_params; 36 | #} 37 | 38 | # deny access to .htaccess files, if Apache's document root 39 | # concurs with nginx's one 40 | # 41 | #location ~ /\.ht { 42 | # deny all; 43 | #} 44 | } 45 | -------------------------------------------------------------------------------- /nat/default.conf: -------------------------------------------------------------------------------- 1 | server { 2 | listen 8080; 3 | server_name localhost; 4 | 5 | #charset koi8-r; 6 | #access_log /var/log/nginx/host.access.log main; 7 | 8 | location / { 9 | root /usr/share/nginx/html; 10 | index index.html index.htm; 11 | } 12 | 13 | #error_page 404 /404.html; 14 | 15 | # redirect server error pages to the static page /50x.html 16 | # 17 | error_page 500 502 503 504 /50x.html; 18 | location = /50x.html { 19 | root /usr/share/nginx/html; 20 | } 21 | 22 | # proxy the PHP scripts to Apache listening on 127.0.0.1:80 23 | # 24 | #location ~ \.php$ { 25 | # proxy_pass http://127.0.0.1; 26 | #} 27 | 28 | # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000 29 | # 30 | #location ~ \.php$ { 31 | # root html; 32 | # fastcgi_pass 127.0.0.1:9000; 33 | # fastcgi_index index.php; 34 | # fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name; 35 | # include fastcgi_params; 36 | #} 37 | 38 | # deny access to .htaccess files, if Apache's document root 39 | # concurs with nginx's one 40 | # 41 | #location ~ /\.ht { 42 | # deny all; 43 | #} 44 | } -------------------------------------------------------------------------------- /nat/dropwatch.stp: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env stap 2 | 3 | ############################################################ 4 | # Dropwatch.stp 5 | # Author: Neil Horman 6 | # An example script to mimic the behavior of the dropwatch utility 7 | # http://fedorahosted.org/dropwatch 8 | ############################################################ 9 | 10 | # Array to hold the list of drop points we find 11 | global locations 12 | 13 | # Note when we turn the monitor on and off 14 | probe begin { printf("Monitoring for dropped packets\n") } 15 | probe end { printf("Stopping dropped packet monitor\n") } 16 | 17 | # increment a drop counter for every location we drop at 18 | probe kernel.trace("kfree_skb") { locations[$location] <<< 1 } 19 | 20 | # Every 5 seconds report our drop locations 21 | probe timer.sec(5) 22 | { 23 | printf("\n") 24 | foreach (l in locations-) { 25 | printf("%d packets dropped at %s\n", 26 | @count(locations[l]), symname(l)) 27 | } 28 | delete locations 29 | } 30 | -------------------------------------------------------------------------------- /nat/nginx.conf: -------------------------------------------------------------------------------- 1 | user nginx; 2 | worker_processes 1; 3 | 4 | error_log /var/log/nginx/error.log warn; 5 | pid /var/run/nginx.pid; 6 | 7 | 8 | events { 9 | worker_connections 1024; 10 | } 11 | 12 | 13 | http { 14 | include /etc/nginx/mime.types; 15 | default_type application/octet-stream; 16 | 17 | log_format main '$remote_addr - $remote_user [$time_local] "$request" ' 18 | '$status $body_bytes_sent "$http_referer" ' 19 | '"$http_user_agent" "$http_x_forwarded_for"'; 20 | 21 | access_log /var/log/nginx/access.log main; 22 | 23 | sendfile on; 24 | tcp_nopush on; 25 | tcp_nodelay on; 26 | 27 | keepalive_timeout 65; 28 | 29 | #gzip on; 30 | 31 | include /etc/nginx/conf.d/*.conf; 32 | } 33 | -------------------------------------------------------------------------------- /network-latency/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM nginx 2 | 3 | LABEL maintainer="feiskyer@gmail.com" 4 | 5 | ADD default.conf /etc/nginx/conf.d/default.conf 6 | ADD nginx.conf /etc/nginx/nginx.conf 7 | -------------------------------------------------------------------------------- /network-latency/Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: run 2 | run: 3 | docker run --name nginx --network=host -itd feisky/nginx:latency 4 | 5 | .PHONY: build 6 | build: 7 | docker build -t feisky/nginx:latency -f Dockerfile . 8 | 9 | .PHONY: push 10 | push: 11 | docker push feisky/nginx:latency 12 | 13 | .PHONY: clean 14 | clean: 15 | docker rm -f nginx || echo "Container nginx already deleted." 16 | -------------------------------------------------------------------------------- /network-latency/README.md: -------------------------------------------------------------------------------- 1 | # 网络延迟案例 2 | 3 | **《[Linux 性能优化实战](https://time.geekbang.org/column/intro/140)》第 40 篇案例。** 4 | 5 | 案例场景: 6 | 7 | * Nginx 延迟大 8 | 9 | ## 构建 Docker 镜像 10 | 11 | ```sh 12 | make build 13 | ``` 14 | 15 | ## 运行案例应用 16 | 17 | ```sh 18 | make run 19 | ``` 20 | 21 | ## 停止应用 22 | 23 | ```sh 24 | make clean 25 | ``` 26 | -------------------------------------------------------------------------------- /network-latency/default.conf: -------------------------------------------------------------------------------- 1 | server { 2 | listen 8080; 3 | server_name localhost; 4 | 5 | #charset koi8-r; 6 | #access_log /var/log/nginx/host.access.log main; 7 | 8 | location / { 9 | root /usr/share/nginx/html; 10 | index index.html index.htm; 11 | } 12 | 13 | #error_page 404 /404.html; 14 | 15 | # redirect server error pages to the static page /50x.html 16 | # 17 | error_page 500 502 503 504 /50x.html; 18 | location = /50x.html { 19 | root /usr/share/nginx/html; 20 | } 21 | 22 | # proxy the PHP scripts to Apache listening on 127.0.0.1:80 23 | # 24 | #location ~ \.php$ { 25 | # proxy_pass http://127.0.0.1; 26 | #} 27 | 28 | # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000 29 | # 30 | #location ~ \.php$ { 31 | # root html; 32 | # fastcgi_pass 127.0.0.1:9000; 33 | # fastcgi_index index.php; 34 | # fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name; 35 | # include fastcgi_params; 36 | #} 37 | 38 | # deny access to .htaccess files, if Apache's document root 39 | # concurs with nginx's one 40 | # 41 | #location ~ /\.ht { 42 | # deny all; 43 | #} 44 | } -------------------------------------------------------------------------------- /network-latency/nginx.conf: -------------------------------------------------------------------------------- 1 | user nginx; 2 | worker_processes 1; 3 | 4 | error_log /var/log/nginx/error.log warn; 5 | pid /var/run/nginx.pid; 6 | 7 | 8 | events { 9 | worker_connections 1024; 10 | } 11 | 12 | 13 | http { 14 | include /etc/nginx/mime.types; 15 | default_type application/octet-stream; 16 | 17 | log_format main '$remote_addr - $remote_user [$time_local] "$request" ' 18 | '$status $body_bytes_sent "$http_referer" ' 19 | '"$http_user_agent" "$http_x_forwarded_for"'; 20 | 21 | access_log /var/log/nginx/access.log main; 22 | 23 | sendfile on; 24 | tcp_nopush off; 25 | tcp_nodelay off; 26 | 27 | keepalive_timeout 65; 28 | 29 | #gzip on; 30 | 31 | include /etc/nginx/conf.d/*.conf; 32 | } 33 | -------------------------------------------------------------------------------- /nginx-high-cpu/Dockerfile.nginx: -------------------------------------------------------------------------------- 1 | FROM nginx 2 | 3 | LABEL maintainer="feiskyer@gmail.com" 4 | 5 | ADD app/ /app 6 | ADD nginx.conf /etc/nginx/nginx.conf -------------------------------------------------------------------------------- /nginx-high-cpu/Dockerfile.php-fpm: -------------------------------------------------------------------------------- 1 | FROM bitnami/php-fpm 2 | 3 | LABEL maintainer="feiskyer@gmail.com" 4 | 5 | ADD app/ /app -------------------------------------------------------------------------------- /nginx-high-cpu/Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: run 2 | run: 3 | docker run --name nginx -p 10000:80 -itd feisky/nginx:cpu 4 | docker run --name phpfpm -itd --network container:nginx feisky/php-fpm:cpu 5 | 6 | .PHONY: build 7 | build: 8 | docker build -t feisky/nginx:cpu -f Dockerfile.nginx . 9 | docker build -t feisky/php-fpm:cpu -f Dockerfile.php-fpm . 10 | 11 | .PHONY: push 12 | push: 13 | docker push feisky/nginx:cpu 14 | docker push feisky/php-fpm:cpu 15 | 16 | .PHONY: clean 17 | clean: 18 | docker rm -f nginx phpfpm || echo "Container nginx already deleted." 19 | -------------------------------------------------------------------------------- /nginx-high-cpu/README.md: -------------------------------------------------------------------------------- 1 | # 应用程序 CPU 使用率过高案例 2 | 3 | **《[Linux 性能优化实战](https://time.geekbang.org/column/intro/140)》第 05 篇案例。** 4 | 5 | 案例场景: 6 | 7 | * 系统的用户 CPU 使用率(usr%)过高 8 | * 可以找出高 CPU 使用率的进程(php-fpm 进程的 CPU 使用率过高) 9 | 10 | ## 构建 Docker 镜像 11 | 12 | ```sh 13 | make build 14 | ``` 15 | 16 | ## 运行案例应用 17 | 18 | ```sh 19 | make run 20 | ``` 21 | 22 | ## 停止应用 23 | 24 | ```sh 25 | make clean 26 | ``` 27 | -------------------------------------------------------------------------------- /nginx-high-cpu/app/404.html: -------------------------------------------------------------------------------- 1 |

404 Not Found!

-------------------------------------------------------------------------------- /nginx-high-cpu/app/index.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /nginx-high-cpu/app/ok.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /nginx-high-cpu/app/phpinfo.php: -------------------------------------------------------------------------------- 1 | }t tag 309 | ; e.g. for a ISO8601 formatted timestring, use: %{%Y-%m-%dT%H:%M:%S%z}t 310 | ; %T: time the log has been written (the request has finished) 311 | ; it can accept a strftime(3) format: 312 | ; %d/%b/%Y:%H:%M:%S %z (default) 313 | ; The strftime(3) format must be encapsuled in a %{}t tag 314 | ; e.g. for a ISO8601 formatted timestring, use: %{%Y-%m-%dT%H:%M:%S%z}t 315 | ; %u: remote user 316 | ; 317 | ; Default: "%R - %u %t \"%m %r\" %s" 318 | ;access.format = "%R - %u %t \"%m %r%Q%q\" %s %f %{mili}d %{kilo}M %C%%" 319 | 320 | ; The log file for slow requests 321 | ; Default Value: not set 322 | ; Note: slowlog is mandatory if request_slowlog_timeout is set 323 | ;slowlog = log/$pool.log.slow 324 | 325 | ; The timeout for serving a single request after which a PHP backtrace will be 326 | ; dumped to the 'slowlog' file. A value of '0s' means 'off'. 327 | ; Available units: s(econds)(default), m(inutes), h(ours), or d(ays) 328 | ; Default Value: 0 329 | ;request_slowlog_timeout = 0 330 | 331 | ; The timeout for serving a single request after which the worker process will 332 | ; be killed. This option should be used when the 'max_execution_time' ini option 333 | ; does not stop script execution for some reason. A value of '0' means 'off'. 334 | ; Available units: s(econds)(default), m(inutes), h(ours), or d(ays) 335 | ; Default Value: 0 336 | request_terminate_timeout = 0 337 | 338 | ; Set open file descriptor rlimit. 339 | ; Default Value: system defined value 340 | ;rlimit_files = 1024 341 | 342 | ; Set max core size rlimit. 343 | ; Possible Values: 'unlimited' or an integer greater or equal to 0 344 | ; Default Value: system defined value 345 | ;rlimit_core = 0 346 | 347 | ; Chroot to this directory at the start. This value must be defined as an 348 | ; absolute path. When this value is not set, chroot is not used. 349 | ; Note: you can prefix with '$prefix' to chroot to the pool prefix or one 350 | ; of its subdirectories. If the pool prefix is not set, the global prefix 351 | ; will be used instead. 352 | ; Note: chrooting is a great security feature and should be used whenever 353 | ; possible. However, all PHP paths will be relative to the chroot 354 | ; (error_log, sessions.save_path, ...). 355 | ; Default Value: not set 356 | ;chroot = 357 | 358 | ; Chdir to this directory at the start. 359 | ; Note: relative path can be used. 360 | ; Default Value: current directory or / when chroot 361 | ;chdir = /var/www 362 | 363 | ; Redirect worker stdout and stderr into main error log. If not set, stdout and 364 | ; stderr will be redirected to /dev/null according to FastCGI specs. 365 | ; Note: on highloaded environement, this can cause some delay in the page 366 | ; process time (several ms). 367 | ; Default Value: no 368 | ;catch_workers_output = yes 369 | 370 | ; Clear environment in FPM workers 371 | ; Prevents arbitrary environment variables from reaching FPM worker processes 372 | ; by clearing the environment in workers before env vars specified in this 373 | ; pool configuration are added. 374 | ; Setting to "no" will make all environment variables available to PHP code 375 | ; via getenv(), $_ENV and $_SERVER. 376 | ; Default Value: yes 377 | ;clear_env = no 378 | 379 | ; Limits the extensions of the main script FPM will allow to parse. This can 380 | ; prevent configuration mistakes on the web server side. You should only limit 381 | ; FPM to .php extensions to prevent malicious users to use other extensions to 382 | ; execute php code. 383 | ; Note: set an empty value to allow all extensions. 384 | ; Default Value: .php 385 | ;security.limit_extensions = .php .php3 .php4 .php5 .php7 386 | 387 | ; Pass environment variables like LD_LIBRARY_PATH. All $VARIABLEs are taken from 388 | ; the current environment. 389 | ; Default Value: clean env 390 | ;env[HOSTNAME] = $HOSTNAME 391 | ;env[PATH] = /usr/local/bin:/usr/bin:/bin 392 | ;env[TMP] = /tmp 393 | ;env[TMPDIR] = /tmp 394 | ;env[TEMP] = /tmp 395 | 396 | ; Additional php.ini defines, specific to this pool of workers. These settings 397 | ; overwrite the values previously defined in the php.ini. The directives are the 398 | ; same as the PHP SAPI: 399 | ; php_value/php_flag - you can set classic ini defines which can 400 | ; be overwritten from PHP call 'ini_set'. 401 | ; php_admin_value/php_admin_flag - these directives won't be overwritten by 402 | ; PHP call 'ini_set' 403 | ; For php_*flag, valid values are on, off, 1, 0, true, false, yes or no. 404 | 405 | ; Defining 'extension' will load the corresponding shared extension from 406 | ; extension_dir. Defining 'disable_functions' or 'disable_classes' will not 407 | ; overwrite previously defined php.ini values, but will append the new value 408 | ; instead. 409 | 410 | ; Note: path INI options can be relative and will be expanded with the prefix 411 | ; (pool, global or /opt/bitnami/php) 412 | 413 | ; Default Value: nothing is defined by default except the values in php.ini and 414 | ; specified at startup with the -d argument 415 | ;php_admin_value[sendmail_path] = /usr/sbin/sendmail -t -i -f www@my.domain.com 416 | ;php_flag[display_errors] = off 417 | ;php_admin_value[error_log] = /var/log/fpm-php.www.log 418 | ;php_admin_flag[log_errors] = on 419 | ;php_admin_value[memory_limit] = 32M 420 | 421 | include=/opt/bitnami/php/etc/environment.conf 422 | include=/opt/bitnami/php/etc/common.conf -------------------------------------------------------------------------------- /nginx-short-process/Dockerfile.nginx: -------------------------------------------------------------------------------- 1 | FROM nginx 2 | 3 | LABEL maintainer="feiskyer@gmail.com" 4 | 5 | ADD app/ /app 6 | ADD nginx.conf /etc/nginx/nginx.conf -------------------------------------------------------------------------------- /nginx-short-process/Dockerfile.php-fpm: -------------------------------------------------------------------------------- 1 | FROM bitnami/php-fpm 2 | 3 | LABEL maintainer="feiskyer@gmail.com" 4 | 5 | RUN apt-get update && apt-get install -y stress && apt-get clean 6 | 7 | ADD app/ /app -------------------------------------------------------------------------------- /nginx-short-process/Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: run 2 | run: 3 | docker run --name nginx -p 10000:80 -itd feisky/nginx:sp 4 | docker run --name phpfpm -itd --network container:nginx feisky/php-fpm:sp 5 | 6 | .PHONY: build 7 | build: 8 | docker build -t feisky/nginx:sp -f Dockerfile.nginx . 9 | docker build -t feisky/php-fpm:sp -f Dockerfile.php-fpm . 10 | 11 | .PHONY: push 12 | push: 13 | docker push feisky/nginx:sp 14 | docker push feisky/php-fpm:sp 15 | 16 | .PHONY: clean 17 | clean: 18 | docker rm -f nginx phpfpm || echo "Container nginx already deleted." 19 | -------------------------------------------------------------------------------- /nginx-short-process/README.md: -------------------------------------------------------------------------------- 1 | # 用户 CPU 使用率过高案例 2 | 3 | **《[Linux 性能优化实战](https://time.geekbang.org/column/intro/140)》第 06 篇案例。** 4 | 5 | 案例场景: 6 | 7 | * 系统的用户 CPU 使用率(usr%)过高 8 | * 没有 CPU 使用率高的进程 9 | 10 | ## 构建 Docker 镜像 11 | 12 | ```sh 13 | make build 14 | ``` 15 | 16 | ## 运行案例应用 17 | 18 | ```sh 19 | make run 20 | ``` 21 | 22 | ## 停止应用 23 | 24 | ```sh 25 | make clean 26 | ``` 27 | -------------------------------------------------------------------------------- /nginx-short-process/app/404.html: -------------------------------------------------------------------------------- 1 |

404 Not Found!

-------------------------------------------------------------------------------- /nginx-short-process/app/index.php: -------------------------------------------------------------------------------- 1 | &1", $output, $status); 4 | if (isset($_GET["verbose"]) && $_GET["verbose"]==1 && $status != 0) { 5 | echo "Server internal error: "; 6 | print_r($output); 7 | } else { 8 | echo "It works!"; 9 | } 10 | 11 | ?> -------------------------------------------------------------------------------- /nginx-short-process/app/ok.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /nginx-short-process/app/phpinfo.php: -------------------------------------------------------------------------------- 1 | }t tag 309 | ; e.g. for a ISO8601 formatted timestring, use: %{%Y-%m-%dT%H:%M:%S%z}t 310 | ; %T: time the log has been written (the request has finished) 311 | ; it can accept a strftime(3) format: 312 | ; %d/%b/%Y:%H:%M:%S %z (default) 313 | ; The strftime(3) format must be encapsuled in a %{}t tag 314 | ; e.g. for a ISO8601 formatted timestring, use: %{%Y-%m-%dT%H:%M:%S%z}t 315 | ; %u: remote user 316 | ; 317 | ; Default: "%R - %u %t \"%m %r\" %s" 318 | ;access.format = "%R - %u %t \"%m %r%Q%q\" %s %f %{mili}d %{kilo}M %C%%" 319 | 320 | ; The log file for slow requests 321 | ; Default Value: not set 322 | ; Note: slowlog is mandatory if request_slowlog_timeout is set 323 | ;slowlog = log/$pool.log.slow 324 | 325 | ; The timeout for serving a single request after which a PHP backtrace will be 326 | ; dumped to the 'slowlog' file. A value of '0s' means 'off'. 327 | ; Available units: s(econds)(default), m(inutes), h(ours), or d(ays) 328 | ; Default Value: 0 329 | ;request_slowlog_timeout = 0 330 | 331 | ; The timeout for serving a single request after which the worker process will 332 | ; be killed. This option should be used when the 'max_execution_time' ini option 333 | ; does not stop script execution for some reason. A value of '0' means 'off'. 334 | ; Available units: s(econds)(default), m(inutes), h(ours), or d(ays) 335 | ; Default Value: 0 336 | request_terminate_timeout = 0 337 | 338 | ; Set open file descriptor rlimit. 339 | ; Default Value: system defined value 340 | ;rlimit_files = 1024 341 | 342 | ; Set max core size rlimit. 343 | ; Possible Values: 'unlimited' or an integer greater or equal to 0 344 | ; Default Value: system defined value 345 | ;rlimit_core = 0 346 | 347 | ; Chroot to this directory at the start. This value must be defined as an 348 | ; absolute path. When this value is not set, chroot is not used. 349 | ; Note: you can prefix with '$prefix' to chroot to the pool prefix or one 350 | ; of its subdirectories. If the pool prefix is not set, the global prefix 351 | ; will be used instead. 352 | ; Note: chrooting is a great security feature and should be used whenever 353 | ; possible. However, all PHP paths will be relative to the chroot 354 | ; (error_log, sessions.save_path, ...). 355 | ; Default Value: not set 356 | ;chroot = 357 | 358 | ; Chdir to this directory at the start. 359 | ; Note: relative path can be used. 360 | ; Default Value: current directory or / when chroot 361 | ;chdir = /var/www 362 | 363 | ; Redirect worker stdout and stderr into main error log. If not set, stdout and 364 | ; stderr will be redirected to /dev/null according to FastCGI specs. 365 | ; Note: on highloaded environement, this can cause some delay in the page 366 | ; process time (several ms). 367 | ; Default Value: no 368 | ;catch_workers_output = yes 369 | 370 | ; Clear environment in FPM workers 371 | ; Prevents arbitrary environment variables from reaching FPM worker processes 372 | ; by clearing the environment in workers before env vars specified in this 373 | ; pool configuration are added. 374 | ; Setting to "no" will make all environment variables available to PHP code 375 | ; via getenv(), $_ENV and $_SERVER. 376 | ; Default Value: yes 377 | ;clear_env = no 378 | 379 | ; Limits the extensions of the main script FPM will allow to parse. This can 380 | ; prevent configuration mistakes on the web server side. You should only limit 381 | ; FPM to .php extensions to prevent malicious users to use other extensions to 382 | ; execute php code. 383 | ; Note: set an empty value to allow all extensions. 384 | ; Default Value: .php 385 | ;security.limit_extensions = .php .php3 .php4 .php5 .php7 386 | 387 | ; Pass environment variables like LD_LIBRARY_PATH. All $VARIABLEs are taken from 388 | ; the current environment. 389 | ; Default Value: clean env 390 | ;env[HOSTNAME] = $HOSTNAME 391 | ;env[PATH] = /usr/local/bin:/usr/bin:/bin 392 | ;env[TMP] = /tmp 393 | ;env[TMPDIR] = /tmp 394 | ;env[TEMP] = /tmp 395 | 396 | ; Additional php.ini defines, specific to this pool of workers. These settings 397 | ; overwrite the values previously defined in the php.ini. The directives are the 398 | ; same as the PHP SAPI: 399 | ; php_value/php_flag - you can set classic ini defines which can 400 | ; be overwritten from PHP call 'ini_set'. 401 | ; php_admin_value/php_admin_flag - these directives won't be overwritten by 402 | ; PHP call 'ini_set' 403 | ; For php_*flag, valid values are on, off, 1, 0, true, false, yes or no. 404 | 405 | ; Defining 'extension' will load the corresponding shared extension from 406 | ; extension_dir. Defining 'disable_functions' or 'disable_classes' will not 407 | ; overwrite previously defined php.ini values, but will append the new value 408 | ; instead. 409 | 410 | ; Note: path INI options can be relative and will be expanded with the prefix 411 | ; (pool, global or /opt/bitnami/php) 412 | 413 | ; Default Value: nothing is defined by default except the values in php.ini and 414 | ; specified at startup with the -d argument 415 | ;php_admin_value[sendmail_path] = /usr/sbin/sendmail -t -i -f www@my.domain.com 416 | ;php_flag[display_errors] = off 417 | ;php_admin_value[error_log] = /var/log/fpm-php.www.log 418 | ;php_admin_flag[log_errors] = on 419 | ;php_admin_value[memory_limit] = 32M 420 | 421 | include=/opt/bitnami/php/etc/environment.conf 422 | include=/opt/bitnami/php/etc/common.conf -------------------------------------------------------------------------------- /nginx-throughput/Dockerfile.nginx: -------------------------------------------------------------------------------- 1 | FROM nginx 2 | 3 | LABEL maintainer="feiskyer@gmail.com" 4 | 5 | RUN apt-get update && \ 6 | apt-get install -y procps && \ 7 | apt-get clean 8 | 9 | ADD app/ /app 10 | ADD nginx.conf /etc/nginx/nginx.conf 11 | ADD init.sh /init.sh 12 | 13 | CMD ["/init.sh"] 14 | -------------------------------------------------------------------------------- /nginx-throughput/Dockerfile.php-fpm: -------------------------------------------------------------------------------- 1 | FROM bitnami/php-fpm 2 | 3 | LABEL maintainer="feiskyer@gmail.com" 4 | 5 | ADD app/ /app -------------------------------------------------------------------------------- /nginx-throughput/Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: run 2 | run: 3 | docker run --name nginx --network host --privileged -itd feisky/nginx-tp 4 | docker run --name phpfpm --network host --privileged -itd feisky/php-fpm-tp 5 | 6 | .PHONY: build 7 | build: 8 | docker build -t feisky/nginx-tp -f Dockerfile.nginx . 9 | docker build -t feisky/php-fpm-tp -f Dockerfile.php-fpm . 10 | 11 | .PHONY: push 12 | push: 13 | docker push feisky/nginx-tp 14 | docker push feisky/php-fpm-tp 15 | 16 | .PHONY: clean 17 | clean: 18 | docker rm -f nginx phpfpm || echo "Container nginx already deleted." 19 | -------------------------------------------------------------------------------- /nginx-throughput/README.md: -------------------------------------------------------------------------------- 1 | # Nginx 吞吐量低案例 2 | 3 | **《[Linux 性能优化实战](https://time.geekbang.org/column/intro/140)》第 52 篇案例。** 4 | 5 | 案例场景:Nginx + PHP 案例,吞吐量低 6 | 7 | ## 构建 Docker 镜像 8 | 9 | ```sh 10 | make build 11 | ``` 12 | 13 | ## 运行案例应用 14 | 15 | ```sh 16 | make run 17 | ``` 18 | 19 | ## 停止应用 20 | 21 | ```sh 22 | make clean 23 | ``` 24 | -------------------------------------------------------------------------------- /nginx-throughput/app/404.html: -------------------------------------------------------------------------------- 1 |

404 Not Found!

-------------------------------------------------------------------------------- /nginx-throughput/app/index.php: -------------------------------------------------------------------------------- 1 | 4 | -------------------------------------------------------------------------------- /nginx-throughput/init.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | sysctl -w net.ipv4.ip_local_port_range='20000 20050' 3 | sysctl -w net.ipv4.tcp_tw_reuse=0 4 | sysctl -w net.ipv4.tcp_fin_timeout=3600 5 | sysctl -w net.ipv4.tcp_max_syn_backlog=100 6 | sysctl -w net.netfilter.nf_conntrack_max=200 7 | sysctl -w net.core.somaxconn=10 8 | 9 | # start nginx 10 | nginx -g "daemon off;" 11 | -------------------------------------------------------------------------------- /nginx-throughput/nginx.conf: -------------------------------------------------------------------------------- 1 | user nginx; 2 | worker_processes 2; 3 | 4 | error_log /var/log/nginx/error.log warn; 5 | pid /var/run/nginx.pid; 6 | 7 | 8 | events { 9 | #use epoll; 10 | worker_connections 1024; 11 | } 12 | 13 | 14 | http { 15 | include /etc/nginx/mime.types; 16 | default_type application/octet-stream; 17 | 18 | log_format main '$remote_addr - $remote_user [$time_local] "$request" ' 19 | '$status $body_bytes_sent "$http_referer" ' 20 | '"$http_user_agent" "$http_x_forwarded_for"'; 21 | 22 | access_log /var/log/nginx/access.log main; 23 | 24 | sendfile on; 25 | #tcp_nopush on; 26 | keepalive_requests 10; 27 | keepalive_timeout 600; 28 | 29 | gzip on; 30 | 31 | server { 32 | listen 80 backlog=10; 33 | server_name localhost; 34 | 35 | 36 | location / { 37 | root /app; 38 | index index.php; 39 | } 40 | 41 | error_page 404 /404.html; 42 | 43 | # redirect server error pages to the static page /50x.html 44 | # 45 | error_page 500 502 503 504 /50x.html; 46 | location = /50x.html { 47 | root /app; 48 | } 49 | 50 | # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000 51 | # 52 | location ~ \.php$ { 53 | root /app; 54 | fastcgi_pass 127.0.0.1:9000; 55 | fastcgi_keep_conn off; 56 | fastcgi_index index.php; 57 | fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; 58 | fastcgi_param SCRIPT_NAME $fastcgi_script_name; 59 | include fastcgi_params; 60 | } 61 | 62 | # deny access to .htaccess files, if Apache's document root 63 | # concurs with nginx's one 64 | # 65 | location ~ /\.ht { 66 | deny all; 67 | } 68 | 69 | location /nginx_status { 70 | stub_status on; 71 | access_log off; 72 | allow 0.0.0.0; 73 | allow 172.17.0.1; 74 | deny all; 75 | } 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /nginx-throughput/php-fpm.d/www.conf: -------------------------------------------------------------------------------- 1 | ; Start a new pool named 'www'. 2 | ; the variable $pool can be used in any directive and will be replaced by the 3 | ; pool name ('www' here) 4 | [www] 5 | 6 | ; Per pool prefix 7 | ; It only applies on the following directives: 8 | ; - 'access.log' 9 | ; - 'slowlog' 10 | ; - 'listen' (unixsocket) 11 | ; - 'chroot' 12 | ; - 'chdir' 13 | ; - 'php_values' 14 | ; - 'php_admin_values' 15 | ; When not set, the global prefix (or /opt/bitnami/php) applies instead. 16 | ; Note: This directive can also be relative to the global prefix. 17 | ; Default Value: none 18 | ;prefix = /path/to/pools/$pool 19 | 20 | ; Unix user/group of processes 21 | ; Note: The user is mandatory. If the group is not set, the default user's group 22 | ; will be used. 23 | user = daemon 24 | group = daemon 25 | 26 | ; The address on which to accept FastCGI requests. 27 | ; Valid syntaxes are: 28 | ; 'ip.add.re.ss:port' - to listen on a TCP socket to a specific IPv4 address on 29 | ; a specific port; 30 | ; '[ip:6:addr:ess]:port' - to listen on a TCP socket to a specific IPv6 address on 31 | ; a specific port; 32 | ; 'port' - to listen on a TCP socket to all addresses 33 | ; (IPv6 and IPv4-mapped) on a specific port; 34 | ; '/path/to/unix/socket' - to listen on a unix socket. 35 | ; Note: This value is mandatory. 36 | listen = 9000 37 | 38 | ; Set listen(2) backlog. 39 | ; Default Value: 511 (-1 on FreeBSD and OpenBSD) 40 | ;listen.backlog = 511 41 | 42 | ; Set permissions for unix socket, if one is used. In Linux, read/write 43 | ; permissions must be set in order to allow connections from a web server. Many 44 | ; BSD-derived systems allow connections regardless of permissions. 45 | ; Default Values: user and group are set as the running user 46 | ; mode is set to 0660 47 | ;listen.owner = daemon 48 | ;listen.group = daemon 49 | ;listen.mode = 0660 50 | ; When POSIX Access Control Lists are supported you can set them using 51 | ; these options, value is a comma separated list of user/group names. 52 | ; When set, listen.owner and listen.group are ignored 53 | ;listen.acl_users = 54 | ;listen.acl_groups = 55 | 56 | ; List of addresses (IPv4/IPv6) of FastCGI clients which are allowed to connect. 57 | ; Equivalent to the FCGI_WEB_SERVER_ADDRS environment variable in the original 58 | ; PHP FCGI (5.2.2+). Makes sense only with a tcp listening socket. Each address 59 | ; must be separated by a comma. If this value is left blank, connections will be 60 | ; accepted from any ip address. 61 | ; Default Value: any 62 | ;listen.allowed_clients = 127.0.0.1 63 | 64 | ; Specify the nice(2) priority to apply to the pool processes (only if set) 65 | ; The value can vary from -19 (highest priority) to 20 (lower priority) 66 | ; Note: - It will only work if the FPM master process is launched as root 67 | ; - The pool processes will inherit the master process priority 68 | ; unless it specified otherwise 69 | ; Default Value: no set 70 | ; process.priority = -19 71 | 72 | ; Set the process dumpable flag (PR_SET_DUMPABLE prctl) even if the process user 73 | ; or group is differrent than the master process user. It allows to create process 74 | ; core dump and ptrace the process for the pool user. 75 | ; Default Value: no 76 | ; process.dumpable = yes 77 | 78 | ; Choose how the process manager will control the number of child processes. 79 | ; Possible Values: 80 | ; static - a fixed number (pm.max_children) of child processes; 81 | ; dynamic - the number of child processes are set dynamically based on the 82 | ; following directives. With this process management, there will be 83 | ; always at least 1 children. 84 | ; pm.max_children - the maximum number of children that can 85 | ; be alive at the same time. 86 | ; pm.start_servers - the number of children created on startup. 87 | ; pm.min_spare_servers - the minimum number of children in 'idle' 88 | ; state (waiting to process). If the number 89 | ; of 'idle' processes is less than this 90 | ; number then some children will be created. 91 | ; pm.max_spare_servers - the maximum number of children in 'idle' 92 | ; state (waiting to process). If the number 93 | ; of 'idle' processes is greater than this 94 | ; number then some children will be killed. 95 | ; ondemand - no children are created at startup. Children will be forked when 96 | ; new requests will connect. The following parameter are used: 97 | ; pm.max_children - the maximum number of children that 98 | ; can be alive at the same time. 99 | ; pm.process_idle_timeout - The number of seconds after which 100 | ; an idle process will be killed. 101 | ; Note: This value is mandatory. 102 | pm = ondemand 103 | 104 | ; The number of child processes to be created when pm is set to 'static' and the 105 | ; maximum number of child processes when pm is set to 'dynamic' or 'ondemand'. 106 | ; This value sets the limit on the number of simultaneous requests that will be 107 | ; served. Equivalent to the ApacheMaxClients directive with mpm_prefork. 108 | ; Equivalent to the PHP_FCGI_CHILDREN environment variable in the original PHP 109 | ; CGI. The below defaults are based on a server without much resources. Don't 110 | ; forget to tweak pm.* to fit your needs. 111 | ; Note: Used when pm is set to 'static', 'dynamic' or 'ondemand' 112 | ; Note: This value is mandatory. 113 | pm.max_children = 5 114 | 115 | ; The number of child processes created on startup. 116 | ; Note: Used only when pm is set to 'dynamic' 117 | ; Default Value: min_spare_servers + (max_spare_servers - min_spare_servers) / 2 118 | pm.start_servers = 2 119 | 120 | ; The desired minimum number of idle server processes. 121 | ; Note: Used only when pm is set to 'dynamic' 122 | ; Note: Mandatory when pm is set to 'dynamic' 123 | pm.min_spare_servers = 1 124 | 125 | ; The desired maximum number of idle server processes. 126 | ; Note: Used only when pm is set to 'dynamic' 127 | ; Note: Mandatory when pm is set to 'dynamic' 128 | pm.max_spare_servers = 3 129 | 130 | ; The number of seconds after which an idle process will be killed. 131 | ; Note: Used only when pm is set to 'ondemand' 132 | ; Default Value: 10s 133 | ;pm.process_idle_timeout = 10s; 134 | 135 | ; The number of requests each child process should execute before respawning. 136 | ; This can be useful to work around memory leaks in 3rd party libraries. For 137 | ; endless request processing specify '0'. Equivalent to PHP_FCGI_MAX_REQUESTS. 138 | ; Default Value: 0 139 | ;pm.max_requests = 500 140 | 141 | ; The URI to view the FPM status page. If this value is not set, no URI will be 142 | ; recognized as a status page. It shows the following informations: 143 | ; pool - the name of the pool; 144 | ; process manager - static, dynamic or ondemand; 145 | ; start time - the date and time FPM has started; 146 | ; start since - number of seconds since FPM has started; 147 | ; accepted conn - the number of request accepted by the pool; 148 | ; listen queue - the number of request in the queue of pending 149 | ; connections (see backlog in listen(2)); 150 | ; max listen queue - the maximum number of requests in the queue 151 | ; of pending connections since FPM has started; 152 | ; listen queue len - the size of the socket queue of pending connections; 153 | ; idle processes - the number of idle processes; 154 | ; active processes - the number of active processes; 155 | ; total processes - the number of idle + active processes; 156 | ; max active processes - the maximum number of active processes since FPM 157 | ; has started; 158 | ; max children reached - number of times, the process limit has been reached, 159 | ; when pm tries to start more children (works only for 160 | ; pm 'dynamic' and 'ondemand'); 161 | ; Value are updated in real time. 162 | ; Example output: 163 | ; pool: www 164 | ; process manager: static 165 | ; start time: 01/Jul/2011:17:53:49 +0200 166 | ; start since: 62636 167 | ; accepted conn: 190460 168 | ; listen queue: 0 169 | ; max listen queue: 1 170 | ; listen queue len: 42 171 | ; idle processes: 4 172 | ; active processes: 11 173 | ; total processes: 15 174 | ; max active processes: 12 175 | ; max children reached: 0 176 | ; 177 | ; By default the status page output is formatted as text/plain. Passing either 178 | ; 'html', 'xml' or 'json' in the query string will return the corresponding 179 | ; output syntax. Example: 180 | ; http://www.foo.bar/status 181 | ; http://www.foo.bar/status?json 182 | ; http://www.foo.bar/status?html 183 | ; http://www.foo.bar/status?xml 184 | ; 185 | ; By default the status page only outputs short status. Passing 'full' in the 186 | ; query string will also return status for each pool process. 187 | ; Example: 188 | ; http://www.foo.bar/status?full 189 | ; http://www.foo.bar/status?json&full 190 | ; http://www.foo.bar/status?html&full 191 | ; http://www.foo.bar/status?xml&full 192 | ; The Full status returns for each process: 193 | ; pid - the PID of the process; 194 | ; state - the state of the process (Idle, Running, ...); 195 | ; start time - the date and time the process has started; 196 | ; start since - the number of seconds since the process has started; 197 | ; requests - the number of requests the process has served; 198 | ; request duration - the duration in µs of the requests; 199 | ; request method - the request method (GET, POST, ...); 200 | ; request URI - the request URI with the query string; 201 | ; content length - the content length of the request (only with POST); 202 | ; user - the user (PHP_AUTH_USER) (or '-' if not set); 203 | ; script - the main script called (or '-' if not set); 204 | ; last request cpu - the %cpu the last request consumed 205 | ; it's always 0 if the process is not in Idle state 206 | ; because CPU calculation is done when the request 207 | ; processing has terminated; 208 | ; last request memory - the max amount of memory the last request consumed 209 | ; it's always 0 if the process is not in Idle state 210 | ; because memory calculation is done when the request 211 | ; processing has terminated; 212 | ; If the process is in Idle state, then informations are related to the 213 | ; last request the process has served. Otherwise informations are related to 214 | ; the current request being served. 215 | ; Example output: 216 | ; ************************ 217 | ; pid: 31330 218 | ; state: Running 219 | ; start time: 01/Jul/2011:17:53:49 +0200 220 | ; start since: 63087 221 | ; requests: 12808 222 | ; request duration: 1250261 223 | ; request method: GET 224 | ; request URI: /test_mem.php?N=10000 225 | ; content length: 0 226 | ; user: - 227 | ; script: /home/fat/web/docs/php/test_mem.php 228 | ; last request cpu: 0.00 229 | ; last request memory: 0 230 | ; 231 | ; Note: There is a real-time FPM status monitoring sample web page available 232 | ; It's available in: /opt/bitnami/php/share/php/fpm/status.html 233 | ; 234 | ; Note: The value must start with a leading slash (/). The value can be 235 | ; anything, but it may not be a good idea to use the .php extension or it 236 | ; may conflict with a real PHP file. 237 | ; Default Value: not set 238 | ;pm.status_path = /status 239 | 240 | ; The ping URI to call the monitoring page of FPM. If this value is not set, no 241 | ; URI will be recognized as a ping page. This could be used to test from outside 242 | ; that FPM is alive and responding, or to 243 | ; - create a graph of FPM availability (rrd or such); 244 | ; - remove a server from a group if it is not responding (load balancing); 245 | ; - trigger alerts for the operating team (24/7). 246 | ; Note: The value must start with a leading slash (/). The value can be 247 | ; anything, but it may not be a good idea to use the .php extension or it 248 | ; may conflict with a real PHP file. 249 | ; Default Value: not set 250 | ;ping.path = /ping 251 | 252 | ; This directive may be used to customize the response of a ping request. The 253 | ; response is formatted as text/plain with a 200 response code. 254 | ; Default Value: pong 255 | ;ping.response = pong 256 | 257 | ; The access log file 258 | ; Default: not set 259 | ;access.log = log/$pool.access.log 260 | 261 | ; The access log format. 262 | ; The following syntax is allowed 263 | ; %%: the '%' character 264 | ; %C: %CPU used by the request 265 | ; it can accept the following format: 266 | ; - %{user}C for user CPU only 267 | ; - %{system}C for system CPU only 268 | ; - %{total}C for user + system CPU (default) 269 | ; %d: time taken to serve the request 270 | ; it can accept the following format: 271 | ; - %{seconds}d (default) 272 | ; - %{miliseconds}d 273 | ; - %{mili}d 274 | ; - %{microseconds}d 275 | ; - %{micro}d 276 | ; %e: an environment variable (same as $_ENV or $_SERVER) 277 | ; it must be associated with embraces to specify the name of the env 278 | ; variable. Some exemples: 279 | ; - server specifics like: %{REQUEST_METHOD}e or %{SERVER_PROTOCOL}e 280 | ; - HTTP headers like: %{HTTP_HOST}e or %{HTTP_USER_AGENT}e 281 | ; %f: script filename 282 | ; %l: content-length of the request (for POST request only) 283 | ; %m: request method 284 | ; %M: peak of memory allocated by PHP 285 | ; it can accept the following format: 286 | ; - %{bytes}M (default) 287 | ; - %{kilobytes}M 288 | ; - %{kilo}M 289 | ; - %{megabytes}M 290 | ; - %{mega}M 291 | ; %n: pool name 292 | ; %o: output header 293 | ; it must be associated with embraces to specify the name of the header: 294 | ; - %{Content-Type}o 295 | ; - %{X-Powered-By}o 296 | ; - %{Transfert-Encoding}o 297 | ; - .... 298 | ; %p: PID of the child that serviced the request 299 | ; %P: PID of the parent of the child that serviced the request 300 | ; %q: the query string 301 | ; %Q: the '?' character if query string exists 302 | ; %r: the request URI (without the query string, see %q and %Q) 303 | ; %R: remote IP address 304 | ; %s: status (response code) 305 | ; %t: server time the request was received 306 | ; it can accept a strftime(3) format: 307 | ; %d/%b/%Y:%H:%M:%S %z (default) 308 | ; The strftime(3) format must be encapsuled in a %{}t tag 309 | ; e.g. for a ISO8601 formatted timestring, use: %{%Y-%m-%dT%H:%M:%S%z}t 310 | ; %T: time the log has been written (the request has finished) 311 | ; it can accept a strftime(3) format: 312 | ; %d/%b/%Y:%H:%M:%S %z (default) 313 | ; The strftime(3) format must be encapsuled in a %{}t tag 314 | ; e.g. for a ISO8601 formatted timestring, use: %{%Y-%m-%dT%H:%M:%S%z}t 315 | ; %u: remote user 316 | ; 317 | ; Default: "%R - %u %t \"%m %r\" %s" 318 | ;access.format = "%R - %u %t \"%m %r%Q%q\" %s %f %{mili}d %{kilo}M %C%%" 319 | 320 | ; The log file for slow requests 321 | ; Default Value: not set 322 | ; Note: slowlog is mandatory if request_slowlog_timeout is set 323 | ;slowlog = log/$pool.log.slow 324 | 325 | ; The timeout for serving a single request after which a PHP backtrace will be 326 | ; dumped to the 'slowlog' file. A value of '0s' means 'off'. 327 | ; Available units: s(econds)(default), m(inutes), h(ours), or d(ays) 328 | ; Default Value: 0 329 | ;request_slowlog_timeout = 0 330 | 331 | ; The timeout for serving a single request after which the worker process will 332 | ; be killed. This option should be used when the 'max_execution_time' ini option 333 | ; does not stop script execution for some reason. A value of '0' means 'off'. 334 | ; Available units: s(econds)(default), m(inutes), h(ours), or d(ays) 335 | ; Default Value: 0 336 | request_terminate_timeout = 0 337 | 338 | ; Set open file descriptor rlimit. 339 | ; Default Value: system defined value 340 | ;rlimit_files = 1024 341 | 342 | ; Set max core size rlimit. 343 | ; Possible Values: 'unlimited' or an integer greater or equal to 0 344 | ; Default Value: system defined value 345 | ;rlimit_core = 0 346 | 347 | ; Chroot to this directory at the start. This value must be defined as an 348 | ; absolute path. When this value is not set, chroot is not used. 349 | ; Note: you can prefix with '$prefix' to chroot to the pool prefix or one 350 | ; of its subdirectories. If the pool prefix is not set, the global prefix 351 | ; will be used instead. 352 | ; Note: chrooting is a great security feature and should be used whenever 353 | ; possible. However, all PHP paths will be relative to the chroot 354 | ; (error_log, sessions.save_path, ...). 355 | ; Default Value: not set 356 | ;chroot = 357 | 358 | ; Chdir to this directory at the start. 359 | ; Note: relative path can be used. 360 | ; Default Value: current directory or / when chroot 361 | ;chdir = /var/www 362 | 363 | ; Redirect worker stdout and stderr into main error log. If not set, stdout and 364 | ; stderr will be redirected to /dev/null according to FastCGI specs. 365 | ; Note: on highloaded environement, this can cause some delay in the page 366 | ; process time (several ms). 367 | ; Default Value: no 368 | ;catch_workers_output = yes 369 | 370 | ; Clear environment in FPM workers 371 | ; Prevents arbitrary environment variables from reaching FPM worker processes 372 | ; by clearing the environment in workers before env vars specified in this 373 | ; pool configuration are added. 374 | ; Setting to "no" will make all environment variables available to PHP code 375 | ; via getenv(), $_ENV and $_SERVER. 376 | ; Default Value: yes 377 | ;clear_env = no 378 | 379 | ; Limits the extensions of the main script FPM will allow to parse. This can 380 | ; prevent configuration mistakes on the web server side. You should only limit 381 | ; FPM to .php extensions to prevent malicious users to use other extensions to 382 | ; execute php code. 383 | ; Note: set an empty value to allow all extensions. 384 | ; Default Value: .php 385 | ;security.limit_extensions = .php .php3 .php4 .php5 .php7 386 | 387 | ; Pass environment variables like LD_LIBRARY_PATH. All $VARIABLEs are taken from 388 | ; the current environment. 389 | ; Default Value: clean env 390 | ;env[HOSTNAME] = $HOSTNAME 391 | ;env[PATH] = /usr/local/bin:/usr/bin:/bin 392 | ;env[TMP] = /tmp 393 | ;env[TMPDIR] = /tmp 394 | ;env[TEMP] = /tmp 395 | 396 | ; Additional php.ini defines, specific to this pool of workers. These settings 397 | ; overwrite the values previously defined in the php.ini. The directives are the 398 | ; same as the PHP SAPI: 399 | ; php_value/php_flag - you can set classic ini defines which can 400 | ; be overwritten from PHP call 'ini_set'. 401 | ; php_admin_value/php_admin_flag - these directives won't be overwritten by 402 | ; PHP call 'ini_set' 403 | ; For php_*flag, valid values are on, off, 1, 0, true, false, yes or no. 404 | 405 | ; Defining 'extension' will load the corresponding shared extension from 406 | ; extension_dir. Defining 'disable_functions' or 'disable_classes' will not 407 | ; overwrite previously defined php.ini values, but will append the new value 408 | ; instead. 409 | 410 | ; Note: path INI options can be relative and will be expanded with the prefix 411 | ; (pool, global or /opt/bitnami/php) 412 | 413 | ; Default Value: nothing is defined by default except the values in php.ini and 414 | ; specified at startup with the -d argument 415 | ;php_admin_value[sendmail_path] = /usr/sbin/sendmail -t -i -f www@my.domain.com 416 | ;php_flag[display_errors] = off 417 | ;php_admin_value[error_log] = /var/log/fpm-php.www.log 418 | ;php_admin_flag[log_errors] = on 419 | ;php_admin_value[memory_limit] = 32M 420 | 421 | include=/opt/bitnami/php/etc/environment.conf 422 | include=/opt/bitnami/php/etc/common.conf -------------------------------------------------------------------------------- /packet-drop/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM nginx 2 | 3 | LABEL maintainer="feiskyer@gmail.com" 4 | 5 | RUN apt-get update && \ 6 | apt-get install -y iproute net-tools iputils-ping iptables tcpdump sysstat ethtool && \ 7 | apt-get clean 8 | 9 | ADD start.sh /start.sh 10 | 11 | CMD ["/start.sh"] -------------------------------------------------------------------------------- /packet-drop/Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: run 2 | run: 3 | docker run --name nginx --hostname nginx --privileged -p 80:80 -itd feisky/nginx:drop 4 | 5 | .PHONY: build 6 | build: 7 | docker build -t feisky/nginx:drop -f Dockerfile . 8 | 9 | .PHONY: push 10 | push: 11 | docker push feisky/nginx:drop 12 | 13 | .PHONY: clean 14 | clean: 15 | docker rm -f nginx || echo "Container nginx already deleted." -------------------------------------------------------------------------------- /packet-drop/README.md: -------------------------------------------------------------------------------- 1 | # 网络丢包案例 2 | 3 | **《[Linux 性能优化实战](https://time.geekbang.org/column/intro/140)》第 47、48 篇案例。** 4 | 5 | 案例场景: 6 | 7 | * Nginx 时不时丢包案例 8 | * Nginx 访问延迟增大 9 | 10 | ## 构建 Docker 镜像 11 | 12 | ```sh 13 | make build 14 | ``` 15 | 16 | ## 运行案例应用 17 | 18 | ```sh 19 | make run 20 | ``` 21 | 22 | ## 停止应用 23 | 24 | ```sh 25 | make clean 26 | ``` 27 | -------------------------------------------------------------------------------- /packet-drop/start.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # Configure smaller mtu 4 | ifconfig eth0 mtu 100 5 | 6 | # Simulate packet drop 7 | tc qdisc add dev eth0 root netem loss 30% 8 | iptables -I INPUT -m statistic --mode random --probability 0.30 -j DROP 9 | iptables -I OUTPUT -m statistic --mode random --probability 0.30 -j DROP 10 | 11 | # Start nginx 12 | nginx -g "daemon off;" -------------------------------------------------------------------------------- /redis-slow/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM python:3.6 2 | 3 | LABEL maintainer="feiskyer@gmail.com" 4 | 5 | RUN pip install flask redis 6 | 7 | EXPOSE 80 8 | ADD app.py /app.py 9 | 10 | CMD ["python", "/app.py"] 11 | -------------------------------------------------------------------------------- /redis-slow/Dockerfile.redis: -------------------------------------------------------------------------------- 1 | FROM redis:alpine 2 | 3 | LABEL maintainer="feiskyer@gmail.com" 4 | 5 | ADD redis.conf /etc/redis.conf 6 | 7 | CMD ["redis-server", "/etc/redis.conf"] -------------------------------------------------------------------------------- /redis-slow/Makefile: -------------------------------------------------------------------------------- 1 | DATA_NUM ?= 5000 2 | 3 | .PHONY: run 4 | run: redis 5 | docker run --name=app --network=container:redis -itd feisky/redis-app 6 | 7 | .PHONY: redis 8 | redis: 9 | docker run --name=redis -itd -p 10000:80 feisky/redis-server 10 | 11 | 12 | .PHONY: build 13 | build: 14 | docker build -t feisky/redis-app -f Dockerfile . 15 | docker build -t feisky/redis-server -f Dockerfile.redis . 16 | 17 | 18 | .PHONY: init 19 | init: 20 | curl http://127.0.0.1:10000/init/$(DATA_NUM) 21 | 22 | 23 | .PHONY: push 24 | push: 25 | docker push feisky/redis-app 26 | docker push feisky/redis-server 27 | 28 | .PHONY: clean 29 | clean: 30 | docker rm -f app redis || echo "Containers already deleted." 31 | -------------------------------------------------------------------------------- /redis-slow/README.md: -------------------------------------------------------------------------------- 1 | # Redis 延迟严重案例 2 | 3 | **《[Linux 性能优化实战](https://time.geekbang.org/column/intro/140)》第 29 篇案例。** 4 | 5 | 案例场景: 6 | 7 | * Redis 响应延迟严重 8 | * 系统 CPU 使用率 iowait% 高 9 | 10 | 本案例由 Python+Redis 两个容器组成。其中,Python 容器是一个基于 Flask 的应用,它会利用 Redis 来管理应用程序的缓存,并对外提供三个 HTTP 接口: 11 | 12 | * `/`:返回 `hello redis`; 13 | * `/init/`:插入指定数量的缓存数据,如不指定数量,则默认为 5000 条; 14 | * 缓存的键格式为 `uuid:` 15 | * 缓存的值为 `good`、`bad` 或 `normal` 三者之一 16 | * `/get_cache/`:查询指定值的缓存数据并返回处理时间,其中的 type_name 参数只支持 'good', 'bad' 和 'normal'。 17 | 18 | ## 构建 Docker 镜像 19 | 20 | ```sh 21 | make build 22 | ``` 23 | 24 | ## 运行案例应用 25 | 26 | ```sh 27 | make run 28 | ``` 29 | 30 | ## 停止应用 31 | 32 | ```sh 33 | make clean 34 | ``` 35 | -------------------------------------------------------------------------------- /redis-slow/app.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: UTF-8 -*- 3 | from functools import wraps 4 | from time import time 5 | import json 6 | import random 7 | import uuid 8 | import redis 9 | from flask import Flask, jsonify 10 | 11 | app = Flask(__name__) 12 | redis_client = redis.StrictRedis( 13 | host="127.0.0.1", charset="utf-8", port=6379, db=0, decode_responses=True) 14 | 15 | 16 | def timing(f): 17 | '''wrapper for elapsed_seconds''' 18 | @wraps(f) 19 | def wrapper(*args, **kwargs): 20 | start = time() 21 | result = f(*args, **kwargs) 22 | end = time() 23 | data = json.loads(result.get_data()) 24 | data["elapsed_seconds"] = end-start 25 | return jsonify(data) 26 | return wrapper 27 | 28 | 29 | @app.route('/') 30 | def hello_world(): 31 | '''handler for /''' 32 | return 'hello redis\n' 33 | 34 | 35 | @app.route('/get_cache', defaults={'type_name': 'good'}) 36 | @app.route("/get_cache/") 37 | @timing 38 | def get_cache(type_name): 39 | '''handler for /get_cache''' 40 | for key in redis_client.scan_iter("uuid:*"): 41 | value = redis_client.get(key) 42 | if value == type_name: 43 | redis_client.sadd(type_name, key[5:]) 44 | data = list(redis_client.smembers(type_name)) 45 | redis_client.delete(type_name) 46 | return jsonify({"type": type_name, 'count': len(data), 'data': data}) 47 | 48 | 49 | @app.route('/get_cache_data', defaults={'type_name': 'good'}) 50 | @app.route("/get_cache_data/") 51 | @timing 52 | def get_cache_data(type_name): 53 | '''handler for /get_cache_data''' 54 | keys = [key for key in redis_client.scan_iter("uuid:*")] 55 | values = redis_client.mget(keys) 56 | matched_keys = set([keys[idx][5:] for idx, value in enumerate(values) if value == type_name ]) 57 | return jsonify({"type": type_name, 'count': len(matched_keys), 'data': list(matched_keys)}) 58 | 59 | 60 | @app.route('/init', defaults={'num':5000}) 61 | @app.route('/init/') 62 | @timing 63 | def initialize(num): 64 | '''handler for /init''' 65 | redis_client.flushall() 66 | types = ('good', 'bad', 'normal') 67 | sample_size = int(num) 68 | random_pool = random.sample(range(0, sample_size), sample_size) 69 | 70 | for i in range(sample_size): 71 | key = uuid.uuid1() 72 | redis_client.set('uuid:{}'.format(key), types[(random_pool[i]+i) % 3]) 73 | 74 | return jsonify({"keys_initialized": sample_size}) 75 | 76 | 77 | if __name__ == '__main__': 78 | app.run(host='0.0.0.0', port=80) 79 | -------------------------------------------------------------------------------- /short-lived-process/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM ubuntu 2 | 3 | LABEL maintainer="feiskyer@gmail.com" 4 | 5 | RUN apt-get update && apt-get install -y stress && apt-get clean 6 | 7 | ADD app /app 8 | ADD app.c /app.c 9 | 10 | CMD ["/app"] 11 | -------------------------------------------------------------------------------- /short-lived-process/Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: build 2 | build: 3 | gcc -o app app.c 4 | docker build -t feisky/app:short-process -f Dockerfile . 5 | 6 | .PHONY: push 7 | push: 8 | docker push feisky/app:short-process 9 | 10 | .PHONY: run 11 | run: 12 | docker run --name=app -itd feisky/app:short-process 13 | 14 | .PHONY: clean 15 | clean: 16 | rm -f app 17 | docker rm -f app || echo "Container app already deleted." 18 | -------------------------------------------------------------------------------- /short-lived-process/README.md: -------------------------------------------------------------------------------- 1 | # 短时进程案例 2 | 3 | **注:该案例未包含在专栏中,专栏以 [Nginx 的案例](../nginx-short-process/README.md)讲解类似问题的分析思路。** 4 | 5 | 案例场景: 6 | 7 | * 系统的用户 CPU 使用率(usr%)过高 8 | * 没有 CPU 使用率高的进程 9 | 10 | ## 构建 Docker 镜像 11 | 12 | ```sh 13 | make build 14 | ``` 15 | 16 | ## 运行案例应用 17 | 18 | ```sh 19 | make run 20 | ``` 21 | 22 | ## 停止应用 23 | 24 | ```sh 25 | make clean 26 | ``` 27 | -------------------------------------------------------------------------------- /short-lived-process/app.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | void create_process() 8 | { 9 | // fake I/O with stress (via write()/unlink()). 10 | char *argv[6] = { "stress", "--timeout", "1", "--hdd", "1", NULL }; 11 | 12 | if (fork() == 0) { 13 | if (execvp("stress", argv) < 0) { 14 | perror("Exec error"); 15 | _exit(1); 16 | } 17 | _exit(0); 18 | } 19 | } 20 | 21 | int main(void) 22 | { 23 | signal(SIGCHLD,SIG_IGN); // Avoid zombie process. 24 | int i = 0; 25 | for (;;) { 26 | for (i = 0; i < 3; i++) { 27 | create_process(); 28 | } 29 | sleep(5); 30 | } 31 | 32 | wait(NULL); 33 | return 0; 34 | } -------------------------------------------------------------------------------- /tomcat/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM tomcat:8 2 | 3 | LABEL maintainer="feiskyer@gmail.com" 4 | 5 | RUN apt-get update && apt-get install -y procps && apt-get clean 6 | 7 | COPY index.jsp /usr/local/tomcat/webapps/ROOT/index.jsp 8 | -------------------------------------------------------------------------------- /tomcat/Dockerfile.jre11: -------------------------------------------------------------------------------- 1 | FROM tomcat:jre11 2 | 3 | LABEL maintainer="feiskyer@gmail.com" 4 | 5 | RUN apt-get update && apt-get install -y procps && apt-get clean 6 | 7 | COPY index.jsp /usr/local/tomcat/webapps/ROOT/index.jsp 8 | -------------------------------------------------------------------------------- /tomcat/Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: run 2 | run: 3 | docker run --name tomcat --cpus 0.1 -m 512M -p 8080:8080 -itd feisky/tomcat:8 4 | 5 | .PHONY: run-jre11 6 | run-jre11: 7 | docker run --name tomcat-jre11 --cpus 0.1 -m 512M -p 8080:8080 -itd feisky/tomcat:11 8 | 9 | .PHONY: build 10 | build: 11 | docker build -t feisky/tomcat:11 -f Dockerfile.jre11 . 12 | docker build -t feisky/tomcat:8 -f Dockerfile . 13 | 14 | .PHONY: push 15 | push: 16 | docker push feisky/tomcat:11 17 | docker push feisky/tomcat:8 18 | 19 | .PHONY: clean 20 | clean: 21 | docker rm -f tomcat tomcat-jre11 || echo "Container comcat already deleted." 22 | -------------------------------------------------------------------------------- /tomcat/README.md: -------------------------------------------------------------------------------- 1 | # Docker 运行 Tomcat 案例 2 | 3 | **《[Linux 性能优化实战](https://time.geekbang.org/column/intro/140)》第 46 篇案例。** 4 | 5 | 案例场景: 6 | 7 | * Docker 运行 Tomcat 时启动异常缓慢 8 | 9 | ## 构建 Docker 镜像 10 | 11 | ```sh 12 | make build 13 | ``` 14 | 15 | ## 运行案例应用 16 | 17 | ```sh 18 | make run 19 | ``` 20 | 21 | ## 停止应用 22 | 23 | ```sh 24 | make clean 25 | ``` 26 | -------------------------------------------------------------------------------- /tomcat/index.jsp: -------------------------------------------------------------------------------- 1 | <% 2 | byte data[] = new byte[256*1024*1024]; 3 | out.println("Hello, wolrd!"); 4 | %> --------------------------------------------------------------------------------