diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 5b35b6d..5d6459c 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -19,7 +19,6 @@ env: BUILDKIT_IMAGE: moby/buildkit@sha256:28a898719c18a33f4e8000685287fa36fd0dd9560c6440227d3a732d79bb41d8 GOLANGCI_LINT_VERSION: v2.13.1 GORELEASER_VERSION: v2.18.0 - GOPRIVATE: github.com/dynamia-ai/* jobs: go: @@ -39,11 +38,6 @@ jobs: runs-on: ${{ matrix.runner }} timeout-minutes: 30 steps: - - name: Require private module token - env: - HAMI_ENTERPRISE_REPO_TOKEN: ${{ secrets.HAMI_ENTERPRISE_REPO_TOKEN }} - run: test -n "$HAMI_ENTERPRISE_REPO_TOKEN" - - name: Checkout source uses: actions/checkout@v7 with: @@ -74,10 +68,6 @@ jobs: install-only: true - name: Run local CI contract - env: - GIT_CONFIG_COUNT: "1" - GIT_CONFIG_KEY_0: url.https://x-access-token:${{ secrets.HAMI_ENTERPRISE_REPO_TOKEN }}@github.com/.insteadOf - GIT_CONFIG_VALUE_0: https://github.com/ run: make ci image: @@ -102,11 +92,6 @@ jobs: IMAGE_SOURCE: ${{ github.server_url }}/${{ github.repository }} IMAGE_REVISION: ${{ github.sha }} steps: - - name: Require private module token - env: - HAMI_ENTERPRISE_REPO_TOKEN: ${{ secrets.HAMI_ENTERPRISE_REPO_TOKEN }} - run: test -n "$HAMI_ENTERPRISE_REPO_TOKEN" - - name: Checkout source uses: actions/checkout@v7 with: @@ -127,8 +112,6 @@ jobs: driver-opts: image=${{ env.BUILDKIT_IMAGE }} - name: Build and load without publishing - env: - HAMI_ENTERPRISE_REPO_TOKEN: ${{ secrets.HAMI_ENTERPRISE_REPO_TOKEN }} run: make build-image - name: Inspect image diff --git a/.github/workflows/release.yaml b/.github/workflows/release.yaml index 1871662..b9b2030 100644 --- a/.github/workflows/release.yaml +++ b/.github/workflows/release.yaml @@ -15,7 +15,6 @@ env: BUILDX_VERSION: v0.36.1 BUILDKIT_IMAGE: moby/buildkit@sha256:28a898719c18a33f4e8000685287fa36fd0dd9560c6440227d3a732d79bb41d8 DOCKER_BUILD_RECORD_UPLOAD: "false" - GOPRIVATE: github.com/dynamia-ai/* GOLANGCI_LINT_VERSION: v2.13.1 GORELEASER_VERSION: v2.18.0 OSSUTIL_VERSION: 2.3.0 @@ -54,11 +53,6 @@ jobs: git merge-base --is-ancestor "$GITHUB_SHA" refs/remotes/origin/main echo "source-date-epoch=$(git show -s --format=%ct "$GITHUB_SHA")" >> "$GITHUB_OUTPUT" - - name: Validate private module credential - env: - HAMI_ENTERPRISE_REPO_TOKEN: ${{ secrets.HAMI_ENTERPRISE_REPO_TOKEN }} - run: test -n "$HAMI_ENTERPRISE_REPO_TOKEN" - - name: Set up Go uses: actions/setup-go@v7 with: @@ -73,10 +67,6 @@ jobs: install-only: true - name: Run release checks - env: - GIT_CONFIG_COUNT: "1" - GIT_CONFIG_KEY_0: url.https://x-access-token:${{ secrets.HAMI_ENTERPRISE_REPO_TOKEN }}@github.com/.insteadOf - GIT_CONFIG_VALUE_0: https://github.com/ run: make ci - name: Build release artifacts with GoReleaser @@ -85,10 +75,6 @@ jobs: distribution: goreleaser version: ${{ env.GORELEASER_VERSION }} args: release --clean - env: - GIT_CONFIG_COUNT: "1" - GIT_CONFIG_KEY_0: url.https://x-access-token:${{ secrets.HAMI_ENTERPRISE_REPO_TOKEN }}@github.com/.insteadOf - GIT_CONFIG_VALUE_0: https://github.com/ - name: Verify release archive contents run: bash hack/verify-release-archives.sh dist "$GITHUB_REF_NAME" diff --git a/.github/workflows/rolling-release.yaml b/.github/workflows/rolling-release.yaml index c9ba27d..b48f19b 100644 --- a/.github/workflows/rolling-release.yaml +++ b/.github/workflows/rolling-release.yaml @@ -23,7 +23,6 @@ env: BUILDX_VERSION: v0.36.1 BUILDKIT_IMAGE: moby/buildkit@sha256:28a898719c18a33f4e8000685287fa36fd0dd9560c6440227d3a732d79bb41d8 DOCKER_BUILD_RECORD_UPLOAD: "false" - GOPRIVATE: github.com/dynamia-ai/* GOLANGCI_LINT_VERSION: v2.13.1 GORELEASER_VERSION: v2.18.0 OSSUTIL_VERSION: 2.3.0 @@ -103,11 +102,6 @@ jobs: echo "- Revision: \`$revision\`" } >> "$GITHUB_STEP_SUMMARY" - - name: Validate private module credential - env: - HAMI_ENTERPRISE_REPO_TOKEN: ${{ secrets.HAMI_ENTERPRISE_REPO_TOKEN }} - run: test -n "$HAMI_ENTERPRISE_REPO_TOKEN" - - name: Set up Go uses: actions/setup-go@v7 with: @@ -122,10 +116,6 @@ jobs: install-only: true - name: Run release checks - env: - GIT_CONFIG_COUNT: "1" - GIT_CONFIG_KEY_0: url.https://x-access-token:${{ secrets.HAMI_ENTERPRISE_REPO_TOKEN }}@github.com/.insteadOf - GIT_CONFIG_VALUE_0: https://github.com/ run: make ci - name: Build snapshot artifacts with GoReleaser @@ -136,9 +126,6 @@ jobs: args: release --snapshot --clean env: RELEASE_VERSION: ${{ steps.release.outputs.version }} - GIT_CONFIG_COUNT: "1" - GIT_CONFIG_KEY_0: url.https://x-access-token:${{ secrets.HAMI_ENTERPRISE_REPO_TOKEN }}@github.com/.insteadOf - GIT_CONFIG_VALUE_0: https://github.com/ - name: Verify release archive contents env: diff --git a/Dockerfile b/Dockerfile index 7d18922..fc49bcd 100644 --- a/Dockerfile +++ b/Dockerfile @@ -8,31 +8,18 @@ ARG VERSION=devel ARG REVISION=unknown ARG BUILD_DATE=unknown -ENV GOPRIVATE=github.com/dynamia-ai/* - WORKDIR /src -RUN apk add --no-cache ca-certificates git - COPY go.mod go.sum ./ -RUN --mount=type=secret,id=github_token,required=true \ - set -eu; \ - token="$(cat /run/secrets/github_token)"; \ - git config --global url."https://x-access-token:${token}@github.com/".insteadOf "https://github.com/"; \ - GOWORK=off go mod download; \ - rm -f "${HOME}/.gitconfig" +RUN GOWORK=off go mod download COPY *.go ./ +COPY internal/ ./internal/ COPY skills/ ./skills/ -RUN --mount=type=secret,id=github_token,required=true \ - set -eu; \ - token="$(cat /run/secrets/github_token)"; \ - git config --global url."https://x-access-token:${token}@github.com/".insteadOf "https://github.com/"; \ - CGO_ENABLED=0 GOOS="${TARGETOS}" GOARCH="${TARGETARCH}" GOWORK=off \ +RUN CGO_ENABLED=0 GOOS="${TARGETOS}" GOARCH="${TARGETARCH}" GOWORK=off \ go build -trimpath \ -ldflags "-s -w -X main.cliVersion=${VERSION} -X main.cliRevision=${REVISION} -X main.cliBuildDate=${BUILD_DATE}" \ - -o /out/hami-cli .; \ - rm -f "${HOME}/.gitconfig" + -o /out/hami-cli . FROM gcr.io/distroless/static-debian12:nonroot diff --git a/Makefile b/Makefile index 59090b7..3330d60 100644 --- a/Makefile +++ b/Makefile @@ -54,7 +54,6 @@ verify: test vet git diff --check define build_image - test -n "$${HAMI_ENTERPRISE_REPO_TOKEN}" $(DOCKER) buildx build \ --file "$(DOCKERFILE)" \ --platform "$(1)" \ @@ -64,7 +63,6 @@ define build_image --build-arg "VERSION=$(VERSION)" \ --build-arg "REVISION=$(IMAGE_REVISION)" \ --build-arg "BUILD_DATE=$(BUILD_DATE)" \ - --secret id=github_token,env=HAMI_ENTERPRISE_REPO_TOKEN \ --load \ "$(IMAGE_CONTEXT)" endef diff --git a/docs/architecture.md b/docs/architecture.md index a2baf14..b926a2b 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -22,6 +22,8 @@ 厂商运行时插件仍处于设计阶段。 +[`internal/resourcepool/v1alpha1`](../internal/resourcepool/v1alpha1) 定义 CLI 使用的 Kubernetes 对象。修改对象定义时,需保持 API 组和版本、JSON 字段以及设备命名和标签规则与已部署的资源池 CRD 一致。 + ## 目标命令模型 厂商运行时能力计划收敛到统一入口: @@ -71,8 +73,8 @@ cmd/root - 建立独立 Go 模块并原样迁入资源池命令和测试。 - 在新仓库验证独立构建、安装和发布。 -- 从 `hami-enterprise` 删除旧 CLI 源码,保留独立发布的资源池 API。 +- 从 `hami-enterprise` 删除旧 CLI 源码,由 `hami-cli` 维护资源池客户端类型。 - 根据真实 NVIDIA Docker PoC 固定共享运行合同和 NVIDIA 插件。 - 在独立验证 Ascend 注入合同后接入 Ascend 插件。 -迁移完成前,不应在两个仓库同时修改 CLI 行为。进入删除阶段后,`hami-enterprise` 只维护资源池服务端和公开 API,CLI 行为由本仓库维护。 +迁移完成前,不应在两个仓库同时修改 CLI 行为。进入删除阶段后,`hami-enterprise` 维护资源池服务端和 CRD,`hami-cli` 维护客户端类型和命令行为。 diff --git a/docs/releasing.md b/docs/releasing.md index 3dfaf28..e6027ad 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -85,7 +85,6 @@ GHCR 验证会检查清单 digest,以及 `linux/amd64`、`linux/arm64` 镜像 仓库需要以下 Actions secrets: -- `HAMI_ENTERPRISE_REPO_TOKEN`:对 `github.com/dynamia-ai/hami-enterprise` 具有只读 `Contents` 权限,用于解析私有 Go 模块。 - `ALIYUN_OSS_ACCESS_KEY_ID`、`ALIYUN_OSS_ACCESS_KEY_SECRET`:OSS 访问凭据。 - `ALIYUN_OSS_BUCKET`、`ALIYUN_OSS_ENDPOINT`、`ALIYUN_OSS_REGION`:OSS Bucket、API 端点和区域。 - `S3_ACCESS_KEY_ID`、`S3_SECRET_ACCESS_KEY`:S3 兼容存储访问凭据。 @@ -108,9 +107,7 @@ OSS 发布身份需要读写对象和设置对象 ACL,S3 发布身份需要读 ## 凭据边界 -Pull Request 和 `main` 的 CI 都需要读取私有资源池 API 模块。`hami-cli` 仓库的 write 权限不得授予无权读取 `hami-enterprise` 的用户,否则同仓库 PR 代码执行边界会扩大私有模块访问范围。 - -调整任一仓库成员权限时,需要重新核对这一条件。如果两个仓库的写入和读取边界不再一致,应先停用 Pull Request 中使用私有模块 token 的 job,再改用具备审批保护的凭据边界。 +Pull Request 和 `main` 的 CI 使用仓库源码和公开 Go 模块构建。云存储访问凭据仅用于发布任务。 GHCR package 的写权限只能授予本仓库发布 workflow。其他主体拥有写权限时,可以在 workflow 完成后将已验证的稳定标签指向其他镜像。稳定交付必须保留并使用 `image@sha256:...` 引用,不能只依赖标签。 diff --git a/go.mod b/go.mod index 2a31ac9..9b3a360 100644 --- a/go.mod +++ b/go.mod @@ -3,7 +3,6 @@ module github.com/dynamia-ai/hami-cli go 1.27.0 require ( - github.com/dynamia-ai/hami-enterprise/pkg/resourcepool/api v0.0.0-20260916034425-492db1bedb3f github.com/lathe-cli/kitup/go v0.1.4 github.com/lathe-cli/kitup/go-cobra v0.1.4 github.com/spf13/cobra v1.10.2 diff --git a/go.sum b/go.sum index 38a7873..c57c394 100644 --- a/go.sum +++ b/go.sum @@ -10,8 +10,6 @@ github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSs github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/dynamia-ai/hami-enterprise/pkg/resourcepool/api v0.0.0-20260916034425-492db1bedb3f h1:K219Pu9Senfmsw7XUsAkZaghMFt8ONulxYTnb6H+6EM= -github.com/dynamia-ai/hami-enterprise/pkg/resourcepool/api v0.0.0-20260916034425-492db1bedb3f/go.mod h1:ZM1AWRXzsPuvqt717dSuc4hbNwW0F4Y8tipjY5tgNeE= github.com/emicklei/go-restful/v3 v3.13.0 h1:C4Bl2xDndpU6nJ4bc1jXd+uTmYPVUwkD6bFY/oTyCes= github.com/emicklei/go-restful/v3 v3.13.0/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRry+4bhvbpWn3mrbc= github.com/evanphx/json-patch/v5 v5.9.11 h1:/8HVnzMq13/3x9TPvjG08wUGqBTmZBsCWzjTM0wiaDU= diff --git a/internal/resourcepool/v1alpha1/conventions.go b/internal/resourcepool/v1alpha1/conventions.go new file mode 100644 index 0000000..8f74d9c --- /dev/null +++ b/internal/resourcepool/v1alpha1/conventions.go @@ -0,0 +1,34 @@ +package v1alpha1 + +import ( + "crypto/sha256" + "encoding/hex" + "maps" + "strings" +) + +const ( + PoolLabel = "resource.hami.io/pool" + DeviceTypeLabel = "resource.hami.io/device-type" + NVIDIADeviceType = "NVIDIA" +) + +// DeviceObjectName uses the RPM naming convention to look up existing devices. +func DeviceObjectName(identity DeviceIdentity) string { + key := identity.NodeName + "\x00" + identity.DeviceType + "\x00" + identity.DeviceID + digest := sha256.Sum256([]byte(key)) + return "gpu-" + hex.EncodeToString(digest[:16]) +} + +// PoolLabels keeps user labels and derives the indexes from the device spec. +func PoolLabels(device *GPUDevice) map[string]string { + labels := make(map[string]string, len(device.Labels)+2) + maps.Copy(labels, device.Labels) + labels[DeviceTypeLabel] = strings.ToLower(device.Spec.Identity.DeviceType) + if ref := device.Spec.PoolRef; ref != nil { + labels[PoolLabel] = ref.Name + } else { + delete(labels, PoolLabel) + } + return labels +} diff --git a/internal/resourcepool/v1alpha1/deepcopy.go b/internal/resourcepool/v1alpha1/deepcopy.go new file mode 100644 index 0000000..5eccdfc --- /dev/null +++ b/internal/resourcepool/v1alpha1/deepcopy.go @@ -0,0 +1,169 @@ +package v1alpha1 + +import ( + "slices" + + "k8s.io/apimachinery/pkg/runtime" +) + +func (in *PoolReference) DeepCopy() *PoolReference { + if in == nil { + return nil + } + return new(*in) +} + +func (in *ResourcePool) DeepCopy() *ResourcePool { + if in == nil { + return nil + } + out := new(ResourcePool) + in.DeepCopyInto(out) + return out +} + +func (in *ResourcePool) DeepCopyInto(out *ResourcePool) { + *out = *in + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + if defaults := in.Spec.WorkloadDefaults; defaults != nil { + out.Spec.WorkloadDefaults = new(*defaults) + if policy := defaults.SchedulingPolicy; policy != nil { + out.Spec.WorkloadDefaults.SchedulingPolicy = new(*policy) + } + } + if quota := in.Spec.Quota; quota != nil { + out.Spec.Quota = new(*quota) + if quota.CPU != nil { + out.Spec.Quota.CPU = new(quota.CPU.DeepCopy()) + } + if quota.Memory != nil { + out.Spec.Quota.Memory = new(quota.Memory.DeepCopy()) + } + } + out.Status.Conditions = slices.Clone(in.Status.Conditions) + if quota := in.Status.Quota; quota != nil { + out.Status.Quota = new(*quota) + out.Status.Quota.Used = quota.Used.deepCopy() + out.Status.Quota.Reserved = quota.Reserved.deepCopy() + out.Status.Quota.Reservations = slices.Clone(quota.Reservations) + for i, reservation := range quota.Reservations { + out.Status.Quota.Reservations[i].Delta = reservation.Delta.deepCopy() + out.Status.Quota.Reservations[i].Target = reservation.Target.deepCopy() + } + } +} + +func (in ResourcePoolResourceUsage) deepCopy() ResourcePoolResourceUsage { + return ResourcePoolResourceUsage{CPU: in.CPU.DeepCopy(), Memory: in.Memory.DeepCopy()} +} + +func (in *ResourcePool) DeepCopyObject() runtime.Object { + if in == nil { + return nil + } + return in.DeepCopy() +} + +func (in *ResourcePoolList) DeepCopyObject() runtime.Object { + if in == nil { + return nil + } + out := new(ResourcePoolList) + in.DeepCopyInto(out) + return out +} + +func (in *ResourcePoolList) DeepCopyInto(out *ResourcePoolList) { + *out = *in + in.ListMeta.DeepCopyInto(&out.ListMeta) + out.Items = slices.Clone(in.Items) + for i := range in.Items { + in.Items[i].DeepCopyInto(&out.Items[i]) + } +} + +func (in *GPUDevice) DeepCopy() *GPUDevice { + if in == nil { + return nil + } + out := new(GPUDevice) + in.DeepCopyInto(out) + return out +} + +func (in *GPUDevice) DeepCopyInto(out *GPUDevice) { + *out = *in + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + out.Spec.PoolRef = in.Spec.PoolRef.DeepCopy() + out.Status.Conditions = slices.Clone(in.Status.Conditions) + out.Status.Allocations = slices.Clone(in.Status.Allocations) + for i, allocation := range in.Status.Allocations { + if mig := allocation.MIG; mig != nil { + out.Status.Allocations[i].MIG = new(*mig) + if mig.GPUInstanceID != nil { + out.Status.Allocations[i].MIG.GPUInstanceID = new(*mig.GPUInstanceID) + } + if mig.ComputeInstanceID != nil { + out.Status.Allocations[i].MIG.ComputeInstanceID = new(*mig.ComputeInstanceID) + } + } + } +} + +func (in *GPUDevice) DeepCopyObject() runtime.Object { + if in == nil { + return nil + } + return in.DeepCopy() +} + +func (in *GPUDeviceList) DeepCopyObject() runtime.Object { + if in == nil { + return nil + } + out := new(GPUDeviceList) + in.DeepCopyInto(out) + return out +} + +func (in *GPUDeviceList) DeepCopyInto(out *GPUDeviceList) { + *out = *in + in.ListMeta.DeepCopyInto(&out.ListMeta) + out.Items = slices.Clone(in.Items) + for i := range in.Items { + in.Items[i].DeepCopyInto(&out.Items[i]) + } +} + +func (in *ResourcePoolBinding) DeepCopyObject() runtime.Object { + if in == nil { + return nil + } + out := new(ResourcePoolBinding) + in.DeepCopyInto(out) + return out +} + +func (in *ResourcePoolBinding) DeepCopyInto(out *ResourcePoolBinding) { + *out = *in + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + out.Status.Conditions = slices.Clone(in.Status.Conditions) +} + +func (in *ResourcePoolBindingList) DeepCopyObject() runtime.Object { + if in == nil { + return nil + } + out := new(ResourcePoolBindingList) + in.DeepCopyInto(out) + return out +} + +func (in *ResourcePoolBindingList) DeepCopyInto(out *ResourcePoolBindingList) { + *out = *in + in.ListMeta.DeepCopyInto(&out.ListMeta) + out.Items = slices.Clone(in.Items) + for i := range in.Items { + in.Items[i].DeepCopyInto(&out.Items[i]) + } +} diff --git a/internal/resourcepool/v1alpha1/types.go b/internal/resourcepool/v1alpha1/types.go new file mode 100644 index 0000000..0b28537 --- /dev/null +++ b/internal/resourcepool/v1alpha1/types.go @@ -0,0 +1,195 @@ +// Package v1alpha1 defines the resource.hami.io/v1alpha1 objects used by hami-cli. +package v1alpha1 + +import ( + "k8s.io/apimachinery/pkg/api/resource" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/apimachinery/pkg/types" +) + +var GroupVersion = schema.GroupVersion{Group: "resource.hami.io", Version: "v1alpha1"} + +func AddToScheme(scheme *runtime.Scheme) error { + scheme.AddKnownTypes(GroupVersion, + &ResourcePool{}, &ResourcePoolList{}, + &GPUDevice{}, &GPUDeviceList{}, + &ResourcePoolBinding{}, &ResourcePoolBindingList{}, + ) + metav1.AddToGroupVersion(scheme, GroupVersion) + return nil +} + +type PoolReference struct { + Name string `json:"name"` +} + +type NodeSchedulerPolicy string + +const ( + NodeSchedulerPolicyBinpack NodeSchedulerPolicy = "binpack" + NodeSchedulerPolicySpread NodeSchedulerPolicy = "spread" +) + +type GPUSchedulerPolicy string + +const ( + GPUSchedulerPolicyBinpack GPUSchedulerPolicy = "binpack" + GPUSchedulerPolicySpread GPUSchedulerPolicy = "spread" + GPUSchedulerPolicyTopologyAware GPUSchedulerPolicy = "topology-aware" + GPUSchedulerPolicyMutex GPUSchedulerPolicy = "mutex" + GPUSchedulerPolicyNUMA GPUSchedulerPolicy = "numa" +) + +type ResourcePool struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + Spec ResourcePoolSpec `json:"spec"` + Status ResourcePoolStatus `json:"status,omitempty"` +} + +type ResourcePoolList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []ResourcePool `json:"items"` +} + +type ResourcePoolSpec struct { + DisplayName string `json:"displayName,omitempty"` + WorkloadDefaults *ResourcePoolWorkloadDefaults `json:"workloadDefaults,omitempty"` + Quota *ResourcePoolQuotaSpec `json:"quota,omitempty"` +} + +type ResourcePoolWorkloadDefaults struct { + SchedulingPolicy *ResourcePoolSchedulingPolicy `json:"schedulingPolicy,omitempty"` +} + +type ResourcePoolSchedulingPolicy struct { + Node NodeSchedulerPolicy `json:"node,omitempty"` + GPU GPUSchedulerPolicy `json:"gpu,omitempty"` +} + +type ResourcePoolQuotaSpec struct { + CPU *resource.Quantity `json:"cpu,omitempty"` + Memory *resource.Quantity `json:"memory,omitempty"` +} + +type ResourcePoolStatus struct { + ObservedGeneration int64 `json:"observedGeneration,omitempty"` + DiscoveredDevices int32 `json:"discoveredDevices,omitempty"` + HealthyDevices int32 `json:"healthyDevices,omitempty"` + Revision string `json:"revision,omitempty"` + Quota *ResourcePoolQuotaStatus `json:"quota,omitempty"` + Conditions []metav1.Condition `json:"conditions,omitempty"` +} + +type ResourcePoolQuotaStatus struct { + ObservedGeneration int64 `json:"observedGeneration,omitempty"` + Used ResourcePoolResourceUsage `json:"used"` + Reserved ResourcePoolResourceUsage `json:"reserved"` + Reservations []ResourcePoolQuotaReservationStatus `json:"reservations,omitempty"` +} + +type ResourcePoolResourceUsage struct { + CPU resource.Quantity `json:"cpu,omitempty"` + Memory resource.Quantity `json:"memory,omitempty"` +} + +type ResourcePoolQuotaReservationStatus struct { + ID string `json:"id"` + Namespace string `json:"namespace"` + PodName string `json:"podName"` + PodUID types.UID `json:"podUID,omitempty"` + Delta ResourcePoolResourceUsage `json:"delta"` + Target ResourcePoolResourceUsage `json:"target"` + ExpiresAt metav1.Time `json:"expiresAt"` +} + +type GPUDevice struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + Spec GPUDeviceSpec `json:"spec"` + Status GPUDeviceStatus `json:"status,omitempty"` +} + +type GPUDeviceList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []GPUDevice `json:"items"` +} + +type GPUDeviceSpec struct { + Identity DeviceIdentity `json:"identity"` + PoolRef *PoolReference `json:"poolRef,omitempty"` +} + +type DeviceIdentity struct { + NodeName string `json:"nodeName"` + DeviceType string `json:"deviceType"` + DeviceID string `json:"deviceID"` +} + +type GPUDeviceStatus struct { + ObservedGeneration int64 `json:"observedGeneration,omitempty"` + Discovered bool `json:"discovered"` + Healthy bool `json:"healthy"` + Model string `json:"model,omitempty"` + VGPUCount int32 `json:"vgpuCount,omitempty"` + MemoryMiB int32 `json:"memoryMiB,omitempty"` + CorePercent int32 `json:"corePercent,omitempty"` + Conditions []metav1.Condition `json:"conditions,omitempty"` + Allocations []GPUAllocationStatus `json:"allocations,omitempty"` +} + +type GPUAllocationState string + +type GPUAllocationStatus struct { + PodUID types.UID `json:"podUID"` + Namespace string `json:"namespace"` + PodName string `json:"podName"` + ContainerName string `json:"containerName"` + InitContainer bool `json:"initContainer,omitempty"` + RestartableInitContainer bool `json:"restartableInitContainer,omitempty"` + ContainerIndex int32 `json:"containerIndex"` + DeviceIndex int32 `json:"deviceIndex"` + MemoryMiB int32 `json:"memoryMiB,omitempty"` + CorePercent int32 `json:"corePercent,omitempty"` + State GPUAllocationState `json:"state"` + MIG *MIGAllocationStatus `json:"mig,omitempty"` +} + +type MIGAllocationStatus struct { + Profile string `json:"profile"` + Placement MIGPlacementStatus `json:"placement"` + MIGUUID string `json:"migUUID,omitempty"` + GPUInstanceID *uint32 `json:"gpuInstanceID,omitempty"` + ComputeInstanceID *uint32 `json:"computeInstanceID,omitempty"` +} + +type MIGPlacementStatus struct { + Start uint32 `json:"start"` + Size uint32 `json:"size"` +} + +type ResourcePoolBinding struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + Spec ResourcePoolBindingSpec `json:"spec"` + Status ResourcePoolBindingStatus `json:"status,omitempty"` +} + +type ResourcePoolBindingList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []ResourcePoolBinding `json:"items"` +} + +type ResourcePoolBindingSpec struct { + PoolRef PoolReference `json:"poolRef"` +} + +type ResourcePoolBindingStatus struct { + ObservedGeneration int64 `json:"observedGeneration,omitempty"` + Conditions []metav1.Condition `json:"conditions,omitempty"` +} diff --git a/internal/resourcepool/v1alpha1/types_test.go b/internal/resourcepool/v1alpha1/types_test.go new file mode 100644 index 0000000..146388c --- /dev/null +++ b/internal/resourcepool/v1alpha1/types_test.go @@ -0,0 +1,105 @@ +package v1alpha1 + +import ( + "encoding/json" + "maps" + "reflect" + "testing" + + "k8s.io/apimachinery/pkg/api/resource" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/serializer" +) + +func TestResourcePoolObjectsRoundTrip(t *testing.T) { + t.Parallel() + scheme := runtime.NewScheme() + if err := AddToScheme(scheme); err != nil { + t.Fatal(err) + } + decoder := serializer.NewCodecFactory(scheme).UniversalDeserializer() + objects := []string{ + `{"apiVersion":"resource.hami.io/v1alpha1","kind":"ResourcePool","metadata":{"name":"training","creationTimestamp":"2026-11-26T10:00:00Z"}, + "spec":{"quota":{"cpu":"1500m","memory":"2Gi"},"workloadDefaults":{"schedulingPolicy":{"node":"spread","gpu":"topology-aware"}}}, + "status":{"quota":{"observedGeneration":2,"used":{"cpu":"1","memory":"1Gi"},"reserved":{"cpu":"500m","memory":"1Gi"}, + "reservations":[{"id":"r1","namespace":"ml","podName":"trainer","podUID":"pod-1", + "delta":{"cpu":"500m","memory":"1Gi"},"target":{"cpu":"1","memory":"2Gi"},"expiresAt":"2026-11-27T09:00:00Z"}]}}}`, + `{"apiVersion":"resource.hami.io/v1alpha1","kind":"GPUDevice","metadata":{"name":"gpu-a","creationTimestamp":"2026-11-26T10:00:00Z"}, + "spec":{"identity":{"nodeName":"node-a","deviceType":"NVIDIA","deviceID":"GPU-A"},"poolRef":{"name":"training"}}, + "status":{"discovered":true,"healthy":true,"model":"A100","vgpuCount":4,"memoryMiB":40960,"corePercent":100, + "allocations":[{"podUID":"pod-1","namespace":"ml","podName":"trainer","containerName":"init-model", + "initContainer":true,"restartableInitContainer":true,"containerIndex":0,"deviceIndex":0,"memoryMiB":5120, + "corePercent":20,"state":"Active","mig":{"profile":"1g.5gb","placement":{"start":0,"size":1}, + "migUUID":"MIG-A","gpuInstanceID":0,"computeInstanceID":0}}]}}`, + `{"apiVersion":"resource.hami.io/v1alpha1","kind":"ResourcePoolBinding","metadata":{"name":"training","namespace":"ml","creationTimestamp":"2026-11-26T10:00:00Z"}, + "spec":{"poolRef":{"name":"training"}},"status":{"observedGeneration":1}}`, + } + for _, raw := range objects { + obj, gvk, err := decoder.Decode([]byte(raw), nil, nil) + if err != nil { + t.Fatal(err) + } + t.Run(gvk.Kind, func(t *testing.T) { + t.Parallel() + copy := obj.DeepCopyObject() + encoded, err := json.Marshal(copy) + if err != nil { + t.Fatal(err) + } + var want, got any + if err := json.Unmarshal([]byte(raw), &want); err != nil { + t.Fatal(err) + } + if err := json.Unmarshal(encoded, &got); err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(got, want) { + t.Errorf("round trip changed object\ngot: %s\nwant: %s", encoded, raw) + } + // Patch bases and objects stored in the client must own nested data. + adjustment := resource.MustParse("100m") + switch copied := copy.(type) { + case *ResourcePool: + copied.Spec.Quota.CPU.Sub(adjustment) + copied.Status.Quota.Reservations[0].Delta.CPU.Sub(adjustment) + case *GPUDevice: + copied.Spec.PoolRef.Name = "other" + *copied.Status.Allocations[0].MIG.GPUInstanceID = 3 + case *ResourcePoolBinding: + copied.Spec.PoolRef.Name = "other" + } + original, err := json.Marshal(obj) + if err != nil { + t.Fatal(err) + } + if string(original) != string(encoded) { + t.Errorf("changing the copy changed the source object: %s", original) + } + }) + } +} + +func TestGPUDeviceIdentityAndPoolIndexes(t *testing.T) { + t.Parallel() + device := &GPUDevice{Spec: GPUDeviceSpec{ + Identity: DeviceIdentity{NodeName: "node-a", DeviceType: "NVIDIA", DeviceID: "GPU-A"}, + PoolRef: &PoolReference{Name: "training"}, + }} + device.Labels = map[string]string{"team": "ml", "resource.hami.io/pool": "old"} + const wantName = "gpu-5aea37ceecac0d037b703769861f1980" + if got := DeviceObjectName(device.Spec.Identity); got != wantName { + t.Errorf("DeviceObjectName() = %q, want %q", got, wantName) + } + want := map[string]string{"team": "ml", "resource.hami.io/device-type": "nvidia", "resource.hami.io/pool": "training"} + if got := PoolLabels(device); !maps.Equal(got, want) { + t.Errorf("PoolLabels() = %v, want %v", got, want) + } + device.Spec.PoolRef = nil + delete(want, "resource.hami.io/pool") + if got := PoolLabels(device); !maps.Equal(got, want) { + t.Errorf("PoolLabels() after unassign = %v, want %v", got, want) + } + if got := device.Labels["resource.hami.io/pool"]; got != "old" { + t.Errorf("PoolLabels() changed source label to %q", got) + } +} diff --git a/main.go b/main.go index 8a76ed4..5e3286a 100644 --- a/main.go +++ b/main.go @@ -31,7 +31,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" sigsyaml "sigs.k8s.io/yaml" - resourcepoolv1alpha1 "github.com/dynamia-ai/hami-enterprise/pkg/resourcepool/api/v1alpha1" + resourcepoolv1alpha1 "github.com/dynamia-ai/hami-cli/internal/resourcepool/v1alpha1" ) type commandOptions struct { diff --git a/main_test.go b/main_test.go index 575dd18..b84447d 100644 --- a/main_test.go +++ b/main_test.go @@ -28,7 +28,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client/interceptor" sigsyaml "sigs.k8s.io/yaml" - resourcepoolv1alpha1 "github.com/dynamia-ai/hami-enterprise/pkg/resourcepool/api/v1alpha1" + resourcepoolv1alpha1 "github.com/dynamia-ai/hami-cli/internal/resourcepool/v1alpha1" ) func TestRootCommandUsesKubectlPluginDisplayNameAndStandardFlags(t *testing.T) { diff --git a/regex_bindings.go b/regex_bindings.go index 3ab0f49..3a21b7c 100644 --- a/regex_bindings.go +++ b/regex_bindings.go @@ -10,7 +10,7 @@ import ( "sort" "strings" - resourcepoolv1alpha1 "github.com/dynamia-ai/hami-enterprise/pkg/resourcepool/api/v1alpha1" + resourcepoolv1alpha1 "github.com/dynamia-ai/hami-cli/internal/resourcepool/v1alpha1" "github.com/spf13/cobra" corev1 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" diff --git a/regex_bindings_test.go b/regex_bindings_test.go index 95cb621..6043e8e 100644 --- a/regex_bindings_test.go +++ b/regex_bindings_test.go @@ -6,7 +6,7 @@ import ( "strings" "testing" - resourcepoolv1alpha1 "github.com/dynamia-ai/hami-enterprise/pkg/resourcepool/api/v1alpha1" + resourcepoolv1alpha1 "github.com/dynamia-ai/hami-cli/internal/resourcepool/v1alpha1" corev1 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" diff --git a/version.go b/version.go index 9e6a94f..9e76d9a 100644 --- a/version.go +++ b/version.go @@ -6,6 +6,8 @@ import ( "runtime/debug" "strings" "time" + + resourcepoolv1alpha1 "github.com/dynamia-ai/hami-cli/internal/resourcepool/v1alpha1" ) var ( @@ -14,17 +16,14 @@ var ( cliBuildDate = "unknown" ) -const resourcePoolAPIModulePath = "github.com/dynamia-ai/hami-enterprise/pkg/resourcepool/api" - type cliBuildInfo struct { - Version string - Revision string - ResourcePoolAPIRevision string - CommitDate string - BuildDate string - GoVersion string - Compiler string - Platform string + Version string + Revision string + CommitDate string + BuildDate string + GoVersion string + Compiler string + Platform string } func currentCLIBuildInfo() cliBuildInfo { @@ -62,35 +61,14 @@ func resolveCLIBuildInfo(version, revision, buildDate string, buildInfo *debug.B } return cliBuildInfo{ - Version: version, - Revision: revision, - ResourcePoolAPIRevision: dependencyRevision(buildInfo, resourcePoolAPIModulePath), - CommitDate: commitDate, - BuildDate: buildDate, - GoVersion: runtime.Version(), - Compiler: runtime.Compiler, - Platform: fmt.Sprintf("%s/%s", runtime.GOOS, runtime.GOARCH), - } -} - -func dependencyRevision(buildInfo *debug.BuildInfo, modulePath string) string { - if buildInfo == nil { - return "unknown" - } - for _, dependency := range buildInfo.Deps { - if dependency.Path != modulePath { - continue - } - if dependency.Replace != nil { - dependency = dependency.Replace - } - revision, _ := parsePseudoVersion(dependency.Version) - if revision != "" { - return revision - } - return "unknown" + Version: version, + Revision: revision, + CommitDate: commitDate, + BuildDate: buildDate, + GoVersion: runtime.Version(), + Compiler: runtime.Compiler, + Platform: fmt.Sprintf("%s/%s", runtime.GOOS, runtime.GOARCH), } - return "unknown" } func parsePseudoVersion(version string) (string, string) { @@ -118,5 +96,5 @@ commit date: %s build date: %s go version: %s compiler: %s -platform: %s`, info.Version, info.Revision, info.ResourcePoolAPIRevision, info.CommitDate, info.BuildDate, info.GoVersion, info.Compiler, info.Platform) +platform: %s`, info.Version, info.Revision, resourcepoolv1alpha1.GroupVersion, info.CommitDate, info.BuildDate, info.GoVersion, info.Compiler, info.Platform) } diff --git a/version_test.go b/version_test.go index 5bf3c0d..f1b2935 100644 --- a/version_test.go +++ b/version_test.go @@ -81,10 +81,11 @@ func TestResolveCLIBuildInfo(t *testing.T) { } output := parseCLIBuildInfoOutput(t, got.String()) for field, want := range map[string]string{ - "version": test.want.Version, - "revision": test.want.Revision, - "commit date": test.want.CommitDate, - "build date": test.want.BuildDate, + "version": test.want.Version, + "resource pool API": "resource.hami.io/v1alpha1", + "revision": test.want.Revision, + "commit date": test.want.CommitDate, + "build date": test.want.BuildDate, } { if output[field] != want { t.Errorf("version output %q = %q, want %q", field, output[field], want) @@ -93,59 +94,3 @@ func TestResolveCLIBuildInfo(t *testing.T) { }) } } - -func TestResolveCLIBuildInfoResourcePoolAPIRevision(t *testing.T) { - t.Parallel() - tests := []struct { - name string - buildInfo *debug.BuildInfo - want string - }{ - { - name: "pseudo-version", - buildInfo: &debug.BuildInfo{Deps: []*debug.Module{{ - Path: resourcePoolAPIModulePath, - Version: "v0.0.0-20260824104039-b85d4c6f1d21", - }}}, - want: "b85d4c6f1d21", - }, - { - name: "replacement pseudo-version", - buildInfo: &debug.BuildInfo{Deps: []*debug.Module{{ - Path: resourcePoolAPIModulePath, - Replace: &debug.Module{ - Path: resourcePoolAPIModulePath, - Version: "v0.0.0-20260824110000-cafebabefeed", - }, - }}}, - want: "cafebabefeed", - }, - { - name: "missing dependency", - buildInfo: &debug.BuildInfo{}, - want: "unknown", - }, - { - name: "tagged dependency", - buildInfo: &debug.BuildInfo{Deps: []*debug.Module{{ - Path: resourcePoolAPIModulePath, - Version: "v1.2.3", - }}}, - want: "unknown", - }, - } - - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - t.Parallel() - got := resolveCLIBuildInfo("devel", "unknown", "unknown", test.buildInfo) - if got.ResourcePoolAPIRevision != test.want { - t.Errorf("ResourcePoolAPIRevision = %q, want %q", got.ResourcePoolAPIRevision, test.want) - } - output := parseCLIBuildInfoOutput(t, got.String()) - if output["resource pool API"] != test.want { - t.Errorf("version output resource pool API = %q, want %q", output["resource pool API"], test.want) - } - }) - } -}