Require namespace on controller, pod, service objects

This commit is contained in:
derekwaynecarr
2014-09-29 17:17:42 -04:00
parent 1b2c62a8ca
commit e4ec49ee6b
10 changed files with 142 additions and 3 deletions

View File

@@ -17,6 +17,8 @@ limitations under the License.
package api
import (
stderrs "errors"
"code.google.com/p/go.net/context"
)
@@ -25,7 +27,47 @@ type Context interface {
Value(key interface{}) interface{}
}
// NewContext instantiates a base context object for request flows
// The key type is unexported to prevent collisions
type key int
// namespaceKey is the context key for the request namespace.
const namespaceKey key = 0
// NewContext instantiates a base context object for request flows.
func NewContext() Context {
return context.TODO()
}
// NewDefaultContext instantiates a base context object for request flows in the default namespace
func NewDefaultContext() Context {
return WithNamespace(NewContext(), NamespaceDefault)
}
// WithValue returns a copy of parent in which the value associated with key is val.
func WithValue(parent Context, key interface{}, val interface{}) Context {
internalCtx, ok := parent.(context.Context)
if !ok {
panic(stderrs.New("Invalid context type"))
}
return context.WithValue(internalCtx, key, val)
}
// WithNamespace returns a copy of parent in which the namespace value is set
func WithNamespace(parent Context, namespace string) Context {
return WithValue(parent, namespaceKey, namespace)
}
// NamespaceFrom returns the value of the namespace key on the ctx
func NamespaceFrom(ctx Context) (string, bool) {
namespace, ok := ctx.Value(namespaceKey).(string)
return namespace, ok
}
// ValidNamespaceOnCreateOrUpdate returns false if the namespace on the context differs from the resource. If the resource has no namespace, it is set to the value in the context.
func ValidNamespaceOnCreateOrUpdate(ctx Context, resource *JSONBase) bool {
ns, ok := NamespaceFrom(ctx)
if len(resource.Namespace) == 0 {
resource.Namespace = ns
}
return ns == resource.Namespace && ok
}