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
var logger = grpclog.Component("core")
37
// GetCPUTime returns the how much CPU time has passed since the start of this process.
38
func GetCPUTime() int64 {
40
if err := unix.ClockGettime(unix.CLOCK_PROCESS_CPUTIME_ID, &ts); err != nil {
46
// Rusage is an alias for syscall.Rusage under linux environment.
47
type Rusage = syscall.Rusage
49
// GetRusage returns the resource usage of current process.
50
func GetRusage() *Rusage {
52
syscall.Getrusage(syscall.RUSAGE_SELF, rusage)
56
// CPUTimeDiff returns the differences of user CPU time and system CPU time used
57
// between two Rusage structs.
58
func CPUTimeDiff(first *Rusage, latest *Rusage) (float64, float64) {
60
utimeDiffs = latest.Utime.Sec - first.Utime.Sec
61
utimeDiffus = latest.Utime.Usec - first.Utime.Usec
62
stimeDiffs = latest.Stime.Sec - first.Stime.Sec
63
stimeDiffus = latest.Stime.Usec - first.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)