github.com/e154/smart-home@v0.17.2-0.20240311175135-e530a6e5cd45/plugins/memory/actor.go (about) 1 // This file is part of the Smart Home 2 // Program complex distribution https://github.com/e154/smart-home 3 // Copyright (C) 2016-2023, Filippov Alex 4 // 5 // This library is free software: you can redistribute it and/or 6 // modify it under the terms of the GNU Lesser General Public 7 // License as published by the Free Software Foundation; either 8 // version 3 of the License, or (at your option) any later version. 9 // 10 // This library is distributed in the hope that it will be useful, 11 // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 13 // Library General Public License for more details. 14 // 15 // You should have received a copy of the GNU Lesser General Public 16 // License along with this library. If not, see 17 // <https://www.gnu.org/licenses/>. 18 19 package memory 20 21 import ( 22 "sync" 23 24 "github.com/rcrowley/go-metrics" 25 "github.com/shirou/gopsutil/v3/mem" 26 27 "github.com/e154/smart-home/common" 28 m "github.com/e154/smart-home/models" 29 "github.com/e154/smart-home/system/supervisor" 30 ) 31 32 // Actor ... 33 type Actor struct { 34 *supervisor.BaseActor 35 total metrics.Gauge 36 free metrics.Gauge 37 usedPercent metrics.GaugeFloat64 38 updateLock *sync.Mutex 39 } 40 41 // NewActor ... 42 func NewActor(entity *m.Entity, 43 service supervisor.Service) *Actor { 44 45 actor := &Actor{ 46 BaseActor: supervisor.NewBaseActor(entity, service), 47 total: metrics.NewGauge(), 48 free: metrics.NewGauge(), 49 usedPercent: metrics.NewGaugeFloat64(), 50 updateLock: &sync.Mutex{}, 51 } 52 53 if entity != nil { 54 actor.Metric = entity.Metrics 55 } 56 57 return actor 58 } 59 60 func (e *Actor) Destroy() { 61 62 } 63 64 func (e *Actor) selfUpdate() { 65 66 e.updateLock.Lock() 67 defer e.updateLock.Unlock() 68 69 v, _ := mem.VirtualMemory() 70 e.total.Update(int64(v.Total)) 71 e.free.Update(int64(v.Free)) 72 73 usedPercent := common.Rounding32(v.UsedPercent, 2) 74 e.usedPercent.Update(float64(usedPercent)) 75 76 e.AttrMu.Lock() 77 e.Attrs[AttrTotal].Value = v.Total 78 e.Attrs[AttrFree].Value = v.Free 79 e.Attrs[AttrUsedPercent].Value = usedPercent 80 e.AttrMu.Unlock() 81 82 //e.SetMetric(e.Id, "memory", map[string]float32{ 83 // "used_percent": usedPercent, 84 //}) 85 86 e.SaveState(false, false) 87 }