node-api/glue/stats.go

115 lines
2.2 KiB
Go
Raw Normal View History

package glue
2020-07-16 17:05:38 +00:00
import (
"log"
"github.com/jinzhu/gorm"
2020-07-16 17:05:38 +00:00
"github.com/rosti-cz/node-api/apps"
docker "github.com/rosti-cz/node-api/containers"
2020-07-16 17:05:38 +00:00
)
// StatsProcessor covers all methods that are needed
// to gather information about application containers.
type StatsProcessor struct {
DB *gorm.DB
}
// returns instance of getAppProcessor
func (s *StatsProcessor) getAppProcessor() apps.AppsProcessor {
processor := apps.AppsProcessor{
DB: s.DB,
}
processor.Init()
return processor
}
// updateUsage updates various resource usage of the container/app in the database
func (s *StatsProcessor) UpdateUsage(name string) error {
processor := s.getAppProcessor()
app, err := processor.Get(name)
if err != nil {
return err
}
container := docker.Container{
App: &app,
}
state, err := container.GetState()
if err != nil {
return err
}
err = processor.UpdateResources(
name,
state.State,
state.CPUUsage,
state.MemoryUsage,
state.DiskUsageBytes,
state.DiskUsageInodes,
2022-02-03 00:31:47 +00:00
state.Flags,
)
return err
}
// Updates only container's state. Check current status of the container and saves it into the database.
func (s *StatsProcessor) UpdateState(name string) error {
processor := s.getAppProcessor()
app, err := processor.Get(name)
if err != nil {
return err
}
2020-07-23 10:09:06 +00:00
container := docker.Container{
App: &app,
2020-07-23 10:09:06 +00:00
}
state, err := container.Status()
2020-07-16 17:05:38 +00:00
if err != nil {
return err
}
err = processor.UpdateState(
2020-07-23 10:09:06 +00:00
app.Name,
state,
2020-07-23 10:09:06 +00:00
)
return err
2020-07-23 10:09:06 +00:00
}
2020-07-16 17:05:38 +00:00
// gatherStats loops over all applications and calls updateUsage to write various metric into the database.
func (s *StatsProcessor) GatherStats() error {
processor := s.getAppProcessor()
appList, err := processor.List()
2020-07-23 10:09:06 +00:00
if err != nil {
return err
}
2020-07-16 17:05:38 +00:00
for _, app := range appList {
err := s.UpdateUsage(app.Name)
2020-07-16 17:05:38 +00:00
if err != nil {
log.Println("STATS ERROR:", err.Error())
}
}
return nil
}
// gatherStates loops over all apps and updates their container state
func (s *StatsProcessor) GatherStates() error {
processor := s.getAppProcessor()
appList, err := processor.List()
if err != nil {
return err
}
for _, app := range appList {
err := s.UpdateState(app.Name)
if err != nil {
log.Println("STATE ERROR:", err.Error())
}
}
return nil
}