seaweedfs/go/topology/node_list.go

70 lines
1.5 KiB
Go
Raw Normal View History

2012-09-03 08:50:04 +00:00
package topology
import (
"fmt"
"math/rand"
"code.google.com/p/weed-fs/go/storage"
2012-09-03 08:50:04 +00:00
)
type NodeList struct {
nodes map[NodeId]Node
except map[string]Node
}
func NewNodeList(nodes map[NodeId]Node, except map[string]Node) *NodeList {
m := make(map[NodeId]Node, len(nodes)-len(except))
for _, n := range nodes {
if except[n.String()] == nil {
m[n.Id()] = n
}
}
nl := &NodeList{nodes: m}
return nl
}
func (nl *NodeList) FreeSpace() int {
freeSpace := 0
for _, n := range nl.nodes {
freeSpace += n.FreeSpace()
}
return freeSpace
}
2012-09-30 09:20:33 +00:00
func (nl *NodeList) RandomlyPickN(n int, min int) ([]Node, bool) {
2012-09-03 08:50:04 +00:00
var list []Node
for _, n := range nl.nodes {
2012-09-30 09:20:33 +00:00
if n.FreeSpace() >= min {
2012-09-03 08:50:04 +00:00
list = append(list, n)
}
}
2013-01-17 08:56:56 +00:00
if n > len(list) {
return nil, false
2012-09-03 08:50:04 +00:00
}
for i := n; i > 0; i-- {
2013-01-17 08:56:56 +00:00
r := rand.Intn(i)
t := list[r]
list[r] = list[i-1]
list[i-1] = t
2012-09-03 08:50:04 +00:00
}
return list[len(list)-n:], true
}
2012-09-08 23:25:44 +00:00
func (nl *NodeList) ReserveOneVolume(randomVolumeIndex int, vid storage.VolumeId) (bool, *DataNode) {
2012-09-03 08:50:04 +00:00
for _, node := range nl.nodes {
freeSpace := node.FreeSpace()
if randomVolumeIndex >= freeSpace {
randomVolumeIndex -= freeSpace
} else {
2012-09-08 23:25:44 +00:00
if node.IsDataNode() && node.FreeSpace() > 0 {
2012-09-03 08:50:04 +00:00
fmt.Println("vid =", vid, " assigned to node =", node, ", freeSpace =", node.FreeSpace())
2012-09-08 23:25:44 +00:00
return true, node.(*DataNode)
2012-09-03 08:50:04 +00:00
}
children := node.Children()
newNodeList := NewNodeList(children, nl.except)
return newNodeList.ReserveOneVolume(randomVolumeIndex, vid)
}
}
return false, nil
}