84 lines
1.8 KiB
Go
84 lines
1.8 KiB
Go
package service
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"net/http"
|
|
"time"
|
|
|
|
"git.ostiwe.com/ostiwe-com/status/model"
|
|
"git.ostiwe.com/ostiwe-com/status/modules/log"
|
|
"git.ostiwe.com/ostiwe-com/status/repository"
|
|
"github.com/sirupsen/logrus"
|
|
)
|
|
|
|
var (
|
|
httpObserveFailed = errors.New("http observe fail")
|
|
httpObserveMaxTries = errors.New("http observe max tries")
|
|
)
|
|
|
|
func init() {
|
|
log.Global.Put(log.CRON, logrus.New())
|
|
}
|
|
|
|
type Check interface {
|
|
Observe(ctx context.Context, srv *model.Service) error
|
|
RegisterStatus(ctx context.Context, serviceID int, status model.StatusCode) error
|
|
}
|
|
|
|
type check struct {
|
|
serviceRepository repository.Service
|
|
statusRepository repository.Status
|
|
}
|
|
|
|
func NewCheck() Check {
|
|
return &check{
|
|
serviceRepository: repository.NewServiceRepository(),
|
|
statusRepository: repository.NewStatusRepository(),
|
|
}
|
|
}
|
|
|
|
func (c check) Observe(ctx context.Context, srv *model.Service) error {
|
|
return c.observeHttp(srv)
|
|
}
|
|
|
|
func (c check) RegisterStatus(ctx context.Context, serviceID int, status model.StatusCode) error {
|
|
return c.statusRepository.Add(ctx, model.Status{
|
|
ServiceID: serviceID,
|
|
Status: status,
|
|
CreatedAt: time.Now(),
|
|
})
|
|
}
|
|
|
|
func (c check) observeHttp(service *model.Service) error {
|
|
if service.TypeConfig == nil || service.TypeConfig.HTTPConfig == nil {
|
|
return errors.New("service has no config for http")
|
|
}
|
|
|
|
conf := service.TypeConfig.HTTPConfig
|
|
|
|
client := &http.Client{
|
|
Timeout: time.Second * 5,
|
|
}
|
|
|
|
request, err := http.NewRequest(conf.Method, service.Host, nil)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
for s := range conf.Headers {
|
|
request.Header.Set(s, conf.Headers[s])
|
|
}
|
|
|
|
response, err := client.Do(request)
|
|
if err != nil && !errors.Is(err, context.DeadlineExceeded) {
|
|
return err
|
|
}
|
|
|
|
if response.StatusCode != http.StatusOK {
|
|
return httpObserveFailed
|
|
}
|
|
|
|
return nil
|
|
}
|