本文整理匯總了Golang中k8s/io/kubernetes/pkg/api.GetReference函數的典型用法代碼示例。如果您正苦於以下問題:Golang GetReference函數的具體用法?Golang GetReference怎麽用?Golang GetReference使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了GetReference函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: emitEvent
func (e *HookExecutor) emitEvent(deployment *kapi.ReplicationController, eventType, reason, msg string) {
t := unversioned.Time{Time: time.Now()}
var ref *kapi.ObjectReference
if config, err := deployutil.DecodeDeploymentConfig(deployment, e.decoder); err != nil {
glog.Errorf("Unable to decode deployment %s/%s to replication contoller: %v", deployment.Namespace, deployment.Name, err)
if ref, err = kapi.GetReference(deployment); err != nil {
glog.Errorf("Unable to get reference for %#v: %v", deployment, err)
return
}
} else {
if ref, err = kapi.GetReference(config); err != nil {
glog.Errorf("Unable to get reference for %#v: %v", config, err)
return
}
}
event := &kapi.Event{
ObjectMeta: kapi.ObjectMeta{
Name: fmt.Sprintf("%v.%x", ref.Name, t.UnixNano()),
Namespace: ref.Namespace,
},
InvolvedObject: *ref,
Reason: reason,
Message: msg,
FirstTimestamp: t,
LastTimestamp: t,
Count: 1,
Type: eventType,
}
if _, err := e.events.Create(event); err != nil {
glog.Errorf("Could not send event '%#v': %v", event, err)
}
}
示例2: TestReconcileVolume
func TestReconcileVolume(t *testing.T) {
controller, mockClient := makeTestController()
pv := makeTestVolume()
pvc := makeTestClaim()
err := controller.reconcileVolume(pv)
if err != nil {
t.Errorf("Unexpected error %v", err)
}
// watch adds claim to the store.
// we need to add it to our mock client to mimic normal Get call
controller.claimStore.Add(pvc)
mockClient.claim = pvc
// pretend the claim and volume are bound, no provisioning required
claimRef, _ := api.GetReference(pvc)
pv.Spec.ClaimRef = claimRef
err = controller.reconcileVolume(pv)
if err != nil {
t.Errorf("Unexpected error %v", err)
}
pv.Annotations[pvProvisioningRequiredAnnotationKey] = "!pvProvisioningCompleted"
pv.Annotations[qosProvisioningKey] = "foo"
err = controller.reconcileVolume(pv)
if !isAnnotationMatch(pvProvisioningRequiredAnnotationKey, pvProvisioningCompletedAnnotationValue, mockClient.volume.Annotations) {
t.Errorf("Expected %s but got %s", pvProvisioningRequiredAnnotationKey, mockClient.volume.Annotations[pvProvisioningRequiredAnnotationKey])
}
}
示例3: TestWatchHTTP
func TestWatchHTTP(t *testing.T) {
simpleStorage := &SimpleRESTStorage{}
handler := handle(map[string]rest.Storage{"simples": simpleStorage})
server := httptest.NewServer(handler)
defer server.Close()
client := http.Client{}
dest, _ := url.Parse(server.URL)
dest.Path = "/" + prefix + "/" + testGroupVersion.Group + "/" + testGroupVersion.Version + "/watch/simples"
dest.RawQuery = ""
request, err := http.NewRequest("GET", dest.String(), nil)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
response, err := client.Do(request)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
if response.StatusCode != http.StatusOK {
t.Errorf("Unexpected response %#v", response)
}
decoder := json.NewDecoder(response.Body)
for i, item := range watchTestTable {
// Send
simpleStorage.fakeWatch.Action(item.t, item.obj)
// Test receive
var got watchJSON
err := decoder.Decode(&got)
if err != nil {
t.Fatalf("%d: Unexpected error: %v", i, err)
}
if got.Type != item.t {
t.Errorf("%d: Unexpected type: %v", i, got.Type)
}
t.Logf("obj: %v", string(got.Object))
gotObj, err := codec.Decode(got.Object)
if err != nil {
t.Fatalf("Decode error: %v", err)
}
t.Logf("obj: %#v", gotObj)
if _, err := api.GetReference(gotObj); err != nil {
t.Errorf("Unable to construct reference: %v", err)
}
if e, a := item.obj, gotObj; !reflect.DeepEqual(e, a) {
t.Errorf("Expected %#v, got %#v", e, a)
}
}
simpleStorage.fakeWatch.Stop()
var got watchJSON
err = decoder.Decode(&got)
if err == nil {
t.Errorf("Unexpected non-error")
}
}
示例4: Describe
func (d *PodDescriber) Describe(namespace, name string) (string, error) {
rc := d.ReplicationControllers(namespace)
pc := d.Pods(namespace)
pod, err := pc.Get(name)
if err != nil {
eventsInterface := d.Events(namespace)
events, err2 := eventsInterface.List(
labels.Everything(),
eventsInterface.GetFieldSelector(&name, &namespace, nil, nil))
if err2 == nil && len(events.Items) > 0 {
return tabbedString(func(out io.Writer) error {
fmt.Fprintf(out, "Pod '%v': error '%v', but found events.\n", name, err)
DescribeEvents(events, out)
return nil
})
}
return "", err
}
var events *api.EventList
if ref, err := api.GetReference(pod); err != nil {
glog.Errorf("Unable to construct reference to '%#v': %v", pod, err)
} else {
ref.Kind = ""
events, _ = d.Events(namespace).Search(ref)
}
rcs, err := getReplicationControllersForLabels(rc, labels.Set(pod.Labels))
if err != nil {
return "", err
}
return describePod(pod, rcs, events)
}
示例5: RecordConfigEvent
// RecordConfigEvent records an event for the deployment config referenced by the
// deployment.
func RecordConfigEvent(client kclient.EventNamespacer, deployment *kapi.ReplicationController, decoder runtime.Decoder, eventType, reason, msg string) {
t := unversioned.Time{Time: time.Now()}
var obj runtime.Object = deployment
if config, err := deployutil.DecodeDeploymentConfig(deployment, decoder); err == nil {
obj = config
} else {
glog.Errorf("Unable to decode deployment config from %s/%s: %v", deployment.Namespace, deployment.Name, err)
}
ref, err := kapi.GetReference(obj)
if err != nil {
glog.Errorf("Unable to get reference for %#v: %v", obj, err)
return
}
event := &kapi.Event{
ObjectMeta: kapi.ObjectMeta{
Name: fmt.Sprintf("%v.%x", ref.Name, t.UnixNano()),
Namespace: ref.Namespace,
},
InvolvedObject: *ref,
Reason: reason,
Message: msg,
Source: kapi.EventSource{
Component: deployutil.DeployerPodNameFor(deployment),
},
FirstTimestamp: t,
LastTimestamp: t,
Count: 1,
Type: eventType,
}
if _, err := client.Events(ref.Namespace).Create(event); err != nil {
glog.Errorf("Could not create event '%#v': %v", event, err)
}
}
示例6: refJSON
func refJSON(t *testing.T, o runtime.Object) string {
ref, err := api.GetReference(o)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
codec := testapi.Default.Codec()
json := runtime.EncodeOrDie(codec, &api.SerializedReference{Reference: *ref})
return string(json)
}
示例7: reconcileClaim
func (controller *PersistentVolumeProvisionerController) reconcileClaim(claim *api.PersistentVolumeClaim) error {
if controller.provisioner == nil {
return fmt.Errorf("No provisioner configured for controller")
}
// no provisioning requested, return Pending. Claim may be pending indefinitely without a match.
if !keyExists(qosProvisioningKey, claim.Annotations) {
glog.V(5).Infof("PersistentVolumeClaim[%s] no provisioning required", claim.Name)
return nil
}
if len(claim.Spec.VolumeName) != 0 {
glog.V(5).Infof("PersistentVolumeClaim[%s] already bound. No provisioning required", claim.Name)
return nil
}
if isAnnotationMatch(pvProvisioningRequiredAnnotationKey, pvProvisioningCompletedAnnotationValue, claim.Annotations) {
glog.V(5).Infof("PersistentVolumeClaim[%s] is already provisioned.", claim.Name)
return nil
}
glog.V(5).Infof("PersistentVolumeClaim[%s] provisioning", claim.Name)
provisioner, err := newProvisioner(controller.provisioner, claim)
if err != nil {
return fmt.Errorf("Unexpected error getting new provisioner for claim %s: %v\n", claim.Name, err)
}
newVolume, err := provisioner.NewPersistentVolumeTemplate()
if err != nil {
return fmt.Errorf("Unexpected error getting new volume template for claim %s: %v\n", claim.Name, err)
}
claimRef, err := api.GetReference(claim)
if err != nil {
return fmt.Errorf("Unexpected error getting claim reference for %s: %v\n", claim.Name, err)
}
storageClass, _ := claim.Annotations[qosProvisioningKey]
// the creation of this volume is the bind to the claim.
// The claim will match the volume during the next sync period when the volume is in the local cache
newVolume.Spec.ClaimRef = claimRef
newVolume.Annotations[pvProvisioningRequiredAnnotationKey] = "true"
newVolume.Annotations[qosProvisioningKey] = storageClass
newVolume, err = controller.client.CreatePersistentVolume(newVolume)
glog.V(5).Infof("Unprovisioned PersistentVolume[%s] created for PVC[%s], which will be fulfilled in the storage provider", newVolume.Name, claim.Name)
if err != nil {
return fmt.Errorf("PersistentVolumeClaim[%s] failed provisioning: %+v", claim.Name, err)
}
claim.Annotations[pvProvisioningRequiredAnnotationKey] = pvProvisioningCompletedAnnotationValue
_, err = controller.client.UpdatePersistentVolumeClaim(claim)
if err != nil {
glog.Error("error updating persistent volume claim: %v", err)
}
return nil
}
示例8: TestWatchWebsocket
func TestWatchWebsocket(t *testing.T) {
simpleStorage := &SimpleRESTStorage{}
_ = rest.Watcher(simpleStorage) // Give compile error if this doesn't work.
handler := handle(map[string]rest.Storage{"simples": simpleStorage})
server := httptest.NewServer(handler)
// TODO: Uncomment when fix #19254
// defer server.Close()
dest, _ := url.Parse(server.URL)
dest.Scheme = "ws" // Required by websocket, though the server never sees it.
dest.Path = "/" + prefix + "/" + testGroupVersion.Group + "/" + testGroupVersion.Version + "/watch/simples"
dest.RawQuery = ""
ws, err := websocket.Dial(dest.String(), "", "http://localhost")
if err != nil {
t.Errorf("unexpected error: %v", err)
}
try := func(action watch.EventType, object runtime.Object) {
// Send
simpleStorage.fakeWatch.Action(action, object)
// Test receive
var got watchJSON
err := websocket.JSON.Receive(ws, &got)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
if got.Type != action {
t.Errorf("Unexpected type: %v", got.Type)
}
gotObj, err := runtime.Decode(codec, got.Object)
if err != nil {
t.Fatalf("Decode error: %v", err)
}
if _, err := api.GetReference(gotObj); err != nil {
t.Errorf("Unable to construct reference: %v", err)
}
if e, a := object, gotObj; !reflect.DeepEqual(e, a) {
t.Errorf("Expected %#v, got %#v", e, a)
}
}
for _, item := range watchTestTable {
try(item.t, item.obj)
}
simpleStorage.fakeWatch.Stop()
var got watchJSON
err = websocket.JSON.Receive(ws, &got)
if err == nil {
t.Errorf("Unexpected non-error")
}
}
示例9: generateEvent
func (recorder *recorderImpl) generateEvent(object runtime.Object, timestamp unversioned.Time, reason, message string) {
ref, err := api.GetReference(object)
if err != nil {
glog.Errorf("Could not construct reference to: '%#v' due to: '%v'. Will not report event: '%v' '%v'", object, err, reason, message)
return
}
event := makeEvent(ref, reason, message)
event.Source = recorder.source
recorder.Action(watch.Added, event)
}
示例10: generateEvent
func (f *FakeRecorder) generateEvent(obj runtime.Object, timestamp unversioned.Time, eventtype, reason, message string) {
ref, err := api.GetReference(obj)
if err != nil {
return
}
event := f.makeEvent(ref, eventtype, reason, message)
event.Source = f.source
if f.events != nil {
fmt.Println("write event")
f.events = append(f.events, event)
}
}
示例11: refJson
func refJson(t *testing.T, o runtime.Object) string {
ref, err := api.GetReference(o)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
_, _, codec := NewAPIFactory()
json, err := runtime.Encode(codec, &api.SerializedReference{Reference: *ref})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
return string(json)
}
示例12: Get
// Get gets kubernetes resources as pretty printed string
//
// Namespace will set the namespace
func (c *Client) Get(namespace string, reader io.Reader) (string, error) {
// Since we don't know what order the objects come in, let's group them by the types, so
// that when we print them, they come looking good (headers apply to subgroups, etc.)
objs := make(map[string][]runtime.Object)
err := perform(c, namespace, reader, func(info *resource.Info) error {
log.Printf("Doing get for: '%s'", info.Name)
obj, err := resource.NewHelper(info.Client, info.Mapping).Get(info.Namespace, info.Name, info.Export)
if err != nil {
return err
}
// We need to grab the ObjectReference so we can correctly group the objects.
or, err := api.GetReference(obj)
if err != nil {
log.Printf("FAILED GetReference for: %#v\n%v", obj, err)
return err
}
// Use APIVersion/Kind as grouping mechanism. I'm not sure if you can have multiple
// versions per cluster, but this certainly won't hurt anything, so let's be safe.
objType := or.APIVersion + "/" + or.Kind
objs[objType] = append(objs[objType], obj)
return nil
})
// Ok, now we have all the objects grouped by types (say, by v1/Pod, v1/Service, etc.), so
// spin through them and print them. Printer is cool since it prints the header only when
// an object type changes, so we can just rely on that. Problem is it doesn't seem to keep
// track of tab widths
buf := new(bytes.Buffer)
p := kubectl.NewHumanReadablePrinter(kubectl.PrintOptions{})
for t, ot := range objs {
_, err = buf.WriteString("==> " + t + "\n")
if err != nil {
return "", err
}
for _, o := range ot {
err = p.PrintObj(o, buf)
if err != nil {
log.Printf("failed to print object type '%s', object: '%s' :\n %v", t, o, err)
return "", err
}
}
_, err := buf.WriteString("\n")
if err != nil {
return "", err
}
}
return buf.String(), err
}
示例13: GetNodeEvents
// GetNodeEvents gets events associated to node with given name.
func GetNodeEvents(client client.Interface, dsQuery *dataselect.DataSelectQuery, nodeName string) (*common.EventList, error) {
var eventList common.EventList
mc := client.Core().Nodes()
node, _ := mc.Get(nodeName)
if ref, err := api.GetReference(node); err == nil {
ref.UID = types.UID(ref.Name)
events, _ := client.Core().Events(api.NamespaceAll).Search(ref)
eventList = CreateEventList(events.Items, dsQuery)
} else {
log.Print(err)
}
return &eventList, nil
}
示例14: TestFindingPreboundVolumes
func TestFindingPreboundVolumes(t *testing.T) {
claim := &api.PersistentVolumeClaim{
ObjectMeta: api.ObjectMeta{
Name: "claim01",
Namespace: "myns",
SelfLink: testapi.Default.SelfLink("pvc", ""),
},
Spec: api.PersistentVolumeClaimSpec{
AccessModes: []api.PersistentVolumeAccessMode{api.ReadWriteOnce},
Resources: api.ResourceRequirements{Requests: api.ResourceList{api.ResourceName(api.ResourceStorage): resource.MustParse("1Gi")}},
},
}
claimRef, err := api.GetReference(claim)
if err != nil {
t.Errorf("error getting claimRef: %v", err)
}
pv1 := testVolume("pv1", "1Gi")
pv5 := testVolume("pv5", "5Gi")
pv8 := testVolume("pv8", "8Gi")
index := newPersistentVolumeOrderedIndex()
index.store.Add(pv1)
index.store.Add(pv5)
index.store.Add(pv8)
// expected exact match on size
volume, _ := index.findBestMatchForClaim(claim)
if volume.Name != pv1.Name {
t.Errorf("Expected %s but got volume %s instead", pv1.Name, volume.Name)
}
// pretend the exact match is pre-bound. should get the next size up.
pv1.Spec.ClaimRef = &api.ObjectReference{Name: "foo", Namespace: "bar"}
volume, _ = index.findBestMatchForClaim(claim)
if volume.Name != pv5.Name {
t.Errorf("Expected %s but got volume %s instead", pv5.Name, volume.Name)
}
// pretend the exact match is available but the largest volume is pre-bound to the claim.
pv1.Spec.ClaimRef = nil
pv8.Spec.ClaimRef = claimRef
volume, _ = index.findBestMatchForClaim(claim)
if volume.Name != pv8.Name {
t.Errorf("Expected %s but got volume %s instead", pv8.Name, volume.Name)
}
}
示例15: GetNodeEvents
// GetNodeEvents gets events associated to node with given name.
func GetNodeEvents(client client.Interface, nodeName string) (common.EventList, error) {
eventList := common.EventList{
Namespace: api.NamespaceAll,
Events: make([]common.Event, 0),
}
mc := client.Nodes()
node, _ := mc.Get(nodeName)
if ref, err := api.GetReference(node); err == nil {
ref.UID = types.UID(ref.Name)
events, _ := client.Events(api.NamespaceAll).Search(ref)
AppendEvents(events.Items, eventList)
} else {
log.Print(err)
}
return eventList, nil
}