14325: Add management API endpoints for drain/hold/run behavior.
[arvados.git] / lib / dispatchcloud / dispatcher.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package dispatchcloud
6
7 import (
8         "crypto/md5"
9         "encoding/json"
10         "fmt"
11         "net/http"
12         "strings"
13         "sync"
14         "time"
15
16         "git.curoverse.com/arvados.git/lib/cloud"
17         "git.curoverse.com/arvados.git/lib/dispatchcloud/container"
18         "git.curoverse.com/arvados.git/lib/dispatchcloud/scheduler"
19         "git.curoverse.com/arvados.git/lib/dispatchcloud/ssh_executor"
20         "git.curoverse.com/arvados.git/lib/dispatchcloud/worker"
21         "git.curoverse.com/arvados.git/sdk/go/arvados"
22         "git.curoverse.com/arvados.git/sdk/go/auth"
23         "git.curoverse.com/arvados.git/sdk/go/httpserver"
24         "github.com/julienschmidt/httprouter"
25         "github.com/prometheus/client_golang/prometheus"
26         "github.com/prometheus/client_golang/prometheus/promhttp"
27         "github.com/sirupsen/logrus"
28         "golang.org/x/crypto/ssh"
29 )
30
31 const (
32         defaultPollInterval     = time.Second
33         defaultStaleLockTimeout = time.Minute
34 )
35
36 type pool interface {
37         scheduler.WorkerPool
38         Instances() []worker.InstanceView
39         SetIdleBehavior(cloud.InstanceID, worker.IdleBehavior) error
40         Stop()
41 }
42
43 type dispatcher struct {
44         Cluster       *arvados.Cluster
45         InstanceSetID cloud.InstanceSetID
46
47         logger      logrus.FieldLogger
48         reg         *prometheus.Registry
49         instanceSet cloud.InstanceSet
50         pool        pool
51         queue       scheduler.ContainerQueue
52         httpHandler http.Handler
53         sshKey      ssh.Signer
54
55         setupOnce sync.Once
56         stop      chan struct{}
57         stopped   chan struct{}
58 }
59
60 // Start starts the dispatcher. Start can be called multiple times
61 // with no ill effect.
62 func (disp *dispatcher) Start() {
63         disp.setupOnce.Do(disp.setup)
64 }
65
66 // ServeHTTP implements service.Handler.
67 func (disp *dispatcher) ServeHTTP(w http.ResponseWriter, r *http.Request) {
68         disp.Start()
69         disp.httpHandler.ServeHTTP(w, r)
70 }
71
72 // CheckHealth implements service.Handler.
73 func (disp *dispatcher) CheckHealth() error {
74         disp.Start()
75         return nil
76 }
77
78 // Stop dispatching containers and release resources. Typically used
79 // in tests.
80 func (disp *dispatcher) Close() {
81         disp.Start()
82         select {
83         case disp.stop <- struct{}{}:
84         default:
85         }
86         <-disp.stopped
87 }
88
89 // Make a worker.Executor for the given instance.
90 func (disp *dispatcher) newExecutor(inst cloud.Instance) worker.Executor {
91         exr := ssh_executor.New(inst)
92         exr.SetSigners(disp.sshKey)
93         return exr
94 }
95
96 func (disp *dispatcher) typeChooser(ctr *arvados.Container) (arvados.InstanceType, error) {
97         return ChooseInstanceType(disp.Cluster, ctr)
98 }
99
100 func (disp *dispatcher) setup() {
101         disp.initialize()
102         go disp.run()
103 }
104
105 func (disp *dispatcher) initialize() {
106         arvClient := arvados.NewClientFromEnv()
107         if disp.InstanceSetID == "" {
108                 if strings.HasPrefix(arvClient.AuthToken, "v2/") {
109                         disp.InstanceSetID = cloud.InstanceSetID(strings.Split(arvClient.AuthToken, "/")[1])
110                 } else {
111                         // Use some other string unique to this token
112                         // that doesn't reveal the token itself.
113                         disp.InstanceSetID = cloud.InstanceSetID(fmt.Sprintf("%x", md5.Sum([]byte(arvClient.AuthToken))))
114                 }
115         }
116         disp.stop = make(chan struct{}, 1)
117         disp.stopped = make(chan struct{})
118         disp.logger = logrus.StandardLogger()
119
120         if key, err := ssh.ParsePrivateKey(disp.Cluster.Dispatch.PrivateKey); err != nil {
121                 disp.logger.Fatalf("error parsing configured Dispatch.PrivateKey: %s", err)
122         } else {
123                 disp.sshKey = key
124         }
125
126         instanceSet, err := newInstanceSet(disp.Cluster, disp.InstanceSetID, disp.logger)
127         if err != nil {
128                 disp.logger.Fatalf("error initializing driver: %s", err)
129         }
130         disp.instanceSet = &instanceSetProxy{instanceSet}
131         disp.reg = prometheus.NewRegistry()
132         disp.pool = worker.NewPool(disp.logger, arvClient, disp.reg, disp.instanceSet, disp.newExecutor, disp.Cluster)
133         disp.queue = container.NewQueue(disp.logger, disp.reg, disp.typeChooser, arvClient)
134
135         if disp.Cluster.ManagementToken == "" {
136                 disp.httpHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
137                         http.Error(w, "Management API authentication is not configured", http.StatusForbidden)
138                 })
139         } else {
140                 mux := httprouter.New()
141                 mux.HandlerFunc("GET", "/arvados/v1/dispatch/containers", disp.apiContainers)
142                 mux.HandlerFunc("GET", "/arvados/v1/dispatch/instances", disp.apiInstances)
143                 mux.HandlerFunc("POST", "/arvados/v1/dispatch/instances/:instance_id/hold", disp.apiInstanceHold)
144                 mux.HandlerFunc("POST", "/arvados/v1/dispatch/instances/:instance_id/drain", disp.apiInstanceDrain)
145                 mux.HandlerFunc("POST", "/arvados/v1/dispatch/instances/:instance_id/run", disp.apiInstanceRun)
146                 metricsH := promhttp.HandlerFor(disp.reg, promhttp.HandlerOpts{
147                         ErrorLog: disp.logger,
148                 })
149                 mux.Handler("GET", "/metrics", metricsH)
150                 mux.Handler("GET", "/metrics.json", metricsH)
151                 disp.httpHandler = auth.RequireLiteralToken(disp.Cluster.ManagementToken, mux)
152         }
153 }
154
155 func (disp *dispatcher) run() {
156         defer close(disp.stopped)
157         defer disp.instanceSet.Stop()
158         defer disp.pool.Stop()
159
160         staleLockTimeout := time.Duration(disp.Cluster.Dispatch.StaleLockTimeout)
161         if staleLockTimeout == 0 {
162                 staleLockTimeout = defaultStaleLockTimeout
163         }
164         pollInterval := time.Duration(disp.Cluster.Dispatch.PollInterval)
165         if pollInterval <= 0 {
166                 pollInterval = defaultPollInterval
167         }
168         sched := scheduler.New(disp.logger, disp.queue, disp.pool, staleLockTimeout, pollInterval)
169         sched.Start()
170         defer sched.Stop()
171
172         <-disp.stop
173 }
174
175 // Management API: all active and queued containers.
176 func (disp *dispatcher) apiContainers(w http.ResponseWriter, r *http.Request) {
177         var resp struct {
178                 Items []container.QueueEnt
179         }
180         qEntries, _ := disp.queue.Entries()
181         for _, ent := range qEntries {
182                 resp.Items = append(resp.Items, ent)
183         }
184         json.NewEncoder(w).Encode(resp)
185 }
186
187 // Management API: all active instances (cloud VMs).
188 func (disp *dispatcher) apiInstances(w http.ResponseWriter, r *http.Request) {
189         var resp struct {
190                 Items []worker.InstanceView
191         }
192         resp.Items = disp.pool.Instances()
193         json.NewEncoder(w).Encode(resp)
194 }
195
196 // Management API: set idle behavior to "hold" for specified instance.
197 func (disp *dispatcher) apiInstanceHold(w http.ResponseWriter, r *http.Request) {
198         disp.apiInstanceIdleBehavior(w, r, worker.IdleBehaviorHold)
199 }
200
201 // Management API: set idle behavior to "drain" for specified instance.
202 func (disp *dispatcher) apiInstanceDrain(w http.ResponseWriter, r *http.Request) {
203         disp.apiInstanceIdleBehavior(w, r, worker.IdleBehaviorDrain)
204 }
205
206 // Management API: set idle behavior to "run" for specified instance.
207 func (disp *dispatcher) apiInstanceRun(w http.ResponseWriter, r *http.Request) {
208         disp.apiInstanceIdleBehavior(w, r, worker.IdleBehaviorRun)
209 }
210
211 func (disp *dispatcher) apiInstanceIdleBehavior(w http.ResponseWriter, r *http.Request, want worker.IdleBehavior) {
212         params, _ := r.Context().Value(httprouter.ParamsKey).(httprouter.Params)
213         id := cloud.InstanceID(params.ByName("instance_id"))
214         err := disp.pool.SetIdleBehavior(id, want)
215         if err != nil {
216                 httpserver.Error(w, err.Error(), http.StatusNotFound)
217                 return
218         }
219 }