package glue import ( "log" "github.com/jinzhu/gorm" "github.com/rosti-cz/node-api/apps" docker "github.com/rosti-cz/node-api/containers" ) // StatsProcessor covers all methods that are needed // to gather information about application containers. type StatsProcessor struct { DB *gorm.DB DockerSock string } // 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, DockerSock: s.DockerSock, } state, err := container.GetState() if err != nil { return err } err = processor.UpdateResources( name, state.State, state.CPUUsage, state.MemoryUsage, state.DiskUsageBytes, state.DiskUsageInodes, 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 } container := docker.Container{ App: &app, DockerSock: s.DockerSock, } state, err := container.Status() if err != nil { return err } err = processor.UpdateState( app.Name, state, ) return err } // 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() if err != nil { return err } for _, app := range appList { err := s.UpdateUsage(app.Name) 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 }