You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

639 lines
19 KiB

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