mountstats.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606
  1. // Copyright 2018 The Prometheus Authors
  2. // Licensed under the Apache License, Version 2.0 (the "License");
  3. // you may not use this file except in compliance with the License.
  4. // You may obtain a copy of the License at
  5. //
  6. // http://www.apache.org/licenses/LICENSE-2.0
  7. //
  8. // Unless required by applicable law or agreed to in writing, software
  9. // distributed under the License is distributed on an "AS IS" BASIS,
  10. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. // See the License for the specific language governing permissions and
  12. // limitations under the License.
  13. package procfs
  14. // While implementing parsing of /proc/[pid]/mountstats, this blog was used
  15. // heavily as a reference:
  16. // https://utcc.utoronto.ca/~cks/space/blog/linux/NFSMountstatsIndex
  17. //
  18. // Special thanks to Chris Siebenmann for all of his posts explaining the
  19. // various statistics available for NFS.
  20. import (
  21. "bufio"
  22. "fmt"
  23. "io"
  24. "strconv"
  25. "strings"
  26. "time"
  27. )
  28. // Constants shared between multiple functions.
  29. const (
  30. deviceEntryLen = 8
  31. fieldBytesLen = 8
  32. fieldEventsLen = 27
  33. statVersion10 = "1.0"
  34. statVersion11 = "1.1"
  35. fieldTransport10TCPLen = 10
  36. fieldTransport10UDPLen = 7
  37. fieldTransport11TCPLen = 13
  38. fieldTransport11UDPLen = 10
  39. )
  40. // A Mount is a device mount parsed from /proc/[pid]/mountstats.
  41. type Mount struct {
  42. // Name of the device.
  43. Device string
  44. // The mount point of the device.
  45. Mount string
  46. // The filesystem type used by the device.
  47. Type string
  48. // If available additional statistics related to this Mount.
  49. // Use a type assertion to determine if additional statistics are available.
  50. Stats MountStats
  51. }
  52. // A MountStats is a type which contains detailed statistics for a specific
  53. // type of Mount.
  54. type MountStats interface {
  55. mountStats()
  56. }
  57. // A MountStatsNFS is a MountStats implementation for NFSv3 and v4 mounts.
  58. type MountStatsNFS struct {
  59. // The version of statistics provided.
  60. StatVersion string
  61. // The age of the NFS mount.
  62. Age time.Duration
  63. // Statistics related to byte counters for various operations.
  64. Bytes NFSBytesStats
  65. // Statistics related to various NFS event occurrences.
  66. Events NFSEventsStats
  67. // Statistics broken down by filesystem operation.
  68. Operations []NFSOperationStats
  69. // Statistics about the NFS RPC transport.
  70. Transport NFSTransportStats
  71. }
  72. // mountStats implements MountStats.
  73. func (m MountStatsNFS) mountStats() {}
  74. // A NFSBytesStats contains statistics about the number of bytes read and written
  75. // by an NFS client to and from an NFS server.
  76. type NFSBytesStats struct {
  77. // Number of bytes read using the read() syscall.
  78. Read uint64
  79. // Number of bytes written using the write() syscall.
  80. Write uint64
  81. // Number of bytes read using the read() syscall in O_DIRECT mode.
  82. DirectRead uint64
  83. // Number of bytes written using the write() syscall in O_DIRECT mode.
  84. DirectWrite uint64
  85. // Number of bytes read from the NFS server, in total.
  86. ReadTotal uint64
  87. // Number of bytes written to the NFS server, in total.
  88. WriteTotal uint64
  89. // Number of pages read directly via mmap()'d files.
  90. ReadPages uint64
  91. // Number of pages written directly via mmap()'d files.
  92. WritePages uint64
  93. }
  94. // A NFSEventsStats contains statistics about NFS event occurrences.
  95. type NFSEventsStats struct {
  96. // Number of times cached inode attributes are re-validated from the server.
  97. InodeRevalidate uint64
  98. // Number of times cached dentry nodes are re-validated from the server.
  99. DnodeRevalidate uint64
  100. // Number of times an inode cache is cleared.
  101. DataInvalidate uint64
  102. // Number of times cached inode attributes are invalidated.
  103. AttributeInvalidate uint64
  104. // Number of times files or directories have been open()'d.
  105. VFSOpen uint64
  106. // Number of times a directory lookup has occurred.
  107. VFSLookup uint64
  108. // Number of times permissions have been checked.
  109. VFSAccess uint64
  110. // Number of updates (and potential writes) to pages.
  111. VFSUpdatePage uint64
  112. // Number of pages read directly via mmap()'d files.
  113. VFSReadPage uint64
  114. // Number of times a group of pages have been read.
  115. VFSReadPages uint64
  116. // Number of pages written directly via mmap()'d files.
  117. VFSWritePage uint64
  118. // Number of times a group of pages have been written.
  119. VFSWritePages uint64
  120. // Number of times directory entries have been read with getdents().
  121. VFSGetdents uint64
  122. // Number of times attributes have been set on inodes.
  123. VFSSetattr uint64
  124. // Number of pending writes that have been forcefully flushed to the server.
  125. VFSFlush uint64
  126. // Number of times fsync() has been called on directories and files.
  127. VFSFsync uint64
  128. // Number of times locking has been attempted on a file.
  129. VFSLock uint64
  130. // Number of times files have been closed and released.
  131. VFSFileRelease uint64
  132. // Unknown. Possibly unused.
  133. CongestionWait uint64
  134. // Number of times files have been truncated.
  135. Truncation uint64
  136. // Number of times a file has been grown due to writes beyond its existing end.
  137. WriteExtension uint64
  138. // Number of times a file was removed while still open by another process.
  139. SillyRename uint64
  140. // Number of times the NFS server gave less data than expected while reading.
  141. ShortRead uint64
  142. // Number of times the NFS server wrote less data than expected while writing.
  143. ShortWrite uint64
  144. // Number of times the NFS server indicated EJUKEBOX; retrieving data from
  145. // offline storage.
  146. JukeboxDelay uint64
  147. // Number of NFS v4.1+ pNFS reads.
  148. PNFSRead uint64
  149. // Number of NFS v4.1+ pNFS writes.
  150. PNFSWrite uint64
  151. }
  152. // A NFSOperationStats contains statistics for a single operation.
  153. type NFSOperationStats struct {
  154. // The name of the operation.
  155. Operation string
  156. // Number of requests performed for this operation.
  157. Requests uint64
  158. // Number of times an actual RPC request has been transmitted for this operation.
  159. Transmissions uint64
  160. // Number of times a request has had a major timeout.
  161. MajorTimeouts uint64
  162. // Number of bytes sent for this operation, including RPC headers and payload.
  163. BytesSent uint64
  164. // Number of bytes received for this operation, including RPC headers and payload.
  165. BytesReceived uint64
  166. // Duration all requests spent queued for transmission before they were sent.
  167. CumulativeQueueTime time.Duration
  168. // Duration it took to get a reply back after the request was transmitted.
  169. CumulativeTotalResponseTime time.Duration
  170. // Duration from when a request was enqueued to when it was completely handled.
  171. CumulativeTotalRequestTime time.Duration
  172. }
  173. // A NFSTransportStats contains statistics for the NFS mount RPC requests and
  174. // responses.
  175. type NFSTransportStats struct {
  176. // The transport protocol used for the NFS mount.
  177. Protocol string
  178. // The local port used for the NFS mount.
  179. Port uint64
  180. // Number of times the client has had to establish a connection from scratch
  181. // to the NFS server.
  182. Bind uint64
  183. // Number of times the client has made a TCP connection to the NFS server.
  184. Connect uint64
  185. // Duration (in jiffies, a kernel internal unit of time) the NFS mount has
  186. // spent waiting for connections to the server to be established.
  187. ConnectIdleTime uint64
  188. // Duration since the NFS mount last saw any RPC traffic.
  189. IdleTime time.Duration
  190. // Number of RPC requests for this mount sent to the NFS server.
  191. Sends uint64
  192. // Number of RPC responses for this mount received from the NFS server.
  193. Receives uint64
  194. // Number of times the NFS server sent a response with a transaction ID
  195. // unknown to this client.
  196. BadTransactionIDs uint64
  197. // A running counter, incremented on each request as the current difference
  198. // ebetween sends and receives.
  199. CumulativeActiveRequests uint64
  200. // A running counter, incremented on each request by the current backlog
  201. // queue size.
  202. CumulativeBacklog uint64
  203. // Stats below only available with stat version 1.1.
  204. // Maximum number of simultaneously active RPC requests ever used.
  205. MaximumRPCSlotsUsed uint64
  206. // A running counter, incremented on each request as the current size of the
  207. // sending queue.
  208. CumulativeSendingQueue uint64
  209. // A running counter, incremented on each request as the current size of the
  210. // pending queue.
  211. CumulativePendingQueue uint64
  212. }
  213. // parseMountStats parses a /proc/[pid]/mountstats file and returns a slice
  214. // of Mount structures containing detailed information about each mount.
  215. // If available, statistics for each mount are parsed as well.
  216. func parseMountStats(r io.Reader) ([]*Mount, error) {
  217. const (
  218. device = "device"
  219. statVersionPrefix = "statvers="
  220. nfs3Type = "nfs"
  221. nfs4Type = "nfs4"
  222. )
  223. var mounts []*Mount
  224. s := bufio.NewScanner(r)
  225. for s.Scan() {
  226. // Only look for device entries in this function
  227. ss := strings.Fields(string(s.Bytes()))
  228. if len(ss) == 0 || ss[0] != device {
  229. continue
  230. }
  231. m, err := parseMount(ss)
  232. if err != nil {
  233. return nil, err
  234. }
  235. // Does this mount also possess statistics information?
  236. if len(ss) > deviceEntryLen {
  237. // Only NFSv3 and v4 are supported for parsing statistics
  238. if m.Type != nfs3Type && m.Type != nfs4Type {
  239. return nil, fmt.Errorf("cannot parse MountStats for fstype %q", m.Type)
  240. }
  241. statVersion := strings.TrimPrefix(ss[8], statVersionPrefix)
  242. stats, err := parseMountStatsNFS(s, statVersion)
  243. if err != nil {
  244. return nil, err
  245. }
  246. m.Stats = stats
  247. }
  248. mounts = append(mounts, m)
  249. }
  250. return mounts, s.Err()
  251. }
  252. // parseMount parses an entry in /proc/[pid]/mountstats in the format:
  253. // device [device] mounted on [mount] with fstype [type]
  254. func parseMount(ss []string) (*Mount, error) {
  255. if len(ss) < deviceEntryLen {
  256. return nil, fmt.Errorf("invalid device entry: %v", ss)
  257. }
  258. // Check for specific words appearing at specific indices to ensure
  259. // the format is consistent with what we expect
  260. format := []struct {
  261. i int
  262. s string
  263. }{
  264. {i: 0, s: "device"},
  265. {i: 2, s: "mounted"},
  266. {i: 3, s: "on"},
  267. {i: 5, s: "with"},
  268. {i: 6, s: "fstype"},
  269. }
  270. for _, f := range format {
  271. if ss[f.i] != f.s {
  272. return nil, fmt.Errorf("invalid device entry: %v", ss)
  273. }
  274. }
  275. return &Mount{
  276. Device: ss[1],
  277. Mount: ss[4],
  278. Type: ss[7],
  279. }, nil
  280. }
  281. // parseMountStatsNFS parses a MountStatsNFS by scanning additional information
  282. // related to NFS statistics.
  283. func parseMountStatsNFS(s *bufio.Scanner, statVersion string) (*MountStatsNFS, error) {
  284. // Field indicators for parsing specific types of data
  285. const (
  286. fieldAge = "age:"
  287. fieldBytes = "bytes:"
  288. fieldEvents = "events:"
  289. fieldPerOpStats = "per-op"
  290. fieldTransport = "xprt:"
  291. )
  292. stats := &MountStatsNFS{
  293. StatVersion: statVersion,
  294. }
  295. for s.Scan() {
  296. ss := strings.Fields(string(s.Bytes()))
  297. if len(ss) == 0 {
  298. break
  299. }
  300. if len(ss) < 2 {
  301. return nil, fmt.Errorf("not enough information for NFS stats: %v", ss)
  302. }
  303. switch ss[0] {
  304. case fieldAge:
  305. // Age integer is in seconds
  306. d, err := time.ParseDuration(ss[1] + "s")
  307. if err != nil {
  308. return nil, err
  309. }
  310. stats.Age = d
  311. case fieldBytes:
  312. bstats, err := parseNFSBytesStats(ss[1:])
  313. if err != nil {
  314. return nil, err
  315. }
  316. stats.Bytes = *bstats
  317. case fieldEvents:
  318. estats, err := parseNFSEventsStats(ss[1:])
  319. if err != nil {
  320. return nil, err
  321. }
  322. stats.Events = *estats
  323. case fieldTransport:
  324. if len(ss) < 3 {
  325. return nil, fmt.Errorf("not enough information for NFS transport stats: %v", ss)
  326. }
  327. tstats, err := parseNFSTransportStats(ss[1:], statVersion)
  328. if err != nil {
  329. return nil, err
  330. }
  331. stats.Transport = *tstats
  332. }
  333. // When encountering "per-operation statistics", we must break this
  334. // loop and parse them separately to ensure we can terminate parsing
  335. // before reaching another device entry; hence why this 'if' statement
  336. // is not just another switch case
  337. if ss[0] == fieldPerOpStats {
  338. break
  339. }
  340. }
  341. if err := s.Err(); err != nil {
  342. return nil, err
  343. }
  344. // NFS per-operation stats appear last before the next device entry
  345. perOpStats, err := parseNFSOperationStats(s)
  346. if err != nil {
  347. return nil, err
  348. }
  349. stats.Operations = perOpStats
  350. return stats, nil
  351. }
  352. // parseNFSBytesStats parses a NFSBytesStats line using an input set of
  353. // integer fields.
  354. func parseNFSBytesStats(ss []string) (*NFSBytesStats, error) {
  355. if len(ss) != fieldBytesLen {
  356. return nil, fmt.Errorf("invalid NFS bytes stats: %v", ss)
  357. }
  358. ns := make([]uint64, 0, fieldBytesLen)
  359. for _, s := range ss {
  360. n, err := strconv.ParseUint(s, 10, 64)
  361. if err != nil {
  362. return nil, err
  363. }
  364. ns = append(ns, n)
  365. }
  366. return &NFSBytesStats{
  367. Read: ns[0],
  368. Write: ns[1],
  369. DirectRead: ns[2],
  370. DirectWrite: ns[3],
  371. ReadTotal: ns[4],
  372. WriteTotal: ns[5],
  373. ReadPages: ns[6],
  374. WritePages: ns[7],
  375. }, nil
  376. }
  377. // parseNFSEventsStats parses a NFSEventsStats line using an input set of
  378. // integer fields.
  379. func parseNFSEventsStats(ss []string) (*NFSEventsStats, error) {
  380. if len(ss) != fieldEventsLen {
  381. return nil, fmt.Errorf("invalid NFS events stats: %v", ss)
  382. }
  383. ns := make([]uint64, 0, fieldEventsLen)
  384. for _, s := range ss {
  385. n, err := strconv.ParseUint(s, 10, 64)
  386. if err != nil {
  387. return nil, err
  388. }
  389. ns = append(ns, n)
  390. }
  391. return &NFSEventsStats{
  392. InodeRevalidate: ns[0],
  393. DnodeRevalidate: ns[1],
  394. DataInvalidate: ns[2],
  395. AttributeInvalidate: ns[3],
  396. VFSOpen: ns[4],
  397. VFSLookup: ns[5],
  398. VFSAccess: ns[6],
  399. VFSUpdatePage: ns[7],
  400. VFSReadPage: ns[8],
  401. VFSReadPages: ns[9],
  402. VFSWritePage: ns[10],
  403. VFSWritePages: ns[11],
  404. VFSGetdents: ns[12],
  405. VFSSetattr: ns[13],
  406. VFSFlush: ns[14],
  407. VFSFsync: ns[15],
  408. VFSLock: ns[16],
  409. VFSFileRelease: ns[17],
  410. CongestionWait: ns[18],
  411. Truncation: ns[19],
  412. WriteExtension: ns[20],
  413. SillyRename: ns[21],
  414. ShortRead: ns[22],
  415. ShortWrite: ns[23],
  416. JukeboxDelay: ns[24],
  417. PNFSRead: ns[25],
  418. PNFSWrite: ns[26],
  419. }, nil
  420. }
  421. // parseNFSOperationStats parses a slice of NFSOperationStats by scanning
  422. // additional information about per-operation statistics until an empty
  423. // line is reached.
  424. func parseNFSOperationStats(s *bufio.Scanner) ([]NFSOperationStats, error) {
  425. const (
  426. // Number of expected fields in each per-operation statistics set
  427. numFields = 9
  428. )
  429. var ops []NFSOperationStats
  430. for s.Scan() {
  431. ss := strings.Fields(string(s.Bytes()))
  432. if len(ss) == 0 {
  433. // Must break when reading a blank line after per-operation stats to
  434. // enable top-level function to parse the next device entry
  435. break
  436. }
  437. if len(ss) != numFields {
  438. return nil, fmt.Errorf("invalid NFS per-operations stats: %v", ss)
  439. }
  440. // Skip string operation name for integers
  441. ns := make([]uint64, 0, numFields-1)
  442. for _, st := range ss[1:] {
  443. n, err := strconv.ParseUint(st, 10, 64)
  444. if err != nil {
  445. return nil, err
  446. }
  447. ns = append(ns, n)
  448. }
  449. ops = append(ops, NFSOperationStats{
  450. Operation: strings.TrimSuffix(ss[0], ":"),
  451. Requests: ns[0],
  452. Transmissions: ns[1],
  453. MajorTimeouts: ns[2],
  454. BytesSent: ns[3],
  455. BytesReceived: ns[4],
  456. CumulativeQueueTime: time.Duration(ns[5]) * time.Millisecond,
  457. CumulativeTotalResponseTime: time.Duration(ns[6]) * time.Millisecond,
  458. CumulativeTotalRequestTime: time.Duration(ns[7]) * time.Millisecond,
  459. })
  460. }
  461. return ops, s.Err()
  462. }
  463. // parseNFSTransportStats parses a NFSTransportStats line using an input set of
  464. // integer fields matched to a specific stats version.
  465. func parseNFSTransportStats(ss []string, statVersion string) (*NFSTransportStats, error) {
  466. // Extract the protocol field. It is the only string value in the line
  467. protocol := ss[0]
  468. ss = ss[1:]
  469. switch statVersion {
  470. case statVersion10:
  471. var expectedLength int
  472. if protocol == "tcp" {
  473. expectedLength = fieldTransport10TCPLen
  474. } else if protocol == "udp" {
  475. expectedLength = fieldTransport10UDPLen
  476. } else {
  477. return nil, fmt.Errorf("invalid NFS protocol \"%s\" in stats 1.0 statement: %v", protocol, ss)
  478. }
  479. if len(ss) != expectedLength {
  480. return nil, fmt.Errorf("invalid NFS transport stats 1.0 statement: %v", ss)
  481. }
  482. case statVersion11:
  483. var expectedLength int
  484. if protocol == "tcp" {
  485. expectedLength = fieldTransport11TCPLen
  486. } else if protocol == "udp" {
  487. expectedLength = fieldTransport11UDPLen
  488. } else {
  489. return nil, fmt.Errorf("invalid NFS protocol \"%s\" in stats 1.1 statement: %v", protocol, ss)
  490. }
  491. if len(ss) != expectedLength {
  492. return nil, fmt.Errorf("invalid NFS transport stats 1.1 statement: %v", ss)
  493. }
  494. default:
  495. return nil, fmt.Errorf("unrecognized NFS transport stats version: %q", statVersion)
  496. }
  497. // Allocate enough for v1.1 stats since zero value for v1.1 stats will be okay
  498. // in a v1.0 response. Since the stat length is bigger for TCP stats, we use
  499. // the TCP length here.
  500. //
  501. // Note: slice length must be set to length of v1.1 stats to avoid a panic when
  502. // only v1.0 stats are present.
  503. // See: https://github.com/prometheus/node_exporter/issues/571.
  504. ns := make([]uint64, fieldTransport11TCPLen)
  505. for i, s := range ss {
  506. n, err := strconv.ParseUint(s, 10, 64)
  507. if err != nil {
  508. return nil, err
  509. }
  510. ns[i] = n
  511. }
  512. // The fields differ depending on the transport protocol (TCP or UDP)
  513. // From https://utcc.utoronto.ca/%7Ecks/space/blog/linux/NFSMountstatsXprt
  514. //
  515. // For the udp RPC transport there is no connection count, connect idle time,
  516. // or idle time (fields #3, #4, and #5); all other fields are the same. So
  517. // we set them to 0 here.
  518. if protocol == "udp" {
  519. ns = append(ns[:2], append(make([]uint64, 3), ns[2:]...)...)
  520. }
  521. return &NFSTransportStats{
  522. Protocol: protocol,
  523. Port: ns[0],
  524. Bind: ns[1],
  525. Connect: ns[2],
  526. ConnectIdleTime: ns[3],
  527. IdleTime: time.Duration(ns[4]) * time.Second,
  528. Sends: ns[5],
  529. Receives: ns[6],
  530. BadTransactionIDs: ns[7],
  531. CumulativeActiveRequests: ns[8],
  532. CumulativeBacklog: ns[9],
  533. MaximumRPCSlotsUsed: ns[10],
  534. CumulativeSendingQueue: ns[11],
  535. CumulativePendingQueue: ns[12],
  536. }, nil
  537. }