2014-11-16 20:13:20 +00:00
|
|
|
// Copyright (C) 2014 The Syncthing Authors.
|
2014-09-29 19:43:32 +00:00
|
|
|
//
|
2015-03-07 20:36:35 +00:00
|
|
|
// This Source Code Form is subject to the terms of the Mozilla Public
|
|
|
|
// License, v. 2.0. If a copy of the MPL was not distributed with this file,
|
2017-02-09 06:52:18 +00:00
|
|
|
// You can obtain one at https://mozilla.org/MPL/2.0/.
|
2014-09-28 11:00:38 +00:00
|
|
|
|
|
|
|
package model
|
|
|
|
|
|
|
|
import (
|
2015-09-22 17:38:46 +00:00
|
|
|
"github.com/syncthing/syncthing/lib/protocol"
|
2015-08-06 09:29:25 +00:00
|
|
|
"github.com/syncthing/syncthing/lib/sync"
|
2014-09-28 11:00:38 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// deviceActivity tracks the number of outstanding requests per device and can
|
|
|
|
// answer which device is least busy. It is safe for use from multiple
|
|
|
|
// goroutines.
|
|
|
|
type deviceActivity struct {
|
|
|
|
act map[protocol.DeviceID]int
|
|
|
|
mut sync.Mutex
|
|
|
|
}
|
|
|
|
|
|
|
|
func newDeviceActivity() *deviceActivity {
|
|
|
|
return &deviceActivity{
|
|
|
|
act: make(map[protocol.DeviceID]int),
|
2015-04-22 22:54:31 +00:00
|
|
|
mut: sync.NewMutex(),
|
2014-09-28 11:00:38 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-04-15 10:59:41 +00:00
|
|
|
func (m *deviceActivity) leastBusy(availability []Availability) (Availability, bool) {
|
2014-09-28 11:00:38 +00:00
|
|
|
m.mut.Lock()
|
2014-12-08 15:36:15 +00:00
|
|
|
low := 2<<30 - 1
|
2016-04-15 10:59:41 +00:00
|
|
|
found := false
|
|
|
|
var selected Availability
|
|
|
|
for _, info := range availability {
|
|
|
|
if usage := m.act[info.ID]; usage < low {
|
2014-09-28 11:00:38 +00:00
|
|
|
low = usage
|
2016-04-15 10:59:41 +00:00
|
|
|
selected = info
|
|
|
|
found = true
|
2014-09-28 11:00:38 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
m.mut.Unlock()
|
2016-04-15 10:59:41 +00:00
|
|
|
return selected, found
|
2014-09-28 11:00:38 +00:00
|
|
|
}
|
|
|
|
|
2016-04-15 10:59:41 +00:00
|
|
|
func (m *deviceActivity) using(availability Availability) {
|
2014-09-28 11:00:38 +00:00
|
|
|
m.mut.Lock()
|
2016-04-15 10:59:41 +00:00
|
|
|
m.act[availability.ID]++
|
2014-11-29 21:22:50 +00:00
|
|
|
m.mut.Unlock()
|
2014-09-28 11:00:38 +00:00
|
|
|
}
|
|
|
|
|
2016-04-15 10:59:41 +00:00
|
|
|
func (m *deviceActivity) done(availability Availability) {
|
2014-09-28 11:00:38 +00:00
|
|
|
m.mut.Lock()
|
2016-04-15 10:59:41 +00:00
|
|
|
m.act[availability.ID]--
|
2014-11-29 21:22:50 +00:00
|
|
|
m.mut.Unlock()
|
2014-09-28 11:00:38 +00:00
|
|
|
}
|