// containers creates entities from files with the ContainerExtension func (fs FileSource) containers(objects []deploy.KubeObject) (containers []entity.Entity, err error) { info, err := os.Stat(string(fs)) if err != nil { return } // check if file if !info.IsDir() { kubeCtr, err := unmarshalContainer(string(fs)) if err != nil { return nil, err } ctr, err := entity.NewContainer(kubeCtr, kube.ObjectMeta{}, string(fs), objects...) if err != nil { return nil, err } return []entity.Entity{ctr}, nil } dir, err := os.Open(string(fs)) if err != nil { return } defer dir.Close() files, err := dir.Readdir(-1) if err != nil { return } for _, file := range files { if file.Mode().IsRegular() { if filepath.Ext(file.Name()) == ContainerExtension { filename := path.Join(string(fs), file.Name()) kubeCtr, err := unmarshalContainer(filename) if err != nil { return nil, err } ctr, err := entity.NewContainer(kubeCtr, kube.ObjectMeta{}, filename) if err != nil { return nil, err } containers = append(containers, ctr) } } } return containers, nil }
func testWriteAndAttachRandomContainers(t *testing.T, num int, dir string, parent entity.Entity) { for i := 0; i < num; i++ { name := randomString(8) kubeContainer := kube.Container{ Name: name, Image: randomString(6), ImagePullPolicy: kube.PullAlways, TerminationMessagePath: kube.TerminationMessagePathDefault, } filename := path.Join(dir, name+ContainerExtension) container, err := entity.NewContainer(kubeContainer, kube.ObjectMeta{}, filename) assert.NoError(t, err) testWriteYAMLToFile(t, filename, &kubeContainer) assert.NoError(t, parent.Attach(container), "should be able to attach container to pod") } }
func TestSourceContainersDir(t *testing.T) { fs := testTempFileSource(t) defer os.RemoveAll(string(fs)) expected := []*entity.Container{} for i := 0; i < 15+rand.Intn(100); i++ { name := randomString(8) kubeContainer := kube.Container{ Name: name, Image: randomString(6), ImagePullPolicy: kube.PullAlways, } filename := path.Join(string(fs), name+ContainerExtension) container, err := entity.NewContainer(kubeContainer, kube.ObjectMeta{}, filename) assert.NoError(t, err) expected = append(expected, container) testWriteYAMLToFile(t, filename, &kubeContainer) } actual, err := fs.Entities(entity.EntityContainer) assert.NoError(t, err, "should be okay") assert.Len(t, actual, len(expected), "should have same number of containers as start") for _, expectedContainer := range expected { found := false for _, actualContainer := range actual { if expectedContainer.Source() == actualContainer.Source() { found = testCompareEntity(t, expectedContainer, actualContainer) if found { break } } } assert.True(t, found, "should have found container") } }