summaryrefslogtreecommitdiff
path: root/internal/server/scheduler.go
blob: 3cf55ce60d9a1080b8d9ff62eb75ed28bee9dc76 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package server

import (
	"context"
	"fmt"
	"math/rand"
	"time"

	"github.com/mimecast/dtail/internal/clients"
	"github.com/mimecast/dtail/internal/config"
	"github.com/mimecast/dtail/internal/io/logger"
	"github.com/mimecast/dtail/internal/omode"

	gossh "golang.org/x/crypto/ssh"
)

const authLength = 64
const authCharset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@£$%^&*()_+[]"

type scheduler struct {
	authPayload string
}

func newScheduler() *scheduler {
	seededRand := rand.New(rand.NewSource(time.Now().UnixNano()))

	b := make([]byte, authLength)
	for i := range b {
		b[i] = authCharset[seededRand.Intn(len(authCharset))]
	}

	return &scheduler{
		authPayload: string(b),
	}
}

func (s *scheduler) start(ctx context.Context) {
	for {
		select {
		case <-time.After(time.Second * 10):
			s.runJobs(ctx)
			return
		case <-time.After(time.Minute):
			s.runJobs(ctx)
		case <-ctx.Done():
			return
		}
	}
}

func (s *scheduler) runJobs(ctx context.Context) {
	for _, scheduled := range config.Server.Schedule {
		args := clients.Args{
			ConnectionsPerCPU: scheduled.ConnectionsPerCPU,
			Discovery:         scheduled.Discovery,
			ServersStr:        scheduled.Servers,
			What:              scheduled.Files,
			Mode:              omode.MapClient,
			UserName:          config.ScheduledUser,
		}
		args.SSHAuthMethods = append(args.SSHAuthMethods, gossh.Password(s.authPayload))

		client, err := clients.NewMaprClient(args, scheduled.Query)
		if err != nil {
			logger.Error(fmt.Sprintf("Unable to create scheduled job %s", scheduled.Name), err)
			continue
		}

		logger.Info(fmt.Sprintf("Starting scheduled job %s", scheduled.Name))
		status := client.Start(ctx)
		logMessage := fmt.Sprintf("Scheduled job %s exited with status %d", scheduled.Name, status)
		if status != 0 {
			logger.Warn(logMessage)
			continue
		}
		logger.Info(logMessage)
	}
}