2020-09-22 10:56:43 +00:00
|
|
|
package attributes
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"strings"
|
|
|
|
|
2020-11-16 10:26:35 +00:00
|
|
|
"github.com/nspcc-dev/neofs-api-go/pkg/netmap"
|
2020-09-22 10:56:43 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
pairSeparator = "/"
|
|
|
|
keyValueSeparator = ":"
|
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
errEmptyChain = errors.New("empty attribute chain")
|
|
|
|
errNonUniqueBucket = errors.New("attributes must contain unique keys")
|
|
|
|
errUnexpectedKey = errors.New("attributes contain unexpected key")
|
|
|
|
)
|
|
|
|
|
|
|
|
// ParseV2Attributes parses strings like "K1:V1/K2:V2/K3:V3" into netmap
|
|
|
|
// attributes.
|
2020-11-16 10:26:35 +00:00
|
|
|
func ParseV2Attributes(attrs []string, excl []string) ([]*netmap.NodeAttribute, error) {
|
2020-09-22 10:56:43 +00:00
|
|
|
restricted := make(map[string]struct{}, len(excl))
|
|
|
|
for i := range excl {
|
|
|
|
restricted[excl[i]] = struct{}{}
|
|
|
|
}
|
|
|
|
|
2020-11-16 10:26:35 +00:00
|
|
|
cache := make(map[string]*netmap.NodeAttribute, len(attrs))
|
2020-09-22 10:56:43 +00:00
|
|
|
|
|
|
|
for i := range attrs {
|
|
|
|
line := strings.Trim(attrs[i], pairSeparator)
|
|
|
|
chain := strings.Split(line, pairSeparator)
|
|
|
|
if len(chain) == 0 {
|
|
|
|
return nil, errEmptyChain
|
|
|
|
}
|
|
|
|
|
|
|
|
var parentKey string // backtrack parents in next pairs
|
|
|
|
|
|
|
|
for j := range chain {
|
|
|
|
pair := strings.Split(chain[j], keyValueSeparator)
|
|
|
|
if len(pair) != 2 {
|
|
|
|
return nil, fmt.Errorf("incorrect attribute pair %s", chain[j])
|
|
|
|
}
|
|
|
|
|
|
|
|
key := pair[0]
|
|
|
|
value := pair[1]
|
|
|
|
|
2020-11-16 10:26:35 +00:00
|
|
|
if at, ok := cache[key]; ok && at.Value() != value {
|
2020-09-22 10:56:43 +00:00
|
|
|
return nil, errNonUniqueBucket
|
|
|
|
}
|
|
|
|
|
|
|
|
if _, ok := restricted[key]; ok {
|
|
|
|
return nil, errUnexpectedKey
|
|
|
|
}
|
|
|
|
|
2020-11-16 10:26:35 +00:00
|
|
|
attribute := netmap.NewNodeAttribute()
|
2020-09-22 10:56:43 +00:00
|
|
|
attribute.SetKey(key)
|
|
|
|
attribute.SetValue(value)
|
|
|
|
|
|
|
|
if parentKey != "" {
|
2020-11-16 10:26:35 +00:00
|
|
|
attribute.SetParentKeys(parentKey)
|
2020-09-22 10:56:43 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
parentKey = key
|
|
|
|
cache[key] = attribute
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-11-16 10:26:35 +00:00
|
|
|
result := make([]*netmap.NodeAttribute, 0, len(cache))
|
2020-09-22 10:56:43 +00:00
|
|
|
for _, v := range cache {
|
|
|
|
result = append(result, v)
|
|
|
|
}
|
|
|
|
|
|
|
|
return result, nil
|
|
|
|
}
|