Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: return images from resources when sync occurs #642

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion pkg/sync/common/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,6 @@ func NewHookType(t string) (HookType, bool) {
t == string(HookTypePostSync) ||
t == string(HookTypeSyncFail) ||
t == string(HookTypeSkip)

}

type HookDeletePolicy string
Expand All @@ -137,6 +136,8 @@ func NewHookDeletePolicy(p string) (HookDeletePolicy, bool) {
type ResourceSyncResult struct {
// holds associated resource key
ResourceKey kube.ResourceKey
// holds the images associated with the resource
Images []string
// holds resource version
Version string
// holds the execution order
Expand Down
3 changes: 2 additions & 1 deletion pkg/sync/sync_context.go
Original file line number Diff line number Diff line change
Expand Up @@ -1248,7 +1248,7 @@ func (sc *syncContext) runTasks(tasks syncTasks, dryRun bool) runState {
// finally create resources
var tasksGroup syncTasks
for _, task := range createTasks {
//Only wait if the type of the next task is different than the previous type
// Only wait if the type of the next task is different than the previous type
if len(tasksGroup) > 0 && tasksGroup[0].targetObj.GetKind() != task.kind() {
state = sc.processCreateTasks(state, tasksGroup, dryRun)
tasksGroup = syncTasks{task}
Expand Down Expand Up @@ -1308,6 +1308,7 @@ func (sc *syncContext) setResourceResult(task *syncTask, syncStatus common.Resul

res := common.ResourceSyncResult{
ResourceKey: kube.GetResourceKey(task.obj()),
Images: kube.GetResourceImages(task.obj()),
Version: task.version(),
Status: task.syncStatus,
Message: task.message,
Expand Down
28 changes: 28 additions & 0 deletions pkg/utils/kube/kube.go
Original file line number Diff line number Diff line change
Expand Up @@ -404,6 +404,34 @@ func GetDeploymentReplicas(u *unstructured.Unstructured) *int64 {
return &val
}

func GetResourceImages(u *unstructured.Unstructured) []string {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For CronJobs it seems that the image is under spec.jobTemplate.spec.template.spec.containers. Should we also check there?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 6b9063a

var images []string

// Extract containers for resources like pods, without template
containers, found, err := unstructured.NestedSlice(u.Object, "spec", "containers")
if !found || err != nil {
// Extract containers for other resources that have template
containers, found, err = unstructured.NestedSlice(u.Object, "spec", "template", "spec", "containers")
if !found || err != nil {
return nil
}
}

for _, container := range containers {
containerMap, ok := container.(map[string]interface{})
if !ok {
return nil

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we continue instead of returning here? It might be something related to the single container only

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Makes sense to extract as much data as possible. Added continue on 5b2c46f but maybe @andrii-korotkov-verkada has a different take

}
image, found, err := unstructured.NestedString(containerMap, "image")
if !found || err != nil {
continue
}
images = append(images, image)
}

return images
}

// RetryUntilSucceed keep retrying given action with specified interval until action succeed or specified context is done.
func RetryUntilSucceed(ctx context.Context, interval time.Duration, desc string, log logr.Logger, action func() error) {
pollErr := wait.PollUntilContextCancel(ctx, interval, true, func(ctx context.Context) (bool /*done*/, error) {
Expand Down
141 changes: 140 additions & 1 deletion pkg/utils/kube/kube_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,6 @@ func TestUnsetLabels(t *testing.T) {
require.NoError(t, err)
assert.Empty(t, dep.ObjectMeta.Labels)
}

}

func TestCleanKubectlOutput(t *testing.T) {
Expand Down Expand Up @@ -167,6 +166,146 @@ spec:
assert.Nil(t, GetDeploymentReplicas(&noDeployment))
}

func TestGetResourceImagesForResourcesWithTemplate(t *testing.T) {
manifest := []byte(`
apiVersion: extensions/v1beta2
kind: Deployment
metadata:
name: nginx-deployment
labels:
foo: bar
spec:
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:1.7.9
ports:
- containerPort: 80
- name: agent
image: agent:1.0.0
`)

expected := []string{"nginx:1.7.9", "agent:1.0.0"}

deployment := unstructured.Unstructured{}
err := yaml.Unmarshal([]byte(manifest), &deployment)
require.NoError(t, err)

images := GetResourceImages(&deployment)
require.Equal(t, expected, images)
}

func TestGetResourceImagesForPod(t *testing.T) {
manifest := []byte(`
apiVersion: v1
kind: Pod
metadata:
name: example-pod
labels:
app: my-app
spec:
containers:
- name: nginx-container
image: nginx:1.21
ports:
- containerPort: 80
- name: sidecar-container
image: busybox:1.35
command: ["sh", "-c", "echo Hello from the sidecar; sleep 3600"]
`)
expected := []string{"nginx:1.21", "busybox:1.35"}

pod := unstructured.Unstructured{}
err := yaml.Unmarshal([]byte(manifest), &pod)
require.NoError(t, err)

images := GetResourceImages(&pod)
require.Equal(t, expected, images)
}

func TestGetImagesNoImagesPresent(t *testing.T) {
manifests := [][]byte{
[]byte(`
apiVersion: v1
kind: ConfigMap
metadata:
name: example-config
namespace: default
labels:
app: my-app
data:
app.properties: |
key1=value1
key2=value2
key3=value3
log.level: debug
`),
[]byte(`
apiVersion: apps/v1
kind: Deployment
metadata:
name: deployment-no-containers
labels:
foo: bar
spec:
replicas: 1
selector:
matchLabels:
app: agent
template:
metadata:
labels:
app: agent
spec:
volumes:
- name: config-volume
configMap:
name: config
`),
[]byte(`
apiVersion: apps/v1
kind: Deployment
metadata:
name: deployment-without-image
spec:
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: text-service
command: ["echo", "hello"]
`),
[]byte(`
apiVersion: v1
kind: Pod
metadata:
name: example-pod
labels:
app: my-app
spec:
containers:
- name: no-image-container
command: ["echo", "hello"]
`,
),
}

for _, manifest := range manifests {
resource := unstructured.Unstructured{}
err := yaml.Unmarshal([]byte(manifest), &resource)
require.NoError(t, err)

images := GetResourceImages(&resource)
require.Empty(t, images)
}
}

func TestSplitYAML_SingleObject(t *testing.T) {
objs, err := SplitYAML([]byte(depWithLabel))
require.NoError(t, err)
Expand Down
Loading