golint: Fixup issues found in the report

This also increases the max allowed to 5% -- I'm happy to make this
lower if someone asks.
This commit is contained in:
James Shubin
2017-02-22 20:14:22 -05:00
parent b0fce6a80d
commit 98bc96c911
33 changed files with 392 additions and 392 deletions

View File

@@ -29,24 +29,24 @@ import (
// TODO: we could make a new function that masks out the state of certain
// UID's, but at the moment the new Timer code has obsoleted the need...
// Converger is the general interface for implementing a convergence watcher
// Converger is the general interface for implementing a convergence watcher.
type Converger interface { // TODO: need a better name
Register() ConvergerUID
IsConverged(ConvergerUID) bool // is the UID converged ?
SetConverged(ConvergerUID, bool) error // set the converged state of the UID
Unregister(ConvergerUID)
Register() UID
IsConverged(UID) bool // is the UID converged ?
SetConverged(UID, bool) error // set the converged state of the UID
Unregister(UID)
Start()
Pause()
Loop(bool)
ConvergedTimer(ConvergerUID) <-chan time.Time
ConvergedTimer(UID) <-chan time.Time
Status() map[uint64]bool
Timeout() int // returns the timeout that this was created with
SetStateFn(func(bool) error) // sets the stateFn
}
// ConvergerUID is the interface resources can use to notify with if converged
// you'll need to use part of the Converger interface to Register initially too
type ConvergerUID interface {
// UID is the interface resources can use to notify with if converged. You'll
// need to use part of the Converger interface to Register initially too.
type UID interface {
ID() uint64 // get Id
Name() string // get a friendly name
SetName(string)
@@ -61,7 +61,7 @@ type ConvergerUID interface {
StopTimer() error
}
// converger is an implementation of the Converger interface
// converger is an implementation of the Converger interface.
type converger struct {
timeout int // must be zero (instant) or greater seconds to run
stateFn func(bool) error // run on converged state changes with state bool
@@ -73,8 +73,8 @@ type converger struct {
status map[uint64]bool
}
// convergerUID is an implementation of the ConvergerUID interface
type convergerUID struct {
// cuid is an implementation of the UID interface.
type cuid struct {
converger Converger
id uint64
name string // user defined, friendly name
@@ -84,7 +84,7 @@ type convergerUID struct {
wg sync.WaitGroup
}
// NewConverger builds a new converger struct
// NewConverger builds a new converger struct.
func NewConverger(timeout int, stateFn func(bool) error) *converger {
return &converger{
timeout: timeout,
@@ -96,13 +96,13 @@ func NewConverger(timeout int, stateFn func(bool) error) *converger {
}
}
// Register assigns a ConvergerUID to the caller
func (obj *converger) Register() ConvergerUID {
// Register assigns a UID to the caller.
func (obj *converger) Register() UID {
obj.mutex.Lock()
defer obj.mutex.Unlock()
obj.lastid++
obj.status[obj.lastid] = false // initialize as not converged
return &convergerUID{
return &cuid{
converger: obj,
id: obj.lastid,
name: fmt.Sprintf("%d", obj.lastid), // some default
@@ -111,28 +111,28 @@ func (obj *converger) Register() ConvergerUID {
}
}
// IsConverged gets the converged status of a uid
func (obj *converger) IsConverged(uid ConvergerUID) bool {
// IsConverged gets the converged status of a uid.
func (obj *converger) IsConverged(uid UID) bool {
if !uid.IsValid() {
panic(fmt.Sprintf("Id of ConvergerUID(%s) is nil!", uid.Name()))
panic(fmt.Sprintf("the ID of UID(%s) is nil", uid.Name()))
}
obj.mutex.RLock()
isConverged, found := obj.status[uid.ID()] // lookup
obj.mutex.RUnlock()
if !found {
panic("Id of ConvergerUID is unregistered!")
panic("the ID of UID is unregistered")
}
return isConverged
}
// SetConverged updates the converger with the converged state of the UID
func (obj *converger) SetConverged(uid ConvergerUID, isConverged bool) error {
// SetConverged updates the converger with the converged state of the UID.
func (obj *converger) SetConverged(uid UID, isConverged bool) error {
if !uid.IsValid() {
return fmt.Errorf("Id of ConvergerUID(%s) is nil!", uid.Name())
return fmt.Errorf("the ID of UID(%s) is nil", uid.Name())
}
obj.mutex.Lock()
if _, found := obj.status[uid.ID()]; !found {
panic("Id of ConvergerUID is unregistered!")
panic("the ID of UID is unregistered")
}
obj.status[uid.ID()] = isConverged // set
obj.mutex.Unlock() // unlock *before* poke or deadlock!
@@ -144,7 +144,7 @@ func (obj *converger) SetConverged(uid ConvergerUID, isConverged bool) error {
return nil
}
// isConverged returns true if *every* registered uid has converged
// isConverged returns true if *every* registered uid has converged.
func (obj *converger) isConverged() bool {
obj.mutex.RLock() // take a read lock
defer obj.mutex.RUnlock()
@@ -156,10 +156,10 @@ func (obj *converger) isConverged() bool {
return true
}
// Unregister dissociates the ConvergedUID from the converged checking
func (obj *converger) Unregister(uid ConvergerUID) {
// Unregister dissociates the ConvergedUID from the converged checking.
func (obj *converger) Unregister(uid UID) {
if !uid.IsValid() {
panic(fmt.Sprintf("Id of ConvergerUID(%s) is nil!", uid.Name()))
panic(fmt.Sprintf("the ID of UID(%s) is nil", uid.Name()))
}
obj.mutex.Lock()
uid.StopTimer() // ignore any errors
@@ -168,30 +168,30 @@ func (obj *converger) Unregister(uid ConvergerUID) {
uid.InvalidateID()
}
// Start causes a Converger object to start or resume running
// Start causes a Converger object to start or resume running.
func (obj *converger) Start() {
obj.control <- true
}
// Pause causes a Converger object to stop running temporarily
// Pause causes a Converger object to stop running temporarily.
func (obj *converger) Pause() { // FIXME: add a sync ACK on pause before return
obj.control <- false
}
// Loop is the main loop for a Converger object; it usually runs in a goroutine
// TODO: we could eventually have each resource tell us as soon as it converges
// and then keep track of the time delays here, to avoid callers needing select
// Loop is the main loop for a Converger object. It usually runs in a goroutine.
// TODO: we could eventually have each resource tell us as soon as it converges,
// and then keep track of the time delays here, to avoid callers needing select.
// NOTE: when we have very short timeouts, if we start before all the resources
// have joined the map, then it might appears as if we converged before we did!
// have joined the map, then it might appear as if we converged before we did!
func (obj *converger) Loop(startPaused bool) {
if obj.control == nil {
panic("Converger not initialized correctly")
panic("converger not initialized correctly")
}
if startPaused { // start paused without racing
select {
case e := <-obj.control:
if !e {
panic("Converger expected true!")
panic("converger expected true")
}
}
}
@@ -199,13 +199,13 @@ func (obj *converger) Loop(startPaused bool) {
select {
case e := <-obj.control: // expecting "false" which means pause!
if e {
panic("Converger expected false!")
panic("converger expected false")
}
// now i'm paused...
select {
case e := <-obj.control:
if !e {
panic("Converger expected true!")
panic("converger expected true")
}
// restart
// kick once to refresh the check...
@@ -244,9 +244,9 @@ func (obj *converger) Loop(startPaused bool) {
}
}
// ConvergedTimer adds a timeout to a select call and blocks until then
// ConvergedTimer adds a timeout to a select call and blocks until then.
// TODO: this means we could eventually have per resource converged timeouts
func (obj *converger) ConvergedTimer(uid ConvergerUID) <-chan time.Time {
func (obj *converger) ConvergedTimer(uid UID) <-chan time.Time {
// be clever: if i'm already converged, this timeout should block which
// avoids unnecessary new signals being sent! this avoids fast loops if
// we have a low timeout, or in particular a timeout == 0
@@ -280,60 +280,60 @@ func (obj *converger) SetStateFn(stateFn func(bool) error) {
obj.stateFn = stateFn
}
// Id returns the unique id of this UID object
func (obj *convergerUID) ID() uint64 {
// ID returns the unique id of this UID object.
func (obj *cuid) ID() uint64 {
return obj.id
}
// Name returns a user defined name for the specific convergerUID.
func (obj *convergerUID) Name() string {
// Name returns a user defined name for the specific cuid.
func (obj *cuid) Name() string {
return obj.name
}
// SetName sets a user defined name for the specific convergerUID.
func (obj *convergerUID) SetName(name string) {
// SetName sets a user defined name for the specific cuid.
func (obj *cuid) SetName(name string) {
obj.name = name
}
// IsValid tells us if the id is valid or has already been destroyed
func (obj *convergerUID) IsValid() bool {
// IsValid tells us if the id is valid or has already been destroyed.
func (obj *cuid) IsValid() bool {
return obj.id != 0 // an id of 0 is invalid
}
// InvalidateID marks the id as no longer valid
func (obj *convergerUID) InvalidateID() {
// InvalidateID marks the id as no longer valid.
func (obj *cuid) InvalidateID() {
obj.id = 0 // an id of 0 is invalid
}
// IsConverged is a helper function to the regular IsConverged method
func (obj *convergerUID) IsConverged() bool {
// IsConverged is a helper function to the regular IsConverged method.
func (obj *cuid) IsConverged() bool {
return obj.converger.IsConverged(obj)
}
// SetConverged is a helper function to the regular SetConverged notification
func (obj *convergerUID) SetConverged(isConverged bool) error {
// SetConverged is a helper function to the regular SetConverged notification.
func (obj *cuid) SetConverged(isConverged bool) error {
return obj.converger.SetConverged(obj, isConverged)
}
// Unregister is a helper function to unregister myself
func (obj *convergerUID) Unregister() {
// Unregister is a helper function to unregister myself.
func (obj *cuid) Unregister() {
obj.converger.Unregister(obj)
}
// ConvergedTimer is a helper around the regular ConvergedTimer method
func (obj *convergerUID) ConvergedTimer() <-chan time.Time {
// ConvergedTimer is a helper around the regular ConvergedTimer method.
func (obj *cuid) ConvergedTimer() <-chan time.Time {
return obj.converger.ConvergedTimer(obj)
}
// StartTimer runs an invisible timer that automatically converges on timeout.
func (obj *convergerUID) StartTimer() (func() error, error) {
func (obj *cuid) StartTimer() (func() error, error) {
obj.mutex.Lock()
if !obj.running {
obj.timer = make(chan struct{})
obj.running = true
} else {
obj.mutex.Unlock()
return obj.StopTimer, fmt.Errorf("Timer already started!")
return obj.StopTimer, fmt.Errorf("timer already started")
}
obj.mutex.Unlock()
obj.wg.Add(1)
@@ -362,22 +362,22 @@ func (obj *convergerUID) StartTimer() (func() error, error) {
}
// ResetTimer resets the counter to zero if using a StartTimer internally.
func (obj *convergerUID) ResetTimer() error {
func (obj *cuid) ResetTimer() error {
obj.mutex.Lock()
defer obj.mutex.Unlock()
if obj.running {
obj.timer <- struct{}{} // send the reset message
return nil
}
return fmt.Errorf("Timer hasn't been started!")
return fmt.Errorf("timer hasn't been started")
}
// StopTimer stops the running timer permanently until a StartTimer is run.
func (obj *convergerUID) StopTimer() error {
func (obj *cuid) StopTimer() error {
obj.mutex.Lock()
defer obj.mutex.Unlock()
if !obj.running {
return fmt.Errorf("Timer isn't running!")
return fmt.Errorf("timer isn't running")
}
close(obj.timer)
obj.wg.Wait()

View File

@@ -93,7 +93,7 @@ const (
)
var (
errApplyDeltaEventsInconsistent = errors.New("Etcd: ApplyDeltaEvents: Inconsistent key!")
errApplyDeltaEventsInconsistent = errors.New("inconsistent key in ApplyDeltaEvents")
)
// AW is a struct for the AddWatcher queue
@@ -579,7 +579,7 @@ func (obj *EmbdEtcd) CtxError(ctx context.Context, err error) (context.Context,
log.Fatal("Etcd: CtxError: Error: Unexpected lack of error!")
}
if obj.exiting {
obj.ctxErr = fmt.Errorf("Etcd: CtxError: Exit in progress!")
obj.ctxErr = fmt.Errorf("exit in progress")
return ctx, obj.ctxErr
}
@@ -600,14 +600,14 @@ func (obj *EmbdEtcd) CtxError(ctx context.Context, err error) (context.Context,
if retriesErr, ok := err.(*CtxRetriesErr); ok { // custom retry error
log.Printf("Etcd: CtxError: Reason: %s", retriesErr.Error())
if retriesErr.Retries == 0 {
obj.ctxErr = fmt.Errorf("Etcd: CtxError: CtxRetriesErr: No more retries!")
obj.ctxErr = fmt.Errorf("no more retries due to CtxRetriesErr")
return ctx, obj.ctxErr
}
return ctx, nil
}
if permanentErr, ok := err.(*CtxPermanentErr); ok { // custom permanent error
obj.ctxErr = fmt.Errorf("Etcd: CtxError: Reason: %s", permanentErr.Error())
obj.ctxErr = fmt.Errorf("error due to CtxPermanentErr: %s", permanentErr.Error())
return ctx, obj.ctxErr // quit
}
@@ -627,7 +627,7 @@ func (obj *EmbdEtcd) CtxError(ctx context.Context, err error) (context.Context,
}
if err == grpc.ErrClientConnTimeout { // sometimes caused by "too many colons" misconfiguration
return ctx, fmt.Errorf("Etcd: Error: Misconfiguration: %v", err) // permanent failure?
return ctx, fmt.Errorf("misconfiguration: %v", err) // permanent failure?
}
// this can happen if my client connection shuts down, but without any
@@ -671,7 +671,7 @@ func (obj *EmbdEtcd) CtxError(ctx context.Context, err error) (context.Context,
log.Printf("Etcd: CtxError: Reconnecting...")
if err := obj.Connect(true); err != nil {
defer obj.rLock.Unlock()
obj.ctxErr = fmt.Errorf("Etcd: Permanent connect error: %v", err)
obj.ctxErr = fmt.Errorf("permanent connect error: %v", err)
return ctx, obj.ctxErr
}
if obj.flags.Debug {
@@ -695,7 +695,7 @@ func (obj *EmbdEtcd) CtxError(ctx context.Context, err error) (context.Context,
// if you hit this code path here, please report the unmatched error!
log.Printf("Etcd: CtxError: Unknown error(%T): %+v", err, err)
time.Sleep(1 * time.Second)
obj.ctxErr = fmt.Errorf("Etcd: CtxError: Unknown error!")
obj.ctxErr = fmt.Errorf("unknown CtxError")
return ctx, obj.ctxErr
}
@@ -1672,16 +1672,16 @@ func (obj *EmbdEtcd) StartServer(newCluster bool, peerURLsMap etcdtypes.URLsMap)
case <-obj.server.Server.ReadyNotify(): // we hang here if things are bad
log.Printf("Etcd: StartServer: Done starting server!") // it didn't hang!
case <-time.After(time.Duration(maxStartServerTimeout) * time.Second):
e := fmt.Errorf("Etcd: StartServer: Timeout of %d seconds reached!", maxStartServerTimeout)
log.Printf(e.Error())
e := fmt.Errorf("timeout of %d seconds reached", maxStartServerTimeout)
log.Printf("Etcd: StartServer: %s", e.Error())
obj.server.Server.Stop() // trigger a shutdown
obj.serverwg.Add(1) // add for the DestroyServer()
obj.DestroyServer()
return e
// TODO: should we wait for this notification elsewhere?
case <-obj.server.Server.StopNotify(): // it's going down now...
e := fmt.Errorf("Etcd: StartServer: Received stop notification.")
log.Printf(e.Error())
e := fmt.Errorf("received stop notification")
log.Printf("Etcd: StartServer: %s", e.Error())
obj.server.Server.Stop() // trigger a shutdown
obj.serverwg.Add(1) // add for the DestroyServer()
obj.DestroyServer()
@@ -1734,7 +1734,7 @@ func Nominate(obj *EmbdEtcd, hostname string, urls etcdtypes.URLs) error {
}
if _, err := obj.Txn(nil, ops, nil); err != nil {
return fmt.Errorf("Etcd: Nominate failed!") // exit in progress?
return fmt.Errorf("nominate failed") // exit in progress?
}
return nil
}
@@ -1745,7 +1745,7 @@ func Nominated(obj *EmbdEtcd) (etcdtypes.URLsMap, error) {
path := fmt.Sprintf("/%s/nominated/", NS)
keyMap, err := obj.Get(path, etcd.WithPrefix()) // map[string]string, bool
if err != nil {
return nil, fmt.Errorf("Etcd: Nominated isn't available: %v", err)
return nil, fmt.Errorf("nominated isn't available: %v", err)
}
nominated := make(etcdtypes.URLsMap)
for key, val := range keyMap { // loop through directory of nominated
@@ -1758,7 +1758,7 @@ func Nominated(obj *EmbdEtcd) (etcdtypes.URLsMap, error) {
}
urls, err := etcdtypes.NewURLs(strings.Split(val, ","))
if err != nil {
return nil, fmt.Errorf("Etcd: Nominated: Data format error!: %v", err)
return nil, fmt.Errorf("nominated data format error: %v", err)
}
nominated[name] = urls // add to map
if obj.flags.Debug {
@@ -1786,7 +1786,7 @@ func Volunteer(obj *EmbdEtcd, urls etcdtypes.URLs) error {
}
if _, err := obj.Txn(nil, ops, nil); err != nil {
return fmt.Errorf("Etcd: Volunteering failed!") // exit in progress?
return fmt.Errorf("volunteering failed") // exit in progress?
}
return nil
}
@@ -1800,7 +1800,7 @@ func Volunteers(obj *EmbdEtcd) (etcdtypes.URLsMap, error) {
path := fmt.Sprintf("/%s/volunteers/", NS)
keyMap, err := obj.Get(path, etcd.WithPrefix())
if err != nil {
return nil, fmt.Errorf("Etcd: Volunteers aren't available: %v", err)
return nil, fmt.Errorf("volunteers aren't available: %v", err)
}
volunteers := make(etcdtypes.URLsMap)
for key, val := range keyMap { // loop through directory of volunteers
@@ -1813,7 +1813,7 @@ func Volunteers(obj *EmbdEtcd) (etcdtypes.URLsMap, error) {
}
urls, err := etcdtypes.NewURLs(strings.Split(val, ","))
if err != nil {
return nil, fmt.Errorf("Etcd: Volunteers: Data format error!: %v", err)
return nil, fmt.Errorf("volunteers data format error: %v", err)
}
volunteers[name] = urls // add to map
if obj.flags.Debug {
@@ -1841,7 +1841,7 @@ func AdvertiseEndpoints(obj *EmbdEtcd, urls etcdtypes.URLs) error {
}
if _, err := obj.Txn(nil, ops, nil); err != nil {
return fmt.Errorf("Etcd: Endpoint advertising failed!") // exit in progress?
return fmt.Errorf("endpoint advertising failed") // exit in progress?
}
return nil
}
@@ -1855,7 +1855,7 @@ func Endpoints(obj *EmbdEtcd) (etcdtypes.URLsMap, error) {
path := fmt.Sprintf("/%s/endpoints/", NS)
keyMap, err := obj.Get(path, etcd.WithPrefix())
if err != nil {
return nil, fmt.Errorf("Etcd: Endpoints aren't available: %v", err)
return nil, fmt.Errorf("endpoints aren't available: %v", err)
}
endpoints := make(etcdtypes.URLsMap)
for key, val := range keyMap { // loop through directory of endpoints
@@ -1868,7 +1868,7 @@ func Endpoints(obj *EmbdEtcd) (etcdtypes.URLsMap, error) {
}
urls, err := etcdtypes.NewURLs(strings.Split(val, ","))
if err != nil {
return nil, fmt.Errorf("Etcd: Endpoints: Data format error!: %v", err)
return nil, fmt.Errorf("endpoints data format error: %v", err)
}
endpoints[name] = urls // add to map
if obj.flags.Debug {
@@ -1887,7 +1887,7 @@ func SetHostnameConverged(obj *EmbdEtcd, hostname string, isConverged bool) erro
converged := fmt.Sprintf("/%s/converged/%s", NS, hostname)
op := []etcd.Op{etcd.OpPut(converged, fmt.Sprintf("%t", isConverged))}
if _, err := obj.Txn(nil, op, nil); err != nil { // TODO: do we need a skipConv flag here too?
return fmt.Errorf("Etcd: Set converged failed!") // exit in progress?
return fmt.Errorf("set converged failed") // exit in progress?
}
return nil
}
@@ -1901,7 +1901,7 @@ func HostnameConverged(obj *EmbdEtcd) (map[string]bool, error) {
path := fmt.Sprintf("/%s/converged/", NS)
keyMap, err := obj.ComplexGet(path, true, etcd.WithPrefix()) // don't un-converge
if err != nil {
return nil, fmt.Errorf("Etcd: Converged values aren't available: %v", err)
return nil, fmt.Errorf("converged values aren't available: %v", err)
}
converged := make(map[string]bool)
for key, val := range keyMap { // loop through directory...
@@ -1914,7 +1914,7 @@ func HostnameConverged(obj *EmbdEtcd) (map[string]bool, error) {
}
b, err := strconv.ParseBool(val)
if err != nil {
return nil, fmt.Errorf("Etcd: Converged: Data format error!: %v", err)
return nil, fmt.Errorf("converged data format error: %v", err)
}
converged[name] = b // add to map
}
@@ -1946,7 +1946,7 @@ func SetClusterSize(obj *EmbdEtcd, value uint16) error {
key := fmt.Sprintf("/%s/idealClusterSize", NS)
if err := obj.Set(key, strconv.FormatUint(uint64(value), 10)); err != nil {
return fmt.Errorf("Etcd: SetClusterSize failed!") // exit in progress?
return fmt.Errorf("function SetClusterSize failed: %v", err) // exit in progress?
}
return nil
}
@@ -1956,17 +1956,17 @@ func GetClusterSize(obj *EmbdEtcd) (uint16, error) {
key := fmt.Sprintf("/%s/idealClusterSize", NS)
keyMap, err := obj.Get(key)
if err != nil {
return 0, fmt.Errorf("Etcd: GetClusterSize failed: %v", err)
return 0, fmt.Errorf("function GetClusterSize failed: %v", err)
}
val, exists := keyMap[key]
if !exists || val == "" {
return 0, fmt.Errorf("Etcd: GetClusterSize failed: %v", err)
return 0, fmt.Errorf("function GetClusterSize failed: %v", err)
}
v, err := strconv.ParseUint(val, 10, 16)
if err != nil {
return 0, fmt.Errorf("Etcd: GetClusterSize failed: %v", err)
return 0, fmt.Errorf("function GetClusterSize failed: %v", err)
}
return uint16(v), nil
}
@@ -1979,7 +1979,7 @@ func MemberAdd(obj *EmbdEtcd, peerURLs etcdtypes.URLs) (*etcd.MemberAddResponse,
var err error
for {
if obj.exiting { // the exit signal has been sent!
return nil, fmt.Errorf("Exiting...")
return nil, fmt.Errorf("exiting etcd")
}
obj.rLock.RLock()
response, err = obj.client.MemberAdd(ctx, peerURLs.StringSlice())
@@ -2002,7 +2002,7 @@ func MemberRemove(obj *EmbdEtcd, mID uint64) (bool, error) {
ctx := context.Background()
for {
if obj.exiting { // the exit signal has been sent!
return false, fmt.Errorf("Exiting...")
return false, fmt.Errorf("exiting etcd")
}
obj.rLock.RLock()
_, err := obj.client.MemberRemove(ctx, mID)
@@ -2030,7 +2030,7 @@ func Members(obj *EmbdEtcd) (map[uint64]string, error) {
var err error
for {
if obj.exiting { // the exit signal has been sent!
return nil, fmt.Errorf("Exiting...")
return nil, fmt.Errorf("exiting etcd")
}
obj.rLock.RLock()
if obj.flags.Trace {
@@ -2064,7 +2064,7 @@ func Leader(obj *EmbdEtcd) (string, error) {
addresses := obj.LocalhostClientURLs() // heuristic, but probably correct
if len(addresses) == 0 {
// probably a programming error...
return "", fmt.Errorf("Etcd: Leader: Programming error!")
return "", fmt.Errorf("programming error")
}
endpoint := addresses[0].Host // FIXME: arbitrarily picked the first one
@@ -2073,7 +2073,7 @@ func Leader(obj *EmbdEtcd) (string, error) {
var response *etcd.StatusResponse
for {
if obj.exiting { // the exit signal has been sent!
return "", fmt.Errorf("Exiting...")
return "", fmt.Errorf("exiting etcd")
}
obj.rLock.RLock()
@@ -2093,7 +2093,7 @@ func Leader(obj *EmbdEtcd) (string, error) {
return name, nil
}
}
return "", fmt.Errorf("Etcd: Members map is not current!") // not found
return "", fmt.Errorf("members map is not current") // not found
}
// WatchAll returns a channel that outputs a true bool when activity occurs
@@ -2106,7 +2106,7 @@ func WatchAll(obj *EmbdEtcd) chan bool {
// TODO: is this even needed? it used to happen on conn errors
log.Printf("Etcd: Watch: Path: %v", path) // event
if re == nil || re.response.Canceled {
return fmt.Errorf("Etcd: Watch is empty!") // will cause a CtxError+retry
return fmt.Errorf("watch is empty") // will cause a CtxError+retry
}
// we normally need to check if anything changed since the last
// event, since a set (export) with no changes still causes the
@@ -2155,7 +2155,7 @@ func SetResources(obj *EmbdEtcd, hostname string, resourceList []resources.Res)
ifs = append(ifs, etcd.Compare(etcd.Value(path), "=", data)) // desired state
ops = append(ops, etcd.OpPut(path, data))
} else {
return fmt.Errorf("Etcd: SetResources: Error: Can't convert to B64: %v", err)
return fmt.Errorf("can't convert to B64: %v", err)
}
}
@@ -2208,7 +2208,7 @@ func GetResources(obj *EmbdEtcd, hostnameFilter, kindFilter []string) ([]resourc
resourceList := []resources.Res{}
keyMap, err := obj.Get(path, etcd.WithPrefix(), etcd.WithSort(etcd.SortByKey, etcd.SortAscend))
if err != nil {
return nil, fmt.Errorf("Etcd: GetResources: Error: Could not get resources: %v", err)
return nil, fmt.Errorf("could not get resources: %v", err)
}
for key, val := range keyMap {
if !strings.HasPrefix(key, path) { // sanity check
@@ -2217,14 +2217,14 @@ func GetResources(obj *EmbdEtcd, hostnameFilter, kindFilter []string) ([]resourc
str := strings.Split(key[len(path):], "/")
if len(str) != 4 {
return nil, fmt.Errorf("Etcd: GetResources: Error: Unexpected chunk count!")
return nil, fmt.Errorf("unexpected chunk count")
}
hostname, r, kind, name := str[0], str[1], str[2], str[3]
if r != "resources" {
return nil, fmt.Errorf("Etcd: GetResources: Error: Unexpected chunk pattern!")
return nil, fmt.Errorf("unexpected chunk pattern")
}
if kind == "" {
return nil, fmt.Errorf("Etcd: GetResources: Error: Unexpected kind chunk!")
return nil, fmt.Errorf("unexpected kind chunk")
}
// FIXME: ideally this would be a server side filter instead!
@@ -2242,7 +2242,7 @@ func GetResources(obj *EmbdEtcd, hostnameFilter, kindFilter []string) ([]resourc
log.Printf("Etcd: Get: (Hostname, Kind, Name): (%s, %s, %s)", hostname, kind, name)
resourceList = append(resourceList, obj)
} else {
return nil, fmt.Errorf("Etcd: GetResources: Error: Can't convert from B64: %v", err)
return nil, fmt.Errorf("can't convert from B64: %v", err)
}
}
return resourceList, nil
@@ -2270,11 +2270,11 @@ func ApplyDeltaEvents(re *RE, urlsmap etcdtypes.URLsMap) (etcdtypes.URLsMap, err
case etcd.EventTypePut:
val := bytes.NewBuffer(event.Kv.Value).String()
if val == "" {
return nil, fmt.Errorf("Etcd: ApplyDeltaEvents: Value is empty!")
return nil, fmt.Errorf("value in ApplyDeltaEvents is empty")
}
urls, err := etcdtypes.NewURLs(strings.Split(val, ","))
if err != nil {
return nil, fmt.Errorf("Etcd: ApplyDeltaEvents: Format error: %v", err)
return nil, fmt.Errorf("format error in ApplyDeltaEvents: %v", err)
}
urlsmap[key] = urls // add to map
@@ -2291,7 +2291,7 @@ func ApplyDeltaEvents(re *RE, urlsmap etcdtypes.URLsMap) (etcdtypes.URLsMap, err
delete(urlsmap, key)
default:
return nil, fmt.Errorf("Etcd: ApplyDeltaEvents: Error: Unknown event: %+v", event.Type)
return nil, fmt.Errorf("unknown event in ApplyDeltaEvents: %+v", event.Type)
}
}
return urlsmap, nil

View File

@@ -22,14 +22,14 @@ import (
"fmt"
)
//go:generate stringer -type=EventName -output=eventname_stringer.go
//go:generate stringer -type=Kind -output=kind_stringer.go
// EventName represents the type of event being passed.
type EventName int
// Kind represents the type of event being passed.
type Kind int
// The different event names are used in different contexts.
// The different event kinds are used in different contexts.
const (
EventNil EventName = iota
EventNil Kind = iota
EventExit
EventStart
EventPause
@@ -43,7 +43,7 @@ type Resp chan error
// Event is the main struct that stores event information and responses.
type Event struct {
Name EventName
Kind Kind
Resp Resp // channel to send an ack response on, nil to skip
//Wg *sync.WaitGroup // receiver barrier to Wait() for everyone else on
Err error // store an error in our event

View File

@@ -40,10 +40,10 @@ func NewMyGAPI(data gapi.Data, name string, interval uint) (*MyGAPI, error) {
// Init initializes the MyGAPI struct.
func (obj *MyGAPI) Init(data gapi.Data) error {
if obj.initialized {
return fmt.Errorf("Already initialized!")
return fmt.Errorf("already initialized")
}
if obj.Name == "" {
return fmt.Errorf("The graph name must be specified!")
return fmt.Errorf("the graph name must be specified")
}
obj.data = data // store for later
obj.closeChan = make(chan struct{})
@@ -59,7 +59,7 @@ func (obj *MyGAPI) Graph() (*pgraph.Graph, error) {
n1, err := resources.NewNoopRes("noop1")
if err != nil {
return nil, fmt.Errorf("Can't create resource: %v", err)
return nil, fmt.Errorf("can't create resource: %v", err)
}
// we can still build a graph via the yaml method
@@ -168,7 +168,7 @@ func Run() error {
return
}
log.Println("Interrupted by signal")
obj.Exit(fmt.Errorf("Killed by %v", sig))
obj.Exit(fmt.Errorf("killed by %v", sig))
return
case <-exit:
return

View File

@@ -42,10 +42,10 @@ func NewMyGAPI(data gapi.Data, name string, interval uint, count uint) (*MyGAPI,
// Init initializes the MyGAPI struct.
func (obj *MyGAPI) Init(data gapi.Data) error {
if obj.initialized {
return fmt.Errorf("Already initialized!")
return fmt.Errorf("already initialized")
}
if obj.Name == "" {
return fmt.Errorf("The graph name must be specified!")
return fmt.Errorf("the graph name must be specified")
}
obj.data = data // store for later
obj.closeChan = make(chan struct{})
@@ -64,7 +64,7 @@ func (obj *MyGAPI) Graph() (*pgraph.Graph, error) {
for i := uint(0); i < obj.Count; i++ {
n, err := resources.NewNoopRes(fmt.Sprintf("noop%d", i))
if err != nil {
return nil, fmt.Errorf("Can't create resource: %v", err)
return nil, fmt.Errorf("can't create resource: %v", err)
}
v := pgraph.NewVertex(n)
g.AddVertex(v)
@@ -162,7 +162,7 @@ func Run(count uint) error {
return
}
log.Println("Interrupted by signal")
obj.Exit(fmt.Errorf("Killed by %v", sig))
obj.Exit(fmt.Errorf("killed by %v", sig))
return
case <-exit:
return

View File

@@ -41,10 +41,10 @@ func NewMyGAPI(data gapi.Data, name string, interval uint) (*MyGAPI, error) {
// Init initializes the MyGAPI struct.
func (obj *MyGAPI) Init(data gapi.Data) error {
if obj.initialized {
return fmt.Errorf("Already initialized!")
return fmt.Errorf("already initialized")
}
if obj.Name == "" {
return fmt.Errorf("The graph name must be specified!")
return fmt.Errorf("the graph name must be specified")
}
obj.data = data // store for later
obj.closeChan = make(chan struct{})
@@ -217,7 +217,7 @@ func Run() error {
return
}
log.Println("Interrupted by signal")
obj.Exit(fmt.Errorf("Killed by %v", sig))
obj.Exit(fmt.Errorf("killed by %v", sig))
return
case <-exit:
return

View File

@@ -55,17 +55,17 @@ func run(c *cli.Context) error {
if _ = c.String("code"); c.IsSet("code") {
if obj.GAPI != nil {
return fmt.Errorf("Can't combine code GAPI with existing GAPI.")
return fmt.Errorf("can't combine code GAPI with existing GAPI")
}
// TODO: implement DSL GAPI
//obj.GAPI = &dsl.GAPI{
// Code: &s,
//}
return fmt.Errorf("The Code GAPI is not implemented yet!") // TODO: DSL
return fmt.Errorf("the Code GAPI is not implemented yet") // TODO: DSL
}
if y := c.String("yaml"); c.IsSet("yaml") {
if obj.GAPI != nil {
return fmt.Errorf("Can't combine YAML GAPI with existing GAPI.")
return fmt.Errorf("can't combine YAML GAPI with existing GAPI")
}
obj.GAPI = &yamlgraph.GAPI{
File: &y,
@@ -73,7 +73,7 @@ func run(c *cli.Context) error {
}
if p := c.String("puppet"); c.IsSet("puppet") {
if obj.GAPI != nil {
return fmt.Errorf("Can't combine puppet GAPI with existing GAPI.")
return fmt.Errorf("can't combine puppet GAPI with existing GAPI")
}
obj.GAPI = &puppet.GAPI{
PuppetParam: &p,
@@ -135,7 +135,7 @@ func run(c *cli.Context) error {
return
}
log.Println("Interrupted by signal")
obj.Exit(fmt.Errorf("Killed by %v", sig))
obj.Exit(fmt.Errorf("killed by %v", sig))
return
case <-exit:
return
@@ -155,7 +155,7 @@ func CLI(program, version string, flags Flags) error {
// test for sanity
if program == "" || version == "" {
return fmt.Errorf("Program was not compiled correctly. Please see Makefile.")
return fmt.Errorf("program was not compiled correctly, see Makefile")
}
app := cli.NewApp()
app.Name = program // App.name and App.version pass these values through

View File

@@ -104,11 +104,11 @@ type Main struct {
func (obj *Main) Init() error {
if obj.Program == "" || obj.Version == "" {
return fmt.Errorf("You must set the Program and Version strings!")
return fmt.Errorf("you must set the Program and Version strings")
}
if obj.Prefix != nil && obj.TmpPrefix {
return fmt.Errorf("Choosing a prefix and the request for a tmp prefix is illogical!")
return fmt.Errorf("choosing a prefix and the request for a tmp prefix is illogical")
}
obj.idealClusterSize = uint16(obj.IdealClusterSize)
@@ -117,7 +117,7 @@ func (obj *Main) Init() error {
}
if obj.idealClusterSize < 1 {
return fmt.Errorf("IdealClusterSize should be at least one!")
return fmt.Errorf("the IdealClusterSize should be at least one")
}
if obj.NoServer && len(obj.Remotes) > 0 {
@@ -125,19 +125,19 @@ func (obj *Main) Init() error {
// here, so if we're okay with every remote graph running in an
// isolated mode, then this is okay. Improve on this if there's
// someone who really wants to be able to do this.
return fmt.Errorf("The Server is required when using Remotes!")
return fmt.Errorf("the Server is required when using Remotes")
}
if obj.CConns < 0 {
return fmt.Errorf("The CConns value should be at least zero!")
return fmt.Errorf("the CConns value should be at least zero")
}
if obj.ConvergedTimeout >= 0 && obj.CConns > 0 && len(obj.Remotes) > int(obj.CConns) {
return fmt.Errorf("You can't converge if you have more remotes than available connections!")
return fmt.Errorf("you can't converge if you have more remotes than available connections")
}
if obj.Depth < 0 { // user should not be using this argument manually
return fmt.Errorf("Negative values for Depth are not permitted!")
return fmt.Errorf("negative values for Depth are not permitted")
}
// transform the url list inputs into etcd typed lists
@@ -146,19 +146,19 @@ func (obj *Main) Init() error {
util.FlattenListWithSplit(obj.Seeds, []string{",", ";", " "}),
)
if err != nil && len(obj.Seeds) > 0 {
return fmt.Errorf("Seeds didn't parse correctly!")
return fmt.Errorf("the Seeds didn't parse correctly")
}
obj.clientURLs, err = etcdtypes.NewURLs(
util.FlattenListWithSplit(obj.ClientURLs, []string{",", ";", " "}),
)
if err != nil && len(obj.ClientURLs) > 0 {
return fmt.Errorf("ClientURLs didn't parse correctly!")
return fmt.Errorf("the ClientURLs didn't parse correctly")
}
obj.serverURLs, err = etcdtypes.NewURLs(
util.FlattenListWithSplit(obj.ServerURLs, []string{",", ";", " "}),
)
if err != nil && len(obj.ServerURLs) > 0 {
return fmt.Errorf("ServerURLs didn't parse correctly!")
return fmt.Errorf("the ServerURLs didn't parse correctly")
}
obj.exit = make(chan error)
@@ -198,10 +198,10 @@ func (obj *Main) Run() error {
if h := obj.Hostname; h != nil && *h != "" { // override by cli
hostname = *h
} else if err != nil {
return errwrap.Wrapf(err, "Can't get default hostname!")
return errwrap.Wrapf(err, "can't get default hostname")
}
if hostname == "" { // safety check
return fmt.Errorf("Hostname cannot be empty!")
return fmt.Errorf("hostname cannot be empty")
}
var prefix = fmt.Sprintf("/var/lib/%s/", obj.Program) // default prefix
@@ -213,18 +213,18 @@ func (obj *Main) Run() error {
if obj.TmpPrefix || obj.AllowTmpPrefix {
var err error
if prefix, err = ioutil.TempDir("", obj.Program+"-"+hostname+"-"); err != nil {
return fmt.Errorf("Main: Error: Can't create temporary prefix!")
return fmt.Errorf("can't create temporary prefix")
}
log.Println("Main: Warning: Working prefix directory is temporary!")
} else {
return fmt.Errorf("Main: Error: Can't create prefix!")
return fmt.Errorf("can't create prefix")
}
}
log.Printf("Main: Working prefix is: %s", prefix)
pgraphPrefix := fmt.Sprintf("%s/", path.Join(prefix, "pgraph")) // pgraph namespace
if err := os.MkdirAll(pgraphPrefix, 0770); err != nil {
return errwrap.Wrapf(err, "Can't create pgraph prefix")
return errwrap.Wrapf(err, "can't create pgraph prefix")
}
var prom *prometheus.Prometheus
@@ -233,19 +233,19 @@ func (obj *Main) Run() error {
Listen: obj.PrometheusListen,
}
if err := prom.Init(); err != nil {
return errwrap.Wrapf(err, "Can't create initiate Prometheus instance")
return errwrap.Wrapf(err, "can't create initiate Prometheus instance")
}
log.Printf("Main: Prometheus: Starting instance on %s", prom.Listen)
if err := prom.Start(); err != nil {
return errwrap.Wrapf(err, "Can't start initiate Prometheus instance")
return errwrap.Wrapf(err, "can't start initiate Prometheus instance")
}
}
if !obj.NoPgp {
pgpPrefix := fmt.Sprintf("%s/", path.Join(prefix, "pgp"))
if err := os.MkdirAll(pgpPrefix, 0770); err != nil {
return errwrap.Wrapf(err, "Can't create pgp prefix")
return errwrap.Wrapf(err, "can't create pgp prefix")
}
pgpKeyringPath := path.Join(pgpPrefix, pgp.DefaultKeyringFile) // default path
@@ -256,7 +256,7 @@ func (obj *Main) Run() error {
var err error
if obj.pgpKeys, err = pgp.Import(pgpKeyringPath); err != nil && !os.IsNotExist(err) {
return errwrap.Wrapf(err, "Can't import pgp key")
return errwrap.Wrapf(err, "can't import pgp key")
}
if obj.pgpKeys == nil {
@@ -268,17 +268,17 @@ func (obj *Main) Run() error {
name, comment, email, err := pgp.ParseIdentity(identity)
if err != nil {
return errwrap.Wrapf(err, "Can't parse user string")
return errwrap.Wrapf(err, "can't parse user string")
}
// TODO: Make hash configurable
if obj.pgpKeys, err = pgp.Generate(name, comment, email, nil); err != nil {
return errwrap.Wrapf(err, "Can't creating pgp key")
return errwrap.Wrapf(err, "can't create pgp key")
}
if err := obj.pgpKeys.SaveKey(pgpKeyringPath); err != nil {
return errwrap.Wrapf(err, "Can't save pgp key")
return errwrap.Wrapf(err, "can't save pgp key")
}
}
@@ -325,7 +325,7 @@ func (obj *Main) Run() error {
)
if EmbdEtcd == nil {
// TODO: verify EmbdEtcd is not nil below...
obj.Exit(fmt.Errorf("Main: Etcd: Creation failed!"))
obj.Exit(fmt.Errorf("Main: Etcd: Creation failed"))
} else if err := EmbdEtcd.Startup(); err != nil { // startup (returns when etcd main loop is running)
obj.Exit(fmt.Errorf("Main: Etcd: Startup failed: %v", err))
}
@@ -550,14 +550,14 @@ func (obj *Main) Run() error {
if obj.GAPI != nil {
if err := obj.GAPI.Close(); err != nil {
err = errwrap.Wrapf(err, "GAPI closed poorly!")
err = errwrap.Wrapf(err, "the GAPI closed poorly")
reterr = multierr.Append(reterr, err) // list of errors
}
}
configWatcher.Close() // stop sending file changes to remotes
if err := remotes.Exit(); err != nil { // tell all the remote connections to shutdown; waits!
err = errwrap.Wrapf(err, "Remote exited poorly!")
err = errwrap.Wrapf(err, "the Remote exited poorly")
reterr = multierr.Append(reterr, err) // list of errors
}
@@ -568,14 +568,14 @@ func (obj *Main) Run() error {
// cleanup etcd main loop last so it can process everything first
if err := EmbdEtcd.Destroy(); err != nil { // shutdown and cleanup etcd
err = errwrap.Wrapf(err, "Etcd exited poorly!")
err = errwrap.Wrapf(err, "embedded Etcd exited poorly")
reterr = multierr.Append(reterr, err) // list of errors
}
if obj.Prometheus {
log.Printf("Main: Prometheus: Stopping instance")
if err := prom.Stop(); err != nil {
err = errwrap.Wrapf(err, "Prometheus instance exited poorly!")
err = errwrap.Wrapf(err, "the Prometheus instance exited poorly")
reterr = multierr.Append(reterr, err)
}
}

View File

@@ -54,7 +54,7 @@ func (ag *baseGrouper) name() string {
// the name method is the only exception: call it any time without side effects!
func (ag *baseGrouper) init(g *Graph) error {
if ag.graph != nil {
return fmt.Errorf("The init method has already been called!")
return fmt.Errorf("the init method has already been called")
}
ag.graph = g // pointer
ag.vertices = ag.graph.GetVerticesSorted() // cache in deterministic order!
@@ -108,27 +108,27 @@ func (ag *baseGrouper) vertexNext() (v1, v2 *Vertex, err error) {
func (ag *baseGrouper) vertexCmp(v1, v2 *Vertex) error {
if v1 == nil || v2 == nil {
return fmt.Errorf("Vertex is nil!")
return fmt.Errorf("the vertex is nil")
}
if v1 == v2 { // skip yourself
return fmt.Errorf("Vertices are the same!")
return fmt.Errorf("the vertices are the same")
}
if v1.Kind() != v2.Kind() { // we must group similar kinds
// TODO: maybe future resources won't need this limitation?
return fmt.Errorf("The two resources aren't the same kind!")
return fmt.Errorf("the two resources aren't the same kind")
}
// someone doesn't want to group!
if !v1.Meta().AutoGroup || !v2.Meta().AutoGroup {
return fmt.Errorf("One of the autogroup flags is false!")
return fmt.Errorf("one of the autogroup flags is false")
}
if v1.Res.IsGrouped() { // already grouped!
return fmt.Errorf("Already grouped!")
return fmt.Errorf("already grouped")
}
if len(v2.Res.GetGroup()) > 0 { // already has children grouped!
return fmt.Errorf("Already has groups!")
return fmt.Errorf("already has groups")
}
if !v1.Res.GroupCmp(v2.Res) { // resource groupcmp failed!
return fmt.Errorf("The GroupCmp failed!")
return fmt.Errorf("the GroupCmp failed")
}
return nil // success
}
@@ -173,7 +173,7 @@ func (ag *nonReachabilityGrouper) vertexNext() (v1, v2 *Vertex, err error) {
for {
v1, v2, err = ag.baseGrouper.vertexNext() // get all iterable pairs
if err != nil {
log.Fatalf("Error running autoGroup(vertexNext): %v", err)
log.Fatalf("error running autoGroup(vertexNext): %v", err)
}
if v1 != v2 { // ignore self cmp early (perf optimization)
@@ -187,7 +187,7 @@ func (ag *nonReachabilityGrouper) vertexNext() (v1, v2 *Vertex, err error) {
// if we got here, it means we're skipping over this candidate!
if ok, err := ag.baseGrouper.vertexTest(false); err != nil {
log.Fatalf("Error running autoGroup(vertexTest): %v", err)
log.Fatalf("error running autoGroup(vertexTest): %v", err)
} else if !ok {
return nil, nil, nil // done!
}
@@ -284,7 +284,7 @@ func (g *Graph) VertexMerge(v1, v2 *Vertex, vertexMergeFn func(*Vertex, *Vertex)
// 5) creation of a cyclic graph should throw an error
if _, err := g.TopologicalSort(); err != nil { // am i a dag or not?
return errwrap.Wrapf(err, "TopologicalSort failed") // not a dag
return errwrap.Wrapf(err, "the TopologicalSort failed") // not a dag
}
return nil // success
}
@@ -295,14 +295,14 @@ func (g *Graph) autoGroup(ag AutoGrouper) chan string {
go func(strch chan string) {
strch <- fmt.Sprintf("Compile: Grouping: Algorithm: %v...", ag.name())
if err := ag.init(g); err != nil {
log.Fatalf("Error running autoGroup(init): %v", err)
log.Fatalf("error running autoGroup(init): %v", err)
}
for {
var v, w *Vertex
v, w, err := ag.vertexNext() // get pair to compare
if err != nil {
log.Fatalf("Error running autoGroup(vertexNext): %v", err)
log.Fatalf("error running autoGroup(vertexNext): %v", err)
}
merged := false
// save names since they change during the runs
@@ -325,7 +325,7 @@ func (g *Graph) autoGroup(ag AutoGrouper) chan string {
// did these get used?
if ok, err := ag.vertexTest(merged); err != nil {
log.Fatalf("Error running autoGroup(vertexTest): %v", err)
log.Fatalf("error running autoGroup(vertexTest): %v", err)
} else if !ok {
break // done!
}

View File

@@ -69,11 +69,11 @@ func (g *Graph) ExecGraphviz(program, filename string) error {
switch program {
case "dot", "neato", "twopi", "circo", "fdp":
default:
return fmt.Errorf("Invalid graphviz program selected!")
return fmt.Errorf("invalid graphviz program selected")
}
if filename == "" {
return fmt.Errorf("No filename given!")
return fmt.Errorf("no filename given")
}
// run as a normal user if possible when run with sudo
@@ -82,18 +82,18 @@ func (g *Graph) ExecGraphviz(program, filename string) error {
err := ioutil.WriteFile(filename, []byte(g.Graphviz()), 0644)
if err != nil {
return fmt.Errorf("Error writing to filename!")
return fmt.Errorf("error writing to filename")
}
if err1 == nil && err2 == nil {
if err := os.Chown(filename, uid, gid); err != nil {
return fmt.Errorf("Error changing file owner!")
return fmt.Errorf("error changing file owner")
}
}
path, err := exec.LookPath(program)
if err != nil {
return fmt.Errorf("Graphviz is missing!")
return fmt.Errorf("the Graphviz program is missing")
}
out := fmt.Sprintf("%s.png", filename)
@@ -108,7 +108,7 @@ func (g *Graph) ExecGraphviz(program, filename string) error {
}
_, err = cmd.Output()
if err != nil {
return fmt.Errorf("Error writing to image!")
return fmt.Errorf("error writing to image")
}
return nil
}

View File

@@ -493,7 +493,7 @@ func (g *Graph) TopologicalSort() ([]*Vertex, error) { // kahn's algorithm
if in > 0 {
for n := range g.Adjacency[c] {
if remaining[n] > 0 {
return nil, fmt.Errorf("Not a dag!")
return nil, fmt.Errorf("not a dag")
}
}
}
@@ -607,7 +607,7 @@ func (g *Graph) GraphSync(oldGraph *Graph) (*Graph, error) {
vertex2, exists2 := lookup[v2]
if !exists1 || !exists2 { // no match found, bug?
//if vertex1 == nil || vertex2 == nil { // no match found
return nil, fmt.Errorf("New vertices weren't found!") // programming error
return nil, fmt.Errorf("new vertices weren't found") // programming error
}
edge, exists := oldGraph.Adjacency[vertex1][vertex2]

View File

@@ -45,11 +45,11 @@ func TestPgraphT1(t *testing.T) {
G := NewGraph("g1")
if i := G.NumVertices(); i != 0 {
t.Errorf("Should have 0 vertices instead of: %d.", i)
t.Errorf("should have 0 vertices instead of: %d", i)
}
if i := G.NumEdges(); i != 0 {
t.Errorf("Should have 0 edges instead of: %d.", i)
t.Errorf("should have 0 edges instead of: %d", i)
}
v1 := NV("v1")
@@ -58,11 +58,11 @@ func TestPgraphT1(t *testing.T) {
G.AddEdge(v1, v2, e1)
if i := G.NumVertices(); i != 2 {
t.Errorf("Should have 2 vertices instead of: %d.", i)
t.Errorf("should have 2 vertices instead of: %d", i)
}
if i := G.NumEdges(); i != 1 {
t.Errorf("Should have 1 edges instead of: %d.", i)
t.Errorf("should have 1 edges instead of: %d", i)
}
}
@@ -89,7 +89,7 @@ func TestPgraphT2(t *testing.T) {
G.AddEdge(v5, v6, e5)
if i := G.NumVertices(); i != 6 {
t.Errorf("Should have 6 vertices instead of: %d.", i)
t.Errorf("should have 6 vertices instead of: %d", i)
}
}
@@ -117,19 +117,19 @@ func TestPgraphT3(t *testing.T) {
//G.AddEdge(v6, v4, e6)
out1 := G.DFS(v1)
if i := len(out1); i != 3 {
t.Errorf("Should have 3 vertices instead of: %d.", i)
t.Errorf("Found: %v", out1)
t.Errorf("should have 3 vertices instead of: %d", i)
t.Errorf("found: %v", out1)
for _, v := range out1 {
t.Errorf("Value: %v", v.GetName())
t.Errorf("value: %v", v.GetName())
}
}
out2 := G.DFS(v4)
if i := len(out2); i != 3 {
t.Errorf("Should have 3 vertices instead of: %d.", i)
t.Errorf("Found: %v", out1)
t.Errorf("should have 3 vertices instead of: %d", i)
t.Errorf("found: %v", out1)
for _, v := range out1 {
t.Errorf("Value: %v", v.GetName())
t.Errorf("value: %v", v.GetName())
}
}
}
@@ -149,10 +149,10 @@ func TestPgraphT4(t *testing.T) {
out := G.DFS(v1)
if i := len(out); i != 3 {
t.Errorf("Should have 3 vertices instead of: %d.", i)
t.Errorf("Found: %v", out)
t.Errorf("should have 3 vertices instead of: %d", i)
t.Errorf("found: %v", out)
for _, v := range out {
t.Errorf("Value: %v", v.GetName())
t.Errorf("value: %v", v.GetName())
}
}
}
@@ -182,7 +182,7 @@ func TestPgraphT5(t *testing.T) {
save := []*Vertex{v1, v2, v3}
out := G.FilterGraph("new g5", save)
if i := out.NumVertices(); i != 3 {
t.Errorf("Should have 3 vertices instead of: %d.", i)
t.Errorf("should have 3 vertices instead of: %d", i)
}
}
@@ -219,7 +219,7 @@ func TestPgraphT6(t *testing.T) {
}
if i := HeisenbergGraphCount(graphs); i != 2 {
t.Errorf("Should have 2 graphs instead of: %d.", i)
t.Errorf("should have 2 graphs instead of: %d", i)
}
}
@@ -237,31 +237,31 @@ func TestPgraphT7(t *testing.T) {
G.AddEdge(v3, v1, e3)
if i := G.NumVertices(); i != 3 {
t.Errorf("Should have 3 vertices instead of: %d.", i)
t.Errorf("should have 3 vertices instead of: %d", i)
}
G.DeleteVertex(v2)
if i := G.NumVertices(); i != 2 {
t.Errorf("Should have 2 vertices instead of: %d.", i)
t.Errorf("should have 2 vertices instead of: %d", i)
}
G.DeleteVertex(v1)
if i := G.NumVertices(); i != 1 {
t.Errorf("Should have 1 vertices instead of: %d.", i)
t.Errorf("should have 1 vertices instead of: %d", i)
}
G.DeleteVertex(v3)
if i := G.NumVertices(); i != 0 {
t.Errorf("Should have 0 vertices instead of: %d.", i)
t.Errorf("should have 0 vertices instead of: %d", i)
}
G.DeleteVertex(v2) // duplicate deletes don't error...
if i := G.NumVertices(); i != 0 {
t.Errorf("Should have 0 vertices instead of: %d.", i)
t.Errorf("should have 0 vertices instead of: %d", i)
}
}
@@ -271,26 +271,26 @@ func TestPgraphT8(t *testing.T) {
v2 := NV("v2")
v3 := NV("v3")
if VertexContains(v1, []*Vertex{v1, v2, v3}) != true {
t.Errorf("Should be true instead of false.")
t.Errorf("should be true instead of false.")
}
v4 := NV("v4")
v5 := NV("v5")
v6 := NV("v6")
if VertexContains(v4, []*Vertex{v5, v6}) != false {
t.Errorf("Should be false instead of true.")
t.Errorf("should be false instead of true.")
}
v7 := NV("v7")
v8 := NV("v8")
v9 := NV("v9")
if VertexContains(v8, []*Vertex{v7, v8, v9}) != true {
t.Errorf("Should be true instead of false.")
t.Errorf("should be true instead of false.")
}
v1b := NV("v1") // same value, different objects
if VertexContains(v1b, []*Vertex{v1, v2, v3}) != false {
t.Errorf("Should be false instead of true.")
t.Errorf("should be false instead of true.")
}
}
@@ -319,49 +319,49 @@ func TestPgraphT9(t *testing.T) {
indegree := G.InDegree() // map[*Vertex]int
if i := indegree[v1]; i != 0 {
t.Errorf("Indegree of v1 should be 0 instead of: %d.", i)
t.Errorf("indegree of v1 should be 0 instead of: %d", i)
}
if i := indegree[v2]; i != 1 {
t.Errorf("Indegree of v2 should be 1 instead of: %d.", i)
t.Errorf("indegree of v2 should be 1 instead of: %d", i)
}
if i := indegree[v3]; i != 1 {
t.Errorf("Indegree of v3 should be 1 instead of: %d.", i)
t.Errorf("indegree of v3 should be 1 instead of: %d", i)
}
if i := indegree[v4]; i != 2 {
t.Errorf("Indegree of v4 should be 2 instead of: %d.", i)
t.Errorf("indegree of v4 should be 2 instead of: %d", i)
}
if i := indegree[v5]; i != 1 {
t.Errorf("Indegree of v5 should be 1 instead of: %d.", i)
t.Errorf("indegree of v5 should be 1 instead of: %d", i)
}
if i := indegree[v6]; i != 1 {
t.Errorf("Indegree of v6 should be 1 instead of: %d.", i)
t.Errorf("indegree of v6 should be 1 instead of: %d", i)
}
outdegree := G.OutDegree() // map[*Vertex]int
if i := outdegree[v1]; i != 2 {
t.Errorf("Outdegree of v1 should be 2 instead of: %d.", i)
t.Errorf("outdegree of v1 should be 2 instead of: %d", i)
}
if i := outdegree[v2]; i != 1 {
t.Errorf("Outdegree of v2 should be 1 instead of: %d.", i)
t.Errorf("outdegree of v2 should be 1 instead of: %d", i)
}
if i := outdegree[v3]; i != 1 {
t.Errorf("Outdegree of v3 should be 1 instead of: %d.", i)
t.Errorf("outdegree of v3 should be 1 instead of: %d", i)
}
if i := outdegree[v4]; i != 1 {
t.Errorf("Outdegree of v4 should be 1 instead of: %d.", i)
t.Errorf("outdegree of v4 should be 1 instead of: %d", i)
}
if i := outdegree[v5]; i != 1 {
t.Errorf("Outdegree of v5 should be 1 instead of: %d.", i)
t.Errorf("outdegree of v5 should be 1 instead of: %d", i)
}
if i := outdegree[v6]; i != 0 {
t.Errorf("Outdegree of v6 should be 0 instead of: %d.", i)
t.Errorf("outdegree of v6 should be 0 instead of: %d", i)
}
s, err := G.TopologicalSort()
// either possibility is a valid toposort
match := reflect.DeepEqual(s, []*Vertex{v1, v2, v3, v4, v5, v6}) || reflect.DeepEqual(s, []*Vertex{v1, v3, v2, v4, v5, v6})
if err != nil || !match {
t.Errorf("Topological sort failed, error: %v.", err)
t.Errorf("topological sort failed, error: %v", err)
str := "Found:"
for _, v := range s {
str += " " + v.Res.GetName()
@@ -393,7 +393,7 @@ func TestPgraphT10(t *testing.T) {
G.AddEdge(v4, v2, e6) // cycle
if _, err := G.TopologicalSort(); err == nil {
t.Errorf("Topological sort passed, but graph is cyclic!")
t.Errorf("topological sort passed, but graph is cyclic")
}
}
@@ -403,7 +403,7 @@ func TestPgraphReachability0(t *testing.T) {
G := NewGraph("g")
result := G.Reachability(nil, nil)
if result != nil {
t.Logf("Reachability failed!")
t.Logf("reachability failed")
str := "Got:"
for _, v := range result {
str += " " + v.Res.GetName()
@@ -420,7 +420,7 @@ func TestPgraphReachability0(t *testing.T) {
expected := []*Vertex{}
if !reflect.DeepEqual(result, expected) {
t.Logf("Reachability failed!")
t.Logf("reachability failed")
str := "Got:"
for _, v := range result {
str += " " + v.Res.GetName()
@@ -451,7 +451,7 @@ func TestPgraphReachability0(t *testing.T) {
expected := []*Vertex{}
if !reflect.DeepEqual(result, expected) {
t.Logf("Reachability failed!")
t.Logf("reachability failed")
str := "Got:"
for _, v := range result {
str += " " + v.Res.GetName()
@@ -486,7 +486,7 @@ func TestPgraphReachability1(t *testing.T) {
expected := []*Vertex{v1, v2, v3, v4, v5, v6}
if !reflect.DeepEqual(result, expected) {
t.Logf("Reachability failed!")
t.Logf("reachability failed")
str := "Got:"
for _, v := range result {
str += " " + v.Res.GetName()
@@ -523,7 +523,7 @@ func TestPgraphReachability2(t *testing.T) {
// !xor test
if reflect.DeepEqual(result, expected1) == reflect.DeepEqual(result, expected2) {
t.Logf("Reachability failed!")
t.Logf("reachability failed")
str := "Got:"
for _, v := range result {
str += " " + v.Res.GetName()
@@ -558,7 +558,7 @@ func TestPgraphReachability3(t *testing.T) {
expected := []*Vertex{v1, v5, v6}
if !reflect.DeepEqual(result, expected) {
t.Logf("Reachability failed!")
t.Logf("reachability failed")
str := "Got:"
for _, v := range result {
str += " " + v.Res.GetName()
@@ -593,7 +593,7 @@ func TestPgraphReachability4(t *testing.T) {
expected := []*Vertex{v1, v6}
if !reflect.DeepEqual(result, expected) {
t.Logf("Reachability failed!")
t.Logf("reachability failed")
str := "Got:"
for _, v := range result {
str += " " + v.Res.GetName()
@@ -611,19 +611,19 @@ func TestPgraphT11(t *testing.T) {
v6 := NV("v6")
if rev := Reverse([]*Vertex{}); !reflect.DeepEqual(rev, []*Vertex{}) {
t.Errorf("Reverse of vertex slice failed.")
t.Errorf("reverse of vertex slice failed")
}
if rev := Reverse([]*Vertex{v1}); !reflect.DeepEqual(rev, []*Vertex{v1}) {
t.Errorf("Reverse of vertex slice failed.")
t.Errorf("reverse of vertex slice failed")
}
if rev := Reverse([]*Vertex{v1, v2, v3, v4, v5, v6}); !reflect.DeepEqual(rev, []*Vertex{v6, v5, v4, v3, v2, v1}) {
t.Errorf("Reverse of vertex slice failed.")
t.Errorf("reverse of vertex slice failed")
}
if rev := Reverse([]*Vertex{v6, v5, v4, v3, v2, v1}); !reflect.DeepEqual(rev, []*Vertex{v1, v2, v3, v4, v5, v6}) {
t.Errorf("Reverse of vertex slice failed.")
t.Errorf("reverse of vertex slice failed")
}
}
@@ -684,10 +684,10 @@ func ListStrCmp(a, b []string) bool {
// It also compares if grouped element groups are identical
func GraphCmp(g1, g2 *Graph) error {
if n1, n2 := g1.NumVertices(), g2.NumVertices(); n1 != n2 {
return fmt.Errorf("Graph g1 has %d vertices, while g2 has %d.", n1, n2)
return fmt.Errorf("graph g1 has %d vertices, while g2 has %d", n1, n2)
}
if e1, e2 := g1.NumEdges(), g2.NumEdges(); e1 != e2 {
return fmt.Errorf("Graph g1 has %d edges, while g2 has %d.", e1, e2)
return fmt.Errorf("graph g1 has %d edges, while g2 has %d", e1, e2)
}
var m = make(map[*Vertex]*Vertex) // g1 to g2 vertex correspondence
@@ -718,7 +718,7 @@ Loop:
continue Loop
}
}
return fmt.Errorf("Graph g1, has no match in g2 for: %v", v1.GetName())
return fmt.Errorf("fraph g1, has no match in g2 for: %v", v1.GetName())
}
// vertices (and groups) match :)
@@ -727,7 +727,7 @@ Loop:
v2 := m[v1] // lookup in map to get correspondance
// g1.Adjacency[v1] corresponds to g2.Adjacency[v2]
if e1, e2 := len(g1.Adjacency[v1]), len(g2.Adjacency[v2]); e1 != e2 {
return fmt.Errorf("Graph g1, vertex(%v) has %d edges, while g2, vertex(%v) has %d.", v1.GetName(), e1, v2.GetName(), e2)
return fmt.Errorf("graph g1, vertex(%v) has %d edges, while g2, vertex(%v) has %d", v1.GetName(), e1, v2.GetName(), e2)
}
for vv1, ee1 := range g1.Adjacency[v1] {
@@ -754,12 +754,12 @@ Loop:
// does l1 match l2 ?
if !ListStrCmp(l1, l2) { // cmp!
return fmt.Errorf("Graph g1 and g2 don't agree on: %v and %v", vv1.GetName(), vv2.GetName())
return fmt.Errorf("graph g1 and g2 don't agree on: %v and %v", vv1.GetName(), vv2.GetName())
}
// check: (2) ee1 == ee2
if ee1.Name != ee2.Name {
return fmt.Errorf("Graph g1 edge(%v) doesn't match g2 edge(%v)", ee1.Name, ee2.Name)
return fmt.Errorf("graph g1 edge(%v) doesn't match g2 edge(%v)", ee1.Name, ee2.Name)
}
}
}
@@ -1298,9 +1298,9 @@ func TestPgraphGroupingConnected1(t *testing.T) {
func TestDurationAssumptions(t *testing.T) {
var d time.Duration
if (d == 0) != true {
t.Errorf("Empty time.Duration is no longer equal to zero!")
t.Errorf("empty time.Duration is no longer equal to zero")
}
if (d > 0) != false {
t.Errorf("Empty time.Duration is now greater than zero!")
t.Errorf("empty time.Duration is now greater than zero")
}
}

View File

@@ -50,10 +50,10 @@ func NewGAPI(data gapi.Data, puppetParam *string, puppetConf string) (*GAPI, err
// Init initializes the puppet GAPI struct.
func (obj *GAPI) Init(data gapi.Data) error {
if obj.initialized {
return fmt.Errorf("Already initialized!")
return fmt.Errorf("already initialized")
}
if obj.PuppetParam == nil {
return fmt.Errorf("The PuppetParam param must be specified!")
return fmt.Errorf("the PuppetParam param must be specified")
}
obj.data = data // store for later
obj.closeChan = make(chan struct{})
@@ -64,11 +64,11 @@ func (obj *GAPI) Init(data gapi.Data) error {
// Graph returns a current Graph.
func (obj *GAPI) Graph() (*pgraph.Graph, error) {
if !obj.initialized {
return nil, fmt.Errorf("Puppet: GAPI is not initialized!")
return nil, fmt.Errorf("the puppet GAPI is not initialized")
}
config := ParseConfigFromPuppet(*obj.PuppetParam, obj.PuppetConf)
if config == nil {
return nil, fmt.Errorf("Puppet: ParseConfigFromPuppet returned nil!")
return nil, fmt.Errorf("function ParseConfigFromPuppet returned nil")
}
g, err := config.NewGraphFromConfig(obj.data.Hostname, obj.data.World, obj.data.Noop)
return g, err
@@ -80,7 +80,7 @@ func (obj *GAPI) Next() chan error {
return nil
}
puppetChan := func() <-chan time.Time { // helper function
return time.Tick(time.Duration(PuppetInterval(obj.PuppetConf)) * time.Second)
return time.Tick(time.Duration(RefreshInterval(obj.PuppetConf)) * time.Second)
}
ch := make(chan error)
obj.wg.Add(1)
@@ -88,7 +88,7 @@ func (obj *GAPI) Next() chan error {
defer obj.wg.Done()
defer close(ch) // this will run before the obj.wg.Done()
if !obj.initialized {
ch <- fmt.Errorf("Puppet: GAPI is not initialized!")
ch <- fmt.Errorf("the puppet GAPI is not initialized")
return
}
pChan := puppetChan()
@@ -117,7 +117,7 @@ func (obj *GAPI) Next() chan error {
// Close shuts down the Puppet GAPI.
func (obj *GAPI) Close() error {
if !obj.initialized {
return fmt.Errorf("Puppet: GAPI is not initialized!")
return fmt.Errorf("the puppet GAPI is not initialized")
}
close(obj.closeChan)
obj.wg.Wait()

View File

@@ -116,8 +116,8 @@ func ParseConfigFromPuppet(puppetParam, puppetConf string) *yamlgraph.GraphConfi
return &config
}
// PuppetInterval returns the graph refresh interval from the puppet configuration.
func PuppetInterval(puppetConf string) int {
// RefreshInterval returns the graph refresh interval from the puppet configuration.
func RefreshInterval(puppetConf string) int {
if Debug {
log.Printf("Puppet: determining graph refresh interval")
}

View File

@@ -137,7 +137,7 @@ func (obj *RecWatcher) Events() chan Event { return obj.events }
// Watch is the primary listener for this resource and it outputs events.
func (obj *RecWatcher) Watch() error {
if obj.watcher == nil {
return fmt.Errorf("Watcher is not initialized!")
return fmt.Errorf("the watcher is not initialized")
}
patharray := util.PathSplit(obj.safename) // tokenize the path
@@ -170,11 +170,11 @@ func (obj *RecWatcher) Watch() error {
// no space left on device, out of inotify watches
// TODO: consider letting the user fall back to
// polling if they hit this error very often...
return fmt.Errorf("Out of inotify watches: %v", err)
return fmt.Errorf("out of inotify watches: %v", err)
} else if os.IsPermission(err) {
return fmt.Errorf("Permission denied adding a watch: %v", err)
return fmt.Errorf("permission denied adding a watch: %v", err)
}
return fmt.Errorf("Unknown error: %v", err)
return fmt.Errorf("unknown error: %v", err)
}
select {
@@ -289,7 +289,7 @@ func (obj *RecWatcher) Watch() error {
}
case err := <-obj.watcher.Errors:
return fmt.Errorf("Unknown watcher error: %v", err)
return fmt.Errorf("unknown watcher error: %v", err)
case <-obj.exit:
return nil

View File

@@ -705,8 +705,8 @@ type Remotes struct {
exitChan chan struct{} // closes when we should exit
semaphore Semaphore // counting semaphore to limit concurrent connections
hostnames []string // list of hostnames we've seen so far
cuid cv.ConvergerUID // convergerUID for the remote itself
cuids map[string]cv.ConvergerUID // map to each SSH struct with the remote as the key
cuid cv.UID // convergerUID for the remote itself
cuids map[string]cv.UID // map to each SSH struct with the remote as the key
callbackCancelFunc func() // stored callback function cancel function
flags Flags // constant runtime values
@@ -732,7 +732,7 @@ func NewRemotes(clientURLs, remoteURLs []string, noop bool, remotes []string, fi
exitChan: make(chan struct{}),
semaphore: NewSemaphore(int(cConns)),
hostnames: make([]string, len(remotes)),
cuids: make(map[string]cv.ConvergerUID),
cuids: make(map[string]cv.UID),
flags: flags,
}
}

View File

@@ -80,13 +80,13 @@ func (obj *AugeasRes) Default() Res {
// Validate if the params passed in are valid data.
func (obj *AugeasRes) Validate() error {
if !strings.HasPrefix(obj.File, "/") {
return fmt.Errorf("File should start with a slash.")
return fmt.Errorf("the File param should start with a slash")
}
if obj.Lens != "" && !strings.HasSuffix(obj.Lens, ".lns") {
return fmt.Errorf("Lens should have a .lns suffix.")
return fmt.Errorf("the Lens param should have a .lns suffix")
}
if (obj.Lens == "") != (obj.File == "") {
return fmt.Errorf("File and Lens must be specified together.")
return fmt.Errorf("the File and Lens params must be specified together")
}
return obj.BaseRes.Validate()
}

View File

@@ -61,12 +61,12 @@ func (obj *ExecRes) Default() Res {
// Validate if the params passed in are valid data.
func (obj *ExecRes) Validate() error {
if obj.Cmd == "" { // this is the only thing that is really required
return fmt.Errorf("Command can't be empty!")
return fmt.Errorf("command can't be empty")
}
// if we have a watch command, then we don't poll with the if command!
if obj.WatchCmd != "" && obj.PollInt > 0 {
return fmt.Errorf("Don't poll when we have a watch command.")
return fmt.Errorf("don't poll when we have a watch command")
}
return obj.BaseRes.Validate()
@@ -122,7 +122,7 @@ func (obj *ExecRes) Watch() error {
cmdReader, err := cmd.StdoutPipe()
if err != nil {
return errwrap.Wrapf(err, "Error creating StdoutPipe for Cmd")
return errwrap.Wrapf(err, "error creating StdoutPipe for Cmd")
}
scanner := bufio.NewScanner(cmdReader)
@@ -133,7 +133,7 @@ func (obj *ExecRes) Watch() error {
cmd.Process.Kill() // TODO: is this necessary?
}()
if err := cmd.Start(); err != nil {
return errwrap.Wrapf(err, "Error starting Cmd")
return errwrap.Wrapf(err, "error starting Cmd")
}
bufioch, errch = obj.BufioChanScanner(scanner)
@@ -157,10 +157,10 @@ func (obj *ExecRes) Watch() error {
if err == nil { // EOF
// FIXME: add an "if watch command ends/crashes"
// restart or generate error option
return fmt.Errorf("Reached EOF")
return fmt.Errorf("reached EOF")
}
// error reading input?
return errwrap.Wrapf(err, "Unknown error")
return errwrap.Wrapf(err, "unknown error")
case event := <-obj.Events():
if exit, send = obj.ReadEvent(event); exit != nil {
@@ -256,7 +256,7 @@ func (obj *ExecRes) CheckApply(apply bool) (checkOK bool, err error) {
cmd.Stdout = &out
if err := cmd.Start(); err != nil {
return false, errwrap.Wrapf(err, "Error starting Cmd")
return false, errwrap.Wrapf(err, "error starting Cmd")
}
timeout := obj.Timeout
@@ -269,13 +269,13 @@ func (obj *ExecRes) CheckApply(apply bool) (checkOK bool, err error) {
select {
case err := <-done:
if err != nil {
e := errwrap.Wrapf(err, "Error waiting for Cmd")
e := errwrap.Wrapf(err, "error waiting for Cmd")
return false, e
}
case <-util.TimeAfterOrBlock(timeout):
//cmd.Process.Kill() // TODO: is this necessary?
return false, fmt.Errorf("Timeout waiting for Cmd!")
return false, fmt.Errorf("timeout waiting for Cmd")
}
// TODO: if we printed the stdout while the command is running, this

View File

@@ -77,19 +77,19 @@ func (obj *FileRes) Default() Res {
// Validate reports any problems with the struct definition.
func (obj *FileRes) Validate() error {
if obj.Dirname != "" && !strings.HasSuffix(obj.Dirname, "/") {
return fmt.Errorf("Dirname must end with a slash.")
return fmt.Errorf("dirname must end with a slash")
}
if strings.HasPrefix(obj.Basename, "/") {
return fmt.Errorf("Basename must not start with a slash.")
return fmt.Errorf("basename must not start with a slash")
}
if obj.Content != nil && obj.Source != "" {
return fmt.Errorf("Can't specify both Content and Source.")
return fmt.Errorf("can't specify both Content and Source")
}
if obj.isDir && obj.Content != nil { // makes no sense
return fmt.Errorf("Can't specify Content when creating a Dir.")
return fmt.Errorf("can't specify Content when creating a Dir")
}
if obj.Mode != "" {
@@ -138,7 +138,7 @@ func (obj *FileRes) uid() (int, error) {
return strconv.Atoi(u.Uid)
}
return -1, errwrap.Wrapf(err, "Owner lookup error (%s)", obj.Owner)
return -1, errwrap.Wrapf(err, "owner lookup error (%s)", obj.Owner)
}
// Init runs some startup code for this resource.
@@ -207,7 +207,7 @@ func (obj *FileRes) Watch() error {
return nil
}
if err := event.Error; err != nil {
return errwrap.Wrapf(err, "Unknown %s[%s] watcher error", obj.Kind(), obj.GetName())
return errwrap.Wrapf(err, "unknown %s[%s] watcher error", obj.Kind(), obj.GetName())
}
if obj.debug { // don't access event.Body if event.Error isn't nil
log.Printf("%s[%s]: Event(%s): %v", obj.Kind(), obj.GetName(), event.Body.Name, event.Body.Op)
@@ -251,7 +251,7 @@ type FileInfo struct {
// ReadDir reads a directory path, and returns a list of enhanced FileInfo's.
func ReadDir(path string) ([]FileInfo, error) {
if !strings.HasSuffix(path, "/") { // dirs have trailing slashes
return nil, fmt.Errorf("Path must be a directory.")
return nil, fmt.Errorf("path must be a directory")
}
output := []FileInfo{} // my file info
fileInfos, err := ioutil.ReadDir(path)
@@ -265,7 +265,7 @@ func ReadDir(path string) ([]FileInfo, error) {
abs := path + smartPath(fi)
rel, err := filepath.Rel(path, abs) // NOTE: calls Clean()
if err != nil { // shouldn't happen
return nil, errwrap.Wrapf(err, "ReadDir: Unhandled error")
return nil, errwrap.Wrapf(err, "unhandled error in ReadDir")
}
if fi.IsDir() {
rel += "/" // add a trailing slash for dirs
@@ -307,7 +307,7 @@ func (obj *FileRes) fileCheckApply(apply bool, src io.ReadSeeker, dst string, sh
srcFile, isFile := src.(*os.File)
_, isBytes := src.(*bytes.Reader) // supports seeking!
if !isFile && !isBytes {
return "", false, fmt.Errorf("Can't open src as either file or buffer!")
return "", false, fmt.Errorf("can't open src as either file or buffer")
}
var srcStat os.FileInfo
@@ -319,7 +319,7 @@ func (obj *FileRes) fileCheckApply(apply bool, src io.ReadSeeker, dst string, sh
}
// TODO: deal with symlinks
if !srcStat.Mode().IsRegular() { // can't copy non-regular files or dirs
return "", false, fmt.Errorf("Non-regular src file: %s (%q)", srcStat.Name(), srcStat.Mode())
return "", false, fmt.Errorf("non-regular src file: %s (%q)", srcStat.Name(), srcStat.Mode())
}
}
@@ -343,12 +343,12 @@ func (obj *FileRes) fileCheckApply(apply bool, src io.ReadSeeker, dst string, sh
return "", false, nil
}
if !obj.Force {
return "", false, fmt.Errorf("Can't force dir into file: %s", dst)
return "", false, fmt.Errorf("can't force dir into file: %s", dst)
}
cleanDst := path.Clean(dst)
if cleanDst == "" || cleanDst == "/" {
return "", false, fmt.Errorf("Don't want to remove root!") // safety
return "", false, fmt.Errorf("don't want to remove root") // safety
}
// FIXME: respect obj.Recurse here...
// there is a dir here, where we want a file...
@@ -360,7 +360,7 @@ func (obj *FileRes) fileCheckApply(apply bool, src io.ReadSeeker, dst string, sh
} else if err == nil {
if !dstStat.Mode().IsRegular() {
return "", false, fmt.Errorf("Non-regular dst file: %s (%q)", dstStat.Name(), dstStat.Mode())
return "", false, fmt.Errorf("non-regular dst file: %s (%q)", dstStat.Name(), dstStat.Mode())
}
if isFile && os.SameFile(srcStat, dstStat) { // same inode, we're done!
return "", true, nil
@@ -485,7 +485,7 @@ func (obj *FileRes) syncCheckApply(apply bool, src, dst string) (bool, error) {
log.Printf("syncCheckApply: %s -> %s", src, dst)
}
if src == "" || dst == "" {
return false, fmt.Errorf("The src and dst must not be empty!")
return false, fmt.Errorf("the src and dst must not be empty")
}
var checkOK = true
@@ -495,7 +495,7 @@ func (obj *FileRes) syncCheckApply(apply bool, src, dst string) (bool, error) {
dstIsDir := strings.HasSuffix(dst, "/")
if srcIsDir != dstIsDir {
return false, fmt.Errorf("The src and dst must be both either files or directories.")
return false, fmt.Errorf("the src and dst must be both either files or directories")
}
if !srcIsDir && !dstIsDir {
@@ -548,10 +548,10 @@ func (obj *FileRes) syncCheckApply(apply bool, src, dst string) (bool, error) {
if _, ok := smartDst[relPathFile]; ok {
absCleanDst := path.Clean(absDst)
if !obj.Force {
return false, fmt.Errorf("Can't force file into dir: %s", absCleanDst)
return false, fmt.Errorf("can't force file into dir: %s", absCleanDst)
}
if absCleanDst == "" || absCleanDst == "/" {
return false, fmt.Errorf("Don't want to remove root!") // safety
return false, fmt.Errorf("don't want to remove root") // safety
}
log.Printf("syncCheckApply: Removing (force): %s", absCleanDst)
if err := os.Remove(absCleanDst); err != nil {
@@ -596,7 +596,7 @@ func (obj *FileRes) syncCheckApply(apply bool, src, dst string) (bool, error) {
absDst := fileInfo.AbsPath // absolute path (should get removed)
absCleanDst := path.Clean(absDst)
if absCleanDst == "" || absCleanDst == "/" {
return false, fmt.Errorf("Don't want to remove root!") // safety
return false, fmt.Errorf("don't want to remove root") // safety
}
// FIXME: respect obj.Recurse here...
@@ -654,7 +654,7 @@ func (obj *FileRes) contentCheckApply(apply bool) (checkOK bool, _ error) {
// apply portion
if obj.path == "" || obj.path == "/" {
return false, fmt.Errorf("Don't want to remove root!") // safety
return false, fmt.Errorf("don't want to remove root") // safety
}
log.Printf("contentCheckApply: Removing: %s", obj.path)
// FIXME: respect obj.Recurse here...

View File

@@ -64,10 +64,10 @@ func (obj *MsgRes) Validate() error {
invalidCharacters := regexp.MustCompile("[^a-zA-Z0-9_]")
for field := range obj.Fields {
if invalidCharacters.FindString(field) != "" {
return fmt.Errorf("Invalid character in field %s.", field)
return fmt.Errorf("invalid character in field %s", field)
}
if strings.HasPrefix(field, "_") {
return fmt.Errorf("Fields cannot begin with _.")
return fmt.Errorf("fields cannot begin with _")
}
}
return obj.BaseRes.Validate()

View File

@@ -100,13 +100,13 @@ func (obj *NspawnRes) Init() error {
func (obj *NspawnRes) Watch() error {
// this resource depends on systemd ensure that it's running
if !systemdUtil.IsRunningSystemd() {
return fmt.Errorf("Systemd is not running.")
return fmt.Errorf("systemd is not running")
}
// create a private message bus
bus, err := util.SystemBusPrivateUsable()
if err != nil {
return errwrap.Wrapf(err, "Failed to connect to bus")
return errwrap.Wrapf(err, "failed to connect to bus")
}
// add a match rule to match messages going through the message bus
@@ -139,7 +139,7 @@ func (obj *NspawnRes) Watch() error {
} else if event.Name == machineRemoved {
log.Printf("%s[%s]: Machine stopped", obj.Kind(), obj.GetName())
} else {
return fmt.Errorf("Unknown event: %s", event.Name)
return fmt.Errorf("unknown event: %s", event.Name)
}
send = true
obj.StateOK(false) // dirty
@@ -165,13 +165,13 @@ func (obj *NspawnRes) Watch() error {
func (obj *NspawnRes) CheckApply(apply bool) (checkOK bool, err error) {
// this resource depends on systemd ensure that it's running
if !systemdUtil.IsRunningSystemd() {
return false, errors.New("Systemd is not running.")
return false, errors.New("systemd is not running")
}
// connect to org.freedesktop.machine1.Manager
conn, err := machined.New()
if err != nil {
return false, errwrap.Wrapf(err, "Failed to connect to dbus")
return false, errwrap.Wrapf(err, "failed to connect to dbus")
}
// compare the current state with the desired state and perform the
@@ -189,7 +189,7 @@ func (obj *NspawnRes) CheckApply(apply bool) (checkOK bool, err error) {
// error if we need the image ignore if we don't
if _, err = conn.GetImage(obj.GetName()); err != nil && obj.State != stopped {
return false, fmt.Errorf(
"No machine nor image named '%s'",
"no machine nor image named '%s'",
obj.GetName())
}
}
@@ -219,7 +219,7 @@ func (obj *NspawnRes) CheckApply(apply bool) (checkOK bool, err error) {
log.Printf("%s[%s]: Starting machine", obj.Kind(), obj.GetName())
// assume state had to be changed at this point, ignore checkOK
if _, err := obj.svc.CheckApply(apply); err != nil {
return false, errwrap.Wrapf(err, "Nested svc failed")
return false, errwrap.Wrapf(err, "nested svc failed")
}
}
if obj.State == stopped {
@@ -227,7 +227,7 @@ func (obj *NspawnRes) CheckApply(apply bool) (checkOK bool, err error) {
// org.freedesktop.machine1.Manager.KillMachine
log.Printf("%s[%s]: Stopping machine", obj.Kind(), obj.GetName())
if err := conn.TerminateMachine(obj.GetName()); err != nil {
return false, errwrap.Wrapf(err, "Failed to stop machine")
return false, errwrap.Wrapf(err, "failed to stop machine")
}
}

View File

@@ -833,7 +833,7 @@ func FilterPackageIDs(m map[string]*PkPackageIDActionData, packages []string) ([
obj, ok := m[k] // lookup single package
// package doesn't exist, this is an error!
if !ok || !obj.Found || obj.PackageID == "" {
return nil, fmt.Errorf("Can't find package named '%s'.", k)
return nil, fmt.Errorf("can't find package named '%s'", k)
}
result = append(result, obj.PackageID)
}
@@ -848,7 +848,7 @@ func FilterState(m map[string]*PkPackageIDActionData, packages []string, state s
obj, ok := m[k] // lookup single package
// package doesn't exist, this is an error!
if !ok || !obj.Found {
return nil, fmt.Errorf("Can't find package named '%s'.", k)
return nil, fmt.Errorf("can't find package named '%s'", k)
}
var b bool
if state == "installed" {
@@ -865,7 +865,7 @@ func FilterState(m map[string]*PkPackageIDActionData, packages []string, state s
result[k] = b // save
}
if len(pkgs) > 0 {
err = fmt.Errorf("Can't filter non-boolean state on: %v!", strings.Join(pkgs, ","))
err = fmt.Errorf("can't filter non-boolean state on: %v", strings.Join(pkgs, ","))
}
return result, err
}
@@ -877,7 +877,7 @@ func FilterPackageState(m map[string]*PkPackageIDActionData, packages []string,
obj, ok := m[k] // lookup single package
// package doesn't exist, this is an error!
if !ok || !obj.Found {
return nil, fmt.Errorf("Can't find package named '%s'.", k)
return nil, fmt.Errorf("can't find package named '%s'", k)
}
b := false
if state == "installed" && obj.Installed {

View File

@@ -144,11 +144,11 @@ func (obj *PasswordRes) check(value string) error {
return nil
}
if !obj.Saved && length != 0 { // should have no stored password
return fmt.Errorf("Expected empty token only!")
return fmt.Errorf("expected empty token only")
}
if length != obj.Length {
return fmt.Errorf("String length is not %d", obj.Length)
return fmt.Errorf("string length is not %d", obj.Length)
}
Loop:
for i := uint16(0); i < length; i++ {
@@ -158,7 +158,7 @@ Loop:
}
}
// we couldn't find that character, so error!
return fmt.Errorf("Invalid character `%s`", string(value[i]))
return fmt.Errorf("invalid character `%s`", string(value[i]))
}
return nil
}
@@ -187,7 +187,7 @@ func (obj *PasswordRes) Watch() error {
return nil
}
if err := event.Error; err != nil {
return errwrap.Wrapf(err, "Unknown %s[%s] watcher error", obj.Kind(), obj.GetName())
return errwrap.Wrapf(err, "unknown %s[%s] watcher error", obj.Kind(), obj.GetName())
}
send = true
obj.StateOK(false) // dirty

View File

@@ -58,7 +58,7 @@ func (obj *PkgRes) Default() Res {
// Validate checks if the resource data structure was populated correctly.
func (obj *PkgRes) Validate() error {
if obj.State == "" {
return fmt.Errorf("State cannot be empty!")
return fmt.Errorf("state cannot be empty")
}
return obj.BaseRes.Validate()
@@ -73,25 +73,25 @@ func (obj *PkgRes) Init() error {
bus := packagekit.NewBus()
if bus == nil {
return fmt.Errorf("Can't connect to PackageKit bus.")
return fmt.Errorf("can't connect to PackageKit bus")
}
defer bus.Close()
result, err := obj.pkgMappingHelper(bus)
if err != nil {
return errwrap.Wrapf(err, "The pkgMappingHelper failed")
return errwrap.Wrapf(err, "the pkgMappingHelper failed")
}
data, ok := result[obj.Name] // lookup single package (init does just one)
// package doesn't exist, this is an error!
if !ok || !data.Found {
return fmt.Errorf("Can't find package named '%s'.", obj.Name)
return fmt.Errorf("can't find package named '%s'", obj.Name)
}
packageIDs := []string{data.PackageID} // just one for now
filesMap, err := bus.GetFilesByPackageID(packageIDs)
if err != nil {
return errwrap.Wrapf(err, "Can't run GetFilesByPackageID")
return errwrap.Wrapf(err, "can't run GetFilesByPackageID")
}
if files, ok := filesMap[data.PackageID]; ok {
obj.fileList = util.DirifyFileList(files, false)
@@ -106,13 +106,13 @@ func (obj *PkgRes) Init() error {
func (obj *PkgRes) Watch() error {
bus := packagekit.NewBus()
if bus == nil {
return fmt.Errorf("Can't connect to PackageKit bus.")
return fmt.Errorf("can't connect to PackageKit bus")
}
defer bus.Close()
ch, err := bus.WatchChanges()
if err != nil {
return errwrap.Wrapf(err, "Error adding signal match")
return errwrap.Wrapf(err, "error adding signal match")
}
// notify engine that we're running
@@ -189,7 +189,7 @@ func (obj *PkgRes) groupMappingHelper() map[string]string {
for _, x := range g {
pkg, ok := x.(*PkgRes) // convert from Res
if !ok {
log.Fatalf("Grouped member %v is not a %s", x, obj.Kind())
log.Fatalf("grouped member %v is not a %s", x, obj.Kind())
}
result[pkg.Name] = pkg.State
}
@@ -229,13 +229,13 @@ func (obj *PkgRes) CheckApply(apply bool) (checkOK bool, err error) {
bus := packagekit.NewBus()
if bus == nil {
return false, fmt.Errorf("Can't connect to PackageKit bus.")
return false, fmt.Errorf("can't connect to PackageKit bus")
}
defer bus.Close()
result, err := obj.pkgMappingHelper(bus)
if err != nil {
return false, errwrap.Wrapf(err, "The pkgMappingHelper failed")
return false, errwrap.Wrapf(err, "the pkgMappingHelper failed")
}
packageMap := obj.groupMappingHelper() // map[string]string
@@ -248,7 +248,7 @@ func (obj *PkgRes) CheckApply(apply bool) (checkOK bool, err error) {
// eventually we might be able to drop this constraint!
states, err := packagekit.FilterState(result, packageList, obj.State)
if err != nil {
return false, errwrap.Wrapf(err, "The FilterState method failed")
return false, errwrap.Wrapf(err, "the FilterState method failed")
}
data, _ := result[obj.Name] // if above didn't error, we won't either!
validState := util.BoolMapTrue(util.BoolMapValues(states))
@@ -340,7 +340,7 @@ type PkgResAutoEdges struct {
// Next returns the next automatic edge.
func (obj *PkgResAutoEdges) Next() []ResUID {
if obj.testIsNext {
log.Fatal("Expecting a call to Test()")
log.Fatal("expecting a call to Test()")
}
obj.testIsNext = true // set after all the errors paths are past
@@ -368,13 +368,13 @@ func (obj *PkgResAutoEdges) Next() []ResUID {
// Test gets results of the earlier Next() call, & returns if we should continue!
func (obj *PkgResAutoEdges) Test(input []bool) bool {
if !obj.testIsNext {
log.Fatal("Expecting a call to Next()")
log.Fatal("expecting a call to Next()")
}
// ack the svcUID's...
if x := obj.svcUIDs; len(x) > 0 {
if y := len(x); y != len(input) {
log.Fatalf("Expecting %d value(s)!", y)
log.Fatalf("expecting %d value(s)", y)
}
obj.svcUIDs = []ResUID{} // empty
obj.testIsNext = false
@@ -383,7 +383,7 @@ func (obj *PkgResAutoEdges) Test(input []bool) bool {
count := len(obj.fileList)
if count != len(input) {
log.Fatalf("Expecting %d value(s)!", count)
log.Fatalf("expecting %d value(s)", count)
}
obj.testIsNext = false // set after all the errors paths are past

View File

@@ -144,11 +144,11 @@ type Base interface {
Setup()
Reset()
Converger() converger.Converger
ConvergerUIDs() (converger.ConvergerUID, converger.ConvergerUID, converger.ConvergerUID)
ConvergerUIDs() (converger.UID, converger.UID, converger.UID)
GetState() ResState
SetState(ResState)
Event() error
SendEvent(event.EventName, error) error
SendEvent(event.Kind, error) error
ReadEvent(*event.Event) (*error, bool)
Refresh() bool // is there a pending refresh to run?
SetRefresh(bool) // set the refresh state of this resource
@@ -206,9 +206,9 @@ type BaseRes struct {
processChan chan *event.Event
converger converger.Converger // converged tracking
cuid converger.ConvergerUID
wcuid converger.ConvergerUID
pcuid converger.ConvergerUID
cuid converger.UID
wcuid converger.UID
pcuid converger.UID
started chan struct{} // closed when worker is started/running
stopped chan struct{} // closed when worker is stopped/exited
@@ -308,7 +308,7 @@ func (obj *BaseRes) Init() error {
log.Printf("%s[%s]: Init()", obj.Kind(), obj.GetName())
}
if obj.kind == "" {
return fmt.Errorf("Resource did not set kind!")
return fmt.Errorf("resource did not set kind")
}
obj.cuid = obj.converger.Register()
@@ -337,7 +337,7 @@ func (obj *BaseRes) Init() error {
//dir, err := obj.VarDir("")
//if err != nil {
// return errwrap.Wrapf(err, "VarDir failed in Init()")
// return errwrap.Wrapf(err, "the VarDir failed in Init()")
//}
// TODO: this StatefulBool implementation could be eventually swappable
//obj.refreshState = &DiskBool{Path: path.Join(dir, refreshPathToken)}
@@ -438,7 +438,7 @@ func (obj *BaseRes) Converger() converger.Converger {
// ConvergerUIDs returns the ConvergerUIDs for the resource. This is called by
// the various methods that need one of these ConvergerUIDs. They are registered
// by the Init method and unregistered on the resource Close.
func (obj *BaseRes) ConvergerUIDs() (cuid converger.ConvergerUID, wcuid converger.ConvergerUID, pcuid converger.ConvergerUID) {
func (obj *BaseRes) ConvergerUIDs() (cuid, wcuid, pcuid converger.UID) {
return obj.cuid, obj.wcuid, obj.pcuid
}
@@ -479,10 +479,10 @@ func (obj *BaseRes) GroupCmp(res Res) bool {
// GroupRes groups resource (arg) into self.
func (obj *BaseRes) GroupRes(res Res) error {
if l := len(res.GetGroup()); l > 0 {
return fmt.Errorf("Res: %v already contains %d grouped resources!", res, l)
return fmt.Errorf("the %v resource already contains %d grouped resources", res, l)
}
if res.IsGrouped() {
return fmt.Errorf("Res: %v is already grouped!", res)
return fmt.Errorf("the %v resource is already grouped", res)
}
obj.grouped = append(obj.grouped, res)
@@ -556,20 +556,20 @@ func (obj *BaseRes) VarDir(extra string) (string, error) {
// Using extra adds additional dirs onto our namespace. An empty extra
// adds no additional directories.
if obj.prefix == "" {
return "", fmt.Errorf("VarDir prefix is empty!")
return "", fmt.Errorf("the VarDir prefix is empty")
}
if obj.Kind() == "" {
return "", fmt.Errorf("VarDir kind is empty!")
return "", fmt.Errorf("the VarDir kind is empty")
}
if obj.GetName() == "" {
return "", fmt.Errorf("VarDir name is empty!")
return "", fmt.Errorf("the VarDir name is empty")
}
// FIXME: is obj.GetName() sufficiently unique to use as a UID here?
uid := obj.GetName()
p := fmt.Sprintf("%s/", path.Join(obj.prefix, obj.Kind(), uid, extra))
if err := os.MkdirAll(p, 0770); err != nil {
return "", errwrap.Wrapf(err, "Can't create prefix for %s[%s]", obj.Kind(), obj.GetName())
return "", errwrap.Wrapf(err, "can't create prefix for %s[%s]", obj.Kind(), obj.GetName())
}
return p, nil
}

View File

@@ -122,13 +122,13 @@ func TestIFF(t *testing.T) {
func TestReadEvent(t *testing.T) {
//res := FileRes{}
//shouldExit := map[event.EventName]bool{
//shouldExit := map[event.Kind]bool{
// event.EventStart: false,
// event.EventPoke: false,
// event.EventBackPoke: false,
// event.EventExit: true,
//}
//shouldPoke := map[event.EventName]bool{
//shouldPoke := map[event.Kind]bool{
// event.EventStart: true,
// event.EventPoke: true,
// event.EventBackPoke: true,
@@ -136,7 +136,7 @@ func TestReadEvent(t *testing.T) {
//}
//for ev := range shouldExit {
// exit, poke := res.ReadEvent(&event.Event{Name: ev})
// exit, poke := res.ReadEvent(&event.Event{Kind: ev})
// if exit != shouldExit[ev] {
// t.Errorf("resource.ReadEvent returned wrong exit flag for a %v event (%v, should be %v)",
// ev, exit, shouldExit[ev])
@@ -152,7 +152,7 @@ func TestReadEvent(t *testing.T) {
// test result when a pause event is followed by start
//go res.SendEvent(event.EventStart, nil)
//exit, poke := res.ReadEvent(&event.Event{Name: event.EventPause})
//exit, poke := res.ReadEvent(&event.Event{Kind: event.EventPause})
//if exit {
// t.Error("resource.ReadEvent returned wrong exit flag for a pause+start event (true, should be false)")
//}
@@ -162,7 +162,7 @@ func TestReadEvent(t *testing.T) {
// test result when a pause event is followed by exit
//go res.SendEvent(event.EventExit, nil)
//exit, poke = res.ReadEvent(&event.Event{Name: event.EventPause})
//exit, poke = res.ReadEvent(&event.Event{Kind: event.EventPause})
//if !exit {
// t.Error("resource.ReadEvent returned wrong exit flag for a pause+start event (false, should be true)")
//}

View File

@@ -36,13 +36,13 @@ func (obj *BaseRes) Event() error {
obj.processLock.Unlock()
return fmt.Errorf("processChan is already closed")
}
obj.processChan <- &event.Event{Name: event.EventNil, Resp: resp} // trigger process
obj.processChan <- &event.Event{Kind: event.EventNil, Resp: resp} // trigger process
obj.processLock.Unlock()
return resp.Wait()
}
// SendEvent pushes an event into the message queue for a particular vertex.
func (obj *BaseRes) SendEvent(ev event.EventName, err error) error {
func (obj *BaseRes) SendEvent(ev event.Kind, err error) error {
if obj.debug {
if err == nil {
log.Printf("%s[%s]: SendEvent(%+v)", obj.Kind(), obj.GetName(), ev)
@@ -56,7 +56,7 @@ func (obj *BaseRes) SendEvent(ev event.EventName, err error) error {
obj.eventsLock.Unlock()
return fmt.Errorf("eventsChan is already closed")
}
obj.eventsChan <- &event.Event{Name: ev, Resp: resp, Err: err}
obj.eventsChan <- &event.Event{Kind: ev, Resp: resp, Err: err}
if ev == event.EventExit {
obj.eventsDone = true
close(obj.eventsChan) // this is where we properly close this channel!
@@ -72,7 +72,7 @@ func (obj *BaseRes) ReadEvent(ev *event.Event) (exit *error, send bool) {
ev.ACK()
err := ev.Error()
switch ev.Name {
switch ev.Kind {
case event.EventStart:
return nil, true
@@ -96,18 +96,18 @@ func (obj *BaseRes) ReadEvent(ev *event.Event) (exit *error, send bool) {
}
e.ACK()
err := e.Error()
if e.Name == event.EventExit {
if e.Kind == event.EventExit {
return &err, false
} else if e.Name == event.EventStart { // eventContinue
} else if e.Kind == event.EventStart { // eventContinue
return nil, false // don't poke on unpause!
}
// if we get a poke event here, it's a bug!
err = fmt.Errorf("%s[%s]: Unknown event: %v, while paused!", obj.Kind(), obj.GetName(), e)
err = fmt.Errorf("%s[%s]: unknown event: %v, while paused", obj.Kind(), obj.GetName(), e)
panic(err) // TODO: return a special sentinel instead?
//return &err, false
}
}
err = fmt.Errorf("Unknown event: %v", ev)
err = fmt.Errorf("unknown event: %v", ev)
panic(err) // TODO: return a special sentinel instead?
//return &err, false
}
@@ -177,7 +177,7 @@ func (obj *BaseRes) SendRecv(res Res) (map[string]bool, error) {
// i think we probably want the same kind, at least for now...
if kind1 != kind2 {
e := fmt.Errorf("Kind mismatch between %s[%s]: %s and %s[%s]: %s", v.Res.Kind(), v.Res.GetName(), kind1, obj.Kind(), obj.GetName(), kind2)
e := fmt.Errorf("kind mismatch between %s[%s]: %s and %s[%s]: %s", v.Res.Kind(), v.Res.GetName(), kind1, obj.Kind(), obj.GetName(), kind2)
err = multierr.Append(err, e) // list of errors
continue
}
@@ -185,21 +185,21 @@ func (obj *BaseRes) SendRecv(res Res) (map[string]bool, error) {
// if the types don't match, we can't use send->recv
// TODO: do we want to relax this for string -> *string ?
if e := TypeCmp(value1, value2); e != nil {
e := errwrap.Wrapf(e, "Type mismatch between %s[%s] and %s[%s]", v.Res.Kind(), v.Res.GetName(), obj.Kind(), obj.GetName())
e := errwrap.Wrapf(e, "type mismatch between %s[%s] and %s[%s]", v.Res.Kind(), v.Res.GetName(), obj.Kind(), obj.GetName())
err = multierr.Append(err, e) // list of errors
continue
}
// if we can't set, then well this is pointless!
if !value2.CanSet() {
e := fmt.Errorf("Can't set %s[%s].%s", obj.Kind(), obj.GetName(), k)
e := fmt.Errorf("can't set %s[%s].%s", obj.Kind(), obj.GetName(), k)
err = multierr.Append(err, e) // list of errors
continue
}
// if we can't interface, we can't compare...
if !value1.CanInterface() || !value2.CanInterface() {
e := fmt.Errorf("Can't interface %s[%s].%s", obj.Kind(), obj.GetName(), k)
e := fmt.Errorf("can't interface %s[%s].%s", obj.Kind(), obj.GetName(), k)
err = multierr.Append(err, e) // list of errors
continue
}
@@ -221,7 +221,7 @@ func (obj *BaseRes) SendRecv(res Res) (map[string]bool, error) {
func TypeCmp(a, b reflect.Value) error {
ta, tb := a.Type(), b.Type()
if ta != tb {
return fmt.Errorf("Type mismatch: %s != %s", ta, tb)
return fmt.Errorf("type mismatch: %s != %s", ta, tb)
}
// NOTE: it seems we don't need to recurse into pointers to sub check!

View File

@@ -55,10 +55,10 @@ func (obj *SvcRes) Default() Res {
// Validate checks if the resource data structure was populated correctly.
func (obj *SvcRes) Validate() error {
if obj.State != "running" && obj.State != "stopped" && obj.State != "" {
return fmt.Errorf("State must be either `running` or `stopped` or undefined.")
return fmt.Errorf("state must be either `running` or `stopped` or undefined")
}
if obj.Startup != "enabled" && obj.Startup != "disabled" && obj.Startup != "" {
return fmt.Errorf("Startup must be either `enabled` or `disabled` or undefined.")
return fmt.Errorf("startup must be either `enabled` or `disabled` or undefined")
}
return obj.BaseRes.Validate()
}
@@ -73,19 +73,19 @@ func (obj *SvcRes) Init() error {
func (obj *SvcRes) Watch() error {
// obj.Name: svc name
if !systemdUtil.IsRunningSystemd() {
return fmt.Errorf("Systemd is not running.")
return fmt.Errorf("systemd is not running")
}
conn, err := systemd.NewSystemdConnection() // needs root access
if err != nil {
return errwrap.Wrapf(err, "Failed to connect to systemd")
return errwrap.Wrapf(err, "failed to connect to systemd")
}
defer conn.Close()
// if we share the bus with others, we will get each others messages!!
bus, err := util.SystemBusPrivateUsable() // don't share the bus connection!
if err != nil {
return errwrap.Wrapf(err, "Failed to connect to bus")
return errwrap.Wrapf(err, "failed to connect to bus")
}
// XXX: will this detect new units?
@@ -185,7 +185,7 @@ func (obj *SvcRes) Watch() error {
obj.StateOK(false) // dirty
case err := <-subErrors:
return errwrap.Wrapf(err, "Unknown %s[%s] error", obj.Kind(), obj.GetName())
return errwrap.Wrapf(err, "unknown %s[%s] error", obj.Kind(), obj.GetName())
case event := <-obj.Events():
if exit, send = obj.ReadEvent(event); exit != nil {
@@ -205,12 +205,12 @@ func (obj *SvcRes) Watch() error {
// input is true. It returns error info and if the state check passed or not.
func (obj *SvcRes) CheckApply(apply bool) (checkOK bool, err error) {
if !systemdUtil.IsRunningSystemd() {
return false, fmt.Errorf("Systemd is not running.")
return false, fmt.Errorf("systemd is not running")
}
conn, err := systemd.NewSystemdConnection() // needs root access
if err != nil {
return false, errwrap.Wrapf(err, "Failed to connect to systemd")
return false, errwrap.Wrapf(err, "failed to connect to systemd")
}
defer conn.Close()
@@ -218,13 +218,13 @@ func (obj *SvcRes) CheckApply(apply bool) (checkOK bool, err error) {
loadstate, err := conn.GetUnitProperty(svc, "LoadState")
if err != nil {
return false, errwrap.Wrapf(err, "Failed to get load state")
return false, errwrap.Wrapf(err, "failed to get load state")
}
// NOTE: we have to compare variants with other variants, they are really strings...
var notFound = (loadstate.Value == dbus.MakeVariant("not-found"))
if notFound {
return false, errwrap.Wrapf(err, "Failed to find svc: %s", svc)
return false, errwrap.Wrapf(err, "failed to find svc: %s", svc)
}
// XXX: check svc "enabled at boot" or not status...
@@ -232,7 +232,7 @@ func (obj *SvcRes) CheckApply(apply bool) (checkOK bool, err error) {
//conn.GetUnitProperties(svc)
activestate, err := conn.GetUnitProperty(svc, "ActiveState")
if err != nil {
return false, errwrap.Wrapf(err, "Failed to get active state")
return false, errwrap.Wrapf(err, "failed to get active state")
}
var running = (activestate.Value == dbus.MakeVariant("active"))
@@ -260,7 +260,7 @@ func (obj *SvcRes) CheckApply(apply bool) (checkOK bool, err error) {
}
if err != nil {
return false, errwrap.Wrapf(err, "Unable to change startup status")
return false, errwrap.Wrapf(err, "unable to change startup status")
}
// XXX: do we need to use a buffered channel here?
@@ -269,7 +269,7 @@ func (obj *SvcRes) CheckApply(apply bool) (checkOK bool, err error) {
if obj.State == "running" {
_, err = conn.StartUnit(svc, "fail", result)
if err != nil {
return false, errwrap.Wrapf(err, "Failed to start unit")
return false, errwrap.Wrapf(err, "failed to start unit")
}
if refresh {
log.Printf("%s[%s]: Skipping reload, due to pending start", obj.Kind(), obj.GetName())
@@ -278,7 +278,7 @@ func (obj *SvcRes) CheckApply(apply bool) (checkOK bool, err error) {
} else if obj.State == "stopped" {
_, err = conn.StopUnit(svc, "fail", result)
if err != nil {
return false, errwrap.Wrapf(err, "Failed to stop unit")
return false, errwrap.Wrapf(err, "failed to stop unit")
}
if refresh {
log.Printf("%s[%s]: Skipping reload, due to pending stop", obj.Kind(), obj.GetName())
@@ -288,10 +288,10 @@ func (obj *SvcRes) CheckApply(apply bool) (checkOK bool, err error) {
status := <-result
if &status == nil {
return false, fmt.Errorf("Systemd service action result is nil")
return false, fmt.Errorf("systemd service action result is nil")
}
if status != "done" {
return false, fmt.Errorf("Unknown systemd return string: %v", status)
return false, fmt.Errorf("unknown systemd return string: %v", status)
}
if refresh { // we need to reload the service
@@ -333,7 +333,7 @@ type SvcResAutoEdges struct {
// Next returns the next automatic edge.
func (obj *SvcResAutoEdges) Next() []ResUID {
if obj.found {
log.Fatal("Shouldn't be called anymore!")
log.Fatal("shouldn't be called anymore!")
}
if len(obj.data) == 0 { // check length for rare scenarios
return nil
@@ -353,7 +353,7 @@ func (obj *SvcResAutoEdges) Test(input []bool) bool {
return false
}
if len(input) != 1 { // in case we get given bad data
log.Fatal("Expecting a single value!")
log.Fatal("expecting a single value")
}
if input[0] { // if a match is found, we're done!
obj.found = true // no more to find!

View File

@@ -129,7 +129,7 @@ func (obj *VirtRes) Validate() error {
func (obj *VirtRes) Init() error {
if !libvirtInitialized {
if err := libvirt.EventRegisterDefaultImpl(); err != nil {
return errwrap.Wrapf(err, "EventRegisterDefaultImpl failed")
return errwrap.Wrapf(err, "method EventRegisterDefaultImpl failed")
}
libvirtInitialized = true
}
@@ -399,11 +399,11 @@ func (obj *VirtRes) Watch() error {
}
} else {
return fmt.Errorf("Unknown %s[%s] guest agent state: %v", obj.Kind(), obj.GetName(), state)
return fmt.Errorf("unknown %s[%s] guest agent state: %v", obj.Kind(), obj.GetName(), state)
}
case err := <-errorChan:
return fmt.Errorf("Unknown %s[%s] libvirt error: %s", obj.Kind(), obj.GetName(), err)
return fmt.Errorf("unknown %s[%s] libvirt error: %s", obj.Kind(), obj.GetName(), err)
case event := <-obj.Events():
if exit, send = obj.ReadEvent(event); exit != nil {
@@ -490,7 +490,7 @@ func (obj *VirtRes) stateCheckApply(apply bool, dom *libvirt.Domain) (bool, erro
}
if domInfo.State == libvirt.DOMAIN_BLOCKED {
// TODO: what should happen?
return false, fmt.Errorf("Domain %s is blocked!", obj.GetName())
return false, fmt.Errorf("domain %s is blocked", obj.GetName())
}
if !apply {
return false, nil

View File

@@ -40,10 +40,10 @@ func NewMyGAPI(data gapi.Data, name string, interval uint) (*MyGAPI, error) {
// Init initializes the MyGAPI struct.
func (obj *MyGAPI) Init(data gapi.Data) error {
if obj.initialized {
return fmt.Errorf("Already initialized!")
return fmt.Errorf("already initialized")
}
if obj.Name == "" {
return fmt.Errorf("The graph name must be specified!")
return fmt.Errorf("the graph name must be specified")
}
obj.data = data // store for later
@@ -164,7 +164,7 @@ func Run() error {
return
}
log.Println("Interrupted by signal")
obj.Exit(fmt.Errorf("Killed by %v", sig))
obj.Exit(fmt.Errorf("killed by %v", sig))
return
case <-exit:
return

View File

@@ -8,7 +8,7 @@ echo running test-golint.sh
# FIXME: test a range of commits, since only the last patch is checked here
PREVIOUS='HEAD^'
CURRENT='HEAD'
THRESHOLD=15 # percent problems per new LOC
THRESHOLD=5 # percent problems per new LOC
XPWD=`pwd`
ROOT="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && cd .. && pwd )" # dir!
cd "${ROOT}" >/dev/null

View File

@@ -49,10 +49,10 @@ func NewGAPI(data gapi.Data, file *string) (*GAPI, error) {
// Init initializes the yamlgraph GAPI struct.
func (obj *GAPI) Init(data gapi.Data) error {
if obj.initialized {
return fmt.Errorf("Already initialized!")
return fmt.Errorf("already initialized")
}
if obj.File == nil {
return fmt.Errorf("The File param must be specified!")
return fmt.Errorf("the File param must be specified")
}
obj.data = data // store for later
obj.closeChan = make(chan struct{})

View File

@@ -86,7 +86,7 @@ func (c *GraphConfig) Parse(data []byte) error {
return err
}
if c.Graph == "" {
return errors.New("Graph config: invalid `graph`")
return errors.New("graph config: invalid graph")
}
return nil
}
@@ -122,7 +122,7 @@ func (c *GraphConfig) NewGraphFromConfig(hostname string, world gapi.World, noop
x := slice.Index(j).Interface()
res, ok := x.(resources.Res) // convert to Res type
if !ok {
return nil, fmt.Errorf("Config: Error: Can't convert: %v of type: %T to Res.", x, x)
return nil, fmt.Errorf("Config: Error: Can't convert: %v of type: %T to Res", x, x)
}
//if noop { // now done in mgmtmain
// res.Meta().Noop = noop
@@ -220,16 +220,16 @@ func (c *GraphConfig) NewGraphFromConfig(hostname string, world gapi.World, noop
for _, e := range c.Edges {
if _, ok := lookup[util.FirstToUpper(e.From.Kind)]; !ok {
return nil, fmt.Errorf("Can't find 'from' resource!")
return nil, fmt.Errorf("can't find 'from' resource")
}
if _, ok := lookup[util.FirstToUpper(e.To.Kind)]; !ok {
return nil, fmt.Errorf("Can't find 'to' resource!")
return nil, fmt.Errorf("can't find 'to' resource")
}
if _, ok := lookup[util.FirstToUpper(e.From.Kind)][e.From.Name]; !ok {
return nil, fmt.Errorf("Can't find 'from' name!")
return nil, fmt.Errorf("can't find 'from' name")
}
if _, ok := lookup[util.FirstToUpper(e.To.Kind)][e.To.Name]; !ok {
return nil, fmt.Errorf("Can't find 'to' name!")
return nil, fmt.Errorf("can't find 'to' name")
}
from := lookup[util.FirstToUpper(e.From.Kind)][e.From.Name]
to := lookup[util.FirstToUpper(e.To.Kind)][e.To.Name]