File: provider.go

package info (click to toggle)
gitlab-ci-multi-runner 14.10.1-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 31,248 kB
  • sloc: sh: 1,694; makefile: 384; asm: 79; ruby: 68
file content (645 lines) | stat: -rw-r--r-- 17,564 bytes parent folder | download
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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
package machine

import (
	"errors"
	"fmt"
	"sync"
	"time"

	"github.com/prometheus/client_golang/prometheus"
	"github.com/sirupsen/logrus"

	"gitlab.com/gitlab-org/gitlab-runner/common"
	"gitlab.com/gitlab-org/gitlab-runner/helpers/docker"
)

type machineProvider struct {
	name        string
	machine     docker.Machine
	details     machinesDetails
	runners     runnersDetails
	lock        sync.RWMutex
	acquireLock sync.Mutex
	// provider stores a real executor that is used to start run the builds
	provider common.ExecutorProvider

	stuckRemoveLock sync.Mutex

	// metrics
	totalActions      *prometheus.CounterVec
	currentStatesDesc *prometheus.Desc
	creationHistogram prometheus.Histogram
	stoppingHistogram prometheus.Histogram
	removalHistogram  prometheus.Histogram
}

func (m *machineProvider) machineDetails(name string, acquire bool) *machineDetails {
	details := m.ensureDetails(name)
	if acquire {
		details = m.tryAcquireMachineDetails(details)
	}

	return details
}

func (m *machineProvider) ensureDetails(name string) *machineDetails {
	m.lock.Lock()
	defer m.lock.Unlock()

	details, ok := m.details[name]
	if !ok {
		now := time.Now()
		details = &machineDetails{
			Name:      name,
			Created:   now,
			Used:      now,
			LastSeen:  now,
			UsedCount: 1, // any machine that we find we mark as already used
			State:     machineStateIdle,
		}
		m.details[name] = details
	}

	return details
}

var errNoConfig = errors.New("no runner config specified")

func (m *machineProvider) runnerMachinesCoordinator(config *common.RunnerConfig) (*runnerMachinesCoordinator, error) {
	if config == nil {
		return nil, errNoConfig
	}

	m.lock.Lock()
	defer m.lock.Unlock()

	details, ok := m.runners[config.GetToken()]
	if !ok {
		details = newRunnerMachinesCoordinator()
		m.runners[config.GetToken()] = details
	}

	return details, nil
}

func (m *machineProvider) create(config *common.RunnerConfig, state machineState) (*machineDetails, chan error) {
	name := newMachineName(config)
	details := m.machineDetails(name, true)
	m.lock.Lock()
	details.State = machineStateCreating
	details.UsedCount = 0
	details.RetryCount = 0
	details.LastSeen = time.Now()
	m.lock.Unlock()
	errCh := make(chan error, 1)

	// Create machine with the required configuration asynchronously
	coordinator, err := m.runnerMachinesCoordinator(config)
	if err != nil {
		errCh <- err
		return nil, errCh
	}

	go coordinator.waitForGrowthCapacity(config.Machine.MaxGrowthRate, func() {
		m.createWithGrowthCapacity(coordinator, config, details, state, errCh)
	})

	return details, errCh
}

func (m *machineProvider) createWithGrowthCapacity(
	coordinator *runnerMachinesCoordinator,
	config *common.RunnerConfig,
	details *machineDetails,
	state machineState,
	errCh chan error,
) {
	logger := logrus.WithField("name", details.Name)
	started := time.Now()

	err := m.machine.Create(config.Machine.MachineDriver, details.Name, config.Machine.MachineOptions...)
	if err != nil {
		logger.WithField("time", time.Since(started)).
			WithError(err).
			Errorln("Machine creation failed")
		_ = m.remove(details.Name, "Failed to create")
	} else {
		m.lock.Lock()
		details.State = state
		details.Used = time.Now()
		m.lock.Unlock()
		creationTime := time.Since(started)
		m.lock.RLock()
		logger.WithField("duration", creationTime).
			WithField("now", time.Now()).
			WithField("retries", details.RetryCount).
			Infoln("Machine created")
		m.lock.RUnlock()
		m.totalActions.WithLabelValues("created").Inc()
		m.creationHistogram.Observe(creationTime.Seconds())

		// Signal that a new machine is available. When there's contention, there's no guarantee between the
		// ordering of reading from errCh and the availability check.
		coordinator.addAvailableMachine()
	}
	errCh <- err
}

func (m *machineProvider) findFreeMachine(skipCache bool, machines ...string) (details *machineDetails) {
	// Enumerate all machines in reverse order, to always take the newest machines first
	for idx := range machines {
		name := machines[len(machines)-idx-1]
		details := m.machineDetails(name, true)
		if details == nil {
			continue
		}

		// Check if node is running
		canConnect := m.machine.CanConnect(name, skipCache)
		if !canConnect {
			_ = m.remove(name, "machine is unavailable")
			continue
		}
		return details
	}

	return nil
}

func (m *machineProvider) findFreeExistingMachine(config *common.RunnerConfig) (*machineDetails, error) {
	machines, err := m.loadMachines(config)
	if err != nil {
		return nil, err
	}

	return m.findFreeMachine(true, machines...), nil
}

func (m *machineProvider) useMachine(config *common.RunnerConfig) (*machineDetails, error) {
	details, err := m.findFreeExistingMachine(config)
	if err != nil || details != nil {
		return details, err
	}

	return m.createAndAcquireMachine(config)
}

func (m *machineProvider) createAndAcquireMachine(config *common.RunnerConfig) (*machineDetails, error) {
	coordinator, err := m.runnerMachinesCoordinator(config)
	if err != nil {
		return nil, err
	}

	newDetails, errCh := m.create(config, machineStateIdle)
	// Use either a free machine, or the created machine; whichever comes first. There's no guarantee that the created
	// machine can be used by us because between the time the machine is created, and the acquisition of the machine,
	// another goroutine may have found it via findFreeMachine and acquired it.
	var details *machineDetails
	for details == nil && err == nil {
		select {
		case err = <-errCh:
			if err != nil {
				return nil, err
			}

			details = m.tryAcquireMachineDetails(newDetails)
		case <-coordinator.availableMachineSignal():
			// Even though the signal is fired and we are *almost* sure that
			// there's a machine available, let's use the getAvailableMachine
			// method so that the internal counter is synchonized with what
			// we are actually doing and so that we can be sure that no other
			// goroutine that didn't accept the signal and instead used the ticker
			// hasn't already snatched a machine
			details, err = m.tryGetFreeExistingMachineFromCoordinator(config, coordinator)
		case <-time.After(time.Second):
			details, err = m.tryGetFreeExistingMachineFromCoordinator(config, coordinator)
		}
	}

	return details, err
}

func (m *machineProvider) tryGetFreeExistingMachineFromCoordinator(
	config *common.RunnerConfig,
	coordinator *runnerMachinesCoordinator,
) (*machineDetails, error) {
	if coordinator.getAvailableMachine() {
		return m.findFreeExistingMachine(config)
	}

	return nil, nil
}

func (m *machineProvider) tryAcquireMachineDetails(details *machineDetails) *machineDetails {
	m.lock.Lock()
	defer m.lock.Unlock()

	if details.isUsed() {
		return nil
	}

	details.State = machineStateAcquired
	return details
}

func (m *machineProvider) retryUseMachine(config *common.RunnerConfig) (details *machineDetails, err error) {
	// Try to find a machine
	for i := 0; i < 3; i++ {
		details, err = m.useMachine(config)
		if err == nil {
			break
		}
		time.Sleep(provisionRetryInterval)
	}
	return
}

func (m *machineProvider) removeMachine(details *machineDetails) (err error) {
	if !m.machine.Exist(details.Name) {
		details.logger().
			Warningln("Skipping machine removal, because it doesn't exist")
		return nil
	}

	// This code limits amount of removal of stuck machines to one machine per interval
	if details.isStuckOnRemove() {
		m.stuckRemoveLock.Lock()
		defer m.stuckRemoveLock.Unlock()
	}

	details.logger().Warningln("Stopping machine")
	err = runHistogramCountedOperation(m.stoppingHistogram, func() error {
		return m.machine.Stop(details.Name, machineStopCommandTimeout)
	})
	if err != nil {
		details.logger().
			WithError(err).
			Warningln("Error while stopping machine")
	}

	details.logger().Warningln("Removing machine")
	err = runHistogramCountedOperation(m.removalHistogram, func() error {
		return m.machine.Remove(details.Name)
	})
	if err != nil {
		details.RetryCount++
		time.Sleep(removeRetryInterval)
		return err
	}

	return nil
}

func runHistogramCountedOperation(histogram prometheus.Histogram, operation func() error) error {
	startedAt := time.Now()
	err := operation()
	histogram.Observe(time.Since(startedAt).Seconds())

	return err
}

func (m *machineProvider) finalizeRemoval(details *machineDetails) {
	for {
		err := m.removeMachine(details)
		if err == nil {
			break
		}
	}

	m.lock.Lock()
	defer m.lock.Unlock()
	delete(m.details, details.Name)

	details.logger().
		WithField("now", time.Now()).
		WithField("retries", details.RetryCount).
		Infoln("Machine removed")

	m.totalActions.WithLabelValues("removed").Inc()
}

func (m *machineProvider) remove(machineName string, reason ...interface{}) error {
	m.lock.Lock()
	defer m.lock.Unlock()

	details := m.details[machineName]
	if details == nil {
		return errors.New("machine not found")
	}

	details.Reason = fmt.Sprint(reason...)
	details.State = machineStateRemoving
	details.RetryCount = 0

	details.logger().
		WithField("now", time.Now()).
		Warningln("Requesting machine removal")

	details.Used = time.Now()
	details.writeDebugInformation()

	go m.finalizeRemoval(details)
	return nil
}

func (m *machineProvider) updateMachines(
	machines []string,
	config *common.RunnerConfig,
) (data machinesData, validMachines []string) {
	data.Runner = config.ShortDescription()
	validMachines = make([]string, 0, len(machines))

	for _, name := range machines {
		details := m.machineDetails(name, false)
		details.LastSeen = time.Now()

		reason := shouldRemoveIdle(config, &data, details)
		if reason == dontRemoveIdleMachine {
			validMachines = append(validMachines, name)
		} else {
			_ = m.remove(details.Name, reason)
		}

		data.Add(details)
	}
	return
}

// createMachines starts goroutines that are creating the new machines.
// Limiting strategy is used to ensure the autoscaling parameters are respected.
func (m *machineProvider) createMachines(config *common.RunnerConfig, data *machinesData) {
	for {
		if !canCreateIdle(config, data) {
			return
		}

		// Create a new machine and mark it as Idle
		m.create(config, machineStateIdle)
		data.Creating++
	}
}

// intermediateMachineList returns a list of machines that might not yet be
// persisted on disk, these machines are the ones between being virtually
// created, and `docker-machine create` getting executed we populate this data
// set to overcome the race conditions related to not-full set of machines
// returned by `docker-machine ls -q`
func (m *machineProvider) intermediateMachineList(excludedMachines []string) []string {
	var excludedSet map[string]struct{}
	var intermediateMachines []string

	m.lock.Lock()
	defer m.lock.Unlock()

	for _, details := range m.details {
		if details.isPersistedOnDisk() {
			continue
		}

		// lazy init set, as most of times we don't create new machines
		if excludedSet == nil {
			excludedSet = make(map[string]struct{}, len(excludedMachines))
			for _, excludedMachine := range excludedMachines {
				excludedSet[excludedMachine] = struct{}{}
			}
		}

		if _, ok := excludedSet[details.Name]; ok {
			continue
		}

		intermediateMachines = append(intermediateMachines, details.Name)
	}

	return intermediateMachines
}

func (m *machineProvider) loadMachines(config *common.RunnerConfig) (machines []string, err error) {
	machines, err = m.machine.List()
	if err != nil {
		return nil, err
	}

	machines = append(machines, m.intermediateMachineList(machines)...)
	machines = filterMachineList(machines, machineFilter(config))
	return
}

func (m *machineProvider) Acquire(config *common.RunnerConfig) (common.ExecutorData, error) {
	if config.Machine == nil || config.Machine.MachineName == "" {
		return nil, fmt.Errorf("missing Machine options")
	}

	// Lock updating machines, because two Acquires can be run at the same time
	m.acquireLock.Lock()
	defer m.acquireLock.Unlock()

	machines, err := m.loadMachines(config)
	if err != nil {
		return nil, err
	}

	// Update a list of currently configured machines
	machinesData, validMachines := m.updateMachines(machines, config)

	// Pre-create machines
	m.createMachines(config, &machinesData)

	logger := logrus.WithFields(machinesData.Fields()).
		WithField("runner", config.ShortDescription()).
		WithField("idleCountMin", config.Machine.GetIdleCountMin()).
		WithField("idleCount", config.Machine.GetIdleCount()).
		WithField("idleScaleFactor", config.Machine.GetIdleScaleFactor()).
		WithField("maxMachines", config.Limit).
		WithField("maxMachineCreate", config.Machine.MaxGrowthRate)

	logger.WithField("time", time.Now()).Debugln("Docker Machine Details")
	machinesData.writeDebugInformation()

	// Try to find a free machine
	details := m.findFreeMachine(false, validMachines...)
	if details != nil {
		return details, nil
	}

	if config.Machine.GetIdleCount() == 0 {
		logger.Info("IdleCount is set to 0 so the machine will be created on demand in job context")
	} else if machinesData.Idle == 0 {
		return nil, &common.NoFreeExecutorError{Message: "no free machines that can process builds"}
	}

	return nil, nil
}

//nolint:nakedret
func (m *machineProvider) Use(
	config *common.RunnerConfig,
	data common.ExecutorData,
) (newConfig common.RunnerConfig, newData common.ExecutorData, err error) {
	// Find a new machine
	details, _ := data.(*machineDetails)
	if details == nil || !details.canBeUsed() || !m.machine.CanConnect(details.Name, true) {
		details, err = m.retryUseMachine(config)
		if err != nil {
			return
		}

		// Return details only if this is a new instance
		newData = details
	}

	// Get machine credentials
	dc, err := m.machine.Credentials(details.Name)
	if err != nil {
		if newData != nil {
			m.Release(config, newData)
		}
		newData = nil
		return
	}

	// Create shallow copy of config and store in it docker credentials
	newConfig = *config
	newConfig.Docker = &common.DockerConfig{}
	if config.Docker != nil {
		*newConfig.Docker = *config.Docker
	}
	newConfig.Docker.Credentials = dc

	// Mark machine as used
	details.State = machineStateUsed
	details.Used = time.Now()
	details.UsedCount++
	m.totalActions.WithLabelValues("used").Inc()
	return
}

func (m *machineProvider) Release(config *common.RunnerConfig, data common.ExecutorData) {
	// Release machine
	details, ok := data.(*machineDetails)
	if !ok {
		return
	}

	m.lock.Lock()
	// Mark last used time when is Used
	if details.State == machineStateUsed {
		details.Used = time.Now()
	}
	m.lock.Unlock()

	// Remove machine if we already used it
	if config != nil && config.Machine != nil &&
		config.Machine.MaxBuilds > 0 && details.UsedCount >= config.Machine.MaxBuilds {
		err := m.remove(details.Name, "Too many builds")
		if err == nil {
			return
		}
	}
	m.lock.Lock()
	details.State = machineStateIdle
	m.lock.Unlock()

	// Signal pending builds that a new machine is available.
	if err := m.signalRelease(config); err != nil {
		return
	}
}

func (m *machineProvider) signalRelease(config *common.RunnerConfig) error {
	coordinator, err := m.runnerMachinesCoordinator(config)
	if err != nil && err != errNoConfig {
		return err
	}

	if err != errNoConfig && coordinator != nil {
		coordinator.addAvailableMachine()
	}

	return nil
}

func (m *machineProvider) CanCreate() bool {
	return m.provider.CanCreate()
}

func (m *machineProvider) GetFeatures(features *common.FeaturesInfo) error {
	return m.provider.GetFeatures(features)
}

func (m *machineProvider) GetConfigInfo(input *common.RunnerConfig, output *common.ConfigInfo) {
	m.provider.GetConfigInfo(input, output)
}

func (m *machineProvider) GetDefaultShell() string {
	return m.provider.GetDefaultShell()
}

func (m *machineProvider) Create() common.Executor {
	return &machineExecutor{
		provider: m,
	}
}

func newMachineProvider(name, executor string) *machineProvider {
	provider := common.GetExecutorProvider(executor)
	if provider == nil {
		logrus.Panicln("Missing", executor)
	}

	return &machineProvider{
		name:     name,
		details:  make(machinesDetails),
		runners:  make(runnersDetails),
		machine:  docker.NewMachineCommand(),
		provider: provider,
		totalActions: prometheus.NewCounterVec(
			prometheus.CounterOpts{
				Name: "gitlab_runner_autoscaling_actions_total",
				Help: "The total number of actions executed by the provider.",
				ConstLabels: prometheus.Labels{
					"executor": name,
				},
			},
			[]string{"action"},
		),
		currentStatesDesc: prometheus.NewDesc(
			"gitlab_runner_autoscaling_machine_states",
			"The current number of machines per state in this provider.",
			[]string{"state"},
			prometheus.Labels{
				"executor": name,
			},
		),
		creationHistogram: prometheus.NewHistogram(
			prometheus.HistogramOpts{
				Name:    "gitlab_runner_autoscaling_machine_creation_duration_seconds",
				Help:    "Histogram of machine creation time.",
				Buckets: prometheus.ExponentialBuckets(30, 1.25, 10),
				ConstLabels: prometheus.Labels{
					"executor": name,
				},
			},
		),
		stoppingHistogram: prometheus.NewHistogram(
			prometheus.HistogramOpts{
				Name:    "gitlab_runner_autoscaling_machine_stopping_duration_seconds",
				Help:    "Histogram of machine stopping time.",
				Buckets: []float64{1, 3, 5, 10, 30, 50, 60, 80, 90, 120},
				ConstLabels: prometheus.Labels{
					"executor": name,
				},
			},
		),
		removalHistogram: prometheus.NewHistogram(
			prometheus.HistogramOpts{
				Name:    "gitlab_runner_autoscaling_machine_removal_duration_seconds",
				Help:    "Histogram of machine removal time.",
				Buckets: []float64{1, 3, 5, 10, 30, 50, 60, 80, 90, 120},
				ConstLabels: prometheus.Labels{
					"executor": name,
				},
			},
		),
	}
}