• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Golang util.Now函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中github.com/GoogleCloudPlatform/kubernetes/pkg/util.Now函数的典型用法代码示例。如果您正苦于以下问题:Golang Now函数的具体用法?Golang Now怎么用?Golang Now使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了Now函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: tagReferenceToTagEvent

func tagReferenceToTagEvent(stream *api.ImageStream, tagRef api.TagReference, tagOrID string) (*api.TagEvent, error) {
	switch tagRef.From.Kind {
	case "DockerImage":
		return &api.TagEvent{
			Created:              util.Now(),
			DockerImageReference: tagRef.From.Name,
		}, nil

	case "ImageStreamImage":
		ref, err := api.DockerImageReferenceForStream(stream)
		if err != nil {
			return nil, err
		}

		resolvedIDs := api.ResolveImageID(stream, tagOrID)
		switch len(resolvedIDs) {
		case 1:
			ref.ID = resolvedIDs.List()[0]
			return &api.TagEvent{
				Created:              util.Now(),
				DockerImageReference: ref.String(),
				Image:                ref.ID,
			}, nil
		case 0:
			return nil, fmt.Errorf("no images match the prefix %q", tagOrID)
		default:
			return nil, fmt.Errorf("multiple images match the prefix %q: %s", tagOrID, strings.Join(resolvedIDs.List(), ", "))
		}
	case "ImageStreamTag":
		return api.LatestTaggedImage(stream, tagOrID), nil
	default:
		return nil, fmt.Errorf("invalid from.kind %q: it must be ImageStreamImage or ImageStreamTag", tagRef.From.Kind)
	}
}
开发者ID:pombredanne,项目名称:atomic-enterprise,代码行数:34,代码来源:strategy.go


示例2: checkNodeReady

// checkNodeReady checks raw node ready condition, without transition timestamp set.
func (s *NodeController) checkNodeReady(node *api.Node) *api.NodeCondition {
	switch status, err := s.kubeletClient.HealthCheck(node.Name); {
	case err != nil:
		glog.V(2).Infof("NodeController: node %s health check error: %v", node.Name, err)
		return &api.NodeCondition{
			Type:          api.NodeReady,
			Status:        api.ConditionUnknown,
			Reason:        fmt.Sprintf("Node health check error: %v", err),
			LastProbeTime: util.Now(),
		}
	case status == probe.Failure:
		return &api.NodeCondition{
			Type:          api.NodeReady,
			Status:        api.ConditionNone,
			Reason:        fmt.Sprintf("Node health check failed: kubelet /healthz endpoint returns not ok"),
			LastProbeTime: util.Now(),
		}
	default:
		return &api.NodeCondition{
			Type:          api.NodeReady,
			Status:        api.ConditionFull,
			Reason:        fmt.Sprintf("Node health check succeeded: kubelet /healthz endpoint returns ok"),
			LastProbeTime: util.Now(),
		}
	}
}
开发者ID:vrosnet,项目名称:kubernetes,代码行数:27,代码来源:nodecontroller.go


示例3: HandlePod

// HandlePod updates the state of the build based on the pod state
func (bc *BuildPodController) HandlePod(pod *kapi.Pod) error {
	obj, exists, err := bc.BuildStore.Get(buildKey(pod))
	if err != nil {
		glog.V(4).Infof("Error getting Build for pod %s/%s: %v", pod.Namespace, pod.Name, err)
		return err
	}
	if !exists || obj == nil {
		glog.V(5).Infof("No Build found for pod %s/%s", pod.Namespace, pod.Name)
		return nil
	}

	build := obj.(*buildapi.Build)

	// A cancelling event was triggered for the build, delete its pod and update build status.
	if build.Status.Cancelled {
		glog.V(4).Infof("Cancelling Build %s/%s.", build.Namespace, build.Name)

		if err := bc.CancelBuild(build, pod); err != nil {
			return fmt.Errorf("failed to cancel Build %s/%s: %v, will retry", build.Namespace, build.Name, err)
		}
		return nil
	}

	nextStatus := build.Status.Phase

	switch pod.Status.Phase {
	case kapi.PodRunning:
		// The pod's still running
		nextStatus = buildapi.BuildPhaseRunning
	case kapi.PodSucceeded, kapi.PodFailed:
		// Check the exit codes of all the containers in the pod
		nextStatus = buildapi.BuildPhaseComplete
		for _, info := range pod.Status.ContainerStatuses {
			if info.State.Terminated != nil && info.State.Terminated.ExitCode != 0 {
				nextStatus = buildapi.BuildPhaseFailed
				break
			}
		}
	}

	if build.Status.Phase != nextStatus {
		glog.V(4).Infof("Updating Build %s/%s status %s -> %s", build.Namespace, build.Name, build.Status.Phase, nextStatus)
		build.Status.Phase = nextStatus
		if buildutil.IsBuildComplete(build) {
			now := util.Now()
			build.Status.CompletionTimestamp = &now
		}
		if build.Status.Phase == buildapi.BuildPhaseRunning {
			now := util.Now()
			build.Status.StartTimestamp = &now
		}
		if err := bc.BuildUpdater.Update(build.Namespace, build); err != nil {
			return fmt.Errorf("failed to update Build %s/%s: %v", build.Namespace, build.Name, err)
		}
		glog.V(4).Infof("Build %s/%s status was updated %s -> %s", build.Namespace, build.Name, build.Status.Phase, nextStatus)
	}
	return nil
}
开发者ID:Risar,项目名称:origin,代码行数:59,代码来源:controller.go


示例4: HandlePod

// HandlePod updates the state of the build based on the pod state
func (bc *BuildPodController) HandlePod(pod *kapi.Pod) error {
	obj, exists, err := bc.BuildStore.Get(buildKey(pod))
	if err != nil {
		glog.V(4).Infof("Error getting Build for pod %s/%s: %v", pod.Namespace, pod.Name, err)
		return err
	}
	if !exists || obj == nil {
		glog.V(5).Infof("No Build found for pod %s/%s", pod.Namespace, pod.Name)
		return nil
	}

	build := obj.(*buildapi.Build)

	nextStatus := build.Status.Phase
	switch pod.Status.Phase {
	case kapi.PodRunning:
		// The pod's still running
		nextStatus = buildapi.BuildPhaseRunning
	case kapi.PodSucceeded:
		// Check the exit codes of all the containers in the pod
		nextStatus = buildapi.BuildPhaseComplete
		if len(pod.Status.ContainerStatuses) == 0 {
			// no containers in the pod means something went badly wrong, so the build
			// should be failed.
			glog.V(2).Infof("Failing build %s/%s because the pod has no containers", build.Namespace, build.Name)
			nextStatus = buildapi.BuildPhaseFailed
		} else {
			for _, info := range pod.Status.ContainerStatuses {
				if info.State.Terminated != nil && info.State.Terminated.ExitCode != 0 {
					nextStatus = buildapi.BuildPhaseFailed
					break
				}
			}
		}
	case kapi.PodFailed:
		nextStatus = buildapi.BuildPhaseFailed
	}

	if build.Status.Phase != nextStatus {
		glog.V(4).Infof("Updating Build %s/%s status %s -> %s", build.Namespace, build.Name, build.Status.Phase, nextStatus)
		build.Status.Phase = nextStatus
		if buildutil.IsBuildComplete(build) {
			now := util.Now()
			build.Status.CompletionTimestamp = &now
		}
		if build.Status.Phase == buildapi.BuildPhaseRunning {
			now := util.Now()
			build.Status.StartTimestamp = &now
		}
		if err := bc.BuildUpdater.Update(build.Namespace, build); err != nil {
			return fmt.Errorf("failed to update Build %s/%s: %v", build.Namespace, build.Name, err)
		}
		glog.V(4).Infof("Build %s/%s status was updated %s -> %s", build.Namespace, build.Name, build.Status.Phase, nextStatus)
	}
	return nil
}
开发者ID:patrykattc,项目名称:origin,代码行数:57,代码来源:controller.go


示例5: NewEmptyPolicy

func NewEmptyPolicy(namespace string) *authorizationapi.Policy {
	policy := &authorizationapi.Policy{}
	policy.Name = authorizationapi.PolicyName
	policy.Namespace = namespace
	policy.CreationTimestamp = util.Now()
	policy.LastModified = util.Now()
	policy.Roles = make(map[string]*authorizationapi.Role)

	return policy
}
开发者ID:pombredanne,项目名称:atomic-enterprise,代码行数:10,代码来源:virtual_storage.go


示例6: NewEmptyPolicyBinding

func NewEmptyPolicyBinding(namespace, policyNamespace, policyBindingName string) *authorizationapi.PolicyBinding {
	binding := &authorizationapi.PolicyBinding{}
	binding.Name = policyBindingName
	binding.Namespace = namespace
	binding.CreationTimestamp = util.Now()
	binding.LastModified = util.Now()
	binding.PolicyRef = kapi.ObjectReference{Name: authorizationapi.PolicyName, Namespace: policyNamespace}
	binding.RoleBindings = make(map[string]*authorizationapi.RoleBinding)

	return binding
}
开发者ID:brandon-adams,项目名称:origin,代码行数:11,代码来源:strategy.go


示例7: TestGetEventExisting

func TestGetEventExisting(t *testing.T) {
	// Arrange
	eventTime := util.Now()
	event := api.Event{
		Reason:  "do I exist",
		Message: "I do, oh my",
		InvolvedObject: api.ObjectReference{
			Kind:       "Pod",
			Name:       "clever.name.here",
			Namespace:  "spaceOfName",
			UID:        "D933D32AFB2A238",
			APIVersion: "version",
		},
		Source: api.EventSource{
			Component: "kubelet",
			Host:      "kublet.node4",
		},
		Count:          1,
		FirstTimestamp: eventTime,
		LastTimestamp:  eventTime,
	}
	addOrUpdateEvent(&event)

	// Act
	existingEvent := getEvent(&event)

	// Assert
	compareEventWithHistoryEntry(&event, &existingEvent, t)
}
开发者ID:chenzhen411,项目名称:kubernetes,代码行数:29,代码来源:events_cache_test.go


示例8: TestBuildDecorator

func TestBuildDecorator(t *testing.T) {
	build := &buildapi.Build{
		ObjectMeta: kapi.ObjectMeta{Name: "buildid", Namespace: "default"},
		Parameters: buildapi.BuildParameters{
			Source: buildapi.BuildSource{
				Type: buildapi.BuildSourceGit,
				Git: &buildapi.GitBuildSource{
					URI: "http://github.com/my/repository",
				},
				ContextDir: "context",
			},
			Strategy: buildapi.BuildStrategy{
				Type:           buildapi.DockerBuildStrategyType,
				DockerStrategy: &buildapi.DockerBuildStrategy{},
			},
			Output: buildapi.BuildOutput{
				DockerImageReference: "repository/data",
			},
		},
		Status: buildapi.BuildStatusNew,
	}
	now := util.Now()
	startTime := util.NewTime(now.Time.Add(-1 * time.Minute))
	build.StartTimestamp = &startTime
	err := Decorator(build)
	if err != nil {
		t.Errorf("Unexpected error decorating build")
	}
	if build.Duration <= 0 {
		t.Errorf("Build duration should be greater than zero")
	}
}
开发者ID:cjnygard,项目名称:origin,代码行数:32,代码来源:strategy_test.go


示例9: TestNamespaceStatusStrategy

func TestNamespaceStatusStrategy(t *testing.T) {
	ctx := api.NewDefaultContext()
	if StatusStrategy.NamespaceScoped() {
		t.Errorf("Namespaces should not be namespace scoped")
	}
	if StatusStrategy.AllowCreateOnUpdate() {
		t.Errorf("Namespaces should not allow create on update")
	}
	now := util.Now()
	oldNamespace := &api.Namespace{
		ObjectMeta: api.ObjectMeta{Name: "foo", ResourceVersion: "10"},
		Spec:       api.NamespaceSpec{Finalizers: []api.FinalizerName{"kubernetes"}},
		Status:     api.NamespaceStatus{Phase: api.NamespaceActive},
	}
	namespace := &api.Namespace{
		ObjectMeta: api.ObjectMeta{Name: "foo", ResourceVersion: "9", DeletionTimestamp: &now},
		Status:     api.NamespaceStatus{Phase: api.NamespaceTerminating},
	}
	StatusStrategy.PrepareForUpdate(namespace, oldNamespace)
	if namespace.Status.Phase != api.NamespaceTerminating {
		t.Errorf("Namespace status updates should allow change of phase: %v", namespace.Status.Phase)
	}
	if len(namespace.Spec.Finalizers) != 1 || namespace.Spec.Finalizers[0] != api.FinalizerKubernetes {
		t.Errorf("PrepareForUpdate should have preserved old finalizers")
	}
	errs := StatusStrategy.ValidateUpdate(ctx, namespace, oldNamespace)
	if len(errs) != 0 {
		t.Errorf("Unexpected error %v", errs)
	}
	if namespace.ResourceVersion != "9" {
		t.Errorf("Incoming resource version on update should not be mutated")
	}
}
开发者ID:chenzhen411,项目名称:kubernetes,代码行数:33,代码来源:rest_test.go


示例10: TestEventCreate

func TestEventCreate(t *testing.T) {
	objReference := &api.ObjectReference{
		Kind:            "foo",
		Namespace:       "nm",
		Name:            "objref1",
		UID:             "uid",
		APIVersion:      "apiv1",
		ResourceVersion: "1",
	}
	timeStamp := util.Now()
	event := &api.Event{
		//namespace: namespace{"default"},
		Condition:      "Running",
		InvolvedObject: *objReference,
		Timestamp:      timeStamp,
	}
	c := &testClient{
		Request: testRequest{
			Method: "POST",
			Path:   "/events",
			Body:   event,
		},
		Response: Response{StatusCode: 200, Body: event},
	}

	response, err := c.Setup().Events("").Create(event)

	if err != nil {
		t.Errorf("%#v should be nil.", err)
	}

	if e, a := *objReference, response.InvolvedObject; !reflect.DeepEqual(e, a) {
		t.Errorf("%#v != %#v.", e, a)
	}
}
开发者ID:nhr,项目名称:kubernetes,代码行数:35,代码来源:events_test.go


示例11: TestDeleteNamespaceWithIncompleteFinalizers

func TestDeleteNamespaceWithIncompleteFinalizers(t *testing.T) {
	now := util.Now()
	fakeEtcdClient, helper := newHelper(t)
	fakeEtcdClient.ChangeIndex = 1
	fakeEtcdClient.Data["/registry/namespaces/foo"] = tools.EtcdResponseWithError{
		R: &etcd.Response{
			Node: &etcd.Node{
				Value: runtime.EncodeOrDie(latest.Codec, &api.Namespace{
					ObjectMeta: api.ObjectMeta{
						Name:              "foo",
						DeletionTimestamp: &now,
					},
					Spec: api.NamespaceSpec{
						Finalizers: []api.FinalizerName{api.FinalizerKubernetes},
					},
					Status: api.NamespaceStatus{Phase: api.NamespaceActive},
				}),
				ModifiedIndex: 1,
				CreatedIndex:  1,
			},
		},
	}
	storage, _, _ := NewStorage(helper)
	_, err := storage.Delete(api.NewDefaultContext(), "foo", nil)
	if err == nil {
		t.Fatalf("expected error: %v", err)
	}
}
开发者ID:SivagnanamCiena,项目名称:calico-kubernetes,代码行数:28,代码来源:etcd_test.go


示例12: NewFilterBeforePredicate

// NewFilterBeforePredicate is a function that returns true if the build was created before the current time minus specified duration
func NewFilterBeforePredicate(d time.Duration) FilterPredicate {
	now := util.Now()
	before := util.NewTime(now.Time.Add(-1 * d))
	return func(build *buildapi.Build) bool {
		return build.CreationTimestamp.Before(before)
	}
}
开发者ID:pombredanne,项目名称:atomic-enterprise,代码行数:8,代码来源:data.go


示例13: Create

func (rs *REST) Create(ctx api.Context, obj runtime.Object) (<-chan apiserver.RESTResult, error) {
	minion, ok := obj.(*api.Minion)
	if !ok {
		return nil, fmt.Errorf("not a minion: %#v", obj)
	}
	if minion.Name == "" {
		return nil, fmt.Errorf("ID should not be empty: %#v", minion)
	}

	minion.CreationTimestamp = util.Now()

	return apiserver.MakeAsync(func() (runtime.Object, error) {
		err := rs.registry.CreateMinion(ctx, minion)
		if err != nil {
			return nil, err
		}
		minionName := minion.Name
		minion, err := rs.registry.GetMinion(ctx, minionName)
		if err == ErrNotHealty {
			return rs.toApiMinion(minionName), nil
		}
		if minion == nil {
			return nil, ErrDoesNotExist
		}
		if err != nil {
			return nil, err
		}
		return minion, nil
	}), nil
}
开发者ID:ericcapricorn,项目名称:kubernetes,代码行数:30,代码来源:rest.go


示例14: TestSort

// TestSort verifies that builds are sorted by most recently created
func TestSort(t *testing.T) {
	present := util.Now()
	past := util.NewTime(present.Time.Add(-1 * time.Minute))
	builds := []*buildapi.Build{
		{
			ObjectMeta: kapi.ObjectMeta{
				Name:              "past",
				CreationTimestamp: past,
			},
		},
		{
			ObjectMeta: kapi.ObjectMeta{
				Name:              "present",
				CreationTimestamp: present,
			},
		},
	}
	sort.Sort(sortableBuilds(builds))
	if builds[0].Name != "present" {
		t.Errorf("Unexpected sort order")
	}
	if builds[1].Name != "past" {
		t.Errorf("Unexpected sort order")
	}
}
开发者ID:pombredanne,项目名称:atomic-enterprise,代码行数:26,代码来源:sort_test.go


示例15: Create

func (rs *REST) Create(obj runtime.Object) (<-chan runtime.Object, error) {
	minion, ok := obj.(*api.Minion)
	if !ok {
		return nil, fmt.Errorf("not a minion: %#v", obj)
	}
	if minion.ID == "" {
		return nil, fmt.Errorf("ID should not be empty: %#v", minion)
	}

	minion.CreationTimestamp = util.Now()

	return apiserver.MakeAsync(func() (runtime.Object, error) {
		err := rs.registry.Insert(minion.ID)
		if err != nil {
			return nil, err
		}
		contains, err := rs.registry.Contains(minion.ID)
		if err != nil {
			return nil, err
		}
		if contains {
			return rs.toApiMinion(minion.ID), nil
		}
		return nil, fmt.Errorf("unable to add minion %#v", minion)
	}), nil
}
开发者ID:asim,项目名称:kubernetes,代码行数:26,代码来源:rest.go


示例16: TestAddOrUpdateEventNoExisting

func TestAddOrUpdateEventNoExisting(t *testing.T) {
	// Arrange
	eventTime := util.Now()
	event := api.Event{
		Reason:  "my reasons are many",
		Message: "my message is love",
		InvolvedObject: api.ObjectReference{
			Kind:       "Pod",
			Name:       "awesome.name",
			Namespace:  "betterNamespace",
			UID:        "C934D34AFB20242",
			APIVersion: "version",
		},
		Source: api.EventSource{
			Component: "kubelet",
			Host:      "kublet.node1",
		},
		Count:          1,
		FirstTimestamp: eventTime,
		LastTimestamp:  eventTime,
	}

	// Act
	result := addOrUpdateEvent(&event)

	// Assert
	compareEventWithHistoryEntry(&event, &result, t)
}
开发者ID:chenzhen411,项目名称:kubernetes,代码行数:28,代码来源:events_cache_test.go


示例17: TestEventGet

func TestEventGet(t *testing.T) {
	objReference := &api.ObjectReference{
		Kind:            "foo",
		Namespace:       "nm",
		Name:            "objref1",
		UID:             "uid",
		APIVersion:      "apiv1",
		ResourceVersion: "1",
	}
	timeStamp := util.Now()
	event := &api.Event{
		InvolvedObject: *objReference,
		Timestamp:      timeStamp,
	}
	c := &testClient{
		Request: testRequest{
			Method: "GET",
			Path:   "/events/1",
			Body:   nil,
		},
		Response: Response{StatusCode: 200, Body: event},
	}

	response, err := c.Setup().Events("").Get("1")

	if err != nil {
		t.Errorf("%#v should be nil.", err)
	}

	if e, r := event.InvolvedObject, response.InvolvedObject; !reflect.DeepEqual(e, r) {
		t.Errorf("%#v != %#v.", e, r)
	}
}
开发者ID:hortonworks,项目名称:kubernetes-yarn,代码行数:33,代码来源:events_test.go


示例18: TestSort

// TestSort verifies that builds are sorted by most recently created
func TestSort(t *testing.T) {
	present := util.Now()
	past := util.NewTime(present.Time.Add(-1 * time.Minute))
	controllers := []*kapi.ReplicationController{
		{
			ObjectMeta: kapi.ObjectMeta{
				Name:              "past",
				CreationTimestamp: past,
			},
		},
		{
			ObjectMeta: kapi.ObjectMeta{
				Name:              "present",
				CreationTimestamp: present,
			},
		},
	}
	sort.Sort(sortableReplicationControllers(controllers))
	if controllers[0].Name != "present" {
		t.Errorf("Unexpected sort order")
	}
	if controllers[1].Name != "past" {
		t.Errorf("Unexpected sort order")
	}
}
开发者ID:cjnygard,项目名称:origin,代码行数:26,代码来源:sort_test.go


示例19: NewFilterBeforePredicate

// NewFilterBeforePredicate is a function that returns true if the build was created before the current time minus specified duration
func NewFilterBeforePredicate(d time.Duration) FilterPredicate {
	now := util.Now()
	before := util.NewTime(now.Time.Add(-1 * d))
	return func(item *kapi.ReplicationController) bool {
		return item.CreationTimestamp.Before(before)
	}
}
开发者ID:cjnygard,项目名称:origin,代码行数:8,代码来源:data.go


示例20: SetPodStatus

func (s *statusManager) SetPodStatus(pod *api.Pod, status api.PodStatus) {
	podFullName := kubecontainer.GetPodFullName(pod)
	s.podStatusesLock.Lock()
	defer s.podStatusesLock.Unlock()
	oldStatus, found := s.podStatuses[podFullName]

	// ensure that the start time does not change across updates.
	if found && oldStatus.StartTime != nil {
		status.StartTime = oldStatus.StartTime
	}

	// if the status has no start time, we need to set an initial time
	// TODO(yujuhong): Consider setting StartTime when generating the pod
	// status instead, which would allow statusManager to become a simple cache
	// again.
	if status.StartTime.IsZero() {
		if pod.Status.StartTime.IsZero() {
			// the pod did not have a previously recorded value so set to now
			now := util.Now()
			status.StartTime = &now
		} else {
			// the pod had a recorded value, but the kubelet restarted so we need to rebuild cache
			// based on last observed value
			status.StartTime = pod.Status.StartTime
		}
	}

	if !found || !reflect.DeepEqual(oldStatus, status) {
		s.podStatuses[podFullName] = status
		s.podStatusChannel <- podStatusSyncRequest{pod, status}
	} else {
		glog.V(3).Infof("Ignoring same pod status for %s - old: %s new: %s", podFullName, oldStatus, status)
	}
}
开发者ID:mbforbes,项目名称:kubernetes,代码行数:34,代码来源:status_manager.go



注:本文中的github.com/GoogleCloudPlatform/kubernetes/pkg/util.Now函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang util.ObjectDiff函数代码示例发布时间:2022-05-23
下一篇:
Golang util.NewUUID函数代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap