2022-10-20 19:59:46 +00:00
|
|
|
package main
|
2022-10-16 18:33:31 +00:00
|
|
|
|
|
|
|
import (
|
2024-06-23 12:37:10 +00:00
|
|
|
"context"
|
|
|
|
"errors"
|
2024-06-10 20:31:29 +00:00
|
|
|
"fmt"
|
2024-09-04 17:44:58 +00:00
|
|
|
"io/fs"
|
2023-08-05 21:53:17 +00:00
|
|
|
"isle/daemon"
|
2024-12-16 13:59:11 +00:00
|
|
|
"isle/toolkit"
|
2024-06-23 12:37:10 +00:00
|
|
|
"net"
|
|
|
|
"net/http"
|
2024-07-16 15:30:36 +00:00
|
|
|
"os"
|
2024-06-23 12:37:10 +00:00
|
|
|
|
|
|
|
"dev.mediocregopher.com/mediocre-go-lib.git/mctx"
|
|
|
|
"dev.mediocregopher.com/mediocre-go-lib.git/mlog"
|
2022-10-16 18:33:31 +00:00
|
|
|
)
|
|
|
|
|
2024-12-16 13:59:11 +00:00
|
|
|
const (
|
|
|
|
daemonHTTPSocketDefaultPath = "/tmp/isle-daemon.sock"
|
|
|
|
daemonHTTPSocketPathEnvVar = "ISLE_DAEMON_HTTP_SOCKET_PATH"
|
|
|
|
daemonHTTPRPCPath = "/rpc/v0.json"
|
|
|
|
)
|
|
|
|
|
|
|
|
func httpSocketPath() string {
|
|
|
|
return toolkit.EnvOr(
|
|
|
|
daemonHTTPSocketPathEnvVar,
|
|
|
|
func() string { return daemonHTTPSocketDefaultPath },
|
|
|
|
)
|
|
|
|
}
|
2024-06-23 12:37:10 +00:00
|
|
|
|
|
|
|
func newHTTPServer(
|
2024-09-07 11:52:32 +00:00
|
|
|
ctx context.Context, logger *mlog.Logger, daemonInst *daemon.Daemon,
|
2024-06-23 12:37:10 +00:00
|
|
|
) (
|
|
|
|
*http.Server, error,
|
|
|
|
) {
|
2024-12-16 13:59:11 +00:00
|
|
|
socketPath := httpSocketPath()
|
2024-09-04 17:44:58 +00:00
|
|
|
ctx = mctx.Annotate(ctx, "socketPath", socketPath)
|
|
|
|
|
|
|
|
if err := os.Remove(socketPath); errors.Is(err, fs.ErrNotExist) {
|
|
|
|
// No problem
|
|
|
|
} else if err != nil {
|
|
|
|
return nil, fmt.Errorf(
|
|
|
|
"removing %q prior to listening: %w", socketPath, err,
|
|
|
|
)
|
|
|
|
} else {
|
|
|
|
logger.WarnString(
|
|
|
|
ctx, "Deleted existing socket file prior to listening, it's possible a previous daemon failed to shutdown gracefully",
|
|
|
|
)
|
|
|
|
}
|
2024-09-01 10:20:37 +00:00
|
|
|
|
2024-07-06 12:26:06 +00:00
|
|
|
l, err := net.Listen("unix", socketPath)
|
2024-06-23 12:37:10 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf(
|
2024-07-16 15:30:36 +00:00
|
|
|
"listening on socket %q: %w", socketPath, err,
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := os.Chmod(socketPath, 0660); err != nil {
|
|
|
|
return nil, fmt.Errorf(
|
|
|
|
"setting permissions of %q to 0660: %w", socketPath, err,
|
2024-06-23 12:37:10 +00:00
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
logger.Info(ctx, "HTTP server socket created")
|
|
|
|
httpMux := http.NewServeMux()
|
2024-09-07 11:52:32 +00:00
|
|
|
httpMux.Handle(daemonHTTPRPCPath, daemonInst.HTTPRPCHandler())
|
2024-06-23 12:37:10 +00:00
|
|
|
|
|
|
|
srv := &http.Server{Handler: httpMux}
|
|
|
|
|
|
|
|
go func() {
|
|
|
|
if err := srv.Serve(l); !errors.Is(err, http.ErrServerClosed) {
|
|
|
|
logger.Fatal(ctx, "HTTP server unexpectedly shut down", err)
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
return srv, nil
|
|
|
|
}
|