本文整理汇总了Golang中k8s/io/kubernetes/pkg/api.ReplicationController类的典型用法代码示例。如果您正苦于以下问题:Golang ReplicationController类的具体用法?Golang ReplicationController怎么用?Golang ReplicationController使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ReplicationController类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: Rename
func Rename(c coreclient.ReplicationControllersGetter, rc *api.ReplicationController, newName string) error {
oldName := rc.Name
rc.Name = newName
rc.ResourceVersion = ""
// First delete the oldName RC and orphan its pods.
trueVar := true
err := c.ReplicationControllers(rc.Namespace).Delete(oldName, &api.DeleteOptions{OrphanDependents: &trueVar})
if err != nil && !errors.IsNotFound(err) {
return err
}
err = wait.Poll(5*time.Second, 60*time.Second, func() (bool, error) {
_, err := c.ReplicationControllers(rc.Namespace).Get(oldName)
if err == nil {
return false, nil
} else if errors.IsNotFound(err) {
return true, nil
} else {
return false, err
}
})
if err != nil {
return err
}
// Then create the same RC with the new name.
_, err = c.ReplicationControllers(rc.Namespace).Create(rc)
if err != nil {
return err
}
return nil
}
示例2: Rename
func Rename(c client.ReplicationControllersNamespacer, rc *api.ReplicationController, newName string) error {
oldName := rc.Name
rc.Name = newName
rc.ResourceVersion = ""
_, err := c.ReplicationControllers(rc.Namespace).Create(rc)
if err != nil {
return err
}
err = c.ReplicationControllers(rc.Namespace).Delete(oldName)
if err != nil && !errors.IsNotFound(err) {
return err
}
return nil
}
示例3: Rename
func Rename(c RollingUpdaterClient, rc *api.ReplicationController, newName string) error {
oldName := rc.Name
rc.Name = newName
rc.ResourceVersion = ""
_, err := c.CreateReplicationController(rc.Namespace, rc)
if err != nil {
return err
}
err = c.DeleteReplicationController(rc.Namespace, oldName)
if err != nil && !errors.IsNotFound(err) {
return err
}
return nil
}
示例4: getOrCreateTargetControllerWithClient
// getOrCreateTargetControllerWithClient looks for an existing controller with
// sourceId. If found, the existing controller is returned with true
// indicating that the controller already exists. If the controller isn't
// found, a new one is created and returned along with false indicating the
// controller was created.
//
// Existing controllers are validated to ensure their sourceIdAnnotation
// matches sourceId; if there's a mismatch, an error is returned.
func (r *RollingUpdater) getOrCreateTargetControllerWithClient(controller *api.ReplicationController, sourceId string) (*api.ReplicationController, bool, error) {
existingRc, err := r.existingController(controller)
if err != nil {
if !errors.IsNotFound(err) {
// There was an error trying to find the controller; don't assume we
// should create it.
return nil, false, err
}
if controller.Spec.Replicas <= 0 {
return nil, false, fmt.Errorf("Invalid controller spec for %s; required: > 0 replicas, actual: %d\n", controller.Name, controller.Spec)
}
// The controller wasn't found, so create it.
if controller.Annotations == nil {
controller.Annotations = map[string]string{}
}
controller.Annotations[desiredReplicasAnnotation] = fmt.Sprintf("%d", controller.Spec.Replicas)
controller.Annotations[sourceIdAnnotation] = sourceId
controller.Spec.Replicas = 0
newRc, err := r.c.ReplicationControllers(r.ns).Create(controller)
return newRc, false, err
}
// Validate and use the existing controller.
annotations := existingRc.Annotations
source := annotations[sourceIdAnnotation]
_, ok := annotations[desiredReplicasAnnotation]
if source != sourceId || !ok {
return nil, false, fmt.Errorf("Missing/unexpected annotations for controller %s, expected %s : %s", controller.Name, sourceId, annotations)
}
return existingRc, true, nil
}
示例5: deployerPod
func deployerPod(deployment *kapi.ReplicationController, alternateName string, related bool) *kapi.Pod {
deployerPodName := deployutil.DeployerPodNameForDeployment(deployment.Name)
if len(alternateName) > 0 {
deployerPodName = alternateName
}
deployment.Namespace = "test"
pod := &kapi.Pod{
ObjectMeta: kapi.ObjectMeta{
Name: deployerPodName,
Namespace: deployment.Namespace,
Labels: map[string]string{
deployapi.DeployerPodForDeploymentLabel: deployment.Name,
},
Annotations: map[string]string{
deployapi.DeploymentAnnotation: deployment.Name,
},
},
}
if !related {
delete(pod.Annotations, deployapi.DeploymentAnnotation)
}
return pod
}
示例6: updateRCRevision
func (dc *DeploymentController) updateRCRevision(rc api.ReplicationController, revision string) error {
if rc.Annotations == nil {
rc.Annotations = make(map[string]string)
}
rc.Annotations[deploymentutil.RevisionAnnotation] = revision
_, err := dc.client.Legacy().ReplicationControllers(rc.ObjectMeta.Namespace).Update(&rc)
return err
}
示例7: validateRC
func validateRC(rc *kube.ReplicationController) error {
errList := validation.ValidateReplicationController(rc).Filter(
// remove errors about missing template
func(e error) bool {
return e.Error() == "spec.template: Required value"
},
)
meta := rc.GetObjectMeta()
if len(meta.GetName()) == 0 && len(meta.GetGenerateName()) > 0 {
errList = errList.Filter(func(e error) bool {
return e.Error() == "metadata.name: Required value: name or generateName is required"
})
}
return errList.ToAggregate()
}
示例8: TestWatchControllers
func TestWatchControllers(t *testing.T) {
fakeWatch := watch.NewFake()
c := &fake.Clientset{}
c.AddWatchReactor("*", core.DefaultWatchReactor(fakeWatch, nil))
manager := NewReplicationManagerFromClient(c, controller.NoResyncPeriodFunc, BurstReplicas, 0)
manager.podStoreSynced = alwaysReady
var testControllerSpec api.ReplicationController
received := make(chan string)
// The update sent through the fakeWatcher should make its way into the workqueue,
// and eventually into the syncHandler. The handler validates the received controller
// and closes the received channel to indicate that the test can finish.
manager.syncHandler = func(key string) error {
obj, exists, err := manager.rcStore.Store.GetByKey(key)
if !exists || err != nil {
t.Errorf("Expected to find controller under key %v", key)
}
controllerSpec := *obj.(*api.ReplicationController)
if !api.Semantic.DeepDerivative(controllerSpec, testControllerSpec) {
t.Errorf("Expected %#v, but got %#v", testControllerSpec, controllerSpec)
}
close(received)
return nil
}
// Start only the rc watcher and the workqueue, send a watch event,
// and make sure it hits the sync method.
stopCh := make(chan struct{})
defer close(stopCh)
go manager.rcController.Run(stopCh)
go wait.Until(manager.worker, 10*time.Millisecond, stopCh)
testControllerSpec.Name = "foo"
fakeWatch.Add(&testControllerSpec)
select {
case <-received:
case <-time.After(wait.ForeverTestTimeout):
t.Errorf("Expected 1 call but got 0")
}
}
示例9: createReplicationController
func createReplicationController(c *gin.Context) {
namespace := c.Param("ns")
rcjson := c.PostForm("json")
var rc api.ReplicationController
err := json.Unmarshal([]byte(rcjson), &rc)
if err != nil {
c.HTML(http.StatusInternalServerError, "error", gin.H{"error": err.Error()})
return
}
if rc.Spec.Selector == nil {
rc.Spec.Selector = make(map[string]string)
}
rc.Spec.Selector["managed-by"] = rc.Name
if rc.Spec.Template.Labels == nil {
rc.Spec.Template.Labels = make(map[string]string)
}
rc.Spec.Template.Labels["managed-by"] = rc.Name
rc.Spec.Template.Spec.Containers[0].Name = rc.Name
var meta api.ObjectMeta // clean metadata
meta.Name = rc.Name
meta.GenerateName = rc.GenerateName
meta.Labels = rc.Labels
meta.Annotations = rc.Annotations
if meta.Labels != nil {
meta.Labels["managed-by"] = rc.Name
}
rc.ObjectMeta = meta
_, err = kubeclient.Get().ReplicationControllers(namespace).Create(&rc)
if err != nil {
c.HTML(http.StatusInternalServerError, "error", gin.H{"error": err.Error()})
return
}
c.Redirect(http.StatusMovedPermanently, fmt.Sprintf("/namespaces/%s", namespace))
}
示例10: setNewRCAnnotations
// setNewRCAnnotations sets new rc's annotations appropriately by updating its revision and
// copying required deployment annotations to it; it returns true if rc's annotation is changed.
func setNewRCAnnotations(deployment *extensions.Deployment, rc *api.ReplicationController, newRevision string) bool {
// First, copy deployment's annotations
annotationChanged := copyDeploymentAnnotationsToRC(deployment, rc)
// Then, update RC's revision annotation
if rc.Annotations == nil {
rc.Annotations = make(map[string]string)
}
if rc.Annotations[deploymentutil.RevisionAnnotation] != newRevision {
rc.Annotations[deploymentutil.RevisionAnnotation] = newRevision
annotationChanged = true
glog.V(4).Infof("updating RC %q's revision to %s - %+v\n", rc.Name, newRevision)
}
return annotationChanged
}
示例11: copyDeploymentAnnotationsToRC
// copyDeploymentAnnotationsToRC copies deployment's annotations to rc's annotations,
// and returns true if rc's annotation is changed
func copyDeploymentAnnotationsToRC(deployment *extensions.Deployment, rc *api.ReplicationController) bool {
rcAnnotationsChanged := false
if rc.Annotations == nil {
rc.Annotations = make(map[string]string)
}
for k, v := range deployment.Annotations {
// Skip apply annotations
// TODO: How to decide which annotations should / should not be copied?
// See https://github.com/kubernetes/kubernetes/pull/20035#issuecomment-179558615
if k == kubectl.LastAppliedConfigAnnotation || rc.Annotations[k] == v {
continue
}
rc.Annotations[k] = v
rcAnnotationsChanged = true
}
return rcAnnotationsChanged
}
示例12: GetOrCreatePodSpec
// GetOrCreatePodSpec returns the PodSpec for this ReplicationController
// lazily creating structures as required
func GetOrCreatePodSpec(rc *api.ReplicationController) *api.PodSpec {
spec := &rc.Spec
if spec == nil {
rc.Spec = api.ReplicationControllerSpec{}
spec = &rc.Spec
}
template := spec.Template
if template == nil {
spec.Template = &api.PodTemplateSpec{}
template = spec.Template
}
podSpec := &template.Spec
if podSpec == nil {
template.Spec = api.PodSpec{}
podSpec = &template.Spec
}
return podSpec
}
示例13: updateReplicationControllerStatus
// updateReplicationControllerStatus attempts to update the Status.Replicas of the given controller, with a single GET/PUT retry.
func updateReplicationControllerStatus(c unversionedcore.ReplicationControllerInterface, rc api.ReplicationController, newStatus api.ReplicationControllerStatus) (updateErr error) {
// This is the steady state. It happens when the rc doesn't have any expectations, since
// we do a periodic relist every 30s. If the generations differ but the replicas are
// the same, a caller might've resized to the same replica count.
if rc.Status.Replicas == newStatus.Replicas &&
rc.Status.FullyLabeledReplicas == newStatus.FullyLabeledReplicas &&
rc.Status.ReadyReplicas == newStatus.ReadyReplicas &&
rc.Status.AvailableReplicas == newStatus.AvailableReplicas &&
rc.Generation == rc.Status.ObservedGeneration &&
reflect.DeepEqual(rc.Status.Conditions, newStatus.Conditions) {
return nil
}
// Save the generation number we acted on, otherwise we might wrongfully indicate
// that we've seen a spec update when we retry.
// TODO: This can clobber an update if we allow multiple agents to write to the
// same status.
newStatus.ObservedGeneration = rc.Generation
var getErr error
for i, rc := 0, &rc; ; i++ {
glog.V(4).Infof(fmt.Sprintf("Updating replica count for rc: %s/%s, ", rc.Namespace, rc.Name) +
fmt.Sprintf("replicas %d->%d (need %d), ", rc.Status.Replicas, newStatus.Replicas, rc.Spec.Replicas) +
fmt.Sprintf("fullyLabeledReplicas %d->%d, ", rc.Status.FullyLabeledReplicas, newStatus.FullyLabeledReplicas) +
fmt.Sprintf("readyReplicas %d->%d, ", rc.Status.ReadyReplicas, newStatus.ReadyReplicas) +
fmt.Sprintf("availableReplicas %d->%d, ", rc.Status.AvailableReplicas, newStatus.AvailableReplicas) +
fmt.Sprintf("sequence No: %v->%v", rc.Status.ObservedGeneration, newStatus.ObservedGeneration))
rc.Status = newStatus
_, updateErr = c.UpdateStatus(rc)
if updateErr == nil || i >= statusUpdateRetries {
return updateErr
}
// Update the controller with the latest resource version for the next poll
if rc, getErr = c.Get(rc.Name); getErr != nil {
// If the GET fails we can't trust status.Replicas anymore. This error
// is bound to be more interesting than the update failure.
return getErr
}
}
}
示例14: RunRollingUpdate
func RunRollingUpdate(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string, options *RollingUpdateOptions) error {
if len(os.Args) > 1 && os.Args[1] == "rollingupdate" {
printDeprecationWarning("rolling-update", "rollingupdate")
}
err := validateArguments(cmd, options.Filenames, args)
if err != nil {
return err
}
deploymentKey := cmdutil.GetFlagString(cmd, "deployment-label-key")
filename := ""
image := cmdutil.GetFlagString(cmd, "image")
pullPolicy := cmdutil.GetFlagString(cmd, "image-pull-policy")
oldName := args[0]
rollback := cmdutil.GetFlagBool(cmd, "rollback")
period := cmdutil.GetFlagDuration(cmd, "update-period")
interval := cmdutil.GetFlagDuration(cmd, "poll-interval")
timeout := cmdutil.GetFlagDuration(cmd, "timeout")
dryrun := cmdutil.GetFlagBool(cmd, "dry-run")
outputFormat := cmdutil.GetFlagString(cmd, "output")
container := cmdutil.GetFlagString(cmd, "container")
if len(options.Filenames) > 0 {
filename = options.Filenames[0]
}
cmdNamespace, enforceNamespace, err := f.DefaultNamespace()
if err != nil {
return err
}
client, err := f.Client()
if err != nil {
return err
}
var newRc *api.ReplicationController
// fetch rc
oldRc, err := client.ReplicationControllers(cmdNamespace).Get(oldName)
if err != nil {
if !errors.IsNotFound(err) || len(image) == 0 || len(args) > 1 {
return err
}
// We're in the middle of a rename, look for an RC with a source annotation of oldName
newRc, err := kubectl.FindSourceController(client, cmdNamespace, oldName)
if err != nil {
return err
}
return kubectl.Rename(client, newRc, oldName)
}
var keepOldName bool
var replicasDefaulted bool
mapper, typer := f.Object(cmdutil.GetIncludeThirdPartyAPIs(cmd))
if len(filename) != 0 {
schema, err := f.Validator(cmdutil.GetFlagBool(cmd, "validate"), cmdutil.GetFlagString(cmd, "schema-cache-dir"))
if err != nil {
return err
}
request := resource.NewBuilder(mapper, typer, resource.ClientMapperFunc(f.ClientForMapping), f.Decoder(true)).
Schema(schema).
NamespaceParam(cmdNamespace).DefaultNamespace().
FilenameParam(enforceNamespace, false, filename).
Do()
obj, err := request.Object()
if err != nil {
return err
}
var ok bool
// Handle filename input from stdin. The resource builder always returns an api.List
// when creating resource(s) from a stream.
if list, ok := obj.(*api.List); ok {
if len(list.Items) > 1 {
return cmdutil.UsageError(cmd, "%s specifies multiple items", filename)
}
obj = list.Items[0]
}
newRc, ok = obj.(*api.ReplicationController)
if !ok {
if gvk, err := typer.ObjectKind(obj); err == nil {
return cmdutil.UsageError(cmd, "%s contains a %v not a ReplicationController", filename, gvk)
}
glog.V(4).Infof("Object %#v is not a ReplicationController", obj)
return cmdutil.UsageError(cmd, "%s does not specify a valid ReplicationController", filename)
}
infos, err := request.Infos()
if err != nil || len(infos) != 1 {
glog.V(2).Infof("was not able to recover adequate information to discover if .spec.replicas was defaulted")
} else {
replicasDefaulted = isReplicasDefaulted(infos[0])
}
}
// If the --image option is specified, we need to create a new rc with at least one different selector
// than the old rc. This selector is the hash of the rc, with a suffix to provide uniqueness for
// same-image updates.
if len(image) != 0 {
codec := api.Codecs.LegacyCodec(client.APIVersion())
//.........这里部分代码省略.........
示例15: RunRollingUpdate
func RunRollingUpdate(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string, options *RollingUpdateOptions) error {
if len(os.Args) > 1 && os.Args[1] == "rollingupdate" {
printDeprecationWarning("rolling-update", "rollingupdate")
}
deploymentKey, filename, image, oldName, err := validateArguments(cmd, options.Filenames, args)
if err != nil {
return err
}
period := cmdutil.GetFlagDuration(cmd, "update-period")
interval := cmdutil.GetFlagDuration(cmd, "poll-interval")
timeout := cmdutil.GetFlagDuration(cmd, "timeout")
dryrun := cmdutil.GetFlagBool(cmd, "dry-run")
outputFormat := cmdutil.GetFlagString(cmd, "output")
cmdNamespace, enforceNamespace, err := f.DefaultNamespace()
if err != nil {
return err
}
client, err := f.Client()
if err != nil {
return err
}
var newRc *api.ReplicationController
// fetch rc
oldRc, err := client.ReplicationControllers(cmdNamespace).Get(oldName)
if err != nil {
if !errors.IsNotFound(err) || len(image) == 0 || len(args) > 1 {
return err
}
// We're in the middle of a rename, look for an RC with a source annotation of oldName
newRc, err := kubectl.FindSourceController(client, cmdNamespace, oldName)
if err != nil {
return err
}
return kubectl.Rename(client, newRc, oldName)
}
var keepOldName bool
var replicasDefaulted bool
mapper, typer := f.Object()
if len(filename) != 0 {
schema, err := f.Validator(cmdutil.GetFlagBool(cmd, "validate"))
if err != nil {
return err
}
request := resource.NewBuilder(mapper, typer, f.ClientMapperForCommand()).
Schema(schema).
NamespaceParam(cmdNamespace).DefaultNamespace().
FilenameParam(enforceNamespace, filename).
Do()
obj, err := request.Object()
if err != nil {
return err
}
var ok bool
// Handle filename input from stdin. The resource builder always returns an api.List
// when creating resource(s) from a stream.
if list, ok := obj.(*api.List); ok {
if len(list.Items) > 1 {
return cmdutil.UsageError(cmd, "%s specifies multiple items", filename)
}
obj = list.Items[0]
}
newRc, ok = obj.(*api.ReplicationController)
if !ok {
if _, kind, err := typer.ObjectVersionAndKind(obj); err == nil {
return cmdutil.UsageError(cmd, "%s contains a %s not a ReplicationController", filename, kind)
}
glog.V(4).Infof("Object %#v is not a ReplicationController", obj)
return cmdutil.UsageError(cmd, "%s does not specify a valid ReplicationController", filename)
}
infos, err := request.Infos()
if err != nil || len(infos) != 1 {
glog.V(2).Infof("was not able to recover adequate information to discover if .spec.replicas was defaulted")
} else {
replicasDefaulted = isReplicasDefaulted(infos[0])
}
}
// If the --image option is specified, we need to create a new rc with at least one different selector
// than the old rc. This selector is the hash of the rc, which will differ because the new rc has a
// different image.
if len(image) != 0 {
keepOldName = len(args) == 1
newName := findNewName(args, oldRc)
if newRc, err = kubectl.LoadExistingNextReplicationController(client, cmdNamespace, newName); err != nil {
return err
}
if newRc != nil {
fmt.Fprintf(out, "Found existing update in progress (%s), resuming.\n", newRc.Name)
} else {
newRc, err = kubectl.CreateNewControllerFromCurrentController(client, cmdNamespace, oldName, newName, image, deploymentKey)
if err != nil {
return err
}
}
//.........这里部分代码省略.........