Merge pull request #1129 from VojtechVitek/godoc

Godoc improvements
pull/6/head
Tim Hockin 2014-09-02 09:45:05 -07:00
commit 5bed06f614
71 changed files with 486 additions and 243 deletions

18
pkg/api/errors/doc.go Normal file
View File

@ -0,0 +1,18 @@
/*
Copyright 2014 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Package errors provides detailed error types for api field validation.
package errors

View File

@ -25,7 +25,7 @@ import (
)
// codec defines methods for serializing and deserializing API
// objects
// objects.
type codec interface {
Encode(obj interface{}) (data []byte, err error)
Decode(data []byte) (interface{}, error)
@ -33,7 +33,7 @@ type codec interface {
}
// resourceVersioner provides methods for setting and retrieving
// the resource version from an API object
// the resource version from an API object.
type resourceVersioner interface {
SetResourceVersion(obj interface{}, version uint64) error
ResourceVersion(obj interface{}) (uint64, error)
@ -187,7 +187,7 @@ func Encode(obj interface{}) (data []byte, err error) {
return conversionScheme.Encode(obj)
}
// Ensures that obj is a pointer of some sort. Returns a reflect.Value of the
// enforcePtr ensures that obj is a pointer of some sort. Returns a reflect.Value of the
// dereferenced pointer, ensuring that it is settable/addressable.
// Returns an error if this is not possible.
func enforcePtr(obj interface{}) (reflect.Value, error) {

View File

@ -21,8 +21,8 @@ import (
"reflect"
)
// NewJSONBaseVersioner returns a resourceVersioner that can set or retrieve
// ResourceVersion on objects derived from JSONBase.
// NewJSONBaseResourceVersioner returns a resourceVersioner that can set or
// retrieve ResourceVersion on objects derived from JSONBase.
func NewJSONBaseResourceVersioner() resourceVersioner {
return &jsonBaseResourceVersioner{}
}
@ -46,7 +46,7 @@ func (v jsonBaseResourceVersioner) SetResourceVersion(obj interface{}, version u
return nil
}
// JSONBase lets you work with a JSONBase from any of the versioned or
// JSONBaseInterface lets you work with a JSONBase from any of the versioned or
// internal APIObjects.
type JSONBaseInterface interface {
ID() string
@ -98,9 +98,9 @@ func (g genericJSONBase) SetResourceVersion(version uint64) {
*g.resourceVersion = version
}
// fieldPtr puts the address address of fieldName, which must be a member of v,
// into dest, which must be an address of a variable to which this field's address
// can be assigned.
// fieldPtr puts the address of fieldName, which must be a member of v,
// into dest, which must be an address of a variable to which this field's
// address can be assigned.
func fieldPtr(v reflect.Value, fieldName string, dest interface{}) error {
field := v.FieldByName(fieldName)
if !field.IsValid() {
@ -123,7 +123,7 @@ func fieldPtr(v reflect.Value, fieldName string, dest interface{}) error {
return fmt.Errorf("Couldn't assign/convert %v to %v", field.Type(), v.Type())
}
// newGenericJSONBase makes a new generic JSONBase from v, which must be an
// newGenericJSONBase creates a new generic JSONBase from v, which must be an
// addressable/setable reflect.Value having the same fields as api.JSONBase.
// Returns an error if this isn't the case.
func newGenericJSONBase(v reflect.Value) (genericJSONBase, error) {

View File

@ -87,14 +87,14 @@ type VolumeSource struct {
EmptyDirectory *EmptyDirectory `yaml:"emptyDir" json:"emptyDir"`
}
// Bare host directory volume.
// HostDirectory represents bare host directory volume.
type HostDirectory struct {
Path string `yaml:"path" json:"path"`
}
type EmptyDirectory struct{}
// Port represents a network port in a single container
// Port represents a network port in a single container.
type Port struct {
// Optional: If specified, this must be a DNS_LABEL. Each named port
// in a pod must have a unique name.
@ -109,7 +109,7 @@ type Port struct {
HostIP string `yaml:"hostIP,omitempty" json:"hostIP,omitempty"`
}
// VolumeMount describes a mounting of a Volume within a container
// VolumeMount describes a mounting of a Volume within a container.
type VolumeMount struct {
// Required: This must match the Name of a Volume [above].
Name string `yaml:"name" json:"name"`
@ -119,7 +119,7 @@ type VolumeMount struct {
MountPath string `yaml:"mountPath,omitempty" json:"mountPath,omitempty"`
}
// EnvVar represents an environment variable present in a Container
// EnvVar represents an environment variable present in a Container.
type EnvVar struct {
// Required: This must be a C_IDENTIFIER.
Name string `yaml:"name" json:"name"`
@ -137,7 +137,7 @@ type HTTPGetProbe struct {
Host string `yaml:"host,omitempty" json:"host,omitempty"`
}
// TCPSocketProbe describes a liveness probe based on opening a socket
// TCPSocketProbe describes a liveness probe based on opening a socket.
type TCPSocketProbe struct {
// Required: Port to connect to.
Port util.IntOrString `yaml:"port,omitempty" json:"port,omitempty"`
@ -148,7 +148,7 @@ type ExecProbe struct {
// Command is the command line to execute inside the container, the working directory for the
// command is root ('/') in the container's filesystem. The command is simply exec'd, it is
// not run inside a shell, so traditional shell instructions ('|', etc) won't work. To use
// a shell, you need to explicitly call out to that shell
// a shell, you need to explicitly call out to that shell.
Command []string `yaml:"command,omitempty" json:"command,omitempty"`
}
@ -187,7 +187,7 @@ type Container struct {
LivenessProbe *LivenessProbe `yaml:"livenessProbe,omitempty" json:"livenessProbe,omitempty"`
}
// Event is the representation of an event logged to etcd backends
// Event is the representation of an event logged to etcd backends.
type Event struct {
Event string `json:"event,omitempty"`
Manifest *ContainerManifest `json:"manifest,omitempty"`
@ -197,7 +197,7 @@ type Event struct {
// The below types are used by kube_client and api_server.
// JSONBase is shared by all objects sent to, or returned from the client
// JSONBase is shared by all objects sent to, or returned from the client.
type JSONBase struct {
Kind string `json:"kind,omitempty" yaml:"kind,omitempty"`
ID string `json:"id,omitempty" yaml:"id,omitempty"`
@ -238,7 +238,7 @@ type RestartPolicy struct {
Type RestartPolicyType `yaml:"type,omitempty" json:"type,omitempty"`
}
// PodState is the state of a pod, used as either input (desired state) or output (current state)
// PodState is the state of a pod, used as either input (desired state) or output (current state).
type PodState struct {
Manifest ContainerManifest `json:"manifest,omitempty" yaml:"manifest,omitempty"`
Status PodStatus `json:"status,omitempty" yaml:"status,omitempty"`
@ -262,7 +262,7 @@ type PodList struct {
Items []Pod `json:"items" yaml:"items,omitempty"`
}
// Pod is a collection of containers, used as either input (create, update) or as output (list, get)
// Pod is a collection of containers, used as either input (create, update) or as output (list, get).
type Pod struct {
JSONBase `json:",inline" yaml:",inline"`
Labels map[string]string `json:"labels,omitempty" yaml:"labels,omitempty"`
@ -270,7 +270,7 @@ type Pod struct {
CurrentState PodState `json:"currentState,omitempty" yaml:"currentState,omitempty"`
}
// ReplicationControllerState is the state of a replication controller, either input (create, update) or as output (list, get)
// ReplicationControllerState is the state of a replication controller, either input (create, update) or as output (list, get).
type ReplicationControllerState struct {
Replicas int `json:"replicas" yaml:"replicas"`
ReplicaSelector map[string]string `json:"replicaSelector,omitempty" yaml:"replicaSelector,omitempty"`
@ -283,20 +283,20 @@ type ReplicationControllerList struct {
Items []ReplicationController `json:"items,omitempty" yaml:"items,omitempty"`
}
// ReplicationController represents the configuration of a replication controller
// ReplicationController represents the configuration of a replication controller.
type ReplicationController struct {
JSONBase `json:",inline" yaml:",inline"`
DesiredState ReplicationControllerState `json:"desiredState,omitempty" yaml:"desiredState,omitempty"`
Labels map[string]string `json:"labels,omitempty" yaml:"labels,omitempty"`
}
// PodTemplate holds the information used for creating pods
// PodTemplate holds the information used for creating pods.
type PodTemplate struct {
DesiredState PodState `json:"desiredState,omitempty" yaml:"desiredState,omitempty"`
Labels map[string]string `json:"labels,omitempty" yaml:"labels,omitempty"`
}
// ServiceList holds a list of services
// ServiceList holds a list of services.
type ServiceList struct {
JSONBase `json:",inline" yaml:",inline"`
Items []Service `json:"items" yaml:"items"`
@ -421,7 +421,7 @@ const (
// Status code 202
StatusReasonWorking StatusReason = "working"
// ResourceTypeNotFound means one or more resources required for this operation
// StatusReasonNotFound means one or more resources required for this operation
// could not be found.
// Details (optional):
// "kind" string - the kind attribute of the missing resource
@ -438,14 +438,14 @@ const (
// Status code 409
StatusReasonAlreadyExists StatusReason = "already_exists"
// ResourceTypeConflict means the requested update operation cannot be completed
// StatusReasonConflict means the requested update operation cannot be completed
// due to a conflict in the operation. The client may need to alter the request.
// Each resource may define custom details that indicate the nature of the
// conflict.
// Status code 409
StatusReasonConflict StatusReason = "conflict"
// ResourceTypeInvalid means the requested create or update operation cannot be
// StatusReasonInvalid means the requested create or update operation cannot be
// completed due to invalid data provided as part of the request. The client may
// need to alter the request. When set, the client may use the StatusDetails
// message field as a summary of the issues encountered.

View File

@ -14,5 +14,5 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
// Package v1beta1 is the v1beta1 version of the API
// Package v1beta1 is the v1beta1 version of the API.
package v1beta1

View File

@ -87,14 +87,14 @@ type VolumeSource struct {
EmptyDirectory *EmptyDirectory `yaml:"emptyDir" json:"emptyDir"`
}
// Bare host directory volume.
// HostDirectory represents bare host directory volume.
type HostDirectory struct {
Path string `yaml:"path" json:"path"`
}
type EmptyDirectory struct{}
// Port represents a network port in a single container
// Port represents a network port in a single container.
type Port struct {
// Optional: If specified, this must be a DNS_LABEL. Each named port
// in a pod must have a unique name.
@ -109,7 +109,7 @@ type Port struct {
HostIP string `yaml:"hostIP,omitempty" json:"hostIP,omitempty"`
}
// VolumeMount describes a mounting of a Volume within a container
// VolumeMount describes a mounting of a Volume within a container.
type VolumeMount struct {
// Required: This must match the Name of a Volume [above].
Name string `yaml:"name" json:"name"`
@ -125,7 +125,7 @@ type VolumeMount struct {
MountType string `yaml:"mountType,omitempty" json:"mountType,omitempty"`
}
// EnvVar represents an environment variable present in a Container
// EnvVar represents an environment variable present in a Container.
type EnvVar struct {
// Required: This must be a C_IDENTIFIER.
// Exactly one of the following must be set. If both are set, prefer Name.
@ -146,7 +146,7 @@ type HTTPGetProbe struct {
Host string `yaml:"host,omitempty" json:"host,omitempty"`
}
// TCPSocketProbe describes a liveness probe based on opening a socket
// TCPSocketProbe describes a liveness probe based on opening a socket.
type TCPSocketProbe struct {
// Required: Port to connect to.
Port util.IntOrString `yaml:"port,omitempty" json:"port,omitempty"`
@ -197,7 +197,7 @@ type Container struct {
LivenessProbe *LivenessProbe `yaml:"livenessProbe,omitempty" json:"livenessProbe,omitempty"`
}
// Event is the representation of an event logged to etcd backends
// Event is the representation of an event logged to etcd backends.
type Event struct {
Event string `json:"event,omitempty"`
Manifest *ContainerManifest `json:"manifest,omitempty"`
@ -207,7 +207,7 @@ type Event struct {
// The below types are used by kube_client and api_server.
// JSONBase is shared by all objects sent to, or returned from the client
// JSONBase is shared by all objects sent to, or returned from the client.
type JSONBase struct {
Kind string `json:"kind,omitempty" yaml:"kind,omitempty"`
ID string `json:"id,omitempty" yaml:"id,omitempty"`
@ -248,7 +248,7 @@ type RestartPolicy struct {
Type RestartPolicyType `yaml:"type,omitempty" json:"type,omitempty"`
}
// PodState is the state of a pod, used as either input (desired state) or output (current state)
// PodState is the state of a pod, used as either input (desired state) or output (current state).
type PodState struct {
Manifest ContainerManifest `json:"manifest,omitempty" yaml:"manifest,omitempty"`
Status PodStatus `json:"status,omitempty" yaml:"status,omitempty"`
@ -272,7 +272,7 @@ type PodList struct {
Items []Pod `json:"items" yaml:"items,omitempty"`
}
// Pod is a collection of containers, used as either input (create, update) or as output (list, get)
// Pod is a collection of containers, used as either input (create, update) or as output (list, get).
type Pod struct {
JSONBase `json:",inline" yaml:",inline"`
Labels map[string]string `json:"labels,omitempty" yaml:"labels,omitempty"`
@ -280,7 +280,7 @@ type Pod struct {
CurrentState PodState `json:"currentState,omitempty" yaml:"currentState,omitempty"`
}
// ReplicationControllerState is the state of a replication controller, either input (create, update) or as output (list, get)
// ReplicationControllerState is the state of a replication controller, either input (create, update) or as output (list, get).
type ReplicationControllerState struct {
Replicas int `json:"replicas" yaml:"replicas"`
ReplicaSelector map[string]string `json:"replicaSelector,omitempty" yaml:"replicaSelector,omitempty"`
@ -293,20 +293,20 @@ type ReplicationControllerList struct {
Items []ReplicationController `json:"items,omitempty" yaml:"items,omitempty"`
}
// ReplicationController represents the configuration of a replication controller
// ReplicationController represents the configuration of a replication controller.
type ReplicationController struct {
JSONBase `json:",inline" yaml:",inline"`
DesiredState ReplicationControllerState `json:"desiredState,omitempty" yaml:"desiredState,omitempty"`
Labels map[string]string `json:"labels,omitempty" yaml:"labels,omitempty"`
}
// PodTemplate holds the information used for creating pods
// PodTemplate holds the information used for creating pods.
type PodTemplate struct {
DesiredState PodState `json:"desiredState,omitempty" yaml:"desiredState,omitempty"`
Labels map[string]string `json:"labels,omitempty" yaml:"labels,omitempty"`
}
// ServiceList holds a list of services
// ServiceList holds a list of services.
type ServiceList struct {
JSONBase `json:",inline" yaml:",inline"`
Items []Service `json:"items" yaml:"items"`
@ -369,9 +369,9 @@ type Status struct {
JSONBase `json:",inline" yaml:",inline"`
// One of: "success", "failure", "working" (for operations not yet completed)
Status string `json:"status,omitempty" yaml:"status,omitempty"`
// A human readable description of the status of this operation.
// A human-readable description of the status of this operation.
Message string `json:"message,omitempty" yaml:"message,omitempty"`
// A machine readable description of why this operation is in the
// A machine-readable description of why this operation is in the
// "failure" or "working" status. If this value is empty there
// is no information available. A Reason clarifies an HTTP status
// code but does not override it.
@ -434,7 +434,7 @@ const (
// Status code 202
StatusReasonWorking StatusReason = "working"
// ResourceTypeNotFound means one or more resources required for this operation
// StatusReasonNotFound means one or more resources required for this operation
// could not be found.
// Details (optional):
// "kind" string - the kind attribute of the missing resource
@ -451,7 +451,7 @@ const (
// Status code 409
StatusReasonAlreadyExists StatusReason = "alreadyExists"
// ResourceTypeConflict means the requested update operation cannot be completed
// StatusReasonConflict means the requested update operation cannot be completed
// due to a conflict in the operation. The client may need to alter the request.
// Each resource may define custom details that indicate the nature of the
// conflict.

View File

@ -172,7 +172,8 @@ func AccumulateUniquePorts(containers []Container, accumulator map[int]bool, ext
return allErrs
}
// Checks for colliding Port.HostPort values across a slice of containers.
// checkHostPortConflicts checks for colliding Port.HostPort values across
// a slice of containers.
func checkHostPortConflicts(containers []Container) errs.ErrorList {
allPorts := map[int]bool{}
return AccumulateUniquePorts(containers, allPorts, func(p *Port) int { return p.HostPort })
@ -245,7 +246,7 @@ func ValidatePodState(podState *PodState) errs.ErrorList {
return allErrs
}
// Pod tests if required fields in the pod are set.
// ValidatePod tests if required fields in the pod are set.
func ValidatePod(pod *Pod) errs.ErrorList {
allErrs := errs.ErrorList{}
if len(pod.ID) == 0 {

View File

@ -31,8 +31,7 @@ import (
"github.com/golang/glog"
)
// Codec defines methods for serializing and deserializing API
// objects.
// Codec defines methods for serializing and deserializing API objects.
type Codec interface {
Encode(obj interface{}) (data []byte, err error)
Decode(data []byte) (interface{}, error)
@ -117,7 +116,7 @@ func InstallSupport(mux mux) {
mux.HandleFunc("/", handleIndex)
}
// RecoverPanics wraps an http Handler to recover and log panics
// RecoverPanics wraps an http Handler to recover and log panics.
func RecoverPanics(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
defer func() {
@ -142,12 +141,12 @@ func RecoverPanics(handler http.Handler) http.Handler {
})
}
// handleVersionReq writes the server's version information.
// handleVersion writes the server's version information.
func handleVersion(w http.ResponseWriter, req *http.Request) {
writeRawJSON(http.StatusOK, version.Get(), w)
}
// writeJSON renders an object as JSON to the response
// writeJSON renders an object as JSON to the response.
func writeJSON(statusCode int, codec Codec, object interface{}, w http.ResponseWriter) {
output, err := codec.Encode(object)
if err != nil {
@ -159,7 +158,7 @@ func writeJSON(statusCode int, codec Codec, object interface{}, w http.ResponseW
w.Write(output)
}
// errorJSON renders an error to the response
// errorJSON renders an error to the response.
func errorJSON(err error, codec Codec, w http.ResponseWriter) {
status := errToAPIStatus(err)
writeJSON(status.Code, codec, status, w)
@ -193,7 +192,7 @@ func readBody(req *http.Request) ([]byte, error) {
return ioutil.ReadAll(req.Body)
}
// splitPath returns the segments for a URL path
// splitPath returns the segments for a URL path.
func splitPath(path string) []string {
path = strings.Trim(path, "/")
if path == "" {

View File

@ -14,5 +14,5 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
// Package apiserver contains the code that provides a RESTful api service
// Package apiserver contains the code that provides a RESTful api service.
package apiserver

View File

@ -25,7 +25,7 @@ import (
"github.com/GoogleCloudPlatform/kubernetes/pkg/tools"
)
// apiServerError is an error intended for consumption by a REST API server
// apiServerError is an error intended for consumption by a REST API server.
type apiServerError struct {
api.Status
}
@ -49,7 +49,7 @@ func NewNotFoundErr(kind, name string) error {
}}
}
// NewAlreadyExistsErr returns an error indicating the item requested exists by that identifier
// NewAlreadyExistsErr returns an error indicating the item requested exists by that identifier.
func NewAlreadyExistsErr(kind, name string) error {
return &apiServerError{api.Status{
Status: api.StatusFailure,
@ -77,7 +77,7 @@ func NewConflictErr(kind, name string, err error) error {
}}
}
// NewInvalidError returns an error indicating the item is invalid and cannot be processed.
// NewInvalidErr returns an error indicating the item is invalid and cannot be processed.
func NewInvalidErr(kind, name string, errs errors.ErrorList) error {
causes := make([]api.StatusCause, 0, len(errs))
for i := range errs {
@ -102,7 +102,7 @@ func NewInvalidErr(kind, name string, errs errors.ErrorList) error {
}}
}
// IsNotFound returns true if the specified error was created by NewNotFoundErr
// IsNotFound returns true if the specified error was created by NewNotFoundErr.
func IsNotFound(err error) bool {
return reasonForError(err) == api.StatusReasonNotFound
}
@ -112,12 +112,12 @@ func IsAlreadyExists(err error) bool {
return reasonForError(err) == api.StatusReasonAlreadyExists
}
// IsConflict determines if the err is an error which indicates the provided update conflicts
// IsConflict determines if the err is an error which indicates the provided update conflicts.
func IsConflict(err error) bool {
return reasonForError(err) == api.StatusReasonConflict
}
// IsInvalid determines if the err is an error which indicates the provided resource is not valid
// IsInvalid determines if the err is an error which indicates the provided resource is not valid.
func IsInvalid(err error) bool {
return reasonForError(err) == api.StatusReasonInvalid
}
@ -154,13 +154,13 @@ func errToAPIStatus(err error) *api.Status {
}
}
// notFound renders a simple not found error
// notFound renders a simple not found error.
func notFound(w http.ResponseWriter, req *http.Request) {
w.WriteHeader(http.StatusNotFound)
fmt.Fprintf(w, "Not Found: %#v", req.RequestURI)
}
// badGatewayError renders a simple bad gateway error
// badGatewayError renders a simple bad gateway error.
func badGatewayError(w http.ResponseWriter, req *http.Request) {
w.WriteHeader(http.StatusBadGateway)
fmt.Fprintf(w, "Bad Gateway: %#v", req.RequestURI)

View File

@ -21,7 +21,7 @@ import (
"net/http"
)
// handleIndex is the root index page for Kubernetes
// handleIndex is the root index page for Kubernetes.
func handleIndex(w http.ResponseWriter, req *http.Request) {
if req.URL.Path != "/" && req.URL.Path != "/index.html" {
notFound(w, req)

View File

@ -21,7 +21,7 @@ import (
"github.com/GoogleCloudPlatform/kubernetes/pkg/watch"
)
// RESTStorage is a generic interface for RESTful storage services
// RESTStorage is a generic interface for RESTful storage services.
// Resources which are exported to the RESTful API of apiserver need to implement this interface.
type RESTStorage interface {
// New returns an empty object that can be used with Create and Update after request data has been put into it.
@ -56,7 +56,7 @@ type ResourceWatcher interface {
Watch(label, field labels.Selector, resourceVersion uint64) (watch.Interface, error)
}
// Redirectors know how to return a remote resource's location.
// Redirector know how to return a remote resource's location.
type Redirector interface {
// ResourceLocation should return the remote location of the given resource, or an error.
ResourceLocation(id string) (remoteLocation string, err error)

View File

@ -102,14 +102,14 @@ func (ops *Operations) NewOperation(from <-chan interface{}) *Operation {
return op
}
// Inserts op into the ops map.
// insert inserts op into the ops map.
func (ops *Operations) insert(op *Operation) {
ops.lock.Lock()
defer ops.lock.Unlock()
ops.ops[op.ID] = op
}
// List operations for an API client.
// List lists operations for an API client.
func (ops *Operations) List() api.ServerOpList {
ops.lock.Lock()
defer ops.lock.Unlock()
@ -126,14 +126,14 @@ func (ops *Operations) List() api.ServerOpList {
return ol
}
// Get returns the operation with the given ID, or nil
// Get returns the operation with the given ID, or nil.
func (ops *Operations) Get(id string) *Operation {
ops.lock.Lock()
defer ops.lock.Unlock()
return ops.ops[id]
}
// Garbage collect operations that have finished longer than maxAge ago.
// expire garbage collect operations that have finished longer than maxAge ago.
func (ops *Operations) expire(maxAge time.Duration) {
ops.lock.Lock()
defer ops.lock.Unlock()
@ -147,7 +147,7 @@ func (ops *Operations) expire(maxAge time.Duration) {
ops.ops = keep
}
// Waits forever for the operation to complete; call via go when
// wait waits forever for the operation to complete; call via go when
// the operation is created. Sets op.finished when the operation
// does complete, and closes the notify channel, in case there
// are any WaitFor() calls in progress.
@ -173,7 +173,7 @@ func (op *Operation) WaitFor(timeout time.Duration) {
}
}
// Returns true if this operation finished before limitTime.
// expired returns true if this operation finished before limitTime.
func (op *Operation) expired(limitTime time.Time) bool {
op.lock.Lock()
defer op.lock.Unlock()

View File

@ -157,7 +157,7 @@ func (h *RESTHandler) handleRESTStorage(parts []string, req *http.Request, w htt
}
}
// createOperation creates an operation to process a channel response
// createOperation creates an operation to process a channel response.
func (h *RESTHandler) createOperation(out <-chan interface{}, sync bool, timeout time.Duration) *Operation {
op := h.ops.NewOperation(out)
if sync {

View File

@ -51,7 +51,7 @@ func getWatchParams(query url.Values) (label, field labels.Selector, resourceVer
return label, field, resourceVersion
}
// handleWatch processes a watch request
// ServeHTTP processes watch requests.
func (h *WatchHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
parts := splitPath(req.URL.Path)
if len(parts) < 1 || req.Method != "GET" {

View File

@ -42,7 +42,7 @@ type Reflector struct {
// WatchFactory should begin a watch at the specified version.
type WatchFactory func(resourceVersion uint64) (watch.Interface, error)
// NewReflector makes a new Reflector object which will keep the given store up to
// NewReflector creates a new Reflector object which will keep the given store up to
// date with the server's contents for the given resource. Reflector promises to
// only put things in the store that have the type of expectedType.
func NewReflector(watchFactory WatchFactory, expectedType interface{}, store Store) *Reflector {

View File

@ -43,7 +43,7 @@ type Interface interface {
MinionInterface
}
// PodInterface has methods to work with Pod resources
// PodInterface has methods to work with Pod resources.
type PodInterface interface {
ListPods(selector labels.Selector) (api.PodList, error)
GetPod(name string) (api.Pod, error)
@ -52,7 +52,7 @@ type PodInterface interface {
UpdatePod(api.Pod) (api.Pod, error)
}
// ReplicationControllerInterface has methods to work with ReplicationController resources
// ReplicationControllerInterface has methods to work with ReplicationController resources.
type ReplicationControllerInterface interface {
ListReplicationControllers(selector labels.Selector) (api.ReplicationControllerList, error)
GetReplicationController(name string) (api.ReplicationController, error)
@ -62,7 +62,7 @@ type ReplicationControllerInterface interface {
WatchReplicationControllers(label, field labels.Selector, resourceVersion uint64) (watch.Interface, error)
}
// ServiceInterface has methods to work with Service resources
// ServiceInterface has methods to work with Service resources.
type ServiceInterface interface {
GetService(name string) (api.Service, error)
CreateService(api.Service) (api.Service, error)
@ -73,7 +73,7 @@ type ServiceInterface interface {
WatchEndpoints(label, field labels.Selector, resourceVersion uint64) (watch.Interface, error)
}
// VersionInterface has a method to retrieve the server version
// VersionInterface has a method to retrieve the server version.
type VersionInterface interface {
ServerVersion() (*version.Info, error)
}
@ -119,14 +119,14 @@ func (s *StatusErr) Error() string {
return fmt.Sprintf("Status: %v (%#v)", s.Status.Status, s.Status)
}
// AuthInfo is used to store authorization information
// AuthInfo is used to store authorization information.
type AuthInfo struct {
User string
Password string
}
// RESTClient holds common code used to work with API resources that follow the
// Kubernetes API pattern
// Kubernetes API pattern.
// Host is the http://... base for the URL
type RESTClient struct {
host string
@ -168,7 +168,7 @@ func NewRESTClient(host string, auth *AuthInfo, path string) (*RESTClient, error
}, nil
}
// normalizePrefix ensures the passed initial value is valid
// normalizePrefix ensures the passed initial value is valid.
func normalizePrefix(host, prefix string) (*url.URL, error) {
if host == "" {
return nil, fmt.Errorf("host must be a URL or a host:port pair")
@ -197,7 +197,8 @@ func (c *RESTClient) Secure() bool {
return c.secure
}
// Execute a request, adds authentication (if auth != nil), and HTTPS cert ignoring.
// doRequest executes a request, adds authentication (if auth != nil), and HTTPS
// cert ignoring.
func (c *RESTClient) doRequest(request *http.Request) ([]byte, error) {
if c.auth != nil {
request.SetBasicAuth(c.auth.User, c.auth.Password)
@ -239,30 +240,30 @@ func (c *RESTClient) doRequest(request *http.Request) ([]byte, error) {
return body, err
}
// ListPods takes a selector, and returns the list of pods that match that selector
// ListPods takes a selector, and returns the list of pods that match that selector.
func (c *Client) ListPods(selector labels.Selector) (result api.PodList, err error) {
err = c.Get().Path("pods").SelectorParam("labels", selector).Do().Into(&result)
return
}
// GetPod takes the name of the pod, and returns the corresponding Pod object, and an error if it occurs
// GetPod takes the name of the pod, and returns the corresponding Pod object, and an error if it occurs.
func (c *Client) GetPod(name string) (result api.Pod, err error) {
err = c.Get().Path("pods").Path(name).Do().Into(&result)
return
}
// DeletePod takes the name of the pod, and returns an error if one occurs
// DeletePod takes the name of the pod, and returns an error if one occurs.
func (c *Client) DeletePod(name string) error {
return c.Delete().Path("pods").Path(name).Do().Error()
}
// CreatePod takes the representation of a pod. Returns the server's representation of the pod, and an error, if it occurs
// CreatePod takes the representation of a pod. Returns the server's representation of the pod, and an error, if it occurs.
func (c *Client) CreatePod(pod api.Pod) (result api.Pod, err error) {
err = c.Post().Path("pods").Body(pod).Do().Into(&result)
return
}
// UpdatePod takes the representation of a pod to update. Returns the server's representation of the pod, and an error, if it occurs
// UpdatePod takes the representation of a pod to update. Returns the server's representation of the pod, and an error, if it occurs.
func (c *Client) UpdatePod(pod api.Pod) (result api.Pod, err error) {
if pod.ResourceVersion == 0 {
err = fmt.Errorf("invalid update object, missing resource version: %v", pod)
@ -272,25 +273,25 @@ func (c *Client) UpdatePod(pod api.Pod) (result api.Pod, err error) {
return
}
// ListReplicationControllers takes a selector, and returns the list of replication controllers that match that selector
// ListReplicationControllers takes a selector, and returns the list of replication controllers that match that selector.
func (c *Client) ListReplicationControllers(selector labels.Selector) (result api.ReplicationControllerList, err error) {
err = c.Get().Path("replicationControllers").SelectorParam("labels", selector).Do().Into(&result)
return
}
// GetReplicationController returns information about a particular replication controller
// GetReplicationController returns information about a particular replication controller.
func (c *Client) GetReplicationController(name string) (result api.ReplicationController, err error) {
err = c.Get().Path("replicationControllers").Path(name).Do().Into(&result)
return
}
// CreateReplicationController creates a new replication controller
// CreateReplicationController creates a new replication controller.
func (c *Client) CreateReplicationController(controller api.ReplicationController) (result api.ReplicationController, err error) {
err = c.Post().Path("replicationControllers").Body(controller).Do().Into(&result)
return
}
// UpdateReplicationController updates an existing replication controller
// UpdateReplicationController updates an existing replication controller.
func (c *Client) UpdateReplicationController(controller api.ReplicationController) (result api.ReplicationController, err error) {
if controller.ResourceVersion == 0 {
err = fmt.Errorf("invalid update object, missing resource version: %v", controller)
@ -343,7 +344,7 @@ func (c *Client) DeleteService(name string) error {
return c.Delete().Path("services").Path(name).Do().Error()
}
// WatchService returns a watch.Interface that watches the requested services.
// WatchServices returns a watch.Interface that watches the requested services.
func (c *Client) WatchServices(label, field labels.Selector, resourceVersion uint64) (watch.Interface, error) {
return c.Get().
Path("watch").
@ -379,7 +380,7 @@ func (c *Client) ServerVersion() (*version.Info, error) {
return &info, nil
}
// Lists all the minions in the cluster.
// ListMinions lists all the minions in the cluster.
func (c *Client) ListMinions() (minionList api.MinionList, err error) {
err = c.Get().Path("minions").Do().Into(&minionList)
return

View File

@ -28,7 +28,7 @@ import (
"github.com/GoogleCloudPlatform/kubernetes/pkg/api"
)
// ErrPodInfoNotAvailable may be returned when the requested pod info is not available
// ErrPodInfoNotAvailable may be returned when the requested pod info is not available.
var ErrPodInfoNotAvailable = errors.New("no pod info available")
// PodInfoGetter is an interface for things that can get information about a pod's containers.
@ -39,7 +39,7 @@ type PodInfoGetter interface {
GetPodInfo(host, podID string) (api.PodInfo, error)
}
// HTTPPodInfoGetter is the default implementation of PodInfoGetter, accesses the kubelet over HTTP
// HTTPPodInfoGetter is the default implementation of PodInfoGetter, accesses the kubelet over HTTP.
type HTTPPodInfoGetter struct {
Client *http.Client
Port uint

View File

@ -39,7 +39,7 @@ import (
// are therefore not allowed to set manually.
var specialParams = util.NewStringSet("sync", "timeout")
// Verb begins a request with a verb (GET, POST, PUT, DELETE)
// Verb begins a request with a verb (GET, POST, PUT, DELETE).
//
// Example usage of Client's request building interface:
// auth, err := LoadAuth(filename)
@ -114,7 +114,7 @@ func (r *Request) Path(item string) *Request {
return r
}
// Sync sets sync/async call status by setting the "sync" parameter to "true"/"false"
// Sync sets sync/async call status by setting the "sync" parameter to "true"/"false".
func (r *Request) Sync(sync bool) *Request {
if r.err != nil {
return r
@ -245,7 +245,8 @@ func (r *Request) finalURL() string {
return finalURL
}
// Attempts to begin watching the requested location. Returns a watch.Interface, or an error.
// Watch attempts to begin watching the requested location.
// Returns a watch.Interface, or an error.
func (r *Request) Watch() (watch.Interface, error) {
if r.err != nil {
return nil, r.err
@ -319,7 +320,7 @@ func (r Result) Get() (interface{}, error) {
return api.Decode(r.body)
}
// Into stores the result into obj, if possible..
// Into stores the result into obj, if possible.
func (r Result) Into(obj interface{}) error {
if r.err != nil {
return r.err
@ -327,7 +328,7 @@ func (r Result) Into(obj interface{}) error {
return api.DecodeInto(r.body, obj)
}
// Returns the error executing the request, nil if no error occurred.
// Error returns the error executing the request, nil if no error occurred.
func (r Result) Error() error {
return r.err
}

View File

@ -20,7 +20,7 @@ import (
"net"
)
// Interface is an abstract, pluggable interface for cloud providers
// Interface is an abstract, pluggable interface for cloud providers.
type Interface interface {
// TCPLoadBalancer returns a balancer interface. Also returns true if the interface is supported, false otherwise.
TCPLoadBalancer() (TCPLoadBalancer, bool)
@ -51,7 +51,7 @@ type Instances interface {
List(filter string) ([]string, error)
}
// Zone represents the location of a particular machine
// Zone represents the location of a particular machine.
type Zone struct {
FailureDomain string
Region string

View File

@ -14,7 +14,5 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
// Package cloudprovider supplies interfaces and implementations for cloud service providers
// Package cloudprovider supplies interfaces and implementations for cloud service providers.
package cloudprovider
import ()

View File

@ -0,0 +1,19 @@
/*
Copyright 2014 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Package fake_cloud is a test-double implementation of cloudprovider
// Interface, TCPLoadBalancer and Instances. It is useful for testing.
package fake_cloud

View File

@ -0,0 +1,19 @@
/*
Copyright 2014 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Package gce_cloud is an implementation of Interface, TCPLoadBalancer
// and Instances for Google Compute Engine.
package gce_cloud

View File

@ -201,7 +201,7 @@ func (gce *GCECloud) IPAddress(instance string) (net.IP, error) {
return ip, nil
}
// This is hacky, compute the delta between hostame and hostname -f
// fqdnSuffix is hacky function to compute the delta between hostame and hostname -f.
func fqdnSuffix() (string, error) {
fullHostname, err := exec.Command("hostname", "-f").Output()
if err != nil {
@ -253,7 +253,8 @@ func (gce *GCECloud) GetZone() (cloudprovider.Zone, error) {
}, nil
}
// gce zone names are of the form: ${region-name}-${ix}.
// getGceRegion returns region of the gce zone. Zone names
// are of the form: ${region-name}-${ix}.
// For example "us-central1-b" has a region of "us-central1".
// So we look for the last '-' and trim to just before that.
func getGceRegion(zone string) (string, error) {

View File

@ -0,0 +1,19 @@
/*
Copyright 2014 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Package vagrant_cloud is an implementation of Interface, TCPLoadBalancer
// and Instances for developer managed Vagrant cluster.
package vagrant_cloud

View File

@ -28,7 +28,7 @@ import (
"github.com/GoogleCloudPlatform/kubernetes/pkg/cloudprovider"
)
// VagrantCloud is an implementation of Interface, TCPLoadBalancer and Instances for developer managed Vagrant cluster
// VagrantCloud is an implementation of Interface, TCPLoadBalancer and Instances for developer managed Vagrant cluster.
type VagrantCloud struct {
saltURL string
saltUser string
@ -40,26 +40,26 @@ func init() {
cloudprovider.RegisterCloudProvider("vagrant", func() (cloudprovider.Interface, error) { return newVagrantCloud() })
}
// SaltToken is an authorization token required by Salt REST API
// SaltToken is an authorization token required by Salt REST API.
type SaltToken struct {
Token string `json:"token"`
User string `json:"user"`
EAuth string `json:"eauth"`
}
// SaltLoginResponse is the response object for a /login operation against Salt REST API
// SaltLoginResponse is the response object for a /login operation against Salt REST API.
type SaltLoginResponse struct {
Data []SaltToken `json:"return"`
}
// SaltMinion is a machine managed by the Salt service
// SaltMinion is a machine managed by the Salt service.
type SaltMinion struct {
Roles []string `json:"roles"`
IP string `json:"minion_ip"`
Host string `json:"host"`
}
// SaltMinions is a map of minion name to machine information
// SaltMinions is a map of minion name to machine information.
type SaltMinions map[string]SaltMinion
// SaltMinionsResponse is the response object for a /minions operation against Salt REST API
@ -77,28 +77,28 @@ func newVagrantCloud() (*VagrantCloud, error) {
}, nil
}
// TCPLoadBalancer returns an implementation of TCPLoadBalancer for Vagrant cloud
// TCPLoadBalancer returns an implementation of TCPLoadBalancer for Vagrant cloud.
func (v *VagrantCloud) TCPLoadBalancer() (cloudprovider.TCPLoadBalancer, bool) {
return nil, false
}
// Instances returns an implementation of Instances for Vagrant cloud
// Instances returns an implementation of Instances for Vagrant cloud.
func (v *VagrantCloud) Instances() (cloudprovider.Instances, bool) {
return v, true
}
// Zones returns an implementation of Zones for Vagrant cloud
// Zones returns an implementation of Zones for Vagrant cloud.
func (v *VagrantCloud) Zones() (cloudprovider.Zones, bool) {
return nil, false
}
// IPAddress returns the address of a particular machine instance
// IPAddress returns the address of a particular machine instance.
func (v *VagrantCloud) IPAddress(instance string) (net.IP, error) {
// since the instance now is the IP in the vagrant env, this is trivial no-op
return net.ParseIP(instance), nil
}
// saltMinionsByRole filters a list of minions that have a matching role
// saltMinionsByRole filters a list of minions that have a matching role.
func (v *VagrantCloud) saltMinionsByRole(minions []SaltMinion, role string) []SaltMinion {
var filteredMinions []SaltMinion
for _, value := range minions {
@ -110,7 +110,7 @@ func (v *VagrantCloud) saltMinionsByRole(minions []SaltMinion, role string) []Sa
return filteredMinions
}
// saltMinions invokes the Salt API for minions using provided token
// saltMinions invokes the Salt API for minions using provided token.
func (v *VagrantCloud) saltMinions(token SaltToken) ([]SaltMinion, error) {
var minions []SaltMinion
@ -139,7 +139,7 @@ func (v *VagrantCloud) saltMinions(token SaltToken) ([]SaltMinion, error) {
return minions, nil
}
// saltLogin invokes the Salt API to get an authorization token
// saltLogin invokes the Salt API to get an authorization token.
func (v *VagrantCloud) saltLogin() (SaltToken, error) {
url := v.saltURL + "/login"
data := neturl.Values{
@ -172,7 +172,7 @@ func (v *VagrantCloud) saltLogin() (SaltToken, error) {
return loginResp.Data[0], nil
}
// List enumerates the set of minions instances known by the cloud provider
// List enumerates the set of minions instances known by the cloud provider.
func (v *VagrantCloud) List(filter string) ([]string, error) {
token, err := v.saltLogin()
if err != nil {

View File

@ -41,7 +41,7 @@ type Converter struct {
Debug DebugLogger
}
// NewConverter makes a new Converter object.
// NewConverter creates a new Converter object.
func NewConverter() *Converter {
return &Converter{
funcs: map[typePair]reflect.Value{},
@ -83,7 +83,7 @@ func (c *Converter) Register(conversionFunc interface{}) error {
return nil
}
// FieldMatchingType contains a list of ways in which struct fields could be
// FieldMatchingFlags contains a list of ways in which struct fields could be
// copied. These constants may be | combined.
type FieldMatchingFlags int
@ -105,7 +105,7 @@ const (
AllowDifferentFieldTypeNames
)
// Returns true if the given flag or combination of flags is set.
// IsSet returns true if the given flag or combination of flags is set.
func (f FieldMatchingFlags) IsSet(flag FieldMatchingFlags) bool {
return f&flag == flag
}

View File

@ -168,7 +168,7 @@ func (metaInsertion) Interpret(in interface{}) (version, kind string) {
return m.Version, m.Kind
}
// DataAPIVersionAndKind will return the APIVersion and Kind of the given wire-format
// DataVersionAndKind will return the APIVersion and Kind of the given wire-format
// enconding of an API Object, or an error.
func (s *Scheme) DataVersionAndKind(data []byte) (version, kind string, err error) {
findKind := s.MetaInsertionFactory.Create("", "")
@ -217,8 +217,8 @@ func maybeCopy(obj interface{}) interface{} {
return v2.Interface()
}
// Ensures that obj is a pointer of some sort. Returns a reflect.Value of the
// dereferenced pointer, ensuring that it is settable/addressable.
// enforcePtr ensures that obj is a pointer of some sort. Returns a reflect.Value
// of the dereferenced pointer, ensuring that it is settable/addressable.
// Returns an error if this is not possible.
func enforcePtr(obj interface{}) (reflect.Value, error) {
v := reflect.ValueOf(obj)

View File

@ -27,7 +27,7 @@ import (
"github.com/golang/glog"
)
// NewEtcdMasterElector returns an implementation of election.MasterElector backed by etcd
// NewEtcdMasterElector returns an implementation of election.MasterElector backed by etcd.
func NewEtcdMasterElector(h tools.EtcdGetSet) MasterElector {
return &etcdMasterElector{etcd: h}
}
@ -41,7 +41,7 @@ type etcdMasterElector struct {
events chan watch.Event
}
// Elect implements the election.MasterElector interface
// Elect implements the election.MasterElector interface.
func (e *etcdMasterElector) Elect(path, id string) watch.Interface {
e.done = make(chan empty)
e.events = make(chan watch.Event)
@ -66,12 +66,12 @@ func (e *etcdMasterElector) run(path, id string) {
}
}
// ResultChan implements the watch.Interface interface
// ResultChan implements the watch.Interface interface.
func (e *etcdMasterElector) ResultChan() <-chan watch.Event {
return e.events
}
// extendMaster attempts to extend ownership of a master lock for TTL seconds
// extendMaster attempts to extend ownership of a master lock for TTL seconds.
// returns "", nil if extension failed
// returns id, nil if extension succeeded
// returns "", err if an error occurred
@ -90,7 +90,7 @@ func (e *etcdMasterElector) extendMaster(path, id string, ttl uint64, res *etcd.
return id, nil
}
// becomeMaster attempts to become the master for this lock
// becomeMaster attempts to become the master for this lock.
// returns "", nil if the attempt failed
// returns id, nil if the attempt succeeded
// returns "", err if an error occurred
@ -106,7 +106,7 @@ func (e *etcdMasterElector) becomeMaster(path, id string, ttl uint64) (string, e
return id, nil
}
// handleMaster performs one loop of master locking
// handleMaster performs one loop of master locking.
// on success it returns <master>, nil
// on error it returns "", err
// in situations where you should try again due to concurrent state changes (e.g. another actor simultaneously acquiring the lock)
@ -138,7 +138,7 @@ func (e *etcdMasterElector) handleMaster(path, id string, ttl uint64) (string, e
return e.extendMaster(path, id, ttl, res)
}
// Master provices a distributed master election lock, maintains lock until failure, or someone sends something in the done channel
// master provices a distributed master election lock, maintains lock until failure, or someone sends something in the done channel.
// The basic algorithm is:
// while !done
// Get the current master

View File

@ -42,9 +42,9 @@ type HealthChecker interface {
var checkerLock = sync.Mutex{}
var checkers = map[string]HealthChecker{}
// Add a health checker to the list of known HealthChecker objects. Any subsequent call to
// NewHealthChecker will know about this HealthChecker.
// panics if 'key' is already present.
// AddHealthChecker adds a health checker to the list of known HealthChecker objects.
// Any subsequent call to NewHealthChecker will know about this HealthChecker.
// Panics if 'key' is already present.
func AddHealthChecker(key string, checker HealthChecker) {
checkerLock.Lock()
defer checkerLock.Unlock()
@ -84,7 +84,7 @@ func (m *muxHealthChecker) HealthCheck(podFullName string, currentState api.PodS
return checker.HealthCheck(podFullName, currentState, container)
}
// A helper function to look up a port in a container by name.
// findPortByName is a helper function to look up a port in a container by name.
// Returns the HostPort if found, -1 if not found.
func findPortByName(container api.Container, portName string) int {
for _, port := range container.Ports {

View File

@ -32,7 +32,6 @@ type HTTPGetInterface interface {
Get(url string) (*http.Response, error)
}
// DoHTTPCheck checks if a GET request to the url succeeds.
// HTTPHealthChecker is an implementation of HealthChecker which checks container health by sending HTTP Get requests.
type HTTPHealthChecker struct {
client HTTPGetInterface
@ -42,7 +41,7 @@ func NewHTTPHealthChecker(client *http.Client) HealthChecker {
return &HTTPHealthChecker{client: &http.Client{}}
}
// Get the components of the target URL. For testability.
// getURLParts parses the components of the target URL. For testability.
func getURLParts(currentState api.PodState, container api.Container) (string, int, string, error) {
params := container.LivenessProbe.HTTPGet
if params == nil {
@ -75,11 +74,12 @@ func getURLParts(currentState api.PodState, container api.Container) (string, in
return host, port, params.Path, nil
}
// Formats a URL from args. For testability.
// formatURL formats a URL from args. For testability.
func formatURL(host string, port int, path string) string {
return fmt.Sprintf("http://%s:%d%s", host, port, path)
}
// DoHTTPCheck checks if a GET request to the url succeeds.
// If the HTTP response code is successful (i.e. 400 > code >= 200), it returns Healthy.
// If the HTTP response code is unsuccessful, it returns Unhealthy.
// It returns Unknown and err if the HTTP communication itself fails.

View File

@ -28,7 +28,7 @@ import (
type TCPHealthChecker struct{}
// Get the components of a TCP connection address. For testability.
// getTCPAddrParts parses the components of a TCP connection address. For testability.
func getTCPAddrParts(currentState api.PodState, container api.Container) (string, int, error) {
params := container.LivenessProbe.TCPSocket
if params == nil {

View File

@ -37,7 +37,7 @@ func Handler(delegate http.Handler, pred StacktracePred) http.Handler {
})
}
// StacktracePred returns true if a stacktrace should be logged for this status
// StacktracePred returns true if a stacktrace should be logged for this status.
type StacktracePred func(httpStatus int) (logStacktrace bool)
// Add a layer on top of ResponseWriter, so we can track latency and error
@ -103,7 +103,7 @@ func Unlogged(w http.ResponseWriter) http.ResponseWriter {
return w
}
// Sets the stacktrace logging predicate, which decides when to log a stacktrace.
// StacktraceWhen sets the stacktrace logging predicate, which decides when to log a stacktrace.
// There's a default, so you don't need to call this unless you don't like the default.
func (rl *respLogger) StacktraceWhen(pred StacktracePred) *respLogger {
rl.logStacktracePred = pred
@ -123,7 +123,7 @@ func StatusIsNot(statuses ...int) StacktracePred {
}
}
// Add additional data to be logged with this request.
// Addf adds additional data to be logged with this request.
func (rl *respLogger) Addf(format string, data ...interface{}) {
rl.addedInfo += "\n" + fmt.Sprintf(format, data...)
}
@ -134,17 +134,17 @@ func (rl *respLogger) Log() {
glog.Infof("%s %s: (%v) %v%v%v", rl.req.Method, rl.req.RequestURI, latency, rl.status, rl.statusStack, rl.addedInfo)
}
// Implement http.ResponseWriter
// Header implements http.ResponseWriter.
func (rl *respLogger) Header() http.Header {
return rl.w.Header()
}
// Implement http.ResponseWriter
// Write implements http.ResponseWriter.
func (rl *respLogger) Write(b []byte) (int, error) {
return rl.w.Write(b)
}
// Implement http.ResponseWriter
// WriteHeader implements http.ResponseWriter.
func (rl *respLogger) WriteHeader(status int) {
rl.status = status
if rl.logStacktracePred(status) {

View File

@ -111,12 +111,12 @@ func Update(name string, client client.Interface, updatePeriod time.Duration) er
})
}
// StopController stops a controller named 'name' by setting replicas to zero
// StopController stops a controller named 'name' by setting replicas to zero.
func StopController(name string, client client.Interface) error {
return ResizeController(name, 0, client)
}
// ResizeController resizes a controller named 'name' by setting replicas to 'replicas'
// ResizeController resizes a controller named 'name' by setting replicas to 'replicas'.
func ResizeController(name string, replicas int, client client.Interface) error {
controller, err := client.GetReplicationController(name)
if err != nil {
@ -159,7 +159,7 @@ func portsFromString(spec string) []api.Port {
return result
}
// RunController creates a new replication controller named 'name' which creates 'replicas' pods running 'image'
// RunController creates a new replication controller named 'name' which creates 'replicas' pods running 'image'.
func RunController(image, name string, replicas int, client client.Interface, portSpec string, servicePort int) error {
controller := api.ReplicationController{
JSONBase: api.JSONBase{
@ -233,7 +233,7 @@ func createService(name string, port int, client client.Interface) (api.Service,
}
// DeleteController deletes a replication controller named 'name', requires that the controller
// already be stopped
// already be stopped.
func DeleteController(name string, client client.Interface) error {
controller, err := client.GetReplicationController(name)
if err != nil {

View File

@ -31,14 +31,14 @@ import (
"gopkg.in/v1/yaml"
)
// ResourcePrinter is an interface that knows how to print API resources
// ResourcePrinter is an interface that knows how to print API resources.
type ResourcePrinter interface {
// Print receives an arbitrary JSON body, formats it and prints it to a writer
// Print receives an arbitrary JSON body, formats it and prints it to a writer.
Print([]byte, io.Writer) error
PrintObj(interface{}, io.Writer) error
}
// IdentityPrinter is an implementation of ResourcePrinter which simply copies the body out to the output stream
// IdentityPrinter is an implementation of ResourcePrinter which simply copies the body out to the output stream.
type IdentityPrinter struct{}
// Print is an implementation of ResourcePrinter.Print which simply writes the data to the Writer.
@ -56,7 +56,7 @@ func (i *IdentityPrinter) PrintObj(obj interface{}, output io.Writer) error {
return i.Print(data, output)
}
// YAMLPrinter is an implementation of ResourcePrinter which parsess JSON, and re-formats as YAML
// YAMLPrinter is an implementation of ResourcePrinter which parsess JSON, and re-formats as YAML.
type YAMLPrinter struct{}
// Print parses the data as JSON, re-formats as YAML and prints the YAML.
@ -93,15 +93,15 @@ type HumanReadablePrinter struct {
handlerMap map[reflect.Type]*handlerEntry
}
// NewHumanReadablePrinter creates a HumanReadablePrinter
// NewHumanReadablePrinter creates a HumanReadablePrinter.
func NewHumanReadablePrinter() *HumanReadablePrinter {
printer := &HumanReadablePrinter{make(map[reflect.Type]*handlerEntry)}
printer.addDefaultHandlers()
return printer
}
// Handler adds a print handler with a given set of columns to HumanReadablePrinter instance
// printFunc is the function that will be called to print an object
// Handler adds a print handler with a given set of columns to HumanReadablePrinter instance.
// printFunc is the function that will be called to print an object.
// It must be of the following type:
// func printFunc(object ObjectType, w io.Writer) error
// where ObjectType is the type of the object that will be printed.
@ -142,7 +142,7 @@ var serviceColumns = []string{"Name", "Labels", "Selector", "Port"}
var minionColumns = []string{"Minion identifier"}
var statusColumns = []string{"Status"}
// handleDefaultTypes adds print handlers for default Kubernetes types
// addDefaultHandlers adds print handlers for default Kubernetes types.
func (h *HumanReadablePrinter) addDefaultHandlers() {
h.Handler(podColumns, printPod)
h.Handler(podColumns, printPodList)

View File

@ -28,17 +28,17 @@ import (
"github.com/golang/glog"
)
// PodConfigNotificationMode describes how changes are sent to the update channel
// PodConfigNotificationMode describes how changes are sent to the update channel.
type PodConfigNotificationMode int
const (
// PodConfigNotificationSnapshot delivers the full configuration as a SET whenever
// any change occurs
// any change occurs.
PodConfigNotificationSnapshot = iota
// PodConfigNotificationSetsAndUpdates delivers an UPDATE message whenever pods are
// PodConfigNotificationSnapshotAndUpdates delivers an UPDATE message whenever pods are
// changed, and a SET message if there are any additions or removals.
PodConfigNotificationSnapshotAndUpdates
// PodConfigNotificationIncremental delivers ADD, UPDATE, and REMOVE to the update channel
// PodConfigNotificationIncremental delivers ADD, UPDATE, and REMOVE to the update channel.
PodConfigNotificationIncremental
)
@ -267,7 +267,7 @@ func filterInvalidPods(pods []kubelet.Pod, source string) (filtered []*kubelet.P
return
}
// Sync sends a copy of the current state through the update channel
// Sync sends a copy of the current state through the update channel.
func (s *podStorage) Sync() {
s.updateLock.Lock()
defer s.updateLock.Unlock()

18
pkg/kubelet/config/doc.go Normal file
View File

@ -0,0 +1,18 @@
/*
Copyright 2014 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Package config implements the pod configuration readers.
package config

View File

@ -14,7 +14,7 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
// Reads the pod configuration from etcd using the Kubernetes etcd schema
// Reads the pod configuration from etcd using the Kubernetes etcd schema.
package config
import (
@ -46,7 +46,7 @@ type SourceEtcd struct {
timeout time.Duration
}
// NewSourceEtcd creates a config source that watches and pulls from a key in etcd
// NewSourceEtcd creates a config source that watches and pulls from a key in etcd.
func NewSourceEtcd(key string, client tools.EtcdClient, updates chan<- interface{}) *SourceEtcd {
config := &SourceEtcd{
key: key,
@ -60,7 +60,7 @@ func NewSourceEtcd(key string, client tools.EtcdClient, updates chan<- interface
return config
}
// run loops forever looking for changes to a key in etcd
// run loops forever looking for changes to a key in etcd.
func (s *SourceEtcd) run() {
index := uint64(0)
for {
@ -76,7 +76,7 @@ func (s *SourceEtcd) run() {
}
// fetchNextState fetches the key (or waits for a change to a key) and then returns
// the nextIndex to read. It will watch no longer than s.waitDuration and then return
// the nextIndex to read. It will watch no longer than s.waitDuration and then return.
func (s *SourceEtcd) fetchNextState(fromIndex uint64) (nextIndex uint64, err error) {
var response *etcd.Response
@ -142,5 +142,4 @@ func stopChannel(until time.Duration) chan bool {
close(stop)
}()
return stop
}

View File

@ -14,7 +14,7 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
// Reads the pod configuration from file or a directory of files
// Reads the pod configuration from file or a directory of files.
package config
import (

View File

@ -14,7 +14,7 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
// Reads the pod configuration from an HTTP GET response
// Reads the pod configuration from an HTTP GET response.
package config
import (

View File

@ -45,7 +45,7 @@ type Server struct {
mux *http.ServeMux
}
// ListenAndServeKubeletServer initializes a server to respond to HTTP network requests on the Kubelet
// ListenAndServeKubeletServer initializes a server to respond to HTTP network requests on the Kubelet.
func ListenAndServeKubeletServer(host HostInterface, updates chan<- interface{}, address string, port uint) {
glog.Infof("Starting to listen on %s:%d", address, port)
handler := NewServer(host, updates)
@ -70,7 +70,7 @@ type HostInterface interface {
ServeLogs(w http.ResponseWriter, req *http.Request)
}
// NewServer initializes and configures a kubelet.Server object to handle HTTP requests
// NewServer initializes and configures a kubelet.Server object to handle HTTP requests.
func NewServer(host HostInterface, updates chan<- interface{}) Server {
server := Server{
host: host,
@ -81,7 +81,7 @@ func NewServer(host HostInterface, updates chan<- interface{}) Server {
return server
}
// InstallDefaultHandlers registers the set of supported HTTP request patterns with the mux
// InstallDefaultHandlers registers the set of supported HTTP request patterns with the mux.
func (s *Server) InstallDefaultHandlers() {
healthz.InstallHandler(s.mux)
s.mux.HandleFunc("/container", s.handleContainer)
@ -93,12 +93,12 @@ func (s *Server) InstallDefaultHandlers() {
s.mux.HandleFunc("/run/", s.handleRun)
}
// error serializes an error object into an HTTP response
// error serializes an error object into an HTTP response.
func (s *Server) error(w http.ResponseWriter, err error) {
http.Error(w, fmt.Sprintf("Internal Error: %v", err), http.StatusInternalServerError)
}
// handleContainer handles container requests against the Kubelet
// handleContainer handles container requests against the Kubelet.
func (s *Server) handleContainer(w http.ResponseWriter, req *http.Request) {
defer req.Body.Close()
data, err := ioutil.ReadAll(req.Body)
@ -119,7 +119,7 @@ func (s *Server) handleContainer(w http.ResponseWriter, req *http.Request) {
}
// handleContainers handles containers requests against the Kubelet
// handleContainers handles containers requests against the Kubelet.
func (s *Server) handleContainers(w http.ResponseWriter, req *http.Request) {
defer req.Body.Close()
data, err := ioutil.ReadAll(req.Body)
@ -142,7 +142,7 @@ func (s *Server) handleContainers(w http.ResponseWriter, req *http.Request) {
}
// handlePodInfo handles podInfo requests against the Kubelet
// handlePodInfo handles podInfo requests against the Kubelet.
func (s *Server) handlePodInfo(w http.ResponseWriter, req *http.Request) {
u, err := url.ParseRequestURI(req.RequestURI)
if err != nil {
@ -176,17 +176,17 @@ func (s *Server) handlePodInfo(w http.ResponseWriter, req *http.Request) {
w.Write(data)
}
// handleStats handles stats requests against the Kubelet
// handleStats handles stats requests against the Kubelet.
func (s *Server) handleStats(w http.ResponseWriter, req *http.Request) {
s.serveStats(w, req)
}
// handleLogs handles logs requests against the Kubelet
// handleLogs handles logs requests against the Kubelet.
func (s *Server) handleLogs(w http.ResponseWriter, req *http.Request) {
s.host.ServeLogs(w, req)
}
// handleSpec handles spec requests against the Kubelet
// handleSpec handles spec requests against the Kubelet.
func (s *Server) handleSpec(w http.ResponseWriter, req *http.Request) {
info, err := s.host.GetMachineInfo()
if err != nil {
@ -203,7 +203,7 @@ func (s *Server) handleSpec(w http.ResponseWriter, req *http.Request) {
}
// handleRun handles requests to run a command inside a container
// handleRun handles requests to run a command inside a container.
func (s *Server) handleRun(w http.ResponseWriter, req *http.Request) {
u, err := url.ParseRequestURI(req.RequestURI)
if err != nil {
@ -228,7 +228,7 @@ func (s *Server) handleRun(w http.ResponseWriter, req *http.Request) {
w.Write(data)
}
// ServeHTTP responds to HTTP requests on the Kubelet
// ServeHTTP responds to HTTP requests on the Kubelet.
func (s *Server) ServeHTTP(w http.ResponseWriter, req *http.Request) {
defer httplog.NewLogged(req, &w).StacktraceWhen(
httplog.StatusIsNot(
@ -239,7 +239,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, req *http.Request) {
s.mux.ServeHTTP(w, req)
}
// serveStats implements stats logic
// serveStats implements stats logic.
func (s *Server) serveStats(w http.ResponseWriter, req *http.Request) {
// /stats/<podfullname>/<containerName>
components := strings.Split(strings.TrimPrefix(path.Clean(req.URL.Path), "/"), "/")

View File

@ -54,7 +54,7 @@ type PodUpdate struct {
Op PodOperation
}
//GetPodFullName returns a name that full identifies a pod across all config sources.
// GetPodFullName returns a name that full identifies a pod across all config sources.
func GetPodFullName(pod *Pod) string {
return fmt.Sprintf("%s.%s", pod.Name, pod.Namespace)
}

View File

@ -130,7 +130,7 @@ func (m *Master) init(cloud cloudprovider.Interface, podInfoGetter client.PodInf
}
}
// API_v1beta1 returns the resources and codec for API version v1beta1
// API_v1beta1 returns the resources and codec for API version v1beta1.
func (m *Master) API_v1beta1() (map[string]apiserver.RESTStorage, apiserver.Codec) {
storage := make(map[string]apiserver.RESTStorage)
for k, v := range m.storage {

View File

@ -46,7 +46,7 @@ func NewPodCache(info client.PodInfoGetter, pods pod.Registry) *PodCache {
}
}
// GetPodInfo Implements the PodInfoGetter.GetPodInfo.
// GetPodInfo implements the PodInfoGetter.GetPodInfo.
// The returned value should be treated as read-only.
// TODO: Remove the host from this call, it's totally unnecessary.
func (p *PodCache) GetPodInfo(host, podID string) (api.PodInfo, error) {

View File

@ -27,7 +27,7 @@ import (
"github.com/golang/glog"
)
// Watcher is the interface needed to receive changes to services and endpoints
// Watcher is the interface needed to receive changes to services and endpoints.
type Watcher interface {
WatchServices(label, field labels.Selector, resourceVersion uint64) (watch.Interface, error)
WatchEndpoints(label, field labels.Selector, resourceVersion uint64) (watch.Interface, error)
@ -44,7 +44,7 @@ type SourceAPI struct {
reconnectDuration time.Duration
}
// NewSourceAPI creates a config source that watches for changes to the services and endpoints
// NewSourceAPI creates a config source that watches for changes to the services and endpoints.
func NewSourceAPI(client Watcher, period time.Duration, services chan<- ServiceUpdate, endpoints chan<- EndpointsUpdate) *SourceAPI {
config := &SourceAPI{
client: client,
@ -68,7 +68,7 @@ func NewSourceAPI(client Watcher, period time.Duration, services chan<- ServiceU
return config
}
// runServices loops forever looking for changes to services
// runServices loops forever looking for changes to services.
func (s *SourceAPI) runServices(resourceVersion *uint64) {
watcher, err := s.client.WatchServices(labels.Everything(), labels.Everything(), *resourceVersion)
if err != nil {
@ -82,7 +82,7 @@ func (s *SourceAPI) runServices(resourceVersion *uint64) {
handleServicesWatch(resourceVersion, ch, s.services)
}
// handleServicesWatch loops over an event channel and delivers config changes to an update channel
// handleServicesWatch loops over an event channel and delivers config changes to an update channel.
func handleServicesWatch(resourceVersion *uint64, ch <-chan watch.Event, updates chan<- ServiceUpdate) {
for {
select {
@ -106,7 +106,7 @@ func handleServicesWatch(resourceVersion *uint64, ch <-chan watch.Event, updates
}
}
// runEndpoints loops forever looking for changes to endpoints
// runEndpoints loops forever looking for changes to endpoints.
func (s *SourceAPI) runEndpoints(resourceVersion *uint64) {
watcher, err := s.client.WatchEndpoints(labels.Everything(), labels.Everything(), *resourceVersion)
if err != nil {
@ -120,7 +120,7 @@ func (s *SourceAPI) runEndpoints(resourceVersion *uint64) {
handleEndpointsWatch(resourceVersion, ch, s.endpoints)
}
// handleEndpointsWatch loops over an event channel and delivers config changes to an update channel
// handleEndpointsWatch loops over an event channel and delivers config changes to an update channel.
func handleEndpointsWatch(resourceVersion *uint64, ch <-chan watch.Event, updates chan<- EndpointsUpdate) {
for {
select {

View File

@ -77,8 +77,8 @@ type EndpointsConfig struct {
store *endpointsStore
}
// NewEndpointConfig creates a new EndpointConfig.
// It immediately runs the created EndpointConfig.
// NewEndpointsConfig creates a new EndpointsConfig.
// It immediately runs the created EndpointsConfig.
func NewEndpointsConfig() *EndpointsConfig {
updates := make(chan struct{})
store := &endpointsStore{updates: updates, endpoints: make(map[string]map[string]api.Endpoints)}

View File

@ -20,7 +20,7 @@ import (
"net"
)
// A LoadBalancer distributes incoming requests to service endpoints.
// LoadBalancer is an interface for distributing incoming requests to service endpoints.
type LoadBalancer interface {
// NextEndpoint returns the endpoint to handle a request for the given
// service and source address.

View File

@ -31,7 +31,7 @@ type BindingStorage struct {
registry Registry
}
// NewBindingStorage makes a new BindingStorage backed by the given bindingRegistry.
// NewBindingStorage creates a new BindingStorage backed by the given bindingRegistry.
func NewBindingStorage(bindingRegistry Registry) *BindingStorage {
return &BindingStorage{
registry: bindingRegistry,

View File

@ -0,0 +1,19 @@
/*
Copyright 2014 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Package controller provides Registry interface and it's RESTStorage
// implementation for storing ReplicationController api objects.
package controller

View File

@ -0,0 +1,19 @@
/*
Copyright 2014 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Package endpoint provides Registry interface and it's RESTStorage
// implementation for storing Endpoint api objects.
package endpoint

View File

@ -37,12 +37,12 @@ func NewStorage(registry Registry) apiserver.RESTStorage {
}
}
// Get satisfies the RESTStorage interface but is unimplemented
// Get satisfies the RESTStorage interface but is unimplemented.
func (rs *Storage) Get(id string) (interface{}, error) {
return rs.registry.GetEndpoints(id)
}
// List satisfies the RESTStorage interface but is unimplemented
// List satisfies the RESTStorage interface but is unimplemented.
func (rs *Storage) List(selector labels.Selector) (interface{}, error) {
return nil, errors.New("unimplemented")
}
@ -53,22 +53,22 @@ func (rs *Storage) Watch(label, field labels.Selector, resourceVersion uint64) (
return rs.registry.WatchEndpoints(label, field, resourceVersion)
}
// Create satisfies the RESTStorage interface but is unimplemented
// Create satisfies the RESTStorage interface but is unimplemented.
func (rs *Storage) Create(obj interface{}) (<-chan interface{}, error) {
return nil, errors.New("unimplemented")
}
// Update satisfies the RESTStorage interface but is unimplemented
// Update satisfies the RESTStorage interface but is unimplemented.
func (rs *Storage) Update(obj interface{}) (<-chan interface{}, error) {
return nil, errors.New("unimplemented")
}
// Delete satisfies the RESTStorage interface but is unimplemented
// Delete satisfies the RESTStorage interface but is unimplemented.
func (rs *Storage) Delete(id string) (<-chan interface{}, error) {
return nil, errors.New("unimplemented")
}
// New implements the RESTStorage interface
// New implements the RESTStorage interface.
func (rs Storage) New() interface{} {
return &api.Endpoints{}
}

19
pkg/registry/etcd/doc.go Normal file
View File

@ -0,0 +1,19 @@
/*
Copyright 2014 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Package etcd provides etcd backend implementation for storing
// PodRegistry, ControllerRegistry and ServiceRegistry api objects.
package etcd

View File

@ -0,0 +1,19 @@
/*
Copyright 2014 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Package minion provides Registry interface and implementation
// for storing Minions.
package minion

View File

@ -26,7 +26,7 @@ import (
var ErrDoesNotExist = fmt.Errorf("The requested resource does not exist.")
// Keep track of a set of minions. Safe for concurrent reading/writing.
// Registry keeps track of a set of minions. Safe for concurrent reading/writing.
type Registry interface {
List() (currentMinions []string, err error)
Insert(minion string) error
@ -34,7 +34,7 @@ type Registry interface {
Contains(minion string) (bool, error)
}
// Initialize a minion registry with a list of minions.
// NewRegistry initializes a minion registry with a list of minions.
func NewRegistry(minions []string) Registry {
m := &minionList{
minions: util.StringSet{},

19
pkg/registry/pod/doc.go Normal file
View File

@ -0,0 +1,19 @@
/*
Copyright 2014 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Package pod provides Registry interface and it's RESTStorage
// implementation for storing Pod api objects.
package pod

View File

@ -34,7 +34,7 @@ import (
"github.com/golang/glog"
)
// RegistryStorage implements the RESTStorage interface in terms of a PodRegistry
// RegistryStorage implements the RESTStorage interface in terms of a PodRegistry.
type RegistryStorage struct {
cloudProvider cloudprovider.Interface
mu sync.Mutex

View File

@ -0,0 +1,19 @@
/*
Copyright 2014 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Package registrytest provides tests for Registry implementations
// for storing Minions, Pods, Schedulers and Services.
package registrytest

View File

@ -0,0 +1,19 @@
/*
Copyright 2014 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Package service provides Registry interface and it's RESTStorage
// implementation for storing Service api objects.
package service

View File

@ -29,12 +29,12 @@ type MinionLister interface {
// FakeMinionLister implements MinionLister on a []string for test purposes.
type FakeMinionLister []string
// List returns minions as a []string
// List returns minions as a []string.
func (f FakeMinionLister) List() ([]string, error) {
return []string(f), nil
}
// PodLister interface represents anything that can list pods for a scheduler
// PodLister interface represents anything that can list pods for a scheduler.
type PodLister interface {
// TODO: make this exactly the same as client's ListPods() method...
ListPods(labels.Selector) ([]api.Pod, error)

19
pkg/service/doc.go Normal file
View File

@ -0,0 +1,19 @@
/*
Copyright 2014 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Package service provides EndpointController implementation
// to manage and sync service endpoints.
package service

View File

@ -30,7 +30,7 @@ import (
"github.com/golang/glog"
)
// A EndpointController manages service endpoints.
// EndpointController manages service endpoints.
type EndpointController struct {
client *client.Client
serviceRegistry service.Registry

View File

@ -32,7 +32,7 @@ type APIEventDecoder struct {
decoder *json.Decoder
}
// NewAPIEventDecoder makes an APIEventDecoder for the given stream.
// NewAPIEventDecoder creates an APIEventDecoder for the given stream.
func NewAPIEventDecoder(stream io.ReadCloser) *APIEventDecoder {
return &APIEventDecoder{
stream: stream,

View File

@ -38,14 +38,14 @@ var (
EtcdErrorValueRequired = &etcd.EtcdError{ErrorCode: EtcdErrorCodeValueRequired}
)
// Codec provides methods for transforming Etcd values into objects and back
// Codec provides methods for transforming Etcd values into objects and back.
type Codec interface {
Encode(obj interface{}) (data []byte, err error)
Decode(data []byte) (interface{}, error)
DecodeInto(data []byte, obj interface{}) error
}
// ResourceVersioner provides methods for managing object modification tracking
// ResourceVersioner provides methods for managing object modification tracking.
type ResourceVersioner interface {
SetResourceVersion(obj interface{}, version uint64) error
ResourceVersion(obj interface{}) (uint64, error)
@ -64,7 +64,7 @@ type EtcdClient interface {
Watch(prefix string, waitIndex uint64, recursive bool, receiver chan *etcd.Response, stop chan bool) (*etcd.Response, error)
}
// Interface exposing only the etcd operations needed by EtcdHelper.
// EtcdGetSet interface exposes only the etcd operations needed by EtcdHelper.
type EtcdGetSet interface {
Get(key string, sort, recursive bool) (*etcd.Response, error)
Set(key, value string, ttl uint64) (*etcd.Response, error)
@ -134,7 +134,7 @@ func (h *EtcdHelper) listEtcdNode(key string) ([]*etcd.Node, uint64, error) {
return result.Node.Nodes, result.EtcdIndex, nil
}
// Extract a go object per etcd node into a slice with the resource version.
// ExtractList extracts a go object per etcd node into a slice with the resource version.
func (h *EtcdHelper) ExtractList(key string, slicePtr interface{}, resourceVersion *uint64) error {
nodes, index, err := h.listEtcdNode(key)
if resourceVersion != nil {
@ -197,7 +197,7 @@ func (h *EtcdHelper) bodyAndExtractObj(key string, objPtr interface{}, ignoreNot
return body, response.Node.ModifiedIndex, err
}
// Create adds a new object at a key unless it already exists
// CreateObj adds a new object at a key unless it already exists.
func (h *EtcdHelper) CreateObj(key string, obj interface{}) error {
data, err := h.Codec.Encode(obj)
if err != nil {
@ -213,7 +213,7 @@ func (h *EtcdHelper) CreateObj(key string, obj interface{}) error {
return err
}
// Delete removes the specified key
// Delete removes the specified key.
func (h *EtcdHelper) Delete(key string, recursive bool) error {
_, err := h.Client.Delete(key, recursive)
return err

View File

@ -71,7 +71,7 @@ func (h *EtcdHelper) WatchAndTransform(key string, resourceVersion uint64, trans
return w, nil
}
// TransformFunc attempts to convert an object to another object for use with a watcher
// TransformFunc attempts to convert an object to another object for use with a watcher.
type TransformFunc func(interface{}) (interface{}, error)
// etcdWatcher converts a native etcd watch to a watch.Interface.
@ -333,7 +333,7 @@ func (w *etcdWatcher) sendResult(res *etcd.Response) {
}
}
// ResultChannel implements watch.Interface.
// ResultChan implements watch.Interface.
func (w *etcdWatcher) ResultChan() <-chan watch.Event {
return w.outgoing
}

View File

@ -91,7 +91,7 @@ type Accessor interface {
MergedState() interface{}
}
// AccessorFunc implements the Accessor interface
// AccessorFunc implements the Accessor interface.
type AccessorFunc func() interface{}
func (f AccessorFunc) MergedState() interface{} {
@ -116,20 +116,20 @@ type Watcher struct {
listeners []Listener
}
// Register a set of listeners that support the Listener interface and
// notify them on changes.
// NewWatcher registers a set of listeners that support the Listener interface
// and notify them on changes.
func NewWatcher() *Watcher {
return &Watcher{}
}
// Register Listener to receive updates of changes.
// Add registers listener to receive updates of changes.
func (m *Watcher) Add(listener Listener) {
m.listenerLock.Lock()
defer m.listenerLock.Unlock()
m.listeners = append(m.listeners, listener)
}
// Notify all listeners
// Notify notifies all listeners.
func (m *Watcher) Notify(instance interface{}) {
m.listenerLock.RLock()
listeners := m.listeners

View File

@ -24,7 +24,7 @@ import (
)
// TestInterface is a simple interface providing Errorf, to make injection for
// testing easier (insert 'yo dawg' meme here)
// testing easier (insert 'yo dawg' meme here).
type TestInterface interface {
Errorf(format string, args ...interface{})
}

View File

@ -88,7 +88,7 @@ func NewIntOrStringFromInt(val int) IntOrString {
return IntOrString{Kind: IntstrInt, IntVal: val}
}
// NewIntOrStringFromInt creates an IntOrString object with a string value.
// NewIntOrStringFromString creates an IntOrString object with a string value.
func NewIntOrStringFromString(val string) IntOrString {
return IntOrString{Kind: IntstrString, StrVal: val}
}

View File

@ -29,13 +29,13 @@ import (
var ErrUnsupportedVolumeType = errors.New("unsupported volume type")
// Interface is a directory used by pods or hosts.
// All method implementations of methods in the volume interface must be idempotent
// All method implementations of methods in the volume interface must be idempotent.
type Interface interface {
// GetPath returns the directory path the volume is mounted to.
GetPath() string
}
// The Builder interface provides the method to set up/mount the volume.
// Builder interface provides method to set up/mount the volume.
type Builder interface {
// Uses Interface to provide the path for Docker binds.
Interface
@ -43,20 +43,20 @@ type Builder interface {
SetUp() error
}
// The Cleaner interface provides the method to cleanup/unmount the volumes.
// Cleaner interface provides method to cleanup/unmount the volumes.
type Cleaner interface {
// TearDown unmounts the volume and removes traces of the SetUp procedure.
TearDown() error
}
// Host Directory volumes represent a bare host directory mount.
// HostDirectory volumes represent a bare host directory mount.
// The directory in Path will be directly exposed to the container.
type HostDirectory struct {
Path string
}
// Host directory mounts require no setup or cleanup, but still
// need to fulfill the interface definitions.
// SetUp implements interface definitions, even though host directory
// mounts don't require any setup or cleanup.
func (hostVol *HostDirectory) SetUp() error {
return nil
}
@ -73,7 +73,7 @@ type EmptyDirectory struct {
RootDir string
}
// SetUp creates the new directory.
// SetUp creates new directory.
func (emptyDir *EmptyDirectory) SetUp() error {
path := emptyDir.GetPath()
err := os.MkdirAll(path, 0750)
@ -100,7 +100,7 @@ func (emptyDir *EmptyDirectory) renameDirectory() (string, error) {
return newPath, nil
}
// Simply delete everything in the directory.
// TearDown simply deletes everything in the directory.
func (emptyDir *EmptyDirectory) TearDown() error {
tmpDir, err := emptyDir.renameDirectory()
if err != nil {
@ -113,12 +113,12 @@ func (emptyDir *EmptyDirectory) TearDown() error {
return nil
}
// Interprets API volume as a HostDirectory
// createHostDirectory interprets API volume as a HostDirectory.
func createHostDirectory(volume *api.Volume) *HostDirectory {
return &HostDirectory{volume.Source.HostDirectory.Path}
}
// Interprets API volume as an EmptyDirectory
// createEmptyDirectory interprets API volume as an EmptyDirectory.
func createEmptyDirectory(volume *api.Volume, podID string, rootDir string) *EmptyDirectory {
return &EmptyDirectory{volume.Name, podID, rootDir}
}
@ -155,8 +155,8 @@ func CreateVolumeCleaner(kind string, name string, podID string, rootDir string)
}
}
// Examines directory structure to determine volumes that are presently
// active and mounted. Returns a map of Cleaner types.
// GetCurrentVolumes examines directory structure to determine volumes that are
// presently active and mounted. Returns a map of Cleaner types.
func GetCurrentVolumes(rootDirectory string) map[string]Cleaner {
currentVolumes := make(map[string]Cleaner)
mountPath := rootDirectory

View File

@ -16,8 +16,6 @@ limitations under the License.
package watch
import ()
// FilterFunc should take an event, possibly modify it in some way, and return
// the modified event. If the event should be ignored, then return keep=false.
type FilterFunc func(in Event) (out Event, keep bool)

View File

@ -73,7 +73,7 @@ func (sw *StreamWatcher) Stop() {
}
}
// In a loop, read a result from the decoder and send down the result channel.
// receive reads result from the decoder in a loop and sends down the result channel.
func (sw *StreamWatcher) receive() {
defer close(sw.result)
defer sw.Stop()

View File

@ -181,7 +181,7 @@ type minionEnumerator struct {
*api.MinionList
}
// Returns the number of items in the pod list.
// Len returns the number of items in the pod list.
func (me *minionEnumerator) Len() int {
if me.MinionList == nil {
return 0
@ -189,7 +189,7 @@ func (me *minionEnumerator) Len() int {
return len(me.Items)
}
// Returns the item (and ID) with the particular index.
// Get returns the item (and ID) with the particular index.
func (me *minionEnumerator) Get(index int) (string, interface{}) {
return me.Items[index].ID, &me.Items[index]
}