1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
17 "git.arvados.org/arvados.git/lib/cloud"
18 "git.arvados.org/arvados.git/lib/config"
19 "git.arvados.org/arvados.git/lib/controller/dblock"
20 "git.arvados.org/arvados.git/lib/ctrlctx"
21 "git.arvados.org/arvados.git/lib/dispatchcloud/container"
22 "git.arvados.org/arvados.git/lib/dispatchcloud/scheduler"
23 "git.arvados.org/arvados.git/lib/dispatchcloud/sshexecutor"
24 "git.arvados.org/arvados.git/lib/dispatchcloud/worker"
25 "git.arvados.org/arvados.git/sdk/go/arvados"
26 "git.arvados.org/arvados.git/sdk/go/auth"
27 "git.arvados.org/arvados.git/sdk/go/ctxlog"
28 "git.arvados.org/arvados.git/sdk/go/health"
29 "git.arvados.org/arvados.git/sdk/go/httpserver"
30 "github.com/julienschmidt/httprouter"
31 "github.com/prometheus/client_golang/prometheus"
32 "github.com/prometheus/client_golang/prometheus/promhttp"
33 "github.com/sirupsen/logrus"
34 "golang.org/x/crypto/ssh"
38 defaultPollInterval = time.Second
39 defaultStaleLockTimeout = time.Minute
45 Instances() []worker.InstanceView
46 SetIdleBehavior(cloud.InstanceID, worker.IdleBehavior) error
47 KillInstance(id cloud.InstanceID, reason string) error
51 type dispatcher struct {
52 Cluster *arvados.Cluster
53 Context context.Context
54 ArvClient *arvados.Client
56 Registry *prometheus.Registry
57 InstanceSetID cloud.InstanceSetID
59 dbConnector ctrlctx.DBConnector
60 logger logrus.FieldLogger
61 instanceSet cloud.InstanceSet
63 queue scheduler.ContainerQueue
64 httpHandler http.Handler
72 // Start starts the dispatcher. Start can be called multiple times
73 // with no ill effect.
74 func (disp *dispatcher) Start() {
75 disp.setupOnce.Do(disp.setup)
78 // ServeHTTP implements service.Handler.
79 func (disp *dispatcher) ServeHTTP(w http.ResponseWriter, r *http.Request) {
81 disp.httpHandler.ServeHTTP(w, r)
84 // CheckHealth implements service.Handler.
85 func (disp *dispatcher) CheckHealth() error {
87 return disp.pool.CheckHealth()
90 // Done implements service.Handler.
91 func (disp *dispatcher) Done() <-chan struct{} {
95 // Stop dispatching containers and release resources. Typically used
97 func (disp *dispatcher) Close() {
100 case disp.stop <- struct{}{}:
106 // Make a worker.Executor for the given instance.
107 func (disp *dispatcher) newExecutor(inst cloud.Instance) worker.Executor {
108 exr := sshexecutor.New(inst)
109 exr.SetTargetPort(disp.Cluster.Containers.CloudVMs.SSHPort)
110 exr.SetSigners(disp.sshKey)
114 func (disp *dispatcher) typeChooser(ctr *arvados.Container) (arvados.InstanceType, error) {
115 return ChooseInstanceType(disp.Cluster, ctr)
118 func (disp *dispatcher) setup() {
123 func (disp *dispatcher) initialize() {
124 disp.logger = ctxlog.FromContext(disp.Context)
125 disp.dbConnector = ctrlctx.DBConnector{PostgreSQL: disp.Cluster.PostgreSQL}
127 disp.ArvClient.AuthToken = disp.AuthToken
129 if disp.InstanceSetID == "" {
130 if strings.HasPrefix(disp.AuthToken, "v2/") {
131 disp.InstanceSetID = cloud.InstanceSetID(strings.Split(disp.AuthToken, "/")[1])
133 // Use some other string unique to this token
134 // that doesn't reveal the token itself.
135 disp.InstanceSetID = cloud.InstanceSetID(fmt.Sprintf("%x", md5.Sum([]byte(disp.AuthToken))))
138 disp.stop = make(chan struct{}, 1)
139 disp.stopped = make(chan struct{})
141 if key, err := config.LoadSSHKey(disp.Cluster.Containers.DispatchPrivateKey); err != nil {
142 disp.logger.Fatalf("error parsing configured Containers.DispatchPrivateKey: %s", err)
146 installPublicKey := disp.sshKey.PublicKey()
147 if !disp.Cluster.Containers.CloudVMs.DeployPublicKey {
148 installPublicKey = nil
151 instanceSet, err := newInstanceSet(disp.Cluster, disp.InstanceSetID, disp.logger, disp.Registry)
153 disp.logger.Fatalf("error initializing driver: %s", err)
155 dblock.Dispatch.Lock(disp.Context, disp.dbConnector.GetDB)
156 disp.instanceSet = instanceSet
157 disp.pool = worker.NewPool(disp.logger, disp.ArvClient, disp.Registry, disp.InstanceSetID, disp.instanceSet, disp.newExecutor, installPublicKey, disp.Cluster)
158 disp.queue = container.NewQueue(disp.logger, disp.Registry, disp.typeChooser, disp.ArvClient)
160 if disp.Cluster.ManagementToken == "" {
161 disp.httpHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
162 http.Error(w, "Management API authentication is not configured", http.StatusForbidden)
165 mux := httprouter.New()
166 mux.HandlerFunc("GET", "/arvados/v1/dispatch/containers", disp.apiContainers)
167 mux.HandlerFunc("POST", "/arvados/v1/dispatch/containers/kill", disp.apiContainerKill)
168 mux.HandlerFunc("GET", "/arvados/v1/dispatch/instances", disp.apiInstances)
169 mux.HandlerFunc("POST", "/arvados/v1/dispatch/instances/hold", disp.apiInstanceHold)
170 mux.HandlerFunc("POST", "/arvados/v1/dispatch/instances/drain", disp.apiInstanceDrain)
171 mux.HandlerFunc("POST", "/arvados/v1/dispatch/instances/run", disp.apiInstanceRun)
172 mux.HandlerFunc("POST", "/arvados/v1/dispatch/instances/kill", disp.apiInstanceKill)
173 metricsH := promhttp.HandlerFor(disp.Registry, promhttp.HandlerOpts{
174 ErrorLog: disp.logger,
176 mux.Handler("GET", "/metrics", metricsH)
177 mux.Handler("GET", "/metrics.json", metricsH)
178 mux.Handler("GET", "/_health/:check", &health.Handler{
179 Token: disp.Cluster.ManagementToken,
181 Routes: health.Routes{"ping": disp.CheckHealth},
183 disp.httpHandler = auth.RequireLiteralToken(disp.Cluster.ManagementToken, mux)
187 func (disp *dispatcher) run() {
188 defer dblock.Dispatch.Unlock()
189 defer close(disp.stopped)
190 defer disp.instanceSet.Stop()
191 defer disp.pool.Stop()
193 staleLockTimeout := time.Duration(disp.Cluster.Containers.StaleLockTimeout)
194 if staleLockTimeout == 0 {
195 staleLockTimeout = defaultStaleLockTimeout
197 pollInterval := time.Duration(disp.Cluster.Containers.CloudVMs.PollInterval)
198 if pollInterval <= 0 {
199 pollInterval = defaultPollInterval
201 sched := scheduler.New(disp.Context, disp.ArvClient, disp.queue, disp.pool, disp.Registry, staleLockTimeout, pollInterval, disp.Cluster.Containers.CloudVMs.MaxInstances, disp.Cluster.Containers.CloudVMs.SupervisorFraction)
208 // Management API: all active and queued containers.
209 func (disp *dispatcher) apiContainers(w http.ResponseWriter, r *http.Request) {
211 Items []container.QueueEnt `json:"items"`
213 qEntries, _ := disp.queue.Entries()
214 for _, ent := range qEntries {
215 resp.Items = append(resp.Items, ent)
217 json.NewEncoder(w).Encode(resp)
220 // Management API: all active instances (cloud VMs).
221 func (disp *dispatcher) apiInstances(w http.ResponseWriter, r *http.Request) {
223 Items []worker.InstanceView `json:"items"`
225 resp.Items = disp.pool.Instances()
226 json.NewEncoder(w).Encode(resp)
229 // Management API: set idle behavior to "hold" for specified instance.
230 func (disp *dispatcher) apiInstanceHold(w http.ResponseWriter, r *http.Request) {
231 disp.apiInstanceIdleBehavior(w, r, worker.IdleBehaviorHold)
234 // Management API: set idle behavior to "drain" for specified instance.
235 func (disp *dispatcher) apiInstanceDrain(w http.ResponseWriter, r *http.Request) {
236 disp.apiInstanceIdleBehavior(w, r, worker.IdleBehaviorDrain)
239 // Management API: set idle behavior to "run" for specified instance.
240 func (disp *dispatcher) apiInstanceRun(w http.ResponseWriter, r *http.Request) {
241 disp.apiInstanceIdleBehavior(w, r, worker.IdleBehaviorRun)
244 // Management API: shutdown/destroy specified instance now.
245 func (disp *dispatcher) apiInstanceKill(w http.ResponseWriter, r *http.Request) {
246 id := cloud.InstanceID(r.FormValue("instance_id"))
248 httpserver.Error(w, "instance_id parameter not provided", http.StatusBadRequest)
251 err := disp.pool.KillInstance(id, "via management API: "+r.FormValue("reason"))
253 httpserver.Error(w, err.Error(), http.StatusNotFound)
258 // Management API: send SIGTERM to specified container's crunch-run
260 func (disp *dispatcher) apiContainerKill(w http.ResponseWriter, r *http.Request) {
261 uuid := r.FormValue("container_uuid")
263 httpserver.Error(w, "container_uuid parameter not provided", http.StatusBadRequest)
266 if !disp.pool.KillContainer(uuid, "via management API: "+r.FormValue("reason")) {
267 httpserver.Error(w, "container not found", http.StatusNotFound)
272 func (disp *dispatcher) apiInstanceIdleBehavior(w http.ResponseWriter, r *http.Request, want worker.IdleBehavior) {
273 id := cloud.InstanceID(r.FormValue("instance_id"))
275 httpserver.Error(w, "instance_id parameter not provided", http.StatusBadRequest)
278 err := disp.pool.SetIdleBehavior(id, want)
280 httpserver.Error(w, err.Error(), http.StatusNotFound)