github.com/u-root/u-root@v7.0.1-0.20200915234505-ad7babab0a8e+incompatible/cmds/core/uptime/uptime.go (about) 1 // Copyright 2013-2019 the u-root Authors. All rights reserved 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 // Get the time the machine has been up 6 // Synopsis: 7 // uptime 8 package main 9 10 import ( 11 "errors" 12 "fmt" 13 "io/ioutil" 14 "log" 15 "strings" 16 "time" 17 ) 18 19 // loadavg takes in the contents of proc/loadavg,it then extracts and returns the three load averages as a string 20 func loadavg(contents string) (loadaverage string, err error) { 21 loadavg := strings.Fields(contents) 22 if len(loadavg) < 3 { 23 return "", fmt.Errorf("error:invalid contents:the contents of proc/loadavg we are trying to process contain less than the required 3 loadavgs") 24 } 25 return loadavg[0] + "," + loadavg[1] + "," + loadavg[2], nil 26 } 27 28 // uptime takes in the contents of proc/uptime it then extracts and returns the uptime in the format Days , Hours , Minutes ,Seconds 29 func uptime(contents string) (*time.Time, error) { 30 uptimeArray := strings.Fields(contents) 31 if len(uptimeArray) == 0 { 32 return nil, errors.New("error:the contents of proc/uptime we are trying to read are empty") 33 } 34 uptimeDuration, err := time.ParseDuration(string(uptimeArray[0]) + "s") 35 if err != nil { 36 return nil, fmt.Errorf("error %v", err) 37 } 38 uptime := time.Time{}.Add(uptimeDuration) 39 40 return &uptime, nil 41 } 42 43 func main() { 44 procUptimeOutput, err := ioutil.ReadFile("/proc/uptime") 45 if err != nil { 46 log.Fatalf("error reading /proc/uptime: %v \n", err) 47 } 48 uptimeTime, err := uptime(string(procUptimeOutput)) 49 if err != nil { 50 log.Fatal(err) 51 } 52 procLoadAvgOutput, err := ioutil.ReadFile("/proc/loadavg") 53 if err != nil { 54 log.Fatalf("error reading /proc/loadavg: %v \n", err) 55 } 56 loadAverage, err := loadavg(string(procLoadAvgOutput)) 57 if err != nil { 58 log.Fatal(err) 59 } 60 //Subtracted one from time.Day() because time.Add(Duration) starts counting at 1 day instead of zero days. 61 fmt.Printf(" %s up %d days, %d hours , %d min ,loadaverage: %s \n", time.Now().Format("15:04:05"), (uptimeTime.Day() - 1), uptimeTime.Hour(), uptimeTime.Minute(), loadAverage) 62 }