Skip to content

Commit

Permalink
implemented clean command
Browse files Browse the repository at this point in the history
  • Loading branch information
ufasoli committed Jun 29, 2020
1 parent 4e2beb9 commit 14231b9
Show file tree
Hide file tree
Showing 7 changed files with 415 additions and 27 deletions.
17 changes: 0 additions & 17 deletions .idea/vcs.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

107 changes: 107 additions & 0 deletions cmd/clean.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
package cmd

import (
"archive/tar"
"fmt"
"github.com/spf13/cobra"
"io"
"io/ioutil"
"log"
"os"
"path"
"path/filepath"
)

var baseFolder string

func init() {
rootCmd.AddCommand(cleanCmd)
cleanCmd.Flags().StringVarP(&baseFolder, "base-folder", "f", "", "the path base folder that will be used to clean: container-volume will be appended to the path")
cleanCmd.MarkFlagRequired("base-folder")
}

var cleanCmd = &cobra.Command{
Use: "clean",
Short: "Cleans the contents in the $PATH/container-volume folder",
Long: `Cleans the contents in the $PATH/container-volume folder`,
Run: func(cmd *cobra.Command, args []string) {

folder := baseFolder + "/container-volume"
fmt.Printf("about to delete content of folder : %v \n", folder)

dir, err := ioutil.ReadDir(folder)

if err != nil {
panic(err)
}
for _, d := range dir {
err := os.RemoveAll(path.Join([]string{folder, d.Name()}...))
if err != nil {
panic(err)
}
}

reader, _, err := getFile("/opt/mdps-gen/static-data/container-volume")
fmt.Printf("About to revert to default structure on folder [%v] \n", baseFolder)

if err != nil {
panic(err)
}
tr := tar.NewReader(reader)

for {
header, err := tr.Next()

switch {

// if no more files are found return
case err == io.EOF:
return

// return any other error
case err != nil:
panic(err)

// if the header is nil, just skip it (not sure how this happens)
case header == nil:
continue
}

// the target location where the dir/file should be created
target := filepath.Join(baseFolder, header.Name)

// the following switch could also be done using fi.Mode(), not sure if there
// a benefit of using one vs. the other.
// fi := header.FileInfo()

// check the file type
switch header.Typeflag {

// if its a dir and it doesn't exist create it
case tar.TypeDir:
if _, err := os.Stat(target); err != nil {
if err := os.MkdirAll(target, 0755); err != nil {
panic(err)
}
}

// if it's a file create it
case tar.TypeReg:
f, err := os.OpenFile(target, os.O_CREATE|os.O_RDWR, os.FileMode(header.Mode))
if err != nil {
panic(err)
}

// copy over contents
if _, err := io.Copy(f, tr); err != nil {
log.Fatal(err)
}

// manually close here after each file operation; defering would cause each file close
// to wait until all operations have completed.
f.Close()
}
}

},
}
2 changes: 2 additions & 0 deletions cmd/list_services.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ var serviceRegex = regexp.MustCompile(`(?P<service>[A-Z0-9_-]+)_enable`)

func init() {
rootCmd.AddCommand(listServicesCmd)

}

var listServicesCmd = &cobra.Command{
Expand All @@ -21,6 +22,7 @@ var listServicesCmd = &cobra.Command{

var ymlConfig map[interface{}]interface{}
err := yaml.Unmarshal([]byte(pullConfig()), &ymlConfig)

if err != nil {
panic(err)
}
Expand Down
64 changes: 55 additions & 9 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ var Stack string
var Version string

const containerName = "platys"
const configFilePath = "/opt/mdps-gen/vars/config.yml"

var rootCmd = &cobra.Command{
Use: "platys",
Expand Down Expand Up @@ -90,18 +91,16 @@ func pullConfig() string {
panic(err)
}

reader, _, err = cli.CopyFromContainer(ctx, resp.ID, "/opt/mdps-gen/vars/config.yml")
reader, _, err = cli.CopyFromContainer(ctx, resp.ID, configFilePath)
if err != nil {
log.Println(err.Error())
}
tr := tar.NewReader(reader)

var config_file = ""
for {
// hdr gives you the header of the tar file
_, err := tr.Next()
if err == io.EOF {
// end of tar archive
if err == io.EOF { // end of tar archive
break
}
if err != nil {
Expand All @@ -110,27 +109,74 @@ func pullConfig() string {
buf := new(bytes.Buffer)
buf.ReadFrom(tr)

// You can use this wholeContent to create new file
config_file = buf.String()
}

stdcopy.StdCopy(os.Stdout, os.Stderr, out)
stopRemoveContainer(resp.ID, cli, ctx)

return config_file
}

func getFile(filePath string) (io.ReadCloser, types.ContainerPathStat, error) {
ctx := context.Background()

cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
if err != nil {
panic(err)
}

reader, err := cli.ImagePull(ctx, Stack, types.ImagePullOptions{})
if err != nil {
panic(err)
}
io.Copy(os.Stdout, reader)

resp, err := cli.ContainerCreate(ctx, &container.Config{
Image: Stack,
Tty: true,
}, nil, nil, containerName)

if err != nil {
panic(err)
}

if err := cli.ContainerStart(ctx, resp.ID, types.ContainerStartOptions{}); err != nil {
panic(err)
}

statusCh, errCh := cli.ContainerWait(ctx, resp.ID, container.WaitConditionNotRunning)
select {
case err := <-errCh:
if err != nil {
panic(err)
}
case <-statusCh:
}

out, err := cli.ContainerLogs(ctx, resp.ID, types.ContainerLogsOptions{ShowStdout: true})
if err != nil {
panic(err)
}

stdcopy.StdCopy(os.Stdout, os.Stderr, out)
defer stopRemoveContainer(resp.ID, cli, ctx) //defer the stop container after copying the file

err = cli.ContainerStop(context.Background(), resp.ID, nil)
return cli.CopyFromContainer(ctx, resp.ID, filePath)
}

func stopRemoveContainer(id string, cli *client.Client, ctx context.Context) {

err := cli.ContainerStop(context.Background(), id, nil)
if err != nil {
panic(err)
}
err = cli.ContainerRemove(ctx, resp.ID, types.ContainerRemoveOptions{
err = cli.ContainerRemove(ctx, id, types.ContainerRemoveOptions{
RemoveVolumes: false,
RemoveLinks: false,
Force: false,
})
if err != nil {
panic(err)
}

return config_file
}
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,6 @@ require (
github.com/opencontainers/go-digest v1.0.0 // indirect
github.com/opencontainers/image-spec v1.0.1 // indirect
github.com/spf13/cobra v1.0.0
golang.org/x/build v0.0.0-20200626001000-e84d0b691ed1
gopkg.in/yaml.v2 v2.2.2
)
Loading

0 comments on commit 14231b9

Please sign in to comment.