1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
18 "git.arvados.org/arvados.git/lib/cmd"
19 "git.arvados.org/arvados.git/lib/dispatchcloud"
20 "git.arvados.org/arvados.git/lib/service"
21 "git.arvados.org/arvados.git/sdk/go/arvados"
22 "git.arvados.org/arvados.git/sdk/go/arvadosclient"
23 "git.arvados.org/arvados.git/sdk/go/auth"
24 "git.arvados.org/arvados.git/sdk/go/ctxlog"
25 "git.arvados.org/arvados.git/sdk/go/dispatch"
26 "git.arvados.org/arvados.git/sdk/go/health"
27 "github.com/julienschmidt/httprouter"
28 "github.com/prometheus/client_golang/prometheus"
29 "github.com/prometheus/client_golang/prometheus/promhttp"
30 "github.com/sirupsen/logrus"
33 var DispatchCommand cmd.Handler = service.Command(arvados.ServiceNameDispatchLSF, newHandler)
35 func newHandler(ctx context.Context, cluster *arvados.Cluster, token string, reg *prometheus.Registry) service.Handler {
36 ac, err := arvados.NewClientFromConfig(cluster)
38 return service.ErrorHandler(ctx, cluster, fmt.Errorf("error initializing client from cluster config: %s", err))
51 type dispatcher struct {
52 Cluster *arvados.Cluster
53 Context context.Context
54 ArvClient *arvados.Client
56 Registry *prometheus.Registry
58 logger logrus.FieldLogger
61 arvDispatcher *dispatch.Dispatcher
62 httpHandler http.Handler
69 // Start starts the dispatcher. Start can be called multiple times
70 // with no ill effect.
71 func (disp *dispatcher) Start() {
72 disp.initOnce.Do(func() {
75 disp.checkLsfQueueForOrphans()
76 err := disp.arvDispatcher.Run(disp.Context)
78 disp.logger.Error(err)
85 // ServeHTTP implements service.Handler.
86 func (disp *dispatcher) ServeHTTP(w http.ResponseWriter, r *http.Request) {
88 disp.httpHandler.ServeHTTP(w, r)
91 // CheckHealth implements service.Handler.
92 func (disp *dispatcher) CheckHealth() error {
96 return errors.New("stopped")
102 // Done implements service.Handler.
103 func (disp *dispatcher) Done() <-chan struct{} {
107 // Stop dispatching containers and release resources. Used by tests.
108 func (disp *dispatcher) Close() {
111 case disp.stop <- struct{}{}:
117 func (disp *dispatcher) init() {
118 disp.logger = ctxlog.FromContext(disp.Context)
119 disp.lsfcli.logger = disp.logger
120 disp.lsfqueue = lsfqueue{
122 period: time.Duration(disp.Cluster.Containers.CloudVMs.PollInterval),
123 lsfcli: &disp.lsfcli,
125 disp.ArvClient.AuthToken = disp.AuthToken
126 disp.stop = make(chan struct{}, 1)
127 disp.stopped = make(chan struct{})
129 arv, err := arvadosclient.New(disp.ArvClient)
131 disp.logger.Fatalf("Error making Arvados client: %v", err)
134 arv.ApiToken = disp.AuthToken
135 disp.arvDispatcher = &dispatch.Dispatcher{
138 BatchSize: disp.Cluster.API.MaxItemsPerResponse,
139 RunContainer: disp.runContainer,
140 PollPeriod: time.Duration(disp.Cluster.Containers.CloudVMs.PollInterval),
141 MinRetryPeriod: time.Duration(disp.Cluster.Containers.MinRetryPeriod),
144 if disp.Cluster.ManagementToken == "" {
145 disp.httpHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
146 http.Error(w, "Management API authentication is not configured", http.StatusForbidden)
149 mux := httprouter.New()
150 metricsH := promhttp.HandlerFor(disp.Registry, promhttp.HandlerOpts{
151 ErrorLog: disp.logger,
153 mux.Handler("GET", "/metrics", metricsH)
154 mux.Handler("GET", "/metrics.json", metricsH)
155 mux.Handler("GET", "/_health/:check", &health.Handler{
156 Token: disp.Cluster.ManagementToken,
158 Routes: health.Routes{"ping": disp.CheckHealth},
160 disp.httpHandler = auth.RequireLiteralToken(disp.Cluster.ManagementToken, mux)
164 func (disp *dispatcher) runContainer(_ *dispatch.Dispatcher, ctr arvados.Container, status <-chan arvados.Container) error {
165 ctx, cancel := context.WithCancel(disp.Context)
168 if ctr.State != dispatch.Locked {
169 // already started by prior invocation
170 } else if _, ok := disp.lsfqueue.JobID(ctr.UUID); !ok {
171 disp.logger.Printf("Submitting container %s to LSF", ctr.UUID)
172 cmd := []string{disp.Cluster.Containers.CrunchRunCommand}
173 cmd = append(cmd, "--runtime-engine="+disp.Cluster.Containers.RuntimeEngine)
174 cmd = append(cmd, disp.Cluster.Containers.CrunchRunArgumentsList...)
175 err := disp.submit(ctr, cmd)
181 disp.logger.Printf("Start monitoring container %v in state %q", ctr.UUID, ctr.State)
182 defer disp.logger.Printf("Done monitoring container %s", ctr.UUID)
184 // If the container disappears from the lsf queue, there is
185 // no point in waiting for further dispatch updates: just
186 // clean up and return.
187 go func(uuid string) {
188 for ctx.Err() == nil {
189 if _, ok := disp.lsfqueue.JobID(uuid); !ok {
190 disp.logger.Printf("container %s job disappeared from LSF queue", uuid)
197 for done := false; !done; {
200 // Disappeared from lsf queue
201 if err := disp.arvDispatcher.Arv.Get("containers", ctr.UUID, nil, &ctr); err != nil {
202 disp.logger.Printf("error getting final container state for %s: %s", ctr.UUID, err)
205 case dispatch.Running:
206 disp.arvDispatcher.UpdateState(ctr.UUID, dispatch.Cancelled)
207 case dispatch.Locked:
208 disp.arvDispatcher.Unlock(ctr.UUID)
211 case updated, ok := <-status:
213 // status channel is closed, which is
214 // how arvDispatcher tells us to stop
215 // touching the container record, kill
216 // off any remaining LSF processes,
221 if updated.State != ctr.State {
222 disp.logger.Infof("container %s changed state from %s to %s", ctr.UUID, ctr.State, updated.State)
225 if ctr.Priority < 1 {
226 disp.logger.Printf("container %s has state %s, priority %d: cancel lsf job", ctr.UUID, ctr.State, ctr.Priority)
229 disp.lsfqueue.SetPriority(ctr.UUID, int64(ctr.Priority))
233 disp.logger.Printf("container %s is done", ctr.UUID)
235 // Try "bkill" every few seconds until the LSF job disappears
237 ticker := time.NewTicker(5 * time.Second)
239 for jobid, ok := disp.lsfqueue.JobID(ctr.UUID); ok; _, ok = disp.lsfqueue.JobID(ctr.UUID) {
240 err := disp.lsfcli.Bkill(jobid)
242 disp.logger.Warnf("%s: bkill(%d): %s", ctr.UUID, jobid, err)
249 func (disp *dispatcher) submit(container arvados.Container, crunchRunCommand []string) error {
250 // Start with an empty slice here to ensure append() doesn't
251 // modify crunchRunCommand's underlying array
253 crArgs = append(crArgs, crunchRunCommand...)
254 crArgs = append(crArgs, container.UUID)
255 crScript := execScript(crArgs)
257 bsubArgs, err := disp.bsubArgs(container)
261 return disp.lsfcli.Bsub(crScript, bsubArgs, disp.ArvClient)
264 func (disp *dispatcher) bkill(ctr arvados.Container) {
265 if jobid, ok := disp.lsfqueue.JobID(ctr.UUID); !ok {
266 disp.logger.Debugf("bkill(%s): redundant, job not in queue", ctr.UUID)
267 } else if err := disp.lsfcli.Bkill(jobid); err != nil {
268 disp.logger.Warnf("%s: bkill(%d): %s", ctr.UUID, jobid, err)
272 func (disp *dispatcher) bsubArgs(container arvados.Container) ([]string, error) {
273 args := []string{"bsub"}
274 args = append(args, disp.Cluster.Containers.LSF.BsubArgumentsList...)
275 args = append(args, "-J", container.UUID)
276 args = append(args, disp.bsubConstraintArgs(container)...)
277 if u := disp.Cluster.Containers.LSF.BsubSudoUser; u != "" {
278 args = append([]string{"sudo", "-E", "-u", u}, args...)
283 func (disp *dispatcher) bsubConstraintArgs(container arvados.Container) []string {
284 // TODO: propagate container.SchedulingParameters.Partitions
285 tmp := int64(math.Ceil(float64(dispatchcloud.EstimateScratchSpace(&container)) / 1048576))
286 vcpus := container.RuntimeConstraints.VCPUs
287 mem := int64(math.Ceil(float64(container.RuntimeConstraints.RAM+
288 container.RuntimeConstraints.KeepCacheRAM+
289 int64(disp.Cluster.Containers.ReserveExtraRAM)) / 1048576))
291 "-n", fmt.Sprintf("%d", vcpus),
292 "-D", fmt.Sprintf("%dMB", mem), // ulimit -d (note this doesn't limit the total container memory usage)
293 "-R", fmt.Sprintf("rusage[mem=%dMB:tmp=%dMB] span[hosts=1]", mem, tmp),
297 // Check the next bjobs report, and invoke TrackContainer for all the
298 // containers in the report. This gives us a chance to cancel existing
299 // Arvados LSF jobs (started by a previous dispatch process) that
300 // never released their LSF job allocations even though their
301 // container states are Cancelled or Complete. See
302 // https://dev.arvados.org/issues/10979
303 func (disp *dispatcher) checkLsfQueueForOrphans() {
304 containerUuidPattern := regexp.MustCompile(`^[a-z0-9]{5}-dz642-[a-z0-9]{15}$`)
305 for _, uuid := range disp.lsfqueue.All() {
306 if !containerUuidPattern.MatchString(uuid) || !strings.HasPrefix(uuid, disp.Cluster.ClusterID) {
309 err := disp.arvDispatcher.TrackContainer(uuid)
311 disp.logger.Warnf("checkLsfQueueForOrphans: TrackContainer(%s): %s", uuid, err)
316 func execScript(args []string) []byte {
317 s := "#!/bin/sh\nexec"
318 for _, w := range args {
320 s += strings.Replace(w, `'`, `'\''`, -1)
323 return []byte(s + "\n")