Compare commits

..

18 Commits

Author SHA1 Message Date
github-actions[bot]
02e13f9dc3 Fix: Enhance shared resource handling to avoid last-applied-configuration pollution (#6998) (#7000)
(cherry picked from commit 552764d48f)

Signed-off-by: Brian Kane <briankane1@gmail.com>
Co-authored-by: Ayush Kumar <65535504+roguepikachu@users.noreply.github.com>
2025-11-26 08:06:12 -08:00
Tianxin Dong
d56da069eb Fix: upgrade workflow to fix suspend (#6623)
* fix: upgrade workflow to fix suspend

Signed-off-by: FogDong <fog@bentoml.com>

* fix: fix gomega version

Signed-off-by: FogDong <fog@bentoml.com>

* Fix: Update docker image and workflow go version to 1.22

Signed-off-by: Anoop Gopalakrishnan <anoop2811@aol.in>

* Fix: do dependency fix check

Signed-off-by: Anoop Gopalakrishnan <anoop2811@aol.in>

* Fix: build failure

Signed-off-by: Anoop Gopalakrishnan <anoop2811@aol.in>

* Fix: build failure

Signed-off-by: Anoop Gopalakrishnan <anoop2811@aol.in>

---------

Signed-off-by: FogDong <fog@bentoml.com>
Signed-off-by: Anoop Gopalakrishnan <anoop2811@aol.in>
Co-authored-by: Anoop Gopalakrishnan <anoop2811@aol.in>
2024-09-29 01:57:45 +05:30
github-actions[bot]
89c1d07a8f Fix(CUE): fix volumns variable err bug in vela-cli (#6619)
Signed-off-by: yukunjie <yukunjie007@163.com>
Co-authored-by: yukunjie <yukunjie007@163.com>
(cherry picked from commit b605e0857c)

Co-authored-by: yukunjie <yukunjie007@163.com>
2024-09-19 09:53:07 +08:00
github-actions[bot]
fa8350bc50 fix: disable auto maxprocs logging (#6618)
Signed-off-by: FogDong <fog@bentoml.com>
(cherry picked from commit d025a6d5af)

Co-authored-by: FogDong <fog@bentoml.com>
2024-09-19 09:51:43 +08:00
Tianxin Dong
8917780555 fix: bump pkg version to fix the client bug (#6507)
Signed-off-by: FogDong <fog@bentoml.com>
2024-04-22 15:31:51 +08:00
曾子恒
f46bfcf131 Fix(CUE): fix variable error bug in startup-probe (#6472)
The original variable is "grtcpSocketpc", but this variable does not
exist in the file. According to the context, it should be "tcpSocket".
In addition, its type needs to be int to work properly.

Signed-off-by: zengziheng <zengziheng@datacloak.com>
Co-authored-by: zengziheng <zengziheng@datacloak.com>
2024-04-07 10:38:33 +08:00
yyzxw
5bdd0db6e7 Chore: update chart readme (#6494)
Signed-off-by: yyzxw <1020938856@qq.com>
Co-authored-by: xiaowu.zhu <xiaowu.zhu@daocloud.io>
2024-04-01 16:06:20 +08:00
yyzxw
838ff055b8 chore: ci yaml err (#6492)
Signed-off-by: xiaowu.zhu <xiaowu.zhu@daocloud.io>
Co-authored-by: xiaowu.zhu <xiaowu.zhu@daocloud.io>
2024-04-01 10:28:12 +08:00
Awadabang
24756fc507 fix: comma ok (#6457)
Signed-off-by: Awadabang <sheunggz@gmail.com>
Co-authored-by: Awadabang <sheunggz@gmail.com>
2024-03-15 22:50:47 +08:00
dependabot[bot]
81b54781a2 Chore: (deps): Bump google.golang.org/protobuf from 1.31.0 to 1.33.0 (#6479)
Bumps google.golang.org/protobuf from 1.31.0 to 1.33.0.

---
updated-dependencies:
- dependency-name: google.golang.org/protobuf
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-03-15 22:49:56 +08:00
dependabot[bot]
d27cc318f2 Chore: (deps): Bump golang.org/x/crypto from 0.18.0 to 0.21.0 (#6474)
Bumps [golang.org/x/crypto](https://github.com/golang/crypto) from 0.18.0 to 0.21.0.
- [Commits](https://github.com/golang/crypto/compare/v0.18.0...v0.21.0)

---
updated-dependencies:
- dependency-name: golang.org/x/crypto
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-03-15 22:48:51 +08:00
Paul Sweeney
4e16b047f9 Fix: allow different service and container port (#6477)
Signed-off-by: kolossi <github@kolossi.co.uk>
Co-authored-by: kolossi <kolossi@github.com>
2024-03-15 22:46:22 +08:00
msun1996
c512bbe93a Fix: zstd encoder concurrency number in k8s container, upgrade kubevela/pkg version to 1.9.0 (#6462) (#6476)
Signed-off-by: hanzhaoyang <hanzhaoyang@jd.com>
Co-authored-by: hanzhaoyang <hanzhaoyang@jd.com>
2024-03-15 22:44:55 +08:00
Daniel Higuero
1a001e5b29 Address GolangCI lint 1.55 errors (#6453)
Signed-off-by: Daniel Higuero <daniel@napptive.com>
2024-02-07 17:27:32 +08:00
Paul Sweeney
42d75e09e5 Fix: add cronjob support for annotations, resources, and volumeMounts (#6422)
* Fix: add cronjob support for annotations, resources, and volumeMounts

Signed-off-by: kolossi <github@kolossi.co.uk>

* Fix: cronjob support change if shortcuts to chained ifs

Signed-off-by: kolossi <github@kolossi.co.uk>

* Fix: cronjob support change if shortcuts to chained ifs

Signed-off-by: kolossi <github@kolossi.co.uk>

---------

Signed-off-by: kolossi <github@kolossi.co.uk>
Co-authored-by: kolossi <kolossi@github.com>
2024-01-22 13:11:52 +08:00
Eray
5101401837 Fix: hpa build-in trait corresponding to cpu parameters when try to use memory (#6434)
Signed-off-by: Eray Arslan <relfishere@gmail.com>
2024-01-22 13:10:26 +08:00
dependabot[bot]
b9bfc4ac75 Chore: (deps): Bump golang.org/x/crypto from 0.14.0 to 0.18.0 (#6442)
Bumps [golang.org/x/crypto](https://github.com/golang/crypto) from 0.14.0 to 0.18.0.
- [Commits](https://github.com/golang/crypto/compare/v0.14.0...v0.18.0)

---
updated-dependencies:
- dependency-name: golang.org/x/crypto
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-01-22 13:09:42 +08:00
Tyler Gillson
86dc53afab Fix: load local ComponentDefinitions recursively (#6414)
* fix: load local componentdefinitions recursively

Signed-off-by: Tyler Gillson <tyler.gillson@gmail.com>

* test: add dry-run offline def dir test

Signed-off-by: Tyler Gillson <tyler.gillson@gmail.com>

* test: fix unit tests

Signed-off-by: Tyler Gillson <tyler.gillson@gmail.com>

---------

Signed-off-by: Tyler Gillson <tyler.gillson@gmail.com>
2024-01-04 08:47:59 -08:00
75 changed files with 1102 additions and 482 deletions

View File

@@ -18,7 +18,7 @@ permissions:
env:
# Common versions
GO_VERSION: '1.19'
GO_VERSION: '1.22'
jobs:
@@ -78,7 +78,8 @@ jobs:
- name: Get Ginkgo
run: |
go install github.com/onsi/ginkgo/v2/ginkgo@v2.10.0
go get github.com/onsi/gomega/...
go get github.com/onsi/gomega@v1.34.2
go mod tidy
- name: Load image
run: |

View File

@@ -9,7 +9,6 @@ on:
branches:
- master
- release-*
-
permissions:
contents: read

View File

@@ -155,6 +155,13 @@ issues:
linters:
- gocritic
# Gosmopolitan complains of internationalization issues on the file that actually defines
# the translation.
- path: i18n\.go
text: "Han"
linters:
- gosmopolitan
# These are performance optimisations rather than style issues per se.
# They warn when function arguments or range values copy a lot of memory
# rather than using a pointer.

View File

@@ -1,6 +1,6 @@
ARG BASE_IMAGE
# Build the manager binary
FROM --platform=${BUILDPLATFORM:-linux/amd64} golang:1.19-alpine@sha256:2381c1e5f8350a901597d633b2e517775eeac7a6682be39225a93b22cfd0f8bb as builder
FROM --platform=${BUILDPLATFORM:-linux/amd64} golang:1.22.7-alpine@sha256:48eab5e3505d8c8b42a06fe5f1cf4c346c167cc6a89e772f31cb9e5c301dcf60 as builder
WORKDIR /workspace
# Copy the Go Modules manifests

View File

@@ -186,6 +186,21 @@ if [ $fluxcd ]; then
fi
```
Make sure all existing KubeVela resources deleted before uninstallation:
```shell
kubectl delete applicationrevisions.core.oam.dev --all
kubectl delete applications.core.oam.dev --all
kubectl delete componentdefinitions.core.oam.dev --all
kubectl delete definitionrevisions.core.oam.dev --all
kubectl delete policies.core.oam.dev --all
kubectl delete policydefinitions.core.oam.dev --all
kubectl delete resourcetrackers.core.oam.dev --all
kubectl delete traitdefinitions.core.oam.dev --all
kubectl delete workflows.core.oam.dev --all
kubectl delete workflowstepdefinitions.core.oam.dev --all
kubectl delete workloaddefinitions.core.oam.dev --all
```
To uninstall the KubeVela helm release:
```shell

View File

@@ -4,7 +4,7 @@ apiVersion: core.oam.dev/v1beta1
kind: TraitDefinition
metadata:
annotations:
definition.oam.dev/description: Add annotations on your workload. if it generates pod, add same annotations for generated pods.
definition.oam.dev/description: Add annotations on your workload. If it generates pod or job, add same annotations for generated pods.
name: annotations
namespace: {{ include "systemDefinitionNamespace" . }}
spec:
@@ -16,17 +16,21 @@ spec:
template: |
// +patchStrategy=jsonMergePatch
patch: {
metadata: annotations: {
let annotationsContent = {
for k, v in parameter {
(k): v
}
}
if context.output.spec != _|_ && context.output.spec.template != _|_ {
spec: template: metadata: annotations: {
for k, v in parameter {
(k): v
}
}
metadata: annotations: annotationsContent
if context.output.spec != _|_ if context.output.spec.template != _|_ {
spec: template: metadata: annotations: annotationsContent
}
if context.output.spec != _|_ if context.output.spec.jobTemplate != _|_ {
spec: jobTemplate: metadata: annotations: annotationsContent
}
if context.output.spec != _|_ if context.output.spec.jobTemplate != _|_ if context.output.spec.jobTemplate.spec != _|_ if context.output.spec.jobTemplate.spec.template != _|_ {
spec: jobTemplate: spec: template: metadata: annotations: annotationsContent
}
}
parameter: [string]: string | null

View File

@@ -11,6 +11,138 @@ spec:
schematic:
cue:
template: |
mountsArray: {
pvc: *[
for v in parameter.volumeMounts.pvc {
{
mountPath: v.mountPath
if v.subPath != _|_ {
subPath: v.subPath
}
name: v.name
}
},
] | []
configMap: *[
for v in parameter.volumeMounts.configMap {
{
mountPath: v.mountPath
if v.subPath != _|_ {
subPath: v.subPath
}
name: v.name
}
},
] | []
secret: *[
for v in parameter.volumeMounts.secret {
{
mountPath: v.mountPath
if v.subPath != _|_ {
subPath: v.subPath
}
name: v.name
}
},
] | []
emptyDir: *[
for v in parameter.volumeMounts.emptyDir {
{
mountPath: v.mountPath
if v.subPath != _|_ {
subPath: v.subPath
}
name: v.name
}
},
] | []
hostPath: *[
for v in parameter.volumeMounts.hostPath {
{
mountPath: v.mountPath
if v.subPath != _|_ {
subPath: v.subPath
}
name: v.name
}
},
] | []
}
volumesArray: {
pvc: *[
for v in parameter.volumeMounts.pvc {
{
name: v.name
persistentVolumeClaim: claimName: v.claimName
}
},
] | []
configMap: *[
for v in parameter.volumeMounts.configMap {
{
name: v.name
configMap: {
defaultMode: v.defaultMode
name: v.cmName
if v.items != _|_ {
items: v.items
}
}
}
},
] | []
secret: *[
for v in parameter.volumeMounts.secret {
{
name: v.name
secret: {
defaultMode: v.defaultMode
secretName: v.secretName
if v.items != _|_ {
items: v.items
}
}
}
},
] | []
emptyDir: *[
for v in parameter.volumeMounts.emptyDir {
{
name: v.name
emptyDir: medium: v.medium
}
},
] | []
hostPath: *[
for v in parameter.volumeMounts.hostPath {
{
name: v.name
hostPath: path: v.path
}
},
] | []
}
volumesList: volumesArray.pvc + volumesArray.configMap + volumesArray.secret + volumesArray.emptyDir + volumesArray.hostPath
deDupVolumesArray: [
for val in [
for i, vi in volumesList {
for j, vj in volumesList if j < i && vi.name == vj.name {
_ignore: true
}
vi
},
] if val._ignore == _|_ {
val
},
]
output: {
if context.clusterVersion.minor < 25 {
apiVersion: "batch/v1beta1"
@@ -90,15 +222,18 @@ spec:
requests: memory: parameter.memory
}
}
if parameter["volumes"] != _|_ {
if parameter["volumes"] != _|_ if parameter["volumeMounts"] == _|_ {
volumeMounts: [ for v in parameter.volumes {
{
mountPath: v.mountPath
name: v.name
}}]
}
if parameter["volumeMounts"] != _|_ {
volumeMounts: mountsArray.pvc + mountsArray.configMap + mountsArray.secret + mountsArray.emptyDir + mountsArray.hostPath
}
}]
if parameter["volumes"] != _|_ {
if parameter["volumes"] != _|_ if parameter["volumeMounts"] == _|_ {
volumes: [ for v in parameter.volumes {
{
name: v.name
@@ -128,6 +263,9 @@ spec:
}
}}]
}
if parameter["volumeMounts"] != _|_ {
volumes: deDupVolumesArray
}
if parameter["imagePullSecrets"] != _|_ {
imagePullSecrets: [ for v in parameter.imagePullSecrets {
name: v
@@ -224,7 +362,58 @@ spec:
// +usage=Specifies the attributes of the memory resource required for the container.
memory?: string
// +usage=Declare volumes and volumeMounts
volumeMounts?: {
// +usage=Mount PVC type volume
pvc?: [...{
name: string
mountPath: string
subPath?: string
// +usage=The name of the PVC
claimName: string
}]
// +usage=Mount ConfigMap type volume
configMap?: [...{
name: string
mountPath: string
subPath?: string
defaultMode: *420 | int
cmName: string
items?: [...{
key: string
path: string
mode: *511 | int
}]
}]
// +usage=Mount Secret type volume
secret?: [...{
name: string
mountPath: string
subPath?: string
defaultMode: *420 | int
secretName: string
items?: [...{
key: string
path: string
mode: *511 | int
}]
}]
// +usage=Mount EmptyDir type volume
emptyDir?: [...{
name: string
mountPath: string
subPath?: string
medium: *"" | "Memory"
}]
// +usage=Mount HostPath type volume
hostPath?: [...{
name: string
mountPath: string
subPath?: string
path: string
}]
}
// +usage=Deprecated field, use volumeMounts instead.
volumes?: [...{
name: string
mountPath: string

View File

@@ -21,22 +21,28 @@ spec:
if parameter.name != _|_ {"-" + parameter.name}
if parameter.name == _|_ {""}
}
let serviceOutputName = "service" + nameSuffix
let serviceMetaName = context.name + nameSuffix
outputs: (serviceOutputName): {
apiVersion: "v1"
kind: "Service"
metadata: name: "\(serviceMetaName)"
spec: {
selector: "app.oam.dev/component": context.name
ports: [
for k, v in parameter.http {
name: "port-" + strconv.FormatInt(v, 10)
port: v
targetPort: v
},
]
let serviceMetaName = {
if (parameter.existingServiceName != _|_) {parameter.existingServiceName}
if (parameter.existingServiceName == _|_) {context.name + nameSuffix}
}
if (parameter.existingServiceName == _|_) {
let serviceOutputName = "service" + nameSuffix
outputs: (serviceOutputName): {
apiVersion: "v1"
kind: "Service"
metadata: name: "\(serviceMetaName)"
spec: {
selector: "app.oam.dev/component": context.name
ports: [
for k, v in parameter.http {
name: "port-" + strconv.FormatInt(v, 10)
port: v
targetPort: v
},
]
}
}
}
@@ -143,6 +149,9 @@ spec:
// +usage=Specify the labels to be added to the ingress
labels?: [string]: string
// +usage=If specified, use an existing Service rather than creating one
existingServiceName?: string
}
status:
customStatus: |-

View File

@@ -55,11 +55,11 @@ spec:
name: "memory"
target: {
type: parameter.mem.type
if parameter.cpu.type == "Utilization" {
averageUtilization: parameter.cpu.value
if parameter.mem.type == "Utilization" {
averageUtilization: parameter.mem.value
}
if parameter.cpu.type == "AverageValue" {
averageValue: parameter.cpu.value
if parameter.mem.type == "AverageValue" {
averageValue: parameter.mem.value
}
}
}

View File

@@ -13,43 +13,54 @@ spec:
- statefulsets.apps
- daemonsets.apps
- jobs.batch
- cronjobs.batch
podDisruptive: true
schematic:
cue:
template: |
patch: spec: template: spec: {
// +patchKey=name
containers: [{
resources: {
if parameter.cpu != _|_ if parameter.memory != _|_ if parameter.requests == _|_ if parameter.limits == _|_ {
// +patchStrategy=retainKeys
requests: {
cpu: parameter.cpu
memory: parameter.memory
}
// +patchStrategy=retainKeys
limits: {
cpu: parameter.cpu
memory: parameter.memory
}
template: |2
let resourceContent = {
resources: {
if parameter.cpu != _|_ if parameter.memory != _|_ if parameter.requests == _|_ if parameter.limits == _|_ {
// +patchStrategy=retainKeys
requests: {
cpu: parameter.cpu
memory: parameter.memory
}
if parameter.requests != _|_ {
// +patchStrategy=retainKeys
requests: {
cpu: parameter.requests.cpu
memory: parameter.requests.memory
}
}
if parameter.limits != _|_ {
// +patchStrategy=retainKeys
limits: {
cpu: parameter.limits.cpu
memory: parameter.limits.memory
}
// +patchStrategy=retainKeys
limits: {
cpu: parameter.cpu
memory: parameter.memory
}
}
}]
if parameter.requests != _|_ {
// +patchStrategy=retainKeys
requests: {
cpu: parameter.requests.cpu
memory: parameter.requests.memory
}
}
if parameter.limits != _|_ {
// +patchStrategy=retainKeys
limits: {
cpu: parameter.limits.cpu
memory: parameter.limits.memory
}
}
}
}
if context.output.spec != _|_ if context.output.spec.template != _|_ {
patch: spec: template: spec: {
// +patchKey=name
containers: [resourceContent]
}
}
if context.output.spec != _|_ if context.output.spec.jobTemplate != _|_ {
patch: spec: jobTemplate: spec: template: spec: {
// +patchKey=name
containers: [resourceContent]
}
}
parameter: {

View File

@@ -65,7 +65,7 @@ spec:
// +usage=Instructions for assessing container startup status by probing a TCP socket. Either this attribute or the exec attribute or the tcpSocket attribute or the httpGet attribute MUST be specified. This attribute is mutually exclusive with the exec attribute and the httpGet attribute and the gRPC attribute.
tcpSocket?: {
// +usage=Number or name of the port to access on the container.
port: string
port: int
// +usage=Host name to connect to, defaults to the pod IP.
host?: string
}
@@ -144,7 +144,7 @@ spec:
grpc: parameter.grpc
}
if parameter.tcpSocket != _|_ {
tcpSocket: parameter.grtcpSocketpc
tcpSocket: parameter.tcpSocket
}
}}
}]

View File

@@ -46,11 +46,11 @@ spec:
}
}
}
if parameter.storage != _|_ && parameter.storage.hostPath != _|_ for v in parameter.storage.hostPath {
{
name: "hostpath-" + v.name
path: v.path
}
},
if parameter.storage != _|_ && parameter.storage.hostPath != _|_ for v in parameter.storage.hostPath {
{
name: "hostpath-" + v.name
path: v.path
}
},
]

View File

@@ -165,14 +165,20 @@ spec:
if parameter["ports"] != _|_ {
ports: [ for v in parameter.ports {
{
containerPort: v.port
protocol: v.protocol
containerPort: {
if v.containerPort != _|_ {v.containerPort}
if v.containerPort == _|_ {v.port}
}
protocol: v.protocol
if v.name != _|_ {
name: v.name
}
if v.name == _|_ {
_name: "port-" + strconv.FormatInt(v.port, 10)
name: *_name | string
_name: {
if v.containerPort != _|_ {"port-" + strconv.FormatInt(v.containerPort, 10)}
if v.containerPort == _|_ {"port-" + strconv.FormatInt(v.port, 10)}
}
name: *_name | string
if v.protocol != "TCP" {
name: _name + "-" + strings.ToLower(v.protocol)
}
@@ -290,14 +296,20 @@ spec:
exposePorts: [
if parameter.ports != _|_ for v in parameter.ports if v.expose == true {
port: v.port
targetPort: v.port
if v.name != _|_ {
name: v.name
}
port: v.port
if v.containerPort != _|_ {targetPort: v.containerPort}
if v.containerPort == _|_ {targetPort: v.port}
if v.name != _|_ {name: v.name}
if v.name == _|_ {
_name: "port-" + strconv.FormatInt(v.port, 10)
name: *_name | string
_name: {
if v.containerPort != _|_ {
"port-" + strconv.FormatInt(v.containerPort, 10)
}
if v.containerPort == _|_ {
"port-" + strconv.FormatInt(v.port, 10)
}
}
name: *_name | string
if v.protocol != "TCP" {
name: _name + "-" + strings.ToLower(v.protocol)
}
@@ -352,6 +364,8 @@ spec:
ports?: [...{
// +usage=Number of port to expose on the pod's IP address
port: int
// +usage=Number of container port to connect to, defaults to port
containerPort?: int
// +usage=Name of the port
name?: string
// +usage=Protocol for port. Must be UDP, TCP, or SCTP

17
go.mod
View File

@@ -36,8 +36,8 @@ require (
github.com/hashicorp/hcl/v2 v2.18.0
github.com/hinshun/vt10x v0.0.0-20180616224451-1954e6464174
github.com/imdario/mergo v0.3.16
github.com/kubevela/pkg v1.8.1-0.20230522085329-7d5e1241a86d
github.com/kubevela/workflow v0.6.0
github.com/kubevela/pkg v1.9.2
github.com/kubevela/workflow v0.6.1
github.com/kyokomi/emoji v2.2.4+incompatible
github.com/magiconair/properties v1.8.7
github.com/mattn/go-runewidth v0.0.15
@@ -67,11 +67,11 @@ require (
github.com/xanzy/go-gitlab v0.91.1
github.com/xlab/treeprint v1.2.0
go.uber.org/multierr v1.11.0
golang.org/x/crypto v0.14.0
golang.org/x/crypto v0.21.0
golang.org/x/oauth2 v0.12.0
golang.org/x/sync v0.4.0
golang.org/x/term v0.13.0
golang.org/x/text v0.13.0
golang.org/x/term v0.18.0
golang.org/x/text v0.14.0
golang.org/x/tools v0.14.0
gomodules.xyz/jsonpatch/v2 v2.4.0
gopkg.in/yaml.v3 v3.0.1
@@ -269,15 +269,16 @@ require (
go.opentelemetry.io/proto/otlp v0.19.0 // indirect
go.starlark.net v0.0.0-20200306205701-8dd3e2ee1dd5 // indirect
go.uber.org/atomic v1.9.0 // indirect
go.uber.org/automaxprocs v1.5.3 // indirect
go.uber.org/zap v1.24.0 // indirect
golang.org/x/mod v0.13.0 // indirect
golang.org/x/net v0.17.0 // indirect
golang.org/x/sys v0.14.0 // indirect
golang.org/x/net v0.21.0 // indirect
golang.org/x/sys v0.18.0 // indirect
golang.org/x/time v0.3.0 // indirect
google.golang.org/appengine v1.6.7 // indirect
google.golang.org/genproto v0.0.0-20230306155012-7f2fa6fef1f4 // indirect
google.golang.org/grpc v1.53.0 // indirect
google.golang.org/protobuf v1.31.0 // indirect
google.golang.org/protobuf v1.33.0 // indirect
gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc // indirect
gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df // indirect
gopkg.in/inf.v0 v0.9.1 // indirect

34
go.sum
View File

@@ -601,10 +601,10 @@ github.com/kr/pty v1.1.8/go.mod h1:O1sed60cT9XZ5uDucP5qwvh+TE3NnUj51EiZO/lmSfw=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/kubevela/pkg v1.8.1-0.20230522085329-7d5e1241a86d h1:QMmTg33lUZEfTz94eYJKa6Nb7GDcEOmuXsXRt/dA5vk=
github.com/kubevela/pkg v1.8.1-0.20230522085329-7d5e1241a86d/go.mod h1:3ZWrl2+zb5ROdC2NJPPrL/4sun4M10wYfRP/9gF9WJE=
github.com/kubevela/workflow v0.6.0 h1:fYXviOYD5zqHs3J61tNbM4HZ85EcZlPm7Fyz8Q5o9Fk=
github.com/kubevela/workflow v0.6.0/go.mod h1:sjLcYqKHKeCQ+w77gijoNILwIShJKnCU+e3q7ETtZGI=
github.com/kubevela/pkg v1.9.2 h1:K6pGoJikf6l8vlfehewmb36hyToX0KpUaQP4NVET/S8=
github.com/kubevela/pkg v1.9.2/go.mod h1:u/MGuFXVSECxvIWdTKS4AQs1H+USfAMQgi30BUrOb04=
github.com/kubevela/workflow v0.6.1 h1:x6ro6dTzi5Rrh0pnnqRbNMlhvhP5Rzsls44gP1C3qzw=
github.com/kubevela/workflow v0.6.1/go.mod h1:sjLcYqKHKeCQ+w77gijoNILwIShJKnCU+e3q7ETtZGI=
github.com/kylelemons/godebug v0.0.0-20170820004349-d65d576e9348/go.mod h1:B69LEHPfb2qLo0BaaOLcbitczOKLWTsrBG9LczfCD4k=
github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=
github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
@@ -819,6 +819,7 @@ github.com/poy/onpar v1.1.2 h1:QaNrNiZx0+Nar5dLgTVp5mXkyoVFIbepjyEoGSnhbAY=
github.com/poy/onpar v1.1.2/go.mod h1:6X8FLNoxyr9kkmnlqpK6LSoiOtrO6MICtWwEuWkLjzg=
github.com/pquerna/cachecontrol v0.0.0-20171018203845-0dec1b30a021/go.mod h1:prYjPmNq4d1NPVmpShWobRqXY3q7Vp+80DqgxxUrUIA=
github.com/pquerna/cachecontrol v0.1.0/go.mod h1:NrUG3Z7Rdu85UNR3vm7SOsl1nFIeSiQnrHV5K9mBcUI=
github.com/prashantv/gostub v1.1.0 h1:BTyx3RfQjRHnUWaGF9oQos79AlQ5k8WNktv7VGvVH4g=
github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw=
github.com/prometheus/client_golang v0.9.3/go.mod h1:/TN21ttK/J9q6uSwhBd54HahCDft0ttaMvbicHlPoso=
github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo=
@@ -1082,6 +1083,8 @@ go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE=
go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
go.uber.org/atomic v1.9.0 h1:ECmE8Bn/WFTYwEW/bpKD3M8VtR/zQVbavAoalC1PYyE=
go.uber.org/atomic v1.9.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
go.uber.org/automaxprocs v1.5.3 h1:kWazyxZUrS3Gs4qUpbwo5kEIMGe/DAvi5Z4tl2NW4j8=
go.uber.org/automaxprocs v1.5.3/go.mod h1:eRbA25aqJrxAbsLO0xy5jVwPt7FQnRgjW+efnwa1WM0=
go.uber.org/goleak v1.1.10/go.mod h1:8a7PlsEVH3e/a/GLqe5IIrQx6GzcnRmZEufDUTk4A7A=
go.uber.org/goleak v1.1.11-0.20210813005559-691160354723/go.mod h1:cwTWslyiVhfpKIDGSZEM2HlOvcqm+tG4zioyIeLoqMQ=
go.uber.org/goleak v1.1.11/go.mod h1:cwTWslyiVhfpKIDGSZEM2HlOvcqm+tG4zioyIeLoqMQ=
@@ -1125,8 +1128,8 @@ golang.org/x/crypto v0.3.1-0.20221117191849-2c476679df9a/go.mod h1:hebNnKkNXi2Uz
golang.org/x/crypto v0.5.0/go.mod h1:NK/OQwhpMQP3MwtdjgLlYHnH9ebylxKWv3e0fK+mkQU=
golang.org/x/crypto v0.7.0/go.mod h1:pYwdfH91IfpZVANVyUOhSIPZaFoJGxTFbZhFTx+dXZU=
golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc=
golang.org/x/crypto v0.14.0 h1:wBqGXzWJW6m1XrIKlAH0Hs1JJ7+9KBwnIO8v66Q9cHc=
golang.org/x/crypto v0.14.0/go.mod h1:MVFd36DqK4CsrnJYDkBA3VC4m2GkXAM0PvzMCn4JQf4=
golang.org/x/crypto v0.21.0 h1:X31++rzVUdKhX5sWmSOFZxx8UW/ldWx55cbf08iNAMA=
golang.org/x/crypto v0.21.0/go.mod h1:0BP7YvVV9gBbVKyeTG0Gyn+gZm94bibOW5BjDEYAOMs=
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20191030013958-a1ab85dbe136/go.mod h1:JXzH8nQsPlswgeRAPE3MuO9GYsAcnJvJ4vnMwN/5qkY=
@@ -1203,8 +1206,8 @@ golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
golang.org/x/net v0.8.0/go.mod h1:QVkue5JL9kW//ek3r6jTKnTFis1tRmNAW2P1shuFdJc=
golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
golang.org/x/net v0.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk=
golang.org/x/net v0.17.0 h1:pVaXccu2ozPjCXewfr1S7xza/zcXTity9cCdXQYSjIM=
golang.org/x/net v0.17.0/go.mod h1:NxSsAGuq816PNPmqtQdLE42eU2Fs7NoRIZrHJAlaCOE=
golang.org/x/net v0.21.0 h1:AQyQV4dYCvJ7vGmJyKki9+PBdyvhkSd8EIx/qb0AYv4=
golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
@@ -1307,8 +1310,8 @@ golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.14.0 h1:Vz7Qs629MkJkGyHxUlRHizWJRG2j8fbQKjELVSNhy7Q=
golang.org/x/sys v0.14.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.18.0 h1:DBdB3niSjOA/O0blCZBqDefyWNYveAYMNF1Wum0DYQ4=
golang.org/x/sys v0.18.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210220032956-6a3ed077a48d/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
@@ -1322,8 +1325,8 @@ golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
golang.org/x/term v0.6.0/go.mod h1:m6U89DPEgQRMq3DNkDClhWw02AUbt2daBVO4cn4Hv9U=
golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo=
golang.org/x/term v0.12.0/go.mod h1:owVbMEjm3cBLCHdkQu9b1opXd4ETQWc3BhuQGKgXgvU=
golang.org/x/term v0.13.0 h1:bb+I9cTfFazGW51MZqBVmZy7+JEJMouUHTUSKVQLBek=
golang.org/x/term v0.13.0/go.mod h1:LTmsnFJwVN6bCy1rVCoS+qHT1HhALEFxKncY3WNNh4U=
golang.org/x/term v0.18.0 h1:FcHjZXDMxI8mM3nwhX9HlKop4C0YQvCVCdwYl2wOtE8=
golang.org/x/term v0.18.0/go.mod h1:ILwASektA3OnRv7amZ1xhE/KTR+u50pbXfZ03+6Nx58=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
@@ -1336,8 +1339,9 @@ golang.org/x/text v0.6.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
golang.org/x/text v0.13.0 h1:ablQoSUd0tRdKxZewP80B+BaqeKJuVhuRxj/dkrun3k=
golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/time v0.0.0-20210220033141-f8bda1e9f3ba/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/time v0.0.0-20210723032227-1f47c861a9ac/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
@@ -1466,8 +1470,8 @@ google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQ
google.golang.org/protobuf v1.27.1/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
google.golang.org/protobuf v1.28.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
google.golang.org/protobuf v1.28.1/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
google.golang.org/protobuf v1.31.0 h1:g0LDEJHgrBl9N9r17Ru3sqWhkIx2NB67okBHPwC7hs8=
google.golang.org/protobuf v1.31.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
google.golang.org/protobuf v1.33.0 h1:uNO2rsAINq/JlFpSdYEKIZ0uKD/R9cpdv0T+yoGwGmI=
google.golang.org/protobuf v1.33.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw=
gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc h1:2gGKlE2+asNV9m7xrywl36YYNnBG5ZQ0r/BOOxqPpmk=
gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc/go.mod h1:m7x9LTH6d71AHyAX77c9yqWCCa3UKHcVEj9y7hAtKDk=

View File

@@ -124,6 +124,9 @@ const (
// InstallerRuntimeOption inject install runtime info into addon options
InstallerRuntimeOption string = "installerRuntimeOption"
// CUEExtension with the expected extension for CUE files
CUEExtension = ".cue"
)
// ParameterFileName is the addon resources/parameter.cue file name
@@ -396,7 +399,7 @@ func readResFile(a *InstallPackage, reader AsyncReader, readPath string) error {
}
file := ElementFile{Data: b, Name: filepath.Base(readPath)}
switch filepath.Ext(filename) {
case ".cue":
case CUEExtension:
a.CUETemplates = append(a.CUETemplates, file)
case ".yaml", ".yml":
a.YAMLTemplates = append(a.YAMLTemplates, file)
@@ -425,7 +428,7 @@ func readDefFile(a *UIData, reader AsyncReader, readPath string) error {
filename := path.Base(readPath)
file := ElementFile{Data: b, Name: filepath.Base(readPath)}
switch filepath.Ext(filename) {
case ".cue":
case CUEExtension:
a.CUEDefinitions = append(a.CUEDefinitions, file)
case ".yaml", ".yml":
a.Definitions = append(a.Definitions, file)
@@ -442,7 +445,7 @@ func readConfigTemplateFile(a *UIData, reader AsyncReader, readPath string) erro
return err
}
filename := path.Base(readPath)
if filepath.Ext(filename) != ".cue" {
if filepath.Ext(filename) != CUEExtension {
return nil
}
file := ElementFile{Data: b, Name: filepath.Base(readPath)}
@@ -458,7 +461,7 @@ func readViewFile(a *InstallPackage, reader AsyncReader, readPath string) error
}
filename := path.Base(readPath)
switch filepath.Ext(filename) {
case ".cue":
case CUEExtension:
a.CUEViews = append(a.CUEViews, ElementFile{Data: b, Name: filepath.Base(readPath)})
case ".yaml", ".yml":
a.YAMLViews = append(a.YAMLViews, ElementFile{Data: b, Name: filepath.Base(readPath)})
@@ -582,7 +585,7 @@ func unmarshalToContent(content []byte) (fileContent *github.RepositoryContent,
if directoryUnmarshalError == nil {
return nil, directoryContent, nil
}
return nil, nil, fmt.Errorf("unmarshalling failed for both file and directory content: %s and %w", fileUnmarshalError, directoryUnmarshalError)
return nil, nil, fmt.Errorf("unmarshalling failed for both file and directory content: %s and %w", fileUnmarshalError.Error(), directoryUnmarshalError)
}
func genAddonAPISchema(addonRes *UIData) error {

View File

@@ -167,7 +167,9 @@ func (p *PushCmd) Push(ctx context.Context) error {
if err != nil {
return err
}
defer func() {
_ = resp.Body.Close()
}()
return handlePushResponse(resp)
}

View File

@@ -203,7 +203,7 @@ type Appfile struct {
// GeneratePolicyManifests generates policy manifests from an appFile
// internal policies like apply-once, topology, will not render manifests
func (af *Appfile) GeneratePolicyManifests(ctx context.Context) ([]*unstructured.Unstructured, error) {
func (af *Appfile) GeneratePolicyManifests(_ context.Context) ([]*unstructured.Unstructured, error) {
var manifests []*unstructured.Unstructured
for _, policy := range af.ParsedPolicies {
un, err := af.generatePolicyUnstructured(policy)

View File

@@ -189,7 +189,7 @@ func (d *Option) PrintDryRun(buff *bytes.Buffer, appName string, comps []*types.
case traitType == definition.AuxiliaryWorkload:
buff.WriteString("## From the auxiliary workload \n")
case traitType != "":
buff.WriteString(fmt.Sprintf("## From the trait %s \n", traitType))
fmt.Fprintf(buff, "## From the trait %s \n", traitType)
}
result, err := yaml.Marshal(t)
if err != nil {

View File

@@ -25,7 +25,7 @@ import (
)
// GetNamespace get namespace from command flags and env
func GetNamespace(f Factory, cmd *cobra.Command) string {
func GetNamespace(_ Factory, cmd *cobra.Command) string {
namespace, err := cmd.Flags().GetString(flagNamespace)
cmdutil.CheckErr(err)
if namespace != "" {

View File

@@ -197,8 +197,8 @@ type Distribution struct {
// CreateDistributionSpec the spec of the distribution
type CreateDistributionSpec struct {
Configs []*NamespacedName
Targets []*ClusterTarget
Configs []*NamespacedName `json:"configs"`
Targets []*ClusterTarget `json:"targets"`
}
// Validation the response of the validation
@@ -612,7 +612,7 @@ func (k *kubeConfigFactory) GetConfig(ctx context.Context, namespace, name strin
// CreateOrUpdateConfig create or update the config.
// Write the expand config to the target server.
func (k *kubeConfigFactory) CreateOrUpdateConfig(ctx context.Context, i *Config, ns string) error {
func (k *kubeConfigFactory) CreateOrUpdateConfig(ctx context.Context, i *Config, _ string) error {
var secret v1.Secret
if err := k.cli.Get(ctx, pkgtypes.NamespacedName{Namespace: i.Namespace, Name: i.Name}, &secret); err == nil {
if secret.Labels[types.LabelConfigType] != i.Template.Name {

View File

@@ -56,7 +56,7 @@ type Response struct {
Message string `json:"message"`
}
func (p *provider) Create(ctx monitorContext.Context, wfCtx wfContext.Context, v *value.Value, act types.Action) error {
func (p *provider) Create(ctx monitorContext.Context, _ wfContext.Context, v *value.Value, _ types.Action) error {
var ccp CreateConfigProperties
if err := v.UnmarshalTo(&ccp); err != nil {
return ErrRequestInvalid
@@ -84,7 +84,7 @@ func (p *provider) Create(ctx monitorContext.Context, wfCtx wfContext.Context, v
return p.factory.CreateOrUpdateConfig(ctx.GetContext(), configItem, ccp.Namespace)
}
func (p *provider) Read(ctx monitorContext.Context, wfCtx wfContext.Context, v *value.Value, act types.Action) error {
func (p *provider) Read(ctx monitorContext.Context, _ wfContext.Context, v *value.Value, _ types.Action) error {
var nn config.NamespacedName
if err := v.UnmarshalTo(&nn); err != nil {
return ErrRequestInvalid
@@ -96,7 +96,7 @@ func (p *provider) Read(ctx monitorContext.Context, wfCtx wfContext.Context, v *
return v.FillObject(content, "config")
}
func (p *provider) List(ctx monitorContext.Context, wfCtx wfContext.Context, v *value.Value, act types.Action) error {
func (p *provider) List(ctx monitorContext.Context, _ wfContext.Context, v *value.Value, _ types.Action) error {
template, err := v.GetString("template")
if err != nil {
return ErrRequestInvalid
@@ -125,7 +125,7 @@ func (p *provider) List(ctx monitorContext.Context, wfCtx wfContext.Context, v *
return v.FillObject(contents, "configs")
}
func (p *provider) Delete(ctx monitorContext.Context, wfCtx wfContext.Context, v *value.Value, act types.Action) error {
func (p *provider) Delete(ctx monitorContext.Context, _ wfContext.Context, v *value.Value, _ types.Action) error {
var nn config.NamespacedName
if err := v.UnmarshalTo(&nn); err != nil {
return errors.New("the request is in valid")

View File

@@ -539,49 +539,49 @@ func (r *Reconciler) SetupWithManager(mgr ctrl.Manager) error {
// filter the changes in workflow status
// let workflow handle its reconcile
UpdateFunc: func(e ctrlEvent.UpdateEvent) bool {
new, isNewApp := e.ObjectNew.DeepCopyObject().(*v1beta1.Application)
newApp, isNewApp := e.ObjectNew.DeepCopyObject().(*v1beta1.Application)
old, isOldApp := e.ObjectOld.DeepCopyObject().(*v1beta1.Application)
if !isNewApp || !isOldApp {
return filterManagedFieldChangesUpdate(e)
}
// We think this event is triggered by resync
if reflect.DeepEqual(old, new) {
if reflect.DeepEqual(old, newApp) {
return true
}
// filter managedFields changes
old.ManagedFields = nil
new.ManagedFields = nil
newApp.ManagedFields = nil
// if the generation is changed, return true to let the controller handle it
if old.Generation != new.Generation {
if old.Generation != newApp.Generation {
return true
}
// filter the events triggered by initial application status
if new.Status.Phase == common.ApplicationRendering || (old.Status.Phase == common.ApplicationRendering && new.Status.Phase == common.ApplicationRunningWorkflow) {
if newApp.Status.Phase == common.ApplicationRendering || (old.Status.Phase == common.ApplicationRendering && newApp.Status.Phase == common.ApplicationRunningWorkflow) {
return false
}
// ignore the changes in workflow status
if old.Status.Workflow != nil && new.Status.Workflow != nil {
if old.Status.Workflow != nil && newApp.Status.Workflow != nil {
// only workflow execution will change the status.workflow
// let workflow backoff to requeue the event
new.Status.Workflow.Steps = old.Status.Workflow.Steps
new.Status.Workflow.ContextBackend = old.Status.Workflow.ContextBackend
new.Status.Workflow.Message = old.Status.Workflow.Message
new.Status.Workflow.EndTime = old.Status.Workflow.EndTime
newApp.Status.Workflow.Steps = old.Status.Workflow.Steps
newApp.Status.Workflow.ContextBackend = old.Status.Workflow.ContextBackend
newApp.Status.Workflow.Message = old.Status.Workflow.Message
newApp.Status.Workflow.EndTime = old.Status.Workflow.EndTime
}
// appliedResources and Services will be changed during the execution of workflow
// once the resources is added, the managed fields will also be changed
new.Status.AppliedResources = old.Status.AppliedResources
new.Status.Services = old.Status.Services
newApp.Status.AppliedResources = old.Status.AppliedResources
newApp.Status.Services = old.Status.Services
// the resource version will be changed if the object is changed
// ignore this change and let reflect.DeepEqual to compare the rest of the object
new.ResourceVersion = old.ResourceVersion
return !reflect.DeepEqual(old, new)
newApp.ResourceVersion = old.ResourceVersion
return !reflect.DeepEqual(old, newApp)
},
CreateFunc: func(e ctrlEvent.CreateEvent) bool {
return true
@@ -616,14 +616,14 @@ func updateObservedGeneration(app *v1beta1.Application) {
// For old k8s version like 1.18.5, the managedField could always update and cause infinite loop
// this function helps filter those events and prevent infinite loop
func filterManagedFieldChangesUpdate(e ctrlEvent.UpdateEvent) bool {
new, isNewRT := e.ObjectNew.DeepCopyObject().(*v1beta1.ResourceTracker)
newTracker, isNewRT := e.ObjectNew.DeepCopyObject().(*v1beta1.ResourceTracker)
old, isOldRT := e.ObjectOld.DeepCopyObject().(*v1beta1.ResourceTracker)
if !isNewRT || !isOldRT {
return true
}
new.ManagedFields = old.ManagedFields
new.ResourceVersion = old.ResourceVersion
return !reflect.DeepEqual(new, old)
newTracker.ManagedFields = old.ManagedFields
newTracker.ResourceVersion = old.ResourceVersion
return !reflect.DeepEqual(newTracker, old)
}
func findObjectForResourceTracker(rt client.Object) []reconcile.Request {

View File

@@ -250,7 +250,8 @@ func ComputeAppRevisionHash(appRevision *v1beta1.ApplicationRevision) (string, e
return "", err
}
for key, wd := range appRevision.Spec.WorkloadDefinitions {
hash, err := utils.ComputeSpecHash(&wd.Spec)
wdCopy := wd
hash, err := utils.ComputeSpecHash(&wdCopy.Spec)
if err != nil {
return "", err
}
@@ -271,7 +272,8 @@ func ComputeAppRevisionHash(appRevision *v1beta1.ApplicationRevision) (string, e
revHash.TraitDefinitionHash[key] = hash
}
for key, pd := range appRevision.Spec.PolicyDefinitions {
hash, err := utils.ComputeSpecHash(&pd.Spec)
pdCopy := pd
hash, err := utils.ComputeSpecHash(&pdCopy.Spec)
if err != nil {
return "", err
}

View File

@@ -463,6 +463,9 @@ func (g *Generator) completeOpenAPISchema(doc *openapi3.T) {
// GenerateCode will call openapi-generator to generate code and modify it
func (g *Generator) GenerateCode() (err error) {
tmpFile, err := os.CreateTemp("", g.meta.name+"-*.json")
if err != nil {
return err
}
_, err = tmpFile.Write(g.openapiSchema)
if err != nil {
return errors.Wrap(err, "write openapi schema to temporary file")

View File

@@ -44,7 +44,9 @@ func (m *Conditioned) GetCondition(ct condition.ConditionType) condition.Conditi
}
// ManagedResourceReferencer is a mock that implements ManagedResourceReferencer interface.
type ManagedResourceReferencer struct{ Ref *corev1.ObjectReference }
type ManagedResourceReferencer struct {
Ref *corev1.ObjectReference `json:"ref"`
}
// SetResourceReference sets the ResourceReference.
func (m *ManagedResourceReferencer) SetResourceReference(r *corev1.ObjectReference) { m.Ref = r }
@@ -53,7 +55,9 @@ func (m *ManagedResourceReferencer) SetResourceReference(r *corev1.ObjectReferen
func (m *ManagedResourceReferencer) GetResourceReference() *corev1.ObjectReference { return m.Ref }
// A WorkloadReferencer references an OAM Workload type.
type WorkloadReferencer struct{ Ref corev1.ObjectReference }
type WorkloadReferencer struct {
Ref corev1.ObjectReference `json:"ref"`
}
// GetWorkloadReference gets the WorkloadReference.
func (w *WorkloadReferencer) GetWorkloadReference() corev1.ObjectReference {
@@ -201,7 +205,7 @@ type LocalSecretReference struct {
// LocalConnectionSecretWriterTo is a mock that implements LocalConnectionSecretWriterTo interface.
type LocalConnectionSecretWriterTo struct {
Ref *LocalSecretReference
Ref *LocalSecretReference `json:"local_secret_ref"`
}
// SetWriteConnectionSecretToReference sets the WriteConnectionSecretToReference.

View File

@@ -31,7 +31,7 @@ import (
)
// ParseOverridePolicyRelatedDefinitions get definitions inside override policy
func ParseOverridePolicyRelatedDefinitions(ctx context.Context, cli client.Client, app *v1beta1.Application, policy v1beta1.AppPolicy) (compDefs []*v1beta1.ComponentDefinition, traitDefs []*v1beta1.TraitDefinition, err error) {
func ParseOverridePolicyRelatedDefinitions(ctx context.Context, cli client.Client, _ *v1beta1.Application, policy v1beta1.AppPolicy) (compDefs []*v1beta1.ComponentDefinition, traitDefs []*v1beta1.TraitDefinition, err error) {
if policy.Properties == nil {
return compDefs, traitDefs, fmt.Errorf("override policy %s must not have empty properties", policy.Name)
}

View File

@@ -58,7 +58,7 @@ type NamespaceAdmissionHandler struct {
}
// Validate check if cross namespace is available
func (h *NamespaceAdmissionHandler) Validate(ctx context.Context, manifests []*unstructured.Unstructured) error {
func (h *NamespaceAdmissionHandler) Validate(_ context.Context, manifests []*unstructured.Unstructured) error {
if !AllowCrossNamespaceResource {
for _, manifest := range manifests {
if manifest.GetNamespace() != h.app.GetNamespace() {
@@ -77,7 +77,7 @@ type ResourceTypeAdmissionHandler struct {
}
// Validate check if resource type is valid
func (h *ResourceTypeAdmissionHandler) Validate(ctx context.Context, manifests []*unstructured.Unstructured) error {
func (h *ResourceTypeAdmissionHandler) Validate(_ context.Context, manifests []*unstructured.Unstructured) error {
if AllowResourceTypes != "" {
if !h.initialized {
h.initialized = true

View File

@@ -18,7 +18,6 @@ package apply
import (
"context"
"encoding/json"
"fmt"
"reflect"
@@ -206,6 +205,20 @@ func (a *APIApplicator) Apply(ctx context.Context, desired client.Object, ao ...
return nil
}
// Short-circuit for shared resources: only patch the shared-by annotation
// This avoids the three-way merge which could pollute last-applied-configuration
if applyAct.isShared {
loggingApply("patching shared resource annotation only", desired, applyAct.quiet)
sharedBy := desired.GetAnnotations()[oam.AnnotationAppSharedBy]
patch := []byte(fmt.Sprintf(`{"metadata":{"annotations":{"%s":"%s"}}}`, oam.AnnotationAppSharedBy, sharedBy))
var patchOpts []client.PatchOption
if applyAct.dryRun {
patchOpts = append(patchOpts, client.DryRunAll)
}
return errors.Wrapf(a.c.Patch(ctx, existing, client.RawPatch(types.MergePatchType, patch), patchOpts...),
"cannot patch shared resource annotation")
}
strategy := applyAct.updateStrategy
if strategy.Op == "" {
if utilfeature.DefaultMutableFeatureGate.Enabled(features.ApplyResourceByReplace) && isUpdatableResource(desired) {
@@ -349,7 +362,7 @@ func NotUpdateRenderHashEqual() ApplyOption {
if !ok {
return nil
}
oldSt := existing.(*unstructured.Unstructured)
oldSt, ok := existing.(*unstructured.Unstructured)
if !ok {
return nil
}
@@ -466,39 +479,39 @@ func DisableUpdateAnnotation() ApplyOption {
// SharedByApp let the resource be sharable
func SharedByApp(app *v1beta1.Application) ApplyOption {
return func(act *applyAction, existing, desired client.Object) error {
// calculate the shared-by annotation
// if resource exists, add the current application into the resource shared-by field
// Calculate the shared-by annotation value
var sharedBy string
if existing != nil && existing.GetAnnotations() != nil {
sharedBy = existing.GetAnnotations()[oam.AnnotationAppSharedBy]
}
sharedBy = AddSharer(sharedBy, app)
// Always add the shared-by annotation to desired (for create case)
util.AddAnnotations(desired, map[string]string{oam.AnnotationAppSharedBy: sharedBy})
if existing == nil {
return nil
}
// resource exists and controlled by current application
// Resource exists - check if controlled by current application
appKey, controlledBy := GetAppKey(app), GetControlledBy(existing)
if controlledBy == "" || appKey == controlledBy {
// Owner app - use normal three-way merge flow
return nil
}
// resource exists but not controlled by current application
// Resource exists but not controlled by current application
if existing.GetAnnotations() == nil || existing.GetAnnotations()[oam.AnnotationAppSharedBy] == "" {
// if the application that controls the resource does not allow sharing, return error
// Owner doesn't allow sharing
return fmt.Errorf("application is controlled by %s but is not sharable", controlledBy)
}
// the application that controls the resource allows sharing, then only mutate the shared-by annotation
// Non-owner sharer: set flags for short-circuit in Apply()
// The short-circuit will only patch the shared-by annotation, avoiding
// any manipulation of the resource spec or last-applied-configuration
act.isShared = true
bs, err := json.Marshal(existing)
if err != nil {
return err
}
if err = json.Unmarshal(bs, desired); err != nil {
return err
}
util.AddAnnotations(desired, map[string]string{oam.AnnotationAppSharedBy: sharedBy})
act.updateAnnotation = false
return nil
}
}

View File

@@ -445,10 +445,11 @@ func TestSharedByApp(t *testing.T) {
app := &v1beta1.Application{ObjectMeta: metav1.ObjectMeta{Name: "app"}}
ao := SharedByApp(app)
testCases := map[string]struct {
existing client.Object
desired client.Object
output client.Object
hasError bool
existing client.Object
desired client.Object
output client.Object
hasError bool
expectIsShared bool
}{
"create new resource": {
existing: nil,
@@ -492,17 +493,17 @@ func TestSharedByApp(t *testing.T) {
"kind": "ConfigMap",
"data": "y",
}},
// Non-owner sharer: desired only gets the shared-by annotation added
// The actual resource content is NOT modified - the short-circuit in Apply()
// will patch only the annotation on the server
output: &unstructured.Unstructured{Object: map[string]interface{}{
"kind": "ConfigMap",
"metadata": map[string]interface{}{
"labels": map[string]interface{}{
oam.LabelAppName: "example",
oam.LabelAppNamespace: "default",
},
"annotations": map[string]interface{}{oam.AnnotationAppSharedBy: "x/y,default/app"},
},
"data": "x",
"data": "y",
}},
expectIsShared: true,
},
"add sharer to existing sharing resource owned by self": {
existing: &unstructured.Unstructured{Object: map[string]interface{}{
@@ -554,16 +555,102 @@ func TestSharedByApp(t *testing.T) {
}},
hasError: true,
},
"non-owner sharer sets short-circuit flags": {
existing: &unstructured.Unstructured{Object: map[string]interface{}{
"apiVersion": "v1",
"kind": "Pod",
"metadata": map[string]interface{}{
"name": "test-pod",
"resourceVersion": "12345",
"labels": map[string]interface{}{
oam.LabelAppName: "app1",
oam.LabelAppNamespace: "default",
},
"annotations": map[string]interface{}{
oam.AnnotationAppSharedBy: "default/app1",
},
},
}},
desired: &unstructured.Unstructured{Object: map[string]interface{}{
"kind": "Pod",
"metadata": map[string]interface{}{
"name": "test-pod",
},
}},
// For non-owner sharers, desired only gets the shared-by annotation added
// The actual patching happens in Apply() via short-circuit
output: &unstructured.Unstructured{Object: map[string]interface{}{
"kind": "Pod",
"metadata": map[string]interface{}{
"name": "test-pod",
"annotations": map[string]interface{}{
oam.AnnotationAppSharedBy: "default/app1,default/app",
},
},
}},
// These flags are checked in the test loop
expectIsShared: true,
},
"non-owner sharer works without last-applied-configuration": {
existing: &unstructured.Unstructured{Object: map[string]interface{}{
"kind": "ConfigMap",
"metadata": map[string]interface{}{
"name": "test-cm",
"labels": map[string]interface{}{
oam.LabelAppName: "app1",
oam.LabelAppNamespace: "default",
},
"annotations": map[string]interface{}{
oam.AnnotationAppSharedBy: "default/app1",
},
},
"data": map[string]interface{}{
"key": "value",
},
}},
desired: &unstructured.Unstructured{Object: map[string]interface{}{
"kind": "ConfigMap",
"metadata": map[string]interface{}{
"name": "test-cm",
},
}},
// For non-owner sharers, desired only gets the shared-by annotation added
output: &unstructured.Unstructured{Object: map[string]interface{}{
"kind": "ConfigMap",
"metadata": map[string]interface{}{
"name": "test-cm",
"annotations": map[string]interface{}{
oam.AnnotationAppSharedBy: "default/app1,default/app",
},
},
}},
expectIsShared: true,
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
r := require.New(t)
err := ao(&applyAction{}, tc.existing, tc.desired)
act := &applyAction{}
err := ao(act, tc.existing, tc.desired)
if tc.hasError {
r.Error(err)
} else {
r.NoError(err)
r.Equal(tc.output, tc.desired)
// Verify short-circuit flags for non-owner sharers
if tc.expectIsShared {
r.True(act.isShared, "isShared should be true for non-owner sharers")
r.False(act.updateAnnotation, "updateAnnotation should be false for non-owner sharers")
}
// Legacy check: When a resource is shared by another app, updateAnnotation should be false
if tc.existing != nil && tc.existing.GetAnnotations() != nil && tc.existing.GetAnnotations()[oam.AnnotationAppSharedBy] != "" {
existingController := GetControlledBy(tc.existing)
if existingController != "" && existingController != GetAppKey(app) {
r.False(act.updateAnnotation, "updateAnnotation should be false when sharing resource controlled by another app")
}
}
}
})
}

View File

@@ -33,7 +33,7 @@ import (
const IndexYaml = "index.yaml"
// LoadRepoIndex load helm repo index
func LoadRepoIndex(ctx context.Context, u string, cred *RepoCredential) (*helmrepo.IndexFile, error) {
func LoadRepoIndex(_ context.Context, u string, cred *RepoCredential) (*helmrepo.IndexFile, error) {
if !strings.HasSuffix(u, "/") {
u = fmt.Sprintf("%s/%s", u, IndexYaml)

View File

@@ -399,9 +399,8 @@ func contains(object *runtime.Object, fieldSelector fields.Selector) bool {
if (negative && fmt.Sprintf("%v", result.String()) != value) ||
(!negative && fmt.Sprintf("%v", result.String()) == value) {
continue
} else {
return false
}
return false
}
return true
}

View File

@@ -42,6 +42,9 @@ const TypeGitlab = "gitlab"
// TypeUnknown represents parse failed
const TypeUnknown = "unknown"
// errInvalidFormatMsg with the message to be returned in case of a format error.
const errInvalidFormatMsg = "invalid format "
// Content contains different type of content needed when building Registry
type Content struct {
OssContent
@@ -103,12 +106,12 @@ func Parse(addr string) (string, *Content, error) {
// 1. https://github.com/<owner>/<repo>/tree/<branch>/<path-to-dir>
// 2. https://github.com/<owner>/<repo>/<path-to-dir>
if len(l) < 3 {
return "", nil, errors.New("invalid format " + addr)
return "", nil, errors.New(errInvalidFormatMsg + addr)
}
if l[2] == "tree" {
// https://github.com/<owner>/<repo>/tree/<branch>/<path-to-dir>
if len(l) < 5 {
return "", nil, errors.New("invalid format " + addr)
return "", nil, errors.New(errInvalidFormatMsg + addr)
}
return TypeGithub, &Content{
GithubContent: GithubContent{
@@ -131,7 +134,7 @@ func Parse(addr string) (string, *Content, error) {
nil
case "api.github.com":
if len(l) != 5 {
return "", nil, errors.New("invalid format " + addr)
return "", nil, errors.New(errInvalidFormatMsg + addr)
}
//https://api.github.com/repos/<owner>/<repo>/contents/<path-to-dir>
return TypeGithub, &Content{
@@ -148,13 +151,13 @@ func Parse(addr string) (string, *Content, error) {
// 1. https://gitee.com/<owner>/<repo>/tree/<branch>/<path-to-dir>
// 2. https://gitee.com/<owner>/<repo>/<path-to-dir>
if len(l) < 3 {
return "", nil, errors.New("invalid format " + addr)
return "", nil, errors.New(errInvalidFormatMsg + addr)
}
switch l[2] {
case "tree":
// https://gitee.com/<owner>/<repo>/tree/<branch>/<path-to-dir>
if len(l) < 5 {
return "", nil, errors.New("invalid format " + addr)
return "", nil, errors.New(errInvalidFormatMsg + addr)
}
return TypeGitee, &Content{
GiteeContent: GiteeContent{

View File

@@ -60,34 +60,34 @@ func (c ViewContext) GetStore() *corev1.ConfigMap {
}
// GetMutableValue get mutable data from workflow context.
func (c ViewContext) GetMutableValue(paths ...string) string {
func (c ViewContext) GetMutableValue(_ ...string) string {
return ""
}
// SetMutableValue set mutable data in workflow context config map.
func (c ViewContext) SetMutableValue(data string, paths ...string) {
func (c ViewContext) SetMutableValue(_ string, _ ...string) {
}
// IncreaseCountValueInMemory increase count in workflow context memory store.
func (c ViewContext) IncreaseCountValueInMemory(paths ...string) int {
func (c ViewContext) IncreaseCountValueInMemory(_ ...string) int {
return 0
}
// SetValueInMemory set data in workflow context memory store.
func (c ViewContext) SetValueInMemory(data interface{}, paths ...string) {
func (c ViewContext) SetValueInMemory(_ interface{}, _ ...string) {
}
// GetValueInMemory get data in workflow context memory store.
func (c ViewContext) GetValueInMemory(paths ...string) (interface{}, bool) {
func (c ViewContext) GetValueInMemory(_ ...string) (interface{}, bool) {
return "", true
}
// DeleteValueInMemory delete data in workflow context memory store.
func (c ViewContext) DeleteValueInMemory(paths ...string) {
func (c ViewContext) DeleteValueInMemory(_ ...string) {
}
// DeleteMutableValue delete mutable data in workflow context.
func (c ViewContext) DeleteMutableValue(paths ...string) {
func (c ViewContext) DeleteMutableValue(_ ...string) {
}
// Commit the workflow context and persist it's content.

View File

@@ -48,7 +48,7 @@ import (
// CollectServiceEndpoints generator service endpoints is available for common component type,
// such as webservice or helm
// it can not support the cloud service component currently
func (h *provider) CollectServiceEndpoints(ctx monitorContext.Context, wfCtx wfContext.Context, v *value.Value, act types.Action) error {
func (h *provider) CollectServiceEndpoints(ctx monitorContext.Context, _ wfContext.Context, v *value.Value, _ types.Action) error {
val, err := v.LookupValue("app")
if err != nil {
return err

View File

@@ -92,7 +92,7 @@ type FilterOption struct {
}
// ListResourcesInApp lists CRs created by Application, this provider queries the object data.
func (h *provider) ListResourcesInApp(ctx monitorContext.Context, wfCtx wfContext.Context, v *value.Value, act types.Action) error {
func (h *provider) ListResourcesInApp(ctx monitorContext.Context, _ wfContext.Context, v *value.Value, _ types.Action) error {
val, err := v.LookupValue("app")
if err != nil {
return err
@@ -113,7 +113,7 @@ func (h *provider) ListResourcesInApp(ctx monitorContext.Context, wfCtx wfContex
}
// ListAppliedResources list applied resource from tracker, this provider only queries the metadata.
func (h *provider) ListAppliedResources(ctx monitorContext.Context, wfCtx wfContext.Context, v *value.Value, act types.Action) error {
func (h *provider) ListAppliedResources(ctx monitorContext.Context, _ wfContext.Context, v *value.Value, _ types.Action) error {
val, err := v.LookupValue("app")
if err != nil {
return err
@@ -138,7 +138,7 @@ func (h *provider) ListAppliedResources(ctx monitorContext.Context, wfCtx wfCont
return fillQueryResult(v, appResList, "list")
}
func (h *provider) CollectResources(ctx monitorContext.Context, wfCtx wfContext.Context, v *value.Value, act types.Action) error {
func (h *provider) CollectResources(ctx monitorContext.Context, _ wfContext.Context, v *value.Value, _ types.Action) error {
val, err := v.LookupValue("app")
if err != nil {
return err
@@ -180,7 +180,7 @@ func (h *provider) CollectResources(ctx monitorContext.Context, wfCtx wfContext.
return fillQueryResult(v, resources, "list")
}
func (h *provider) SearchEvents(ctx monitorContext.Context, wfCtx wfContext.Context, v *value.Value, act types.Action) error {
func (h *provider) SearchEvents(ctx monitorContext.Context, _ wfContext.Context, v *value.Value, _ types.Action) error {
val, err := v.LookupValue("value")
if err != nil {
return err
@@ -209,7 +209,7 @@ func (h *provider) SearchEvents(ctx monitorContext.Context, wfCtx wfContext.Cont
return fillQueryResult(v, eventList.Items, "list")
}
func (h *provider) CollectLogsInPod(ctx monitorContext.Context, wfCtx wfContext.Context, v *value.Value, act types.Action) error {
func (h *provider) CollectLogsInPod(ctx monitorContext.Context, _ wfContext.Context, v *value.Value, _ types.Action) error {
cluster, err := v.GetString("cluster")
if err != nil {
return errors.Wrapf(err, "invalid cluster")

View File

@@ -159,7 +159,7 @@ func (handler *ViewHandler) QueryView(ctx context.Context, qv QueryView) (*value
return viewCtx.GetVar(qv.Export)
}
func (handler *ViewHandler) dispatch(ctx context.Context, cluster string, owner string, manifests ...*unstructured.Unstructured) error {
func (handler *ViewHandler) dispatch(ctx context.Context, cluster string, _ string, manifests ...*unstructured.Unstructured) error {
ctx = multicluster.ContextWithClusterName(ctx, cluster)
applicator := apply.NewAPIApplicator(handler.cli)
for _, manifest := range manifests {
@@ -170,7 +170,7 @@ func (handler *ViewHandler) dispatch(ctx context.Context, cluster string, owner
return nil
}
func (handler *ViewHandler) delete(ctx context.Context, cluster string, owner string, manifest *unstructured.Unstructured) error {
func (handler *ViewHandler) delete(ctx context.Context, _ string, _ string, manifest *unstructured.Unstructured) error {
return handler.cli.Delete(ctx, manifest)
}

View File

@@ -49,7 +49,7 @@ var _ admission.Handler = &MutatingHandler{}
type appMutator func(ctx context.Context, req admission.Request, oldApp *v1beta1.Application, newApp *v1beta1.Application) (bool, error)
func (h *MutatingHandler) handleIdentity(ctx context.Context, req admission.Request, _ *v1beta1.Application, app *v1beta1.Application) (bool, error) {
func (h *MutatingHandler) handleIdentity(_ context.Context, req admission.Request, _ *v1beta1.Application, app *v1beta1.Application) (bool, error) {
if !utilfeature.DefaultMutableFeatureGate.Enabled(features.AuthenticateApplication) {
return false, nil
}
@@ -66,7 +66,7 @@ func (h *MutatingHandler) handleIdentity(ctx context.Context, req admission.Requ
return true, nil
}
func (h *MutatingHandler) handleWorkflow(ctx context.Context, req admission.Request, _ *v1beta1.Application, app *v1beta1.Application) (modified bool, err error) {
func (h *MutatingHandler) handleWorkflow(_ context.Context, _ admission.Request, _ *v1beta1.Application, app *v1beta1.Application) (modified bool, err error) {
if app.Spec.Workflow != nil {
for i, step := range app.Spec.Workflow.Steps {
if step.Name == "" {
@@ -84,7 +84,7 @@ func (h *MutatingHandler) handleWorkflow(ctx context.Context, req admission.Requ
return modified, nil
}
func (h *MutatingHandler) handleSharding(ctx context.Context, req admission.Request, oldApp *v1beta1.Application, newApp *v1beta1.Application) (bool, error) {
func (h *MutatingHandler) handleSharding(_ context.Context, _ admission.Request, oldApp *v1beta1.Application, newApp *v1beta1.Application) (bool, error) {
if sharding.EnableSharding && !utilfeature.DefaultMutableFeatureGate.Enabled(features.DisableWebhookAutoSchedule) {
oid, scheduled := sharding.GetScheduledShardID(oldApp)
_, newScheduled := sharding.GetScheduledShardID(newApp)

View File

@@ -33,7 +33,7 @@ import (
)
// ValidateWorkflow validates the Application workflow
func (h *ValidatingHandler) ValidateWorkflow(ctx context.Context, app *v1beta1.Application) field.ErrorList {
func (h *ValidatingHandler) ValidateWorkflow(_ context.Context, app *v1beta1.Application) field.ErrorList {
var errs field.ErrorList
if app.Spec.Workflow != nil {
stepName := make(map[string]interface{})
@@ -117,7 +117,7 @@ func (h *ValidatingHandler) ValidateCreate(ctx context.Context, app *v1beta1.App
}
// ValidateUpdate validates the Application on update
func (h *ValidatingHandler) ValidateUpdate(ctx context.Context, newApp, oldApp *v1beta1.Application) field.ErrorList {
func (h *ValidatingHandler) ValidateUpdate(ctx context.Context, newApp, _ *v1beta1.Application) field.ErrorList {
// check if the newApp is valid
errs := h.ValidateCreate(ctx, newApp)
// TODO: add more validating

View File

@@ -49,7 +49,7 @@ type MutatingHandler struct {
var _ admission.Handler = &MutatingHandler{}
// Handle handles admission requests.
func (h *MutatingHandler) Handle(ctx context.Context, req admission.Request) admission.Response {
func (h *MutatingHandler) Handle(_ context.Context, req admission.Request) admission.Response {
obj := &v1beta1.ComponentDefinition{}
err := h.Decoder.Decode(req, obj)

View File

@@ -128,7 +128,7 @@ func (h *ValidatingHandler) InjectDecoder(d *admission.Decoder) error {
}
// RegisterValidatingHandler will register TraitDefinition validation to webhook
func RegisterValidatingHandler(mgr manager.Manager, args controller.Args) {
func RegisterValidatingHandler(mgr manager.Manager, _ controller.Args) {
server := mgr.GetWebhookServer()
server.Register("/validating-core-oam-dev-v1alpha2-traitdefinitions", &webhook.Admission{Handler: &ValidatingHandler{
Validators: []TraitDefValidator{
@@ -150,11 +150,11 @@ func ValidateDefinitionReference(_ context.Context, td v1beta1.TraitDefinition)
if len(td.Spec.Reference.Name) > 0 {
return nil
}
cap, err := appfile.ConvertTemplateJSON2Object(td.Name, td.Spec.Extension, td.Spec.Schematic)
capability, err := appfile.ConvertTemplateJSON2Object(td.Name, td.Spec.Extension, td.Spec.Schematic)
if err != nil {
return errors.WithMessage(err, errValidateDefRef)
}
if cap.CueTemplate == "" {
if capability.CueTemplate == "" {
return errors.New(failInfoDefRefOmitted)
}

View File

@@ -50,7 +50,7 @@ type provider struct {
// MakePlacementDecisions
// Deprecated
func (p *provider) MakePlacementDecisions(ctx monitorContext.Context, wfCtx wfContext.Context, v *value.Value, act wfTypes.Action) error {
func (p *provider) MakePlacementDecisions(ctx monitorContext.Context, _ wfContext.Context, v *value.Value, _ wfTypes.Action) error {
policy, err := v.GetString("inputs", "policyName")
if err != nil {
return err
@@ -108,7 +108,7 @@ func (p *provider) MakePlacementDecisions(ctx monitorContext.Context, wfCtx wfCo
// PatchApplication
// Deprecated
func (p *provider) PatchApplication(ctx monitorContext.Context, wfCtx wfContext.Context, v *value.Value, act wfTypes.Action) error {
func (p *provider) PatchApplication(_ monitorContext.Context, _ wfContext.Context, v *value.Value, _ wfTypes.Action) error {
env, err := v.GetString("inputs", "envName")
if err != nil {
return err
@@ -138,7 +138,7 @@ func (p *provider) PatchApplication(ctx monitorContext.Context, wfCtx wfContext.
return v.FillObject(newApp, "outputs")
}
func (p *provider) ListClusters(ctx monitorContext.Context, wfCtx wfContext.Context, v *value.Value, act wfTypes.Action) error {
func (p *provider) ListClusters(ctx monitorContext.Context, _ wfContext.Context, v *value.Value, _ wfTypes.Action) error {
secrets, err := multicluster.ListExistingClusterSecrets(ctx, p.Client)
if err != nil {
return err
@@ -169,7 +169,7 @@ func (p *provider) Deploy(ctx monitorContext.Context, _ wfContext.Context, v *va
return nil
}
func (p *provider) GetPlacementsFromTopologyPolicies(ctx monitorContext.Context, wfCtx wfContext.Context, v *value.Value, act wfTypes.Action) error {
func (p *provider) GetPlacementsFromTopologyPolicies(ctx monitorContext.Context, _ wfContext.Context, v *value.Value, _ wfTypes.Action) error {
policyNames, err := v.GetStringSlice("policies")
if err != nil {
return err

View File

@@ -64,7 +64,7 @@ type provider struct {
}
// RenderComponent render component
func (p *provider) RenderComponent(ctx monitorContext.Context, wfCtx wfContext.Context, v *value.Value, act wfTypes.Action) error {
func (p *provider) RenderComponent(ctx monitorContext.Context, _ wfContext.Context, v *value.Value, _ wfTypes.Action) error {
comp, patcher, clusterName, overrideNamespace, err := lookUpCompInfo(v)
if err != nil {
return err
@@ -93,7 +93,7 @@ func (p *provider) RenderComponent(ctx monitorContext.Context, wfCtx wfContext.C
}
// ApplyComponent apply component.
func (p *provider) ApplyComponent(ctx monitorContext.Context, wfCtx wfContext.Context, v *value.Value, act wfTypes.Action) error {
func (p *provider) ApplyComponent(ctx monitorContext.Context, _ wfContext.Context, v *value.Value, act wfTypes.Action) error {
comp, patcher, clusterName, overrideNamespace, err := lookUpCompInfo(v)
if err != nil {
return err
@@ -155,7 +155,7 @@ func lookUpCompInfo(v *value.Value) (*common.ApplicationComponent, *value.Value,
}
// LoadComponent load component describe info in application.
func (p *provider) LoadComponent(ctx monitorContext.Context, wfCtx wfContext.Context, v *value.Value, act wfTypes.Action) error {
func (p *provider) LoadComponent(ctx monitorContext.Context, _ wfContext.Context, v *value.Value, _ wfTypes.Action) error {
app := &v1beta1.Application{}
// if specify `app`, use specified application otherwise use default application from provider
appSettings, err := v.LookupValue("app")
@@ -200,7 +200,7 @@ func (p *provider) LoadComponent(ctx monitorContext.Context, wfCtx wfContext.Con
}
// LoadComponentInOrder load component describe info in application output will be a list with order defined in application.
func (p *provider) LoadComponentInOrder(ctx monitorContext.Context, wfCtx wfContext.Context, v *value.Value, act wfTypes.Action) error {
func (p *provider) LoadComponentInOrder(ctx monitorContext.Context, _ wfContext.Context, v *value.Value, _ wfTypes.Action) error {
app := &v1beta1.Application{}
// if specify `app`, use specified application otherwise use default application from provider
appSettings, err := v.LookupValue("app")
@@ -232,7 +232,7 @@ func (p *provider) LoadComponentInOrder(ctx monitorContext.Context, wfCtx wfCont
}
// LoadPolicies load policy describe info in application.
func (p *provider) LoadPolicies(ctx monitorContext.Context, wfCtx wfContext.Context, v *value.Value, act wfTypes.Action) error {
func (p *provider) LoadPolicies(_ monitorContext.Context, _ wfContext.Context, v *value.Value, _ wfTypes.Action) error {
for _, po := range p.app.Spec.Policies {
if err := v.FillObject(po, "value", po.Name); err != nil {
return err

View File

@@ -40,7 +40,7 @@ type provider struct {
renderer oamProvider.WorkloadRenderer
}
func (p *provider) LoadTerraformComponents(ctx monitorContext.Context, wfCtx wfContext.Context, v *value.Value, act wfTypes.Action) error {
func (p *provider) LoadTerraformComponents(ctx monitorContext.Context, _ wfContext.Context, v *value.Value, _ wfTypes.Action) error {
var components []common.ApplicationComponent
for _, comp := range p.app.Spec.Components {
wl, err := p.renderer(ctx, comp)
@@ -55,7 +55,7 @@ func (p *provider) LoadTerraformComponents(ctx monitorContext.Context, wfCtx wfC
return v.FillObject(components, "outputs", "components")
}
func (p *provider) GetConnectionStatus(ctx monitorContext.Context, wfCtx wfContext.Context, v *value.Value, act wfTypes.Action) error {
func (p *provider) GetConnectionStatus(_ monitorContext.Context, _ wfContext.Context, v *value.Value, _ wfTypes.Action) error {
componentName, err := v.GetString("inputs", "componentName")
if err != nil {
return errors.Wrapf(err, "failed to get component name")

View File

@@ -33,7 +33,7 @@ const (
type provider struct {
}
func (h *provider) Timestamp(ctx monitorContext.Context, wfCtx wfContext.Context, v *value.Value, act types.Action) error {
func (h *provider) Timestamp(_ monitorContext.Context, _ wfContext.Context, v *value.Value, _ types.Action) error {
date, err := v.GetString("date")
if err != nil {
return err
@@ -52,7 +52,7 @@ func (h *provider) Timestamp(ctx monitorContext.Context, wfCtx wfContext.Context
return v.FillObject(t.Unix(), "timestamp")
}
func (h *provider) Date(ctx monitorContext.Context, wfCtx wfContext.Context, v *value.Value, act types.Action) error {
func (h *provider) Date(_ monitorContext.Context, _ wfContext.Context, v *value.Value, _ types.Action) error {
timestamp, err := v.GetInt64("timestamp")
if err != nil {
return err

View File

@@ -66,7 +66,7 @@ func NewAddonRegistryCommand(c common.Args, ioStreams cmdutil.IOStreams) *cobra.
}
// NewAddAddonRegistryCommand return an addon registry create command
func NewAddAddonRegistryCommand(c common.Args, ioStreams cmdutil.IOStreams) *cobra.Command {
func NewAddAddonRegistryCommand(c common.Args, _ cmdutil.IOStreams) *cobra.Command {
cmd := &cobra.Command{
Use: "add",
Short: "Add an addon registry.",
@@ -103,7 +103,7 @@ add a specified gitlab registry: vela addon registry add my-repo --type gitlab -
}
// NewGetAddonRegistryCommand return an addon registry get command
func NewGetAddonRegistryCommand(c common.Args, ioStreams cmdutil.IOStreams) *cobra.Command {
func NewGetAddonRegistryCommand(c common.Args, _ cmdutil.IOStreams) *cobra.Command {
return &cobra.Command{
Use: "get",
Short: "Get an addon registry.",
@@ -124,7 +124,7 @@ func NewGetAddonRegistryCommand(c common.Args, ioStreams cmdutil.IOStreams) *cob
}
// NewListAddonRegistryCommand return an addon registry list command
func NewListAddonRegistryCommand(c common.Args, ioStreams cmdutil.IOStreams) *cobra.Command {
func NewListAddonRegistryCommand(c common.Args, _ cmdutil.IOStreams) *cobra.Command {
return &cobra.Command{
Use: "list",
Short: "List addon registries.",
@@ -140,7 +140,7 @@ func NewListAddonRegistryCommand(c common.Args, ioStreams cmdutil.IOStreams) *co
}
// NewUpdateAddonRegistryCommand return an addon registry update command
func NewUpdateAddonRegistryCommand(c common.Args, ioStreams cmdutil.IOStreams) *cobra.Command {
func NewUpdateAddonRegistryCommand(c common.Args, _ cmdutil.IOStreams) *cobra.Command {
cmd := &cobra.Command{
Use: "update",
Short: "Update an addon registry.",
@@ -162,7 +162,7 @@ func NewUpdateAddonRegistryCommand(c common.Args, ioStreams cmdutil.IOStreams) *
}
// NewDeleteAddonRegistryCommand return an addon registry delete command
func NewDeleteAddonRegistryCommand(c common.Args, ioStreams cmdutil.IOStreams) *cobra.Command {
func NewDeleteAddonRegistryCommand(c common.Args, _ cmdutil.IOStreams) *cobra.Command {
return &cobra.Command{
Use: "delete",
Short: "Delete an addon registry",

View File

@@ -232,7 +232,7 @@ func NewAddonEnableCommand(c common.Args, ioStream cmdutil.IOStreams) *cobra.Com
}
// AdditionalEndpointPrinter will print endpoints
func AdditionalEndpointPrinter(ctx context.Context, c common.Args, k8sClient client.Client, name, info string, isUpgrade bool) {
func AdditionalEndpointPrinter(ctx context.Context, c common.Args, _ client.Client, name, info string, _ bool) {
err := printAppEndpoints(ctx, addonutil.Addon2AppName(name), types.DefaultKubeVelaNS, Filter{}, c, true)
if err != nil {
fmt.Println("Get application endpoints error:", err)
@@ -361,7 +361,7 @@ func parseAddonArgsToMap(args []string) (map[string]interface{}, error) {
}
// NewAddonDisableCommand create addon disable command
func NewAddonDisableCommand(c common.Args, ioStream cmdutil.IOStreams) *cobra.Command {
func NewAddonDisableCommand(c common.Args, _ cmdutil.IOStreams) *cobra.Command {
cmd := &cobra.Command{
Use: "disable",
Aliases: []string{"uninstall"},
@@ -1180,7 +1180,7 @@ func transClusters(cstr string) []interface{} {
}
// NewAddonPackageCommand create addon package command
func NewAddonPackageCommand(c common.Args) *cobra.Command {
func NewAddonPackageCommand(_ common.Args) *cobra.Command {
cmd := &cobra.Command{
Use: "package",
Short: "package an addon directory",

View File

@@ -53,6 +53,12 @@ const (
FlagNamespace = "namespace"
// FlagInteractive command flag to specify the use of interactive process
FlagInteractive = "interactive"
// CUEExtension with the expected extension for a CUE file.
CUEExtension = ".cue"
// YAMLExtension with the expected extension for a YAML file.
YAMLExtension = ".yaml"
// YMLExtension with an alternative extension for a YAML file as .yml.
YMLExtension = ".yml"
)
func addNamespaceAndEnvArg(cmd *cobra.Command) {

View File

@@ -166,7 +166,7 @@ func buildTemplateFromYAML(templateYAML string, def *pkgdef.Definition) error {
}
// NewDefinitionInitCommand create the `vela def init` command to help user initialize a definition locally
func NewDefinitionInitCommand(c common.Args) *cobra.Command {
func NewDefinitionInitCommand(_ common.Args) *cobra.Command {
cmd := &cobra.Command{
Use: "init DEF_NAME",
Short: "Init a new definition",
@@ -688,7 +688,7 @@ func NewDefinitionEditCommand(c common.Args) *cobra.Command {
}
}
filename := fmt.Sprintf("vela-def-%d", time.Now().UnixNano())
tempFilePath := filepath.Join(os.TempDir(), filename+".cue")
tempFilePath := filepath.Join(os.TempDir(), filename+CUEExtension)
if err := os.WriteFile(tempFilePath, []byte(cueString), 0600); err != nil {
return errors.Wrapf(err, "failed to write temporary file")
}
@@ -821,12 +821,12 @@ func NewDefinitionRenderCommand(c common.Args) *cobra.Command {
err := filepath.Walk(args[0], func(path string, info os.FileInfo, err error) error {
filename := filepath.Base(path)
fileSuffix := filepath.Ext(path)
if fileSuffix != ".cue" {
if fileSuffix != CUEExtension {
return nil
}
inputFilenames = append(inputFilenames, path)
if output != "" {
outputFilenames = append(outputFilenames, filepath.Join(output, strings.ReplaceAll(filename, ".cue", ".yaml")))
outputFilenames = append(outputFilenames, filepath.Join(output, strings.ReplaceAll(filename, CUEExtension, YAMLExtension)))
} else {
outputFilenames = append(outputFilenames, "")
}
@@ -920,7 +920,7 @@ func defApplyOne(ctx context.Context, c common.Args, namespace, defpath string,
def := pkgdef.Definition{Unstructured: unstructured.Unstructured{}}
switch {
case strings.HasSuffix(defpath, ".yaml") || strings.HasSuffix(defpath, ".yml"):
case strings.HasSuffix(defpath, YAMLExtension) || strings.HasSuffix(defpath, YMLExtension):
// In this case, it's not in cue format, it's a yaml
if err = def.FromYAML(defBytes); err != nil {
return "", errors.Wrapf(err, "failed to parse YAML to definition")
@@ -1218,7 +1218,7 @@ func NewDefinitionGenDocCommand(_ common.Args, streams util.IOStreams) *cobra.Co
readers := make([]io.Reader, 0, len(args))
for _, arg := range args {
if !strings.HasSuffix(arg, ".cue") {
if !strings.HasSuffix(arg, CUEExtension) {
return fmt.Errorf("invalid file %s, must be a cue file", arg)
}

View File

@@ -133,7 +133,7 @@ func DryRunApplication(cmdOption *DryRunCmdOptions, c common.Args, namespace str
var objs []*unstructured.Unstructured
if cmdOption.DefinitionFile != "" {
objs, err = ReadDefinitionsFromFile(cmdOption.DefinitionFile)
objs, err = ReadDefinitionsFromFile(cmdOption.DefinitionFile, cmdOption.IOStreams)
if err != nil {
return buff, err
}
@@ -189,7 +189,7 @@ func DryRunApplication(cmdOption *DryRunCmdOptions, c common.Args, namespace str
func readObj(path string) (*unstructured.Unstructured, error) {
switch {
case strings.HasSuffix(path, ".cue"):
case strings.HasSuffix(path, CUEExtension):
def := pkgdef.Definition{Unstructured: unstructured.Unstructured{}}
defBytes, err := os.ReadFile(filepath.Clean(path))
if err != nil {
@@ -211,7 +211,7 @@ func readObj(path string) (*unstructured.Unstructured, error) {
}
// ReadDefinitionsFromFile will read objects from file or dir in the format of yaml
func ReadDefinitionsFromFile(path string) ([]*unstructured.Unstructured, error) {
func ReadDefinitionsFromFile(path string, io cmdutil.IOStreams) ([]*unstructured.Unstructured, error) {
fi, err := os.Stat(path)
if err != nil {
return nil, err
@@ -225,24 +225,31 @@ func ReadDefinitionsFromFile(path string) ([]*unstructured.Unstructured, error)
}
var objs []*unstructured.Unstructured
//nolint:gosec
fis, err := os.ReadDir(path)
if err != nil {
return nil, err
}
for _, fi := range fis {
if fi.IsDir() {
continue
err = filepath.WalkDir(path, func(path string, e os.DirEntry, err error) error {
if e == nil {
io.Errorf("failed to walk nil dir entry %s", path)
return nil
}
fileType := filepath.Ext(fi.Name())
if fileType != ".yaml" && fileType != ".yml" && fileType != ".cue" {
continue
}
obj, err := readObj(filepath.Join(path, fi.Name()))
if err != nil {
return nil, err
io.Errorf("failed to walk dir %s: %v", path, err)
return nil
}
if e.IsDir() {
return nil
}
fileType := filepath.Ext(e.Name())
if fileType != YAMLExtension && fileType != YMLExtension && fileType != CUEExtension {
return nil
}
obj, err := readObj(path)
if err != nil {
return err
}
objs = append(objs, obj)
return nil
})
if err != nil {
return nil, err
}
return objs, nil
}
@@ -255,7 +262,7 @@ func readApplicationFromFile(filename string) (*corev1beta1.Application, error)
fileType := filepath.Ext(filename)
switch fileType {
case ".yaml", ".yml":
case YAMLExtension, YMLExtension:
fileContent, err = yaml.YAMLToJSON(fileContent)
if err != nil {
return nil, err
@@ -281,7 +288,7 @@ func readApplicationFromFiles(cmdOption *DryRunCmdOptions, buff *bytes.Buffer) (
fileType := filepath.Ext(filename)
switch fileType {
case ".yaml", ".yml":
case YAMLExtension, YMLExtension:
// only support one object in one yaml file
fileContent, err = yaml.YAMLToJSON(fileContent)
if err != nil {
@@ -337,7 +344,7 @@ func readApplicationFromFiles(cmdOption *DryRunCmdOptions, buff *bytes.Buffer) (
if !cmdOption.MergeStandaloneFiles {
if wf != nil &&
((app.Spec.Workflow != nil && app.Spec.Workflow.Ref != wf.Name) || app.Spec.Workflow == nil) {
buff.WriteString(fmt.Sprintf("WARNING: workflow %s not referenced by application\n\n", wf.Name))
fmt.Fprintf(buff, "WARNING: workflow %s not referenced by application\n\n", wf.Name)
}
} else {
if wf != nil {
@@ -355,7 +362,7 @@ func readApplicationFromFiles(cmdOption *DryRunCmdOptions, buff *bytes.Buffer) (
for _, policy := range policies {
// check standalone policies
if _, exist := policyNameMap[policy.Name]; !exist && !cmdOption.MergeStandaloneFiles {
buff.WriteString(fmt.Sprintf("WARNING: policy %s not referenced by application\n\n", policy.Name))
fmt.Fprintf(buff, "WARNING: policy %s not referenced by application\n\n", policy.Name)
continue
}
app.Spec.Policies = append(app.Spec.Policies, corev1beta1.AppPolicy{

View File

@@ -223,9 +223,20 @@ var _ = Describe("Testing dry-run", func() {
Expect(buff.String()).Should(ContainSubstring("kind: Deployment"))
})
It("Testing dry-run offline", func() {
It("Testing dry-run offline with definition file", func() {
c := common2.Args{}
opt := DryRunCmdOptions{ApplicationFiles: []string{"test-data/dry-run/testing-dry-run-6.yaml"}, DefinitionFile: "test-data/dry-run/testing-worker-def.yaml", OfflineMode: true}
opt := DryRunCmdOptions{ApplicationFiles: []string{"test-data/dry-run/testing-dry-run-6.yaml"}, DefinitionFile: "test-data/dry-run/definitions/testing-worker-def.yaml", OfflineMode: true}
buff, err := DryRunApplication(&opt, c, "")
Expect(err).Should(BeNil())
Expect(buff.String()).Should(ContainSubstring("# Application(testing-app)"))
Expect(buff.String()).Should(ContainSubstring("name: testing-dryrun"))
Expect(buff.String()).Should(ContainSubstring("kind: Deployment"))
Expect(buff.String()).Should(ContainSubstring("workload.oam.dev/type: myworker"))
})
It("Testing dry-run offline with definition directory", func() {
c := common2.Args{}
opt := DryRunCmdOptions{ApplicationFiles: []string{"test-data/dry-run/testing-dry-run-6.yaml"}, DefinitionFile: "test-data/dry-run/definitions", OfflineMode: true}
buff, err := DryRunApplication(&opt, c, "")
Expect(err).Should(BeNil())
Expect(buff.String()).Should(ContainSubstring("# Application(testing-app)"))
@@ -236,7 +247,7 @@ var _ = Describe("Testing dry-run", func() {
It("Testing dry-run offline with deploy workflow step", func() {
c := common2.Args{}
opt := DryRunCmdOptions{ApplicationFiles: []string{"test-data/dry-run/testing-dry-run-7.yaml"}, DefinitionFile: "test-data/dry-run/testing-worker-def.yaml", OfflineMode: true}
opt := DryRunCmdOptions{ApplicationFiles: []string{"test-data/dry-run/testing-dry-run-7.yaml"}, DefinitionFile: "test-data/dry-run/definitions/testing-worker-def.yaml", OfflineMode: true}
buff, err := DryRunApplication(&opt, c, "")
Expect(err).Should(BeNil())
Expect(buff.String()).Should(ContainSubstring("# Application(testing-app with topology target-prod)"))

View File

@@ -126,7 +126,7 @@ func (opt *KubeApplyOptions) Validate() error {
for _, fileData := range opt.filesData {
switch {
case strings.HasSuffix(fileData.Path, ".yaml"), strings.HasSuffix(fileData.Path, ".yml"):
case strings.HasSuffix(fileData.Path, YAMLExtension), strings.HasSuffix(fileData.Path, YMLExtension):
decoder := yaml.NewDecoder(bytes.NewReader(fileData.Data))
for {
obj := &unstructured.Unstructured{Object: map[string]interface{}{}}

View File

@@ -103,7 +103,7 @@ func LiveDiffApplication(cmdOption *LiveDiffCmdOptions, c common.Args) (bytes.Bu
}
var objs []*unstructured.Unstructured
if cmdOption.DefinitionFile != "" {
objs, err = ReadDefinitionsFromFile(cmdOption.DefinitionFile)
objs, err = ReadDefinitionsFromFile(cmdOption.DefinitionFile, cmdOption.IOStreams)
if err != nil {
return buff, err
}

View File

@@ -285,7 +285,7 @@ func generateSideBar(capabilities []types.Capability, docsPath string) error {
}
for _, c := range components {
if _, err := f.WriteString(fmt.Sprintf(" - [%s](%s/%s.md)\n", c, types.TypeComponentDefinition, c)); err != nil {
if _, err := fmt.Fprintf(f, " - [%s](%s/%s.md)\n", c, types.TypeComponentDefinition, c); err != nil {
return err
}
}
@@ -293,7 +293,7 @@ func generateSideBar(capabilities []types.Capability, docsPath string) error {
return err
}
for _, t := range traits {
if _, err := f.WriteString(fmt.Sprintf(" - [%s](%s/%s.md)\n", t, types.TypeTrait, t)); err != nil {
if _, err := fmt.Fprintf(f, " - [%s](%s/%s.md)\n", t, types.TypeTrait, t); err != nil {
return err
}
}
@@ -301,7 +301,7 @@ func generateSideBar(capabilities []types.Capability, docsPath string) error {
return err
}
for _, t := range workflowSteps {
if _, err := f.WriteString(fmt.Sprintf(" - [%s](%s/%s.md)\n", t, types.TypeWorkflowStep, t)); err != nil {
if _, err := fmt.Fprintf(f, " - [%s](%s/%s.md)\n", t, types.TypeWorkflowStep, t); err != nil {
return err
}
}
@@ -310,7 +310,7 @@ func generateSideBar(capabilities []types.Capability, docsPath string) error {
return err
}
for _, t := range policies {
if _, err := f.WriteString(fmt.Sprintf(" - [%s](%s/%s.md)\n", t, types.TypePolicy, t)); err != nil {
if _, err := fmt.Fprintf(f, " - [%s](%s/%s.md)\n", t, types.TypePolicy, t); err != nil {
return err
}
}
@@ -392,7 +392,7 @@ func generateREADME(capabilities []types.Capability, docsPath string) error {
}
for _, w := range workloads {
if _, err := f.WriteString(fmt.Sprintf(" - [%s](%s/%s.md)\n", w, types.TypeComponentDefinition, w)); err != nil {
if _, err := fmt.Fprintf(f, " - [%s](%s/%s.md)\n", w, types.TypeComponentDefinition, w); err != nil {
return err
}
}
@@ -401,7 +401,7 @@ func generateREADME(capabilities []types.Capability, docsPath string) error {
}
for _, t := range traits {
if _, err := f.WriteString(fmt.Sprintf(" - [%s](%s/%s.md)\n", t, types.TypeTrait, t)); err != nil {
if _, err := fmt.Fprintf(f, " - [%s](%s/%s.md)\n", t, types.TypeTrait, t); err != nil {
return err
}
}
@@ -410,7 +410,7 @@ func generateREADME(capabilities []types.Capability, docsPath string) error {
return err
}
for _, t := range workflowSteps {
if _, err := f.WriteString(fmt.Sprintf(" - [%s](%s/%s.md)\n", t, types.TypeWorkflowStep, t)); err != nil {
if _, err := fmt.Fprintf(f, " - [%s](%s/%s.md)\n", t, types.TypeWorkflowStep, t); err != nil {
return err
}
}
@@ -419,7 +419,7 @@ func generateREADME(capabilities []types.Capability, docsPath string) error {
return err
}
for _, t := range policies {
if _, err := f.WriteString(fmt.Sprintf(" - [%s](%s/%s.md)\n", t, types.TypePolicy, t)); err != nil {
if _, err := fmt.Fprintf(f, " - [%s](%s/%s.md)\n", t, types.TypePolicy, t); err != nil {
return err
}
}

View File

@@ -32,7 +32,7 @@ import (
)
// NewTopCommand will create command `top` for displaying the platform overview
func NewTopCommand(c common.Args, order string, ioStreams cmdutil.IOStreams) *cobra.Command {
func NewTopCommand(c common.Args, order string, _ cmdutil.IOStreams) *cobra.Command {
cmd := &cobra.Command{
Use: "top",
Short: "Launch UI to display the platform overview.",

View File

@@ -28,44 +28,44 @@ import (
var themeConfig = config.ThemeConfig{
Info: struct {
Title config.Color
Text config.Color
Title config.Color `yaml:"title"`
Text config.Color `yaml:"text"`
}{
Title: "royalblue",
Text: "lightgray",
},
Menu: struct {
Description config.Color
Key config.Color
Description config.Color `yaml:"description"`
Key config.Color `yaml:"key"`
}{
Description: "gray",
Key: "royalblue",
},
Logo: struct {
Text config.Color
Text config.Color `yaml:"text"`
}{
Text: "royalblue",
},
Crumbs: struct {
Foreground config.Color
Background config.Color
Foreground config.Color `yaml:"foreground"`
Background config.Color `yaml:"background"`
}{
Foreground: "white",
Background: "royalblue",
},
Border: struct {
App config.Color
Table config.Color
App config.Color `yaml:"app"`
Table config.Color `yaml:"table"`
}{
App: "black",
Table: "lightgray",
},
Table: struct {
Title config.Color
Header config.Color
Body config.Color
CursorBg config.Color
CursorFg config.Color
Title config.Color `yaml:"title"`
Header config.Color `yaml:"header"`
Body config.Color `yaml:"body"`
CursorBg config.Color `yaml:"cursorbg"`
CursorFg config.Color `yaml:"cursorfg"`
}{
Title: "royalblue",
Header: "white",
@@ -74,13 +74,13 @@ var themeConfig = config.ThemeConfig{
CursorFg: "black",
},
Status: struct {
Starting config.Color
Healthy config.Color
UnHealthy config.Color
Waiting config.Color
Succeeded config.Color
Failed config.Color
Unknown config.Color
Starting config.Color `yaml:"starting"`
Healthy config.Color `yaml:"healthy"`
UnHealthy config.Color `yaml:"unhealthy"`
Waiting config.Color `yaml:"waiting"`
Succeeded config.Color `yaml:"succeeded"`
Failed config.Color `yaml:"failed"`
Unknown config.Color `yaml:"unknown"`
}{
Starting: "blue",
Healthy: "green",
@@ -91,22 +91,22 @@ var themeConfig = config.ThemeConfig{
Unknown: "gray",
},
Yaml: struct {
Key config.Color
Colon config.Color
Value config.Color
Key config.Color `yaml:"key"`
Colon config.Color `yaml:"colon"`
Value config.Color `yaml:"value"`
}{
Key: "#d33582",
Colon: "lightgray",
Value: "#839495",
},
Topology: struct {
Line config.Color
App config.Color
Workflow config.Color
Component config.Color
Policy config.Color
Trait config.Color
Kind config.Color
Line config.Color `yaml:"line"`
App config.Color `yaml:"app"`
Workflow config.Color `yaml:"workflow"`
Component config.Color `yaml:"component"`
Policy config.Color `yaml:"policy"`
Trait config.Color `yaml:"trait"`
Kind config.Color `yaml:"kind"`
}{
Line: "cadetblue",
App: "red",

View File

@@ -33,54 +33,54 @@ type Color string
// ThemeConfig is the theme config.
type ThemeConfig struct {
Info struct {
Title Color
Text Color
}
Title Color `yaml:"title"`
Text Color `yaml:"text"`
} `yaml:"info"`
Menu struct {
Description Color
Key Color
}
Description Color `yaml:"description"`
Key Color `yaml:"key"`
} `yaml:"menu"`
Logo struct {
Text Color
}
Text Color `yaml:"text"`
} `yaml:"logo"`
Crumbs struct {
Foreground Color
Background Color
}
Foreground Color `yaml:"foreground"`
Background Color `yaml:"background"`
} `yaml:"crumbs"`
Border struct {
App Color
Table Color
}
App Color `yaml:"app"`
Table Color `yaml:"table"`
} `yaml:"border"`
Table struct {
Title Color
Header Color
Body Color
CursorBg Color
CursorFg Color
}
Title Color `yaml:"title"`
Header Color `yaml:"header"`
Body Color `yaml:"body"`
CursorBg Color `yaml:"cursorbg"`
CursorFg Color `yaml:"cursorfg"`
} `yaml:"table"`
Status struct {
Starting Color
Healthy Color
UnHealthy Color
Waiting Color
Succeeded Color
Failed Color
Unknown Color
}
Starting Color `yaml:"starting"`
Healthy Color `yaml:"healthy"`
UnHealthy Color `yaml:"unhealthy"`
Waiting Color `yaml:"waiting"`
Succeeded Color `yaml:"succeeded"`
Failed Color `yaml:"failed"`
Unknown Color `yaml:"unknown"`
} `yaml:"status"`
Yaml struct {
Key Color
Colon Color
Value Color
}
Key Color `yaml:"key"`
Colon Color `yaml:"colon"`
Value Color `yaml:"value"`
} `yaml:"yaml"`
Topology struct {
Line Color
App Color
Workflow Color
Component Color
Policy Color
Trait Color
Kind Color
}
Line Color `yaml:"line"`
App Color `yaml:"app"`
Workflow Color `yaml:"workflow"`
Component Color `yaml:"component"`
Policy Color `yaml:"policy"`
Trait Color `yaml:"trait"`
Kind Color `yaml:"kind"`
} `yaml:"topology"`
}
var (
@@ -188,44 +188,44 @@ func LoadThemeConfig() *ThemeConfig {
func defaultTheme() *ThemeConfig {
return &ThemeConfig{
Info: struct {
Title Color
Text Color
Title Color `yaml:"title"`
Text Color `yaml:"text"`
}{
Title: "royalblue",
Text: "lightgray",
},
Menu: struct {
Description Color
Key Color
Description Color `yaml:"description"`
Key Color `yaml:"key"`
}{
Description: "gray",
Key: "royalblue",
},
Logo: struct {
Text Color
Text Color `yaml:"text"`
}{
Text: "royalblue",
},
Crumbs: struct {
Foreground Color
Background Color
Foreground Color `yaml:"foreground"`
Background Color `yaml:"background"`
}{
Foreground: "white",
Background: "royalblue",
},
Border: struct {
App Color
Table Color
App Color `yaml:"app"`
Table Color `yaml:"table"`
}{
App: "black",
Table: "lightgray",
},
Table: struct {
Title Color
Header Color
Body Color
CursorBg Color
CursorFg Color
Title Color `yaml:"title"`
Header Color `yaml:"header"`
Body Color `yaml:"body"`
CursorBg Color `yaml:"cursorbg"`
CursorFg Color `yaml:"cursorfg"`
}{
Title: "royalblue",
Header: "white",
@@ -234,22 +234,22 @@ func defaultTheme() *ThemeConfig {
CursorFg: "black",
},
Yaml: struct {
Key Color
Colon Color
Value Color
Key Color `yaml:"key"`
Colon Color `yaml:"colon"`
Value Color `yaml:"value"`
}{
Key: "#d33582",
Colon: "lightgray",
Value: "#839495",
},
Status: struct {
Starting Color
Healthy Color
UnHealthy Color
Waiting Color
Succeeded Color
Failed Color
Unknown Color
Starting Color `yaml:"starting"`
Healthy Color `yaml:"healthy"`
UnHealthy Color `yaml:"unhealthy"`
Waiting Color `yaml:"waiting"`
Succeeded Color `yaml:"succeeded"`
Failed Color `yaml:"failed"`
Unknown Color `yaml:"unknown"`
}{
Starting: "blue",
Healthy: "green",
@@ -260,13 +260,13 @@ func defaultTheme() *ThemeConfig {
Unknown: "gray",
},
Topology: struct {
Line Color
App Color
Workflow Color
Component Color
Policy Color
Trait Color
Kind Color
Line Color `yaml:"line"`
App Color `yaml:"app"`
Workflow Color `yaml:"workflow"`
Component Color `yaml:"component"`
Policy Color `yaml:"policy"`
Trait Color `yaml:"trait"`
Kind Color `yaml:"kind"`
}{
Line: "cadetblue",
App: "red",

View File

@@ -65,18 +65,18 @@ func ListClusters(ctx context.Context, c client.Client) (ClusterList, error) {
cluster, err := multicluster.NewClusterClient(c).Get(context.Background(), key)
if err != nil {
continue
} else {
clusterInfo.alias = cluster.Spec.Alias
clusterInfo.clusterType = string(cluster.Spec.CredentialType)
clusterInfo.endpoint = cluster.Spec.Endpoint
var labels []string
for k, v := range cluster.Labels {
if !strings.HasPrefix(k, config.MetaApiGroupName) {
labels = append(labels, "[blue::]"+k+"="+"[green::]"+v)
}
}
clusterInfo.labels = strings.Join(labels, ",")
}
clusterInfo.alias = cluster.Spec.Alias
clusterInfo.clusterType = string(cluster.Spec.CredentialType)
clusterInfo.endpoint = cluster.Spec.Endpoint
var labels []string
for k, v := range cluster.Labels {
if !strings.HasPrefix(k, config.MetaApiGroupName) {
labels = append(labels, "[blue::]"+k+"="+"[green::]"+v)
}
}
clusterInfo.labels = strings.Join(labels, ",")
list = append(list, clusterInfo)
}
return list, nil

View File

@@ -68,7 +68,7 @@ func collectResource(ctx context.Context, c client.Client, opt query.Option) ([]
var resources = make([]unstructured.Unstructured, 0)
for _, res := range appResList {
if res.ResourceTree != nil {
resources = append(resources, sonLeafResource(*res, res.ResourceTree, opt.Filter.Kind, opt.Filter.APIVersion)...)
resources = append(resources, sonLeafResource(res.ResourceTree, opt.Filter.Kind, opt.Filter.APIVersion)...)
}
if (opt.Filter.Kind == "" && opt.Filter.APIVersion == "") || (res.Kind == opt.Filter.Kind && res.APIVersion == opt.Filter.APIVersion) {
var object unstructured.Unstructured
@@ -82,11 +82,11 @@ func collectResource(ctx context.Context, c client.Client, opt query.Option) ([]
return resources, nil
}
func sonLeafResource(res querytypes.AppliedResource, node *querytypes.ResourceTreeNode, kind string, apiVersion string) []unstructured.Unstructured {
func sonLeafResource(node *querytypes.ResourceTreeNode, kind string, apiVersion string) []unstructured.Unstructured {
objects := make([]unstructured.Unstructured, 0)
if node.LeafNodes != nil {
for i := 0; i < len(node.LeafNodes); i++ {
objects = append(objects, sonLeafResource(res, node.LeafNodes[i], kind, apiVersion)...)
objects = append(objects, sonLeafResource(node.LeafNodes[i], kind, apiVersion)...)
}
}
if (kind == "" && apiVersion == "") || (node.Kind == kind && node.APIVersion == apiVersion) {

View File

@@ -77,7 +77,6 @@ var _ = Describe("test resource", func() {
})
func TestSonLeafResource(t *testing.T) {
res := querytypes.AppliedResource{}
node := &querytypes.ResourceTreeNode{
LeafNodes: []*querytypes.ResourceTreeNode{
{
@@ -85,6 +84,6 @@ func TestSonLeafResource(t *testing.T) {
},
},
}
objs := sonLeafResource(res, node, "", "")
objs := sonLeafResource(node, "", "")
assert.Equal(t, len(objs), 2)
}

View File

@@ -72,7 +72,7 @@ func NewWorkflowCommand(c common.Args, order string, ioStreams cmdutil.IOStreams
}
// NewWorkflowSuspendCommand create workflow suspend command
func NewWorkflowSuspendCommand(c common.Args, ioStream cmdutil.IOStreams, wargs *WorkflowArgs) *cobra.Command {
func NewWorkflowSuspendCommand(_ common.Args, _ cmdutil.IOStreams, wargs *WorkflowArgs) *cobra.Command {
cmd := &cobra.Command{
Use: "suspend",
Short: "Suspend a workflow.",
@@ -97,7 +97,7 @@ func NewWorkflowSuspendCommand(c common.Args, ioStream cmdutil.IOStreams, wargs
}
// NewWorkflowResumeCommand create workflow resume command
func NewWorkflowResumeCommand(c common.Args, ioStream cmdutil.IOStreams, wargs *WorkflowArgs) *cobra.Command {
func NewWorkflowResumeCommand(_ common.Args, _ cmdutil.IOStreams, wargs *WorkflowArgs) *cobra.Command {
cmd := &cobra.Command{
Use: "resume",
Short: "Resume a suspend workflow.",
@@ -122,7 +122,7 @@ func NewWorkflowResumeCommand(c common.Args, ioStream cmdutil.IOStreams, wargs *
}
// NewWorkflowTerminateCommand create workflow terminate command
func NewWorkflowTerminateCommand(c common.Args, ioStream cmdutil.IOStreams, wargs *WorkflowArgs) *cobra.Command {
func NewWorkflowTerminateCommand(_ common.Args, _ cmdutil.IOStreams, wargs *WorkflowArgs) *cobra.Command {
cmd := &cobra.Command{
Use: "terminate",
Short: "Terminate a workflow.",
@@ -143,7 +143,7 @@ func NewWorkflowTerminateCommand(c common.Args, ioStream cmdutil.IOStreams, warg
}
// NewWorkflowRestartCommand create workflow restart command
func NewWorkflowRestartCommand(c common.Args, ioStream cmdutil.IOStreams, wargs *WorkflowArgs) *cobra.Command {
func NewWorkflowRestartCommand(_ common.Args, _ cmdutil.IOStreams, wargs *WorkflowArgs) *cobra.Command {
cmd := &cobra.Command{
Use: "restart",
Short: "Restart a workflow.",
@@ -167,7 +167,7 @@ func NewWorkflowRestartCommand(c common.Args, ioStream cmdutil.IOStreams, wargs
}
// NewWorkflowRollbackCommand create workflow rollback command
func NewWorkflowRollbackCommand(c common.Args, ioStream cmdutil.IOStreams, wargs *WorkflowArgs) *cobra.Command {
func NewWorkflowRollbackCommand(_ common.Args, _ cmdutil.IOStreams, wargs *WorkflowArgs) *cobra.Command {
cmd := &cobra.Command{
Use: "rollback",
Short: "Rollback an application workflow to the latest revision.",
@@ -249,7 +249,7 @@ func NewWorkflowDebugCommand(c common.Args, ioStream cmdutil.IOStreams, wargs *W
}
// NewWorkflowListCommand create workflow list command
func NewWorkflowListCommand(c common.Args, ioStream cmdutil.IOStreams, wargs *WorkflowArgs) *cobra.Command {
func NewWorkflowListCommand(c common.Args, ioStream cmdutil.IOStreams, _ *WorkflowArgs) *cobra.Command {
cmd := &cobra.Command{
Use: "list",
Short: "List running workflows",

View File

@@ -284,7 +284,7 @@ func CollectApplicationResource(ctx context.Context, c client.Client, opt query.
var resources = make([]unstructured.Unstructured, 0)
for _, res := range appResList {
if res.ResourceTree != nil {
resources = append(resources, sonLeafResource(*res, res.ResourceTree, opt.Filter.Kind, opt.Filter.APIVersion)...)
resources = append(resources, sonLeafResource(res.ResourceTree, opt.Filter.Kind, opt.Filter.APIVersion)...)
}
if (opt.Filter.Kind == "" && opt.Filter.APIVersion == "") || (res.Kind == opt.Filter.Kind && res.APIVersion == opt.Filter.APIVersion) {
var object unstructured.Unstructured
@@ -298,11 +298,11 @@ func CollectApplicationResource(ctx context.Context, c client.Client, opt query.
return resources, nil
}
func sonLeafResource(res querytypes.AppliedResource, node *querytypes.ResourceTreeNode, kind string, apiVersion string) []unstructured.Unstructured {
func sonLeafResource(node *querytypes.ResourceTreeNode, kind string, apiVersion string) []unstructured.Unstructured {
objects := make([]unstructured.Unstructured, 0)
if node.LeafNodes != nil {
for i := 0; i < len(node.LeafNodes); i++ {
objects = append(objects, sonLeafResource(res, node.LeafNodes[i], kind, apiVersion)...)
objects = append(objects, sonLeafResource(node.LeafNodes[i], kind, apiVersion)...)
}
}
if (kind == "" && apiVersion == "") || (node.Kind == kind && node.APIVersion == apiVersion) {

View File

@@ -31,7 +31,7 @@ import (
func (g *Generator) convertDecls(x *goast.GenDecl) (decls []Decl, _ error) {
// TODO(iyear): currently only support 'type'
if x.Tok != gotoken.TYPE {
return
return decls, nil
}
for _, spec := range x.Specs {

View File

@@ -125,7 +125,7 @@ func (ref *ConsoleReference) GenerateTerraformCapabilityProperties(capability ty
}
// Show will show capability reference in console
func (ref *ConsoleReference) Show(ctx context.Context, c common.Args, ioStreams cmdutil.IOStreams, capabilityName string, ns string, rev int64) error {
func (ref *ConsoleReference) Show(ctx context.Context, c common.Args, ioStreams cmdutil.IOStreams, capabilityName string, ns string, _ int64) error {
caps, err := ref.getCapabilities(ctx, c)
if err != nil {
return err

View File

@@ -139,7 +139,7 @@ func (ref *MarkdownReference) CreateMarkdown(ctx context.Context, caps []types.C
// GenerateMarkdownForCap will generate markdown for one capability
// nolint:gocyclo
func (ref *MarkdownReference) GenerateMarkdownForCap(ctx context.Context, c types.Capability, pd *packages.PackageDiscover, containSuffix bool) (string, error) {
func (ref *MarkdownReference) GenerateMarkdownForCap(_ context.Context, c types.Capability, pd *packages.PackageDiscover, containSuffix bool) (string, error) {
var (
description string
base string

View File

@@ -100,7 +100,7 @@ func GenerateProviderMarkdown(provider io.Reader, w io.Writer) error {
}
// header
docs.WriteString(fmt.Sprintf("## %s\n", iter.Label()))
fmt.Fprintf(docs, "## %s\n", iter.Label())
doc, _, err := ref.parseParameters("", item.LookupPath(cue.ParsePath(paramsKey)), "*Params*", 0, true)
if err != nil {
@@ -116,7 +116,7 @@ func GenerateProviderMarkdown(provider io.Reader, w io.Writer) error {
}
doc := bytes.NewBuffer(nil)
doc.WriteString(fmt.Sprintf("# %s\n\n", pkg)) // package name header
fmt.Fprintf(doc, "# %s\n\n", pkg) // package name header
doc.Write(docs.Bytes())
doc.WriteString("------\n\n") // footer

View File

@@ -6,6 +6,138 @@
attributes: workload: type: "autodetects.core.oam.dev"
}
template: {
mountsArray: {
pvc: *[
for v in parameter.volumeMounts.pvc {
{
mountPath: v.mountPath
if v.subPath != _|_ {
subPath: v.subPath
}
name: v.name
}
},
] | []
configMap: *[
for v in parameter.volumeMounts.configMap {
{
mountPath: v.mountPath
if v.subPath != _|_ {
subPath: v.subPath
}
name: v.name
}
},
] | []
secret: *[
for v in parameter.volumeMounts.secret {
{
mountPath: v.mountPath
if v.subPath != _|_ {
subPath: v.subPath
}
name: v.name
}
},
] | []
emptyDir: *[
for v in parameter.volumeMounts.emptyDir {
{
mountPath: v.mountPath
if v.subPath != _|_ {
subPath: v.subPath
}
name: v.name
}
},
] | []
hostPath: *[
for v in parameter.volumeMounts.hostPath {
{
mountPath: v.mountPath
if v.subPath != _|_ {
subPath: v.subPath
}
name: v.name
}
},
] | []
}
volumesArray: {
pvc: *[
for v in parameter.volumeMounts.pvc {
{
name: v.name
persistentVolumeClaim: claimName: v.claimName
}
},
] | []
configMap: *[
for v in parameter.volumeMounts.configMap {
{
name: v.name
configMap: {
defaultMode: v.defaultMode
name: v.cmName
if v.items != _|_ {
items: v.items
}
}
}
},
] | []
secret: *[
for v in parameter.volumeMounts.secret {
{
name: v.name
secret: {
defaultMode: v.defaultMode
secretName: v.secretName
if v.items != _|_ {
items: v.items
}
}
}
},
] | []
emptyDir: *[
for v in parameter.volumeMounts.emptyDir {
{
name: v.name
emptyDir: medium: v.medium
}
},
] | []
hostPath: *[
for v in parameter.volumeMounts.hostPath {
{
name: v.name
hostPath: path: v.path
}
},
] | []
}
volumesList: volumesArray.pvc + volumesArray.configMap + volumesArray.secret + volumesArray.emptyDir + volumesArray.hostPath
deDupVolumesArray: [
for val in [
for i, vi in volumesList {
for j, vj in volumesList if j < i && vi.name == vj.name {
_ignore: true
}
vi
},
] if val._ignore == _|_ {
val
},
]
output: {
if context.clusterVersion.minor < 25 {
apiVersion: "batch/v1beta1"
@@ -85,15 +217,18 @@ template: {
requests: memory: parameter.memory
}
}
if parameter["volumes"] != _|_ {
if parameter["volumes"] != _|_ if parameter["volumeMounts"] == _|_ {
volumeMounts: [ for v in parameter.volumes {
{
mountPath: v.mountPath
name: v.name
}}]
}
if parameter["volumeMounts"] != _|_ {
volumeMounts: mountsArray.pvc + mountsArray.configMap + mountsArray.secret + mountsArray.emptyDir + mountsArray.hostPath
}
}]
if parameter["volumes"] != _|_ {
if parameter["volumes"] != _|_ if parameter["volumeMounts"] == _|_ {
volumes: [ for v in parameter.volumes {
{
name: v.name
@@ -123,6 +258,9 @@ template: {
}
}}]
}
if parameter["volumeMounts"] != _|_ {
volumes: deDupVolumesArray
}
if parameter["imagePullSecrets"] != _|_ {
imagePullSecrets: [ for v in parameter.imagePullSecrets {
name: v
@@ -219,7 +357,58 @@ template: {
// +usage=Specifies the attributes of the memory resource required for the container.
memory?: string
// +usage=Declare volumes and volumeMounts
volumeMounts?: {
// +usage=Mount PVC type volume
pvc?: [...{
name: string
mountPath: string
subPath?: string
// +usage=The name of the PVC
claimName: string
}]
// +usage=Mount ConfigMap type volume
configMap?: [...{
name: string
mountPath: string
subPath?: string
defaultMode: *420 | int
cmName: string
items?: [...{
key: string
path: string
mode: *511 | int
}]
}]
// +usage=Mount Secret type volume
secret?: [...{
name: string
mountPath: string
subPath?: string
defaultMode: *420 | int
secretName: string
items?: [...{
key: string
path: string
mode: *511 | int
}]
}]
// +usage=Mount EmptyDir type volume
emptyDir?: [...{
name: string
mountPath: string
subPath?: string
medium: *"" | "Memory"
}]
// +usage=Mount HostPath type volume
hostPath?: [...{
name: string
mountPath: string
subPath?: string
path: string
}]
}
// +usage=Deprecated field, use volumeMounts instead.
volumes?: [...{
name: string
mountPath: string

View File

@@ -212,14 +212,20 @@ template: {
if parameter["ports"] != _|_ {
ports: [ for v in parameter.ports {
{
containerPort: v.port
protocol: v.protocol
containerPort: {
if v.containerPort != _|_ {v.containerPort}
if v.containerPort == _|_ {v.port}
}
protocol: v.protocol
if v.name != _|_ {
name: v.name
}
if v.name == _|_ {
_name: "port-" + strconv.FormatInt(v.port, 10)
name: *_name | string
_name: {
if v.containerPort != _|_ {"port-" + strconv.FormatInt(v.containerPort, 10)}
if v.containerPort == _|_ {"port-" + strconv.FormatInt(v.port, 10)}
}
name: *_name | string
if v.protocol != "TCP" {
name: _name + "-" + strings.ToLower(v.protocol)
}
@@ -337,14 +343,20 @@ template: {
exposePorts: [
if parameter.ports != _|_ for v in parameter.ports if v.expose == true {
port: v.port
targetPort: v.port
if v.name != _|_ {
name: v.name
}
port: v.port
if v.containerPort != _|_ {targetPort: v.containerPort}
if v.containerPort == _|_ {targetPort: v.port}
if v.name != _|_ {name: v.name}
if v.name == _|_ {
_name: "port-" + strconv.FormatInt(v.port, 10)
name: *_name | string
_name: {
if v.containerPort != _|_ {
"port-" + strconv.FormatInt(v.containerPort, 10)
}
if v.containerPort == _|_ {
"port-" + strconv.FormatInt(v.port, 10)
}
}
name: *_name | string
if v.protocol != "TCP" {
name: _name + "-" + strings.ToLower(v.protocol)
}
@@ -399,6 +411,8 @@ template: {
ports?: [...{
// +usage=Number of port to expose on the pod's IP address
port: int
// +usage=Number of container port to connect to, defaults to port
containerPort?: int
// +usage=Name of the port
name?: string
// +usage=Protocol for port. Must be UDP, TCP, or SCTP

View File

@@ -1,7 +1,7 @@
annotations: {
type: "trait"
annotations: {}
description: "Add annotations on your workload. if it generates pod, add same annotations for generated pods."
description: "Add annotations on your workload. If it generates pod or job, add same annotations for generated pods."
attributes: {
podDisruptive: true
appliesToWorkloads: ["*"]
@@ -10,19 +10,23 @@ annotations: {
template: {
// +patchStrategy=jsonMergePatch
patch: {
metadata: {
annotations: {
for k, v in parameter {
(k): v
}
let annotationsContent = {
for k, v in parameter {
(k): v
}
}
if context.output.spec != _|_ && context.output.spec.template != _|_ {
spec: template: metadata: annotations: {
for k, v in parameter {
(k): v
}
}
metadata: {
annotations: annotationsContent
}
if context.output.spec != _|_ if context.output.spec.template != _|_ {
spec: template: metadata: annotations: annotationsContent
}
if context.output.spec != _|_ if context.output.spec.jobTemplate != _|_ {
spec: jobTemplate: metadata: annotations: annotationsContent
}
if context.output.spec != _|_ if context.output.spec.jobTemplate != _|_ if context.output.spec.jobTemplate.spec != _|_ if context.output.spec.jobTemplate.spec.template != _|_ {
spec: jobTemplate: spec: template: metadata: annotations: annotationsContent
}
}
parameter: [string]: string | null

View File

@@ -64,22 +64,28 @@ template: {
if parameter.name != _|_ {"-" + parameter.name}
if parameter.name == _|_ {""}
}
let serviceOutputName = "service" + nameSuffix
let serviceMetaName = context.name + nameSuffix
outputs: (serviceOutputName): {
apiVersion: "v1"
kind: "Service"
metadata: name: "\(serviceMetaName)"
spec: {
selector: "app.oam.dev/component": context.name
ports: [
for k, v in parameter.http {
name: "port-" + strconv.FormatInt(v, 10)
port: v
targetPort: v
},
]
let serviceMetaName = {
if (parameter.existingServiceName != _|_) {parameter.existingServiceName}
if (parameter.existingServiceName == _|_) {context.name + nameSuffix}
}
if (parameter.existingServiceName == _|_) {
let serviceOutputName = "service" + nameSuffix
outputs: (serviceOutputName): {
apiVersion: "v1"
kind: "Service"
metadata: name: "\(serviceMetaName)"
spec: {
selector: "app.oam.dev/component": context.name
ports: [
for k, v in parameter.http {
name: "port-" + strconv.FormatInt(v, 10)
port: v
targetPort: v
},
]
}
}
}
@@ -186,5 +192,8 @@ template: {
// +usage=Specify the labels to be added to the ingress
labels?: [string]: string
// +usage=If specified, use an existing Service rather than creating one
existingServiceName?: string
}
}

View File

@@ -49,11 +49,11 @@ template: {
name: "memory"
target: {
type: parameter.mem.type
if parameter.cpu.type == "Utilization" {
averageUtilization: parameter.cpu.value
if parameter.mem.type == "Utilization" {
averageUtilization: parameter.mem.value
}
if parameter.cpu.type == "AverageValue" {
averageValue: parameter.cpu.value
if parameter.mem.type == "AverageValue" {
averageValue: parameter.mem.value
}
}
}

View File

@@ -4,43 +4,54 @@ resource: {
description: "Add resource requests and limits on K8s pod for your workload which follows the pod spec in path 'spec.template.'"
attributes: {
podDisruptive: true
appliesToWorkloads: ["deployments.apps", "statefulsets.apps", "daemonsets.apps", "jobs.batch"]
appliesToWorkloads: ["deployments.apps", "statefulsets.apps", "daemonsets.apps", "jobs.batch", "cronjobs.batch"]
}
}
template: {
patch: spec: template: spec: {
// +patchKey=name
containers: [{
resources: {
if parameter.cpu != _|_ if parameter.memory != _|_ if parameter.requests == _|_ if parameter.limits == _|_ {
// +patchStrategy=retainKeys
requests: {
cpu: parameter.cpu
memory: parameter.memory
}
// +patchStrategy=retainKeys
limits: {
cpu: parameter.cpu
memory: parameter.memory
}
}
if parameter.requests != _|_ {
// +patchStrategy=retainKeys
requests: {
cpu: parameter.requests.cpu
memory: parameter.requests.memory
}
let resourceContent = {
resources: {
if parameter.cpu != _|_ if parameter.memory != _|_ if parameter.requests == _|_ if parameter.limits == _|_ {
// +patchStrategy=retainKeys
requests: {
cpu: parameter.cpu
memory: parameter.memory
}
if parameter.limits != _|_ {
// +patchStrategy=retainKeys
limits: {
cpu: parameter.limits.cpu
memory: parameter.limits.memory
}
// +patchStrategy=retainKeys
limits: {
cpu: parameter.cpu
memory: parameter.memory
}
}
}]
if parameter.requests != _|_ {
// +patchStrategy=retainKeys
requests: {
cpu: parameter.requests.cpu
memory: parameter.requests.memory
}
}
if parameter.limits != _|_ {
// +patchStrategy=retainKeys
limits: {
cpu: parameter.limits.cpu
memory: parameter.limits.memory
}
}
}
}
if context.output.spec != _|_ if context.output.spec.template != _|_ {
patch: spec: template: spec: {
// +patchKey=name
containers: [resourceContent]
}
}
if context.output.spec != _|_ if context.output.spec.jobTemplate != _|_ {
patch: spec: jobTemplate: spec: template: spec: {
// +patchKey=name
containers: [resourceContent]
}
}
parameter: {

View File

@@ -56,7 +56,7 @@ template: {
// +usage=Instructions for assessing container startup status by probing a TCP socket. Either this attribute or the exec attribute or the tcpSocket attribute or the httpGet attribute MUST be specified. This attribute is mutually exclusive with the exec attribute and the httpGet attribute and the gRPC attribute.
tcpSocket?: {
// +usage=Number or name of the port to access on the container.
port: string
port: int
// +usage=Host name to connect to, defaults to the pod IP.
host?: string
}
@@ -135,7 +135,7 @@ template: {
grpc: parameter.grpc
}
if parameter.tcpSocket != _|_ {
tcpSocket: parameter.grtcpSocketpc
tcpSocket: parameter.tcpSocket
}
}}
}]

View File

@@ -41,11 +41,11 @@ template: {
}
}
}
if parameter.storage != _|_ && parameter.storage.hostPath != _|_ for v in parameter.storage.hostPath {
{
name: "hostpath-" + v.name
path: v.path
}
},
if parameter.storage != _|_ && parameter.storage.hostPath != _|_ for v in parameter.storage.hostPath {
{
name: "hostpath-" + v.name
path: v.path
}
},
]