github.com/lbryio/lbcd@v0.22.119/resourceLogging.go (about)

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"github.com/shirou/gopsutil/v3/disk"
     7  	"github.com/shirou/gopsutil/v3/mem"
     8  	"github.com/shirou/gopsutil/v3/process"
     9  
    10  	"os"
    11  	"path/filepath"
    12  	"time"
    13  )
    14  
    15  func toGB(n uint64) float64 {
    16  	return float64(n) / 1024.0 / 1024.0 / 1024.0
    17  }
    18  
    19  func dirSize(path string) (int64, error) {
    20  	var size int64
    21  	err := filepath.Walk(path, func(_ string, info os.FileInfo, err error) error {
    22  		if err != nil {
    23  			return err
    24  		}
    25  		if !info.IsDir() {
    26  			size += info.Size()
    27  		}
    28  		return err
    29  	})
    30  	return size, err
    31  }
    32  
    33  func logMemoryUsage() {
    34  	last := ""
    35  	tick := time.NewTicker(40 * time.Second)
    36  	for range tick.C {
    37  		m, err := mem.VirtualMemory()
    38  		if err != nil {
    39  			btcdLog.Warnf("When reading memory size: %s", err.Error())
    40  			continue
    41  		}
    42  
    43  		d, err := disk.Usage(cfg.DataDir)
    44  		if err != nil {
    45  			btcdLog.Warnf("When reading disk usage: %s", err.Error())
    46  			continue
    47  		}
    48  
    49  		p, err := process.NewProcess(int32(os.Getpid()))
    50  		if err != nil {
    51  			btcdLog.Warnf("When reading process: %s", err.Error())
    52  			continue
    53  		}
    54  
    55  		m2, err := p.MemoryInfo()
    56  		if err != nil {
    57  			btcdLog.Warnf("When reading memory info: %s", err.Error())
    58  			continue
    59  		}
    60  
    61  		ds, err := dirSize(cfg.DataDir)
    62  		if err != nil {
    63  			btcdLog.Debugf("When reading directory: %s", err.Error())
    64  			continue
    65  		}
    66  
    67  		cur := fmt.Sprintf("RAM: using %.1f GB with %.1f available, DISK: using %.1f GB with %.1f available",
    68  			toGB(m2.RSS), toGB(m.Available), toGB(uint64(ds)), toGB(d.Free))
    69  		if cur != last {
    70  			btcdLog.Infof(cur)
    71  			last = cur
    72  		}
    73  	}
    74  }