Last active
April 2, 2018 17:59
-
-
Save sidneyw/d2c7640b0a32c6a0e1449e32526891f0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"log" | |
"net" | |
"net/http" | |
"os" | |
"os/signal" | |
"path/filepath" | |
"sync" | |
"syscall" | |
"time" | |
) | |
func main() { | |
var plugin = &Plugin{ | |
ID: "sample-plugin", | |
Label: "Sample Weave Plugin", | |
Description: "Adds links to deployments", | |
Interfaces: []string{"reporter"}, | |
APIVersion: 1, | |
sync: sync.Mutex{}, | |
} | |
socketPath := fmt.Sprintf("/var/run/scope/plugins/%s/%s.sock", plugin.ID, plugin.ID) | |
// Handle the exit signal | |
setupSignals(socketPath) | |
listener, err := setupSocket(socketPath) | |
if err != nil { | |
log.Fatal(err) | |
} | |
defer func() { | |
listener.Close() | |
os.RemoveAll(filepath.Dir(socketPath)) | |
}() | |
ticker := time.NewTicker(5 * time.Second) | |
go plugin.poll(ticker) | |
http.HandleFunc("/report", plugin.HandleReport) | |
if err := http.Serve(listener, nil); err != nil { | |
log.Printf("error: %v", err) | |
} | |
} | |
func setupSocket(socketPath string) (net.Listener, error) { | |
os.RemoveAll(filepath.Dir(socketPath)) | |
if err := os.MkdirAll(filepath.Dir(socketPath), 0700); err != nil { | |
return nil, fmt.Errorf("failed to create directory %q: %v", filepath.Dir(socketPath), err) | |
} | |
listener, err := net.Listen("unix", socketPath) | |
if err != nil { | |
return nil, fmt.Errorf("failed to listen on %q: %v", socketPath, err) | |
} | |
log.Printf("Listening on: unix://%s", socketPath) | |
return listener, nil | |
} | |
func setupSignals(socketPath string) { | |
interrupt := make(chan os.Signal, 1) | |
signal.Notify(interrupt, os.Interrupt, syscall.SIGTERM) | |
go func() { | |
<-interrupt | |
os.RemoveAll(filepath.Dir(socketPath)) | |
os.Exit(0) | |
}() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment