-
Notifications
You must be signed in to change notification settings - Fork 0
/
sips.go
103 lines (87 loc) · 2.18 KB
/
sips.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
// sips is the primary implementation of a simple pinning service daemon.
package main
import (
"context"
"errors"
"flag"
"fmt"
"net"
"net/http"
"os"
"os/signal"
"path/filepath"
"time"
"github.com/DeedleFake/sips"
"github.com/DeedleFake/sips/dbs"
"github.com/DeedleFake/sips/internal/cli"
"github.com/DeedleFake/sips/internal/ipfsapi"
"github.com/DeedleFake/sips/internal/log"
)
func run(ctx context.Context) error {
addr := flag.String("addr", ":8080", "address to serve HTTP on")
api := flag.String("api", "http://127.0.0.1:5001", "IPFS API to contact")
apitimeout := flag.Duration("apitimeout", 30*time.Second, "timeout for requests to the IPFS API")
rawdbpath := flag.String("db", "$CONFIG/sips/database.db", "path to database ($CONFIG will be replaced with user config dir path)")
flag.Parse()
dbpath, configDirUsed, err := cli.ExpandConfig(*rawdbpath)
if err != nil {
return err
}
ipfs := ipfsapi.NewClient(
ipfsapi.WithBaseURL(*api),
ipfsapi.WithHTTPClient(&http.Client{
Timeout: *apitimeout,
}),
)
if configDirUsed {
err := os.MkdirAll(filepath.Dir(dbpath), 0770)
if err != nil {
return fmt.Errorf("create config directory: %w", err)
}
}
db, err := dbs.Open(dbpath)
if err != nil {
return fmt.Errorf("open database: %w", err)
}
defer db.Close()
log.Infof("Database opened at %q", dbpath)
ph := PinHandler{
IPFS: ipfs,
DB: db,
}
server := http.Server{
Addr: *addr,
Handler: sips.Handler(&ph),
BaseContext: func(lis net.Listener) context.Context {
return ctx
},
}
shutdown := make(chan error, 1)
go func() {
<-ctx.Done()
sctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
log.Infof("Exiting...")
shutdown <- server.Shutdown(sctx)
}()
log.Infof("Starting server...")
err = server.ListenAndServe()
if err != nil {
if !errors.Is(err, http.ErrServerClosed) {
return fmt.Errorf("start server: %w", err)
}
err = <-shutdown
if err != nil {
return fmt.Errorf("shutdown server: %w", err)
}
}
return nil
}
func main() {
ctx, cancel := signal.NotifyContext(context.Background(), cli.Signals...)
defer cancel()
err := run(ctx)
if err != nil {
log.Fatalf("%v", err)
}
}