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

Implement write-file command #3

Merged
2 commits merged into from
Mar 15, 2022
Merged
Show file tree
Hide file tree
Changes from all 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
10 changes: 10 additions & 0 deletions USAGE.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@ Currently, the agent has the following modes:
`wait-signal`
: Waits for a specific signal or signals before it exits.

`write-file`
: Write standard input into the given file

`license`
: This mode will print the license of the agent and exit.

Expand Down Expand Up @@ -58,6 +61,13 @@ the value of `\0` or a newline (`\n`) is received on `stdin`. This byte will
not be passed to the program and if any other byte is received the agent
will exit to prevent data stream corruption.

## Writing files

The backend APIs do not support adding custom files on the fly in containers.
So the `write-file` mode was created. The mode takes just one argument, the
name and path of the file to write. The contents of the file will be read from
standard input

## Reporting PID

Since most container implementations don't report the PID of the process
Expand Down
2 changes: 2 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,8 @@ func main() {
})
case "wait-signal":
waitSignal(os.Stdout, args[2:], os.Exit)
case "write-file":
writeFile(args[2:], os.Stdin, os.Stderr, os.Exit)
case "license":
license(args[2:])
default:
Expand Down
43 changes: 43 additions & 0 deletions write.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package main

import (
"io"
"os"
"log"
)

func writeFile(args []string, stdin io.Reader, stderr io.Writer, exit exitFunc) {
l := log.New(stderr, "", 0)
if len(args) < 1 {
exit(1)
}

file, err := os.OpenFile(args[0], os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
l.Printf("Error opening file: %+v", err)
exit(1)
}

err = file.Chmod(0600)
if err != nil {
l.Printf("Error chmod'ing file: %+v", err)
exit(1)
}

buf := make([]byte, 8192)
for {
nBytes, err := stdin.Read(buf)
if err != nil {
exit(0)
}

wBytes, err := file.Write(buf[0:nBytes])
if err != nil {
exit(1)
}
if wBytes != nBytes {
// Write should never fail without error
exit(1)
}
}
}