1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
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"
32 defaultPollInterval = time.Second
33 defaultStaleLockTimeout = time.Minute
38 Instances() []worker.InstanceView
39 SetIdleBehavior(cloud.InstanceID, worker.IdleBehavior) error
43 type dispatcher struct {
44 Cluster *arvados.Cluster
45 InstanceSetID cloud.InstanceSetID
47 logger logrus.FieldLogger
48 reg *prometheus.Registry
49 instanceSet cloud.InstanceSet
51 queue scheduler.ContainerQueue
52 httpHandler http.Handler
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)
66 // ServeHTTP implements service.Handler.
67 func (disp *dispatcher) ServeHTTP(w http.ResponseWriter, r *http.Request) {
69 disp.httpHandler.ServeHTTP(w, r)
72 // CheckHealth implements service.Handler.
73 func (disp *dispatcher) CheckHealth() error {
78 // Stop dispatching containers and release resources. Typically used
80 func (disp *dispatcher) Close() {
83 case disp.stop <- struct{}{}:
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.SetTargetPort(disp.Cluster.CloudVMs.SSHPort)
93 exr.SetSigners(disp.sshKey)
97 func (disp *dispatcher) typeChooser(ctr *arvados.Container) (arvados.InstanceType, error) {
98 return ChooseInstanceType(disp.Cluster, ctr)
101 func (disp *dispatcher) setup() {
106 func (disp *dispatcher) initialize() {
107 arvClient := arvados.NewClientFromEnv()
108 if disp.InstanceSetID == "" {
109 if strings.HasPrefix(arvClient.AuthToken, "v2/") {
110 disp.InstanceSetID = cloud.InstanceSetID(strings.Split(arvClient.AuthToken, "/")[1])
112 // Use some other string unique to this token
113 // that doesn't reveal the token itself.
114 disp.InstanceSetID = cloud.InstanceSetID(fmt.Sprintf("%x", md5.Sum([]byte(arvClient.AuthToken))))
117 disp.stop = make(chan struct{}, 1)
118 disp.stopped = make(chan struct{})
119 disp.logger = logrus.StandardLogger()
121 if key, err := ssh.ParsePrivateKey(disp.Cluster.Dispatch.PrivateKey); err != nil {
122 disp.logger.Fatalf("error parsing configured Dispatch.PrivateKey: %s", err)
127 instanceSet, err := newInstanceSet(disp.Cluster, disp.InstanceSetID, disp.logger)
129 disp.logger.Fatalf("error initializing driver: %s", err)
131 disp.instanceSet = &instanceSetProxy{instanceSet}
132 disp.reg = prometheus.NewRegistry()
133 disp.pool = worker.NewPool(disp.logger, arvClient, disp.reg, disp.instanceSet, disp.newExecutor, disp.Cluster)
134 disp.queue = container.NewQueue(disp.logger, disp.reg, disp.typeChooser, arvClient)
136 if disp.Cluster.ManagementToken == "" {
137 disp.httpHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
138 http.Error(w, "Management API authentication is not configured", http.StatusForbidden)
141 mux := httprouter.New()
142 mux.HandlerFunc("GET", "/arvados/v1/dispatch/containers", disp.apiContainers)
143 mux.HandlerFunc("GET", "/arvados/v1/dispatch/instances", disp.apiInstances)
144 mux.HandlerFunc("POST", "/arvados/v1/dispatch/instances/:instance_id/hold", disp.apiInstanceHold)
145 mux.HandlerFunc("POST", "/arvados/v1/dispatch/instances/:instance_id/drain", disp.apiInstanceDrain)
146 mux.HandlerFunc("POST", "/arvados/v1/dispatch/instances/:instance_id/run", disp.apiInstanceRun)
147 metricsH := promhttp.HandlerFor(disp.reg, promhttp.HandlerOpts{
148 ErrorLog: disp.logger,
150 mux.Handler("GET", "/metrics", metricsH)
151 mux.Handler("GET", "/metrics.json", metricsH)
152 disp.httpHandler = auth.RequireLiteralToken(disp.Cluster.ManagementToken, mux)
156 func (disp *dispatcher) run() {
157 defer close(disp.stopped)
158 defer disp.instanceSet.Stop()
159 defer disp.pool.Stop()
161 staleLockTimeout := time.Duration(disp.Cluster.Dispatch.StaleLockTimeout)
162 if staleLockTimeout == 0 {
163 staleLockTimeout = defaultStaleLockTimeout
165 pollInterval := time.Duration(disp.Cluster.Dispatch.PollInterval)
166 if pollInterval <= 0 {
167 pollInterval = defaultPollInterval
169 sched := scheduler.New(disp.logger, disp.queue, disp.pool, staleLockTimeout, pollInterval)
176 // Management API: all active and queued containers.
177 func (disp *dispatcher) apiContainers(w http.ResponseWriter, r *http.Request) {
179 Items []container.QueueEnt `json:"items"`
181 qEntries, _ := disp.queue.Entries()
182 for _, ent := range qEntries {
183 resp.Items = append(resp.Items, ent)
185 json.NewEncoder(w).Encode(resp)
188 // Management API: all active instances (cloud VMs).
189 func (disp *dispatcher) apiInstances(w http.ResponseWriter, r *http.Request) {
191 Items []worker.InstanceView `json:"items"`
193 resp.Items = disp.pool.Instances()
194 json.NewEncoder(w).Encode(resp)
197 // Management API: set idle behavior to "hold" for specified instance.
198 func (disp *dispatcher) apiInstanceHold(w http.ResponseWriter, r *http.Request) {
199 disp.apiInstanceIdleBehavior(w, r, worker.IdleBehaviorHold)
202 // Management API: set idle behavior to "drain" for specified instance.
203 func (disp *dispatcher) apiInstanceDrain(w http.ResponseWriter, r *http.Request) {
204 disp.apiInstanceIdleBehavior(w, r, worker.IdleBehaviorDrain)
207 // Management API: set idle behavior to "run" for specified instance.
208 func (disp *dispatcher) apiInstanceRun(w http.ResponseWriter, r *http.Request) {
209 disp.apiInstanceIdleBehavior(w, r, worker.IdleBehaviorRun)
212 func (disp *dispatcher) apiInstanceIdleBehavior(w http.ResponseWriter, r *http.Request, want worker.IdleBehavior) {
213 params, _ := r.Context().Value(httprouter.ParamsKey).(httprouter.Params)
214 id := cloud.InstanceID(params.ByName("instance_id"))
215 err := disp.pool.SetIdleBehavior(id, want)
217 httpserver.Error(w, err.Error(), http.StatusNotFound)