-
Notifications
You must be signed in to change notification settings - Fork 129
/
schedulerapp.go
242 lines (225 loc) · 9.02 KB
/
schedulerapp.go
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
package scheduler
import (
"fmt"
"net"
"strings"
"time"
"github.com/apache/pulsar-client-go/pulsar"
"github.com/go-redis/redis"
"github.com/google/uuid"
"github.com/grpc-ecosystem/go-grpc-middleware/logging/logrus/ctxlogrus"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus"
log "github.com/sirupsen/logrus"
"golang.org/x/sync/errgroup"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
"github.com/armadaproject/armada/internal/common"
"github.com/armadaproject/armada/internal/common/app"
"github.com/armadaproject/armada/internal/common/auth"
dbcommon "github.com/armadaproject/armada/internal/common/database"
grpcCommon "github.com/armadaproject/armada/internal/common/grpc"
"github.com/armadaproject/armada/internal/common/pulsarutils"
"github.com/armadaproject/armada/internal/common/stringinterner"
schedulerconfig "github.com/armadaproject/armada/internal/scheduler/configuration"
"github.com/armadaproject/armada/internal/scheduler/database"
"github.com/armadaproject/armada/pkg/executorapi"
)
// Run sets up a Scheduler application and runs it until a SIGTERM is received
func Run(config schedulerconfig.Configuration) error {
g, ctx := errgroup.WithContext(app.CreateContextWithShutdown())
logrusLogger := log.NewEntry(log.StandardLogger())
ctx = ctxlogrus.ToContext(ctx, logrusLogger)
// List of services to run concurrently.
// Because we want to start services only once all input validation has been completed,
// we add all services to a slice and start them together at the end of this function.
var services []func() error
//////////////////////////////////////////////////////////////////////////
// Database setup (postgres and redis)
//////////////////////////////////////////////////////////////////////////
log.Infof("Setting up database connections")
db, err := dbcommon.OpenPgxPool(config.Postgres)
if err != nil {
return errors.WithMessage(err, "Error opening connection to postgres")
}
defer db.Close()
jobRepository := database.NewPostgresJobRepository(db, int32(config.DatabaseFetchSize))
executorRepository := database.NewPostgresExecutorRepository(db)
redisClient := redis.NewUniversalClient(config.Redis.AsUniversalOptions())
defer func() {
err := redisClient.Close()
if err != nil {
log.WithError(errors.WithStack(err)).Warnf("Redis client didn't close down cleanly")
}
}()
queueRepository := database.NewLegacyQueueRepository(redisClient)
legacyExecutorRepository := database.NewRedisExecutorRepository(redisClient, "pulsar")
//////////////////////////////////////////////////////////////////////////
// Pulsar
//////////////////////////////////////////////////////////////////////////
log.Infof("Setting up Pulsar connectivity")
pulsarClient, err := pulsarutils.NewPulsarClient(&config.Pulsar)
if err != nil {
return errors.WithMessage(err, "Error creating pulsar client")
}
defer pulsarClient.Close()
pulsarPublisher, err := NewPulsarPublisher(pulsarClient, pulsar.ProducerOptions{
Name: fmt.Sprintf("armada-scheduler-%s", uuid.NewString()),
CompressionType: config.Pulsar.CompressionType,
CompressionLevel: config.Pulsar.CompressionLevel,
BatchingMaxSize: config.Pulsar.MaxAllowedMessageSize,
Topic: config.Pulsar.JobsetEventsTopic,
}, config.PulsarSendTimeout)
if err != nil {
return errors.WithMessage(err, "error creating pulsar publisher")
}
//////////////////////////////////////////////////////////////////////////
// Leader Election
//////////////////////////////////////////////////////////////////////////
leaderController, err := createLeaderController(config.Leader)
if err != nil {
return errors.WithMessage(err, "error creating leader controller")
}
services = append(services, func() error { return leaderController.Run(ctx) })
//////////////////////////////////////////////////////////////////////////
// Executor Api
//////////////////////////////////////////////////////////////////////////
log.Infof("Setting up executor api")
apiProducer, err := pulsarClient.CreateProducer(pulsar.ProducerOptions{
Name: fmt.Sprintf("armada-executor-api-%s", uuid.NewString()),
CompressionType: config.Pulsar.CompressionType,
CompressionLevel: config.Pulsar.CompressionLevel,
BatchingMaxSize: config.Pulsar.MaxAllowedMessageSize,
Topic: config.Pulsar.JobsetEventsTopic,
})
if err != nil {
return errors.Wrapf(err, "error creating pulsar producer for executor api")
}
defer apiProducer.Close()
authServices, err := auth.ConfigureAuth(config.Auth)
if err != nil {
return errors.WithMessage(err, "error creating auth services")
}
grpcServer := grpcCommon.CreateGrpcServer(config.Grpc.KeepaliveParams, config.Grpc.KeepaliveEnforcementPolicy, authServices)
defer grpcServer.GracefulStop()
lis, err := net.Listen("tcp", fmt.Sprintf(":%d", config.Grpc.Port))
if err != nil {
return errors.WithMessage(err, "error setting up grpc server")
}
allowedPcs := config.Scheduling.Preemption.AllowedPriorities()
executorServer, err := NewExecutorApi(
apiProducer,
jobRepository,
executorRepository,
legacyExecutorRepository,
allowedPcs,
config.Scheduling.MaximumJobsToSchedule,
config.Scheduling.Preemption.NodeIdLabel,
config.Scheduling.Preemption.PriorityClassNameOverride,
)
if err != nil {
return errors.WithMessage(err, "error creating executorApi")
}
executorapi.RegisterExecutorApiServer(grpcServer, executorServer)
services = append(services, func() error {
log.Infof("Executor api listening on %s", lis.Addr())
return grpcServer.Serve(lis)
})
services = append(services, grpcCommon.CreateShutdownHandler(ctx, 5*time.Second, grpcServer))
//////////////////////////////////////////////////////////////////////////
// Scheduling
//////////////////////////////////////////////////////////////////////////
log.Infof("setting up scheduling loop")
stringInterner, err := stringinterner.New(config.InternedStringsCacheSize)
if err != nil {
return errors.WithMessage(err, "error creating string interner")
}
submitChecker := NewSubmitChecker(
30*time.Minute,
config.Scheduling,
executorRepository,
)
services = append(services, func() error {
return submitChecker.Run(ctx)
})
if err != nil {
return errors.WithMessage(err, "error creating submit checker")
}
// TODO(reports): Pass in a non-nil SchedulingContextRepository.
schedulingAlgo, err := NewFairSchedulingAlgo(config.Scheduling, config.MaxSchedulingDuration, executorRepository, queueRepository, nil)
if err != nil {
return errors.WithMessage(err, "error creating scheduling algo")
}
scheduler, err := NewScheduler(
jobRepository,
executorRepository,
schedulingAlgo,
leaderController,
pulsarPublisher,
stringInterner,
submitChecker,
config.CyclePeriod,
config.SchedulePeriod,
config.ExecutorTimeout,
config.Scheduling.MaxRetries+1,
config.Scheduling.Preemption.NodeIdLabel,
)
if err != nil {
return errors.WithMessage(err, "error creating scheduler")
}
services = append(services, func() error { return scheduler.Run(ctx) })
//////////////////////////////////////////////////////////////////////////
// Metrics
//////////////////////////////////////////////////////////////////////////
poolAssigner, err := NewPoolAssigner(config.Scheduling.ExecutorTimeout, config.Scheduling, executorRepository)
if err != nil {
return errors.WithMessage(err, "error creating pool assigner")
}
metricsCollector := NewMetricsCollector(
scheduler.jobDb,
queueRepository,
executorRepository,
poolAssigner,
config.Metrics.RefreshInterval)
prometheus.MustRegister(metricsCollector)
services = append(services, func() error { return metricsCollector.Run(ctx) })
shutdownMetricServer := common.ServeMetrics(config.Metrics.Port)
defer shutdownMetricServer()
// start all services
for _, service := range services {
g.Go(service)
}
return g.Wait()
}
func createLeaderController(config schedulerconfig.LeaderConfig) (LeaderController, error) {
switch mode := strings.ToLower(config.Mode); mode {
case "standalone":
log.Infof("Scheduler will run in standalone mode")
return NewStandaloneLeaderController(), nil
case "kubernetes":
log.Infof("Scheduler will run kubernetes mode")
clusterConfig, err := loadClusterConfig()
if err != nil {
return nil, errors.Wrapf(err, "Error creating kubernetes client")
}
clientSet, err := kubernetes.NewForConfig(clusterConfig)
if err != nil {
return nil, errors.Wrapf(err, "Error creating kubernetes client")
}
return NewKubernetesLeaderController(config, clientSet.CoordinationV1()), nil
default:
return nil, errors.Errorf("%s is not a value leader mode", config.Mode)
}
}
func loadClusterConfig() (*rest.Config, error) {
config, err := rest.InClusterConfig()
if err == rest.ErrNotInCluster {
log.Info("Running with default client configuration")
rules := clientcmd.NewDefaultClientConfigLoadingRules()
overrides := &clientcmd.ConfigOverrides{}
return clientcmd.NewNonInteractiveDeferredLoadingClientConfig(rules, overrides).ClientConfig()
}
log.Info("Running with in cluster client configuration")
return config, err
}