5 * Copyright 2018 gRPC authors.
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
21 // Package syscall provides functionalities that grpc uses to get low-level operating system
31 "golang.org/x/sys/unix"
32 "google.golang.org/grpc/grpclog"
35 // GetCPUTime returns the how much CPU time has passed since the start of this process.
36 func GetCPUTime() int64 {
38 if err := unix.ClockGettime(unix.CLOCK_PROCESS_CPUTIME_ID, &ts); err != nil {
44 // Rusage is an alias for syscall.Rusage under linux non-appengine environment.
45 type Rusage syscall.Rusage
47 // GetRusage returns the resource usage of current process.
48 func GetRusage() (rusage *Rusage) {
50 syscall.Getrusage(syscall.RUSAGE_SELF, (*syscall.Rusage)(rusage))
54 // CPUTimeDiff returns the differences of user CPU time and system CPU time used
55 // between two Rusage structs.
56 func CPUTimeDiff(first *Rusage, latest *Rusage) (float64, float64) {
57 f := (*syscall.Rusage)(first)
58 l := (*syscall.Rusage)(latest)
60 utimeDiffs = l.Utime.Sec - f.Utime.Sec
61 utimeDiffus = l.Utime.Usec - f.Utime.Usec
62 stimeDiffs = l.Stime.Sec - f.Stime.Sec
63 stimeDiffus = l.Stime.Usec - f.Stime.Usec
66 uTimeElapsed := float64(utimeDiffs) + float64(utimeDiffus)*1.0e-6
67 sTimeElapsed := float64(stimeDiffs) + float64(stimeDiffus)*1.0e-6
69 return uTimeElapsed, sTimeElapsed
72 // SetTCPUserTimeout sets the TCP user timeout on a connection's socket
73 func SetTCPUserTimeout(conn net.Conn, timeout time.Duration) error {
74 tcpconn, ok := conn.(*net.TCPConn)
76 // not a TCP connection. exit early
79 rawConn, err := tcpconn.SyscallConn()
81 return fmt.Errorf("error getting raw connection: %v", err)
83 err = rawConn.Control(func(fd uintptr) {
84 err = syscall.SetsockoptInt(int(fd), syscall.IPPROTO_TCP, unix.TCP_USER_TIMEOUT, int(timeout/time.Millisecond))
87 return fmt.Errorf("error setting option on socket: %v", err)
93 // GetTCPUserTimeout gets the TCP user timeout on a connection's socket
94 func GetTCPUserTimeout(conn net.Conn) (opt int, err error) {
95 tcpconn, ok := conn.(*net.TCPConn)
97 err = fmt.Errorf("conn is not *net.TCPConn. got %T", conn)
100 rawConn, err := tcpconn.SyscallConn()
102 err = fmt.Errorf("error getting raw connection: %v", err)
105 err = rawConn.Control(func(fd uintptr) {
106 opt, err = syscall.GetsockoptInt(int(fd), syscall.IPPROTO_TCP, unix.TCP_USER_TIMEOUT)
109 err = fmt.Errorf("error getting option on socket: %v", err)