/
daemon.go
251 lines (207 loc) · 5.83 KB
/
daemon.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
package ipfs
import (
"errors"
"fmt"
"net"
"os"
"sync"
log "github.com/Sirupsen/logrus"
e "github.com/pkg/errors"
core "github.com/ipfs/go-ipfs/core"
coreapi "github.com/ipfs/go-ipfs/core/coreapi"
coreiface "github.com/ipfs/go-ipfs/core/coreapi/interface"
fsrepo "github.com/ipfs/go-ipfs/repo/fsrepo"
migrate "github.com/ipfs/go-ipfs/repo/fsrepo/migrations"
"context"
)
// Find the next free tcp port near to `port` (possibly equal to `port`).
// Only `maxTries` number of trials will be made.
// This method is (of course...) racy since the port might be already
// taken again by another process until we startup our service on that port.
func findFreePortAfter(port int, maxTries int) int {
for idx := 0; idx < maxTries; idx++ {
addr := fmt.Sprintf("localhost:%d", port+idx)
lst, err := net.Listen("tcp", addr)
if err != nil {
continue
}
if err := lst.Close(); err != nil {
// continue, this port might be burned.
// should not happen most likely though.
continue
}
return port + idx
}
return port
}
var (
// ErrIsOffline is returned when an online operation was done offline.
ErrIsOffline = errors.New("Node is offline")
)
// Node remembers the settings needed for accessing the ipfs daemon.
type Node struct {
Path string
SwarmPort int
mu sync.Mutex
ipfsNode *core.IpfsNode
// Root context used for all operations.
ctx context.Context
cancel context.CancelFunc
bootstrapAddrs []string
api coreiface.CoreAPI
}
func createNode(ctx context.Context, path string, minSwarmPort int, online bool, bootstrapAddrs []string) (*core.IpfsNode, error) {
if _, err := os.Stat(path); os.IsNotExist(err) {
log.Infof("Creating new ipfs repo at %s since it does not exist yet.", path)
if err := Init(path, 2048); err != nil {
return nil, err
}
}
rp, err := fsrepo.Open(path)
if err == fsrepo.ErrNeedMigration {
log.Infof("the ipfs repo version changed. We need to run a migration now.")
if err := migrate.RunMigration(fsrepo.RepoVersion); err != nil {
log.Errorf("migration failed: %v", err)
return nil, e.Wrapf(err, "migration failed")
}
// Try re-opening it:
rp, err = fsrepo.Open(path)
if err != nil {
return nil, e.Wrapf(err, "failed to open repo after migration")
}
}
if len(bootstrapAddrs) > 0 && rp != nil {
cfg, err := rp.Config()
if err != nil {
return nil, err
}
bootstrapMap := make(map[string]struct{})
for _, entry := range cfg.Bootstrap {
bootstrapMap[entry] = struct{}{}
}
for _, addr := range bootstrapAddrs {
fullAddr := "/dnsaddr/bootstrap.libp2p.io/ipfs/" + addr
if _, ok := bootstrapMap[fullAddr]; ok {
continue
}
cfg.Bootstrap = append(cfg.Bootstrap, fullAddr)
}
if err := rp.SetConfig(cfg); err != nil {
return nil, err
}
}
if err != nil {
log.Errorf("Unable to open repo `%s`: %v", path, err)
return nil, err
}
swarmPort := findFreePortAfter(minSwarmPort, 100)
log.Debugf(
"ipfs node configured to run on swarm port %d",
swarmPort,
)
// Resource on the config keys can be found here:
// https://github.com/ipfs/go-ipfs/blob/master/docs/config.md
config := map[string]interface{}{
"Addresses.Swarm": []string{
fmt.Sprintf("/ip4/0.0.0.0/tcp/%d", swarmPort),
fmt.Sprintf("/ip6/::/tcp/%d", swarmPort),
},
"Addresses.API": "",
"Addresses.Gateway": "",
"Reprovider.Interval": "2h",
"Swarm.EnableRelayHop": true,
"Swarm.ConnMgr.LowWater": 100,
"Swarm.ConnMgr.HighWater": 200,
"Experimental.QUIC": true,
}
for key, value := range config {
if err := rp.SetConfigKey(key, value); err != nil {
return nil, err
}
}
cfg := &core.BuildCfg{
Repo: rp,
Online: online,
ExtraOpts: map[string]bool{
"pubsub": true,
},
}
ipfsNode, err := core.NewNode(ctx, cfg)
if err != nil {
return nil, err
}
return ipfsNode, nil
}
// New creates a new ipfs node manager. No daemon is started yet.
func New(ipfsPath string, bootstrapAddrs []string) (*Node, error) {
return NewWithPort(ipfsPath, bootstrapAddrs, 4001)
}
// NewWithPort creates a new ipfs instance with the repo at `ipfsPath`
// the additional bootstrap addrs in `bootstrapAddrs` at port `swarmPort`.
func NewWithPort(ipfsPath string, bootstrapAddrs []string, swarmPort int) (*Node, error) {
ctx, cancel := context.WithCancel(context.Background())
ipfsNode, err := createNode(ctx, ipfsPath, swarmPort, true, bootstrapAddrs)
if err != nil {
cancel()
return nil, err
}
return &Node{
Path: ipfsPath,
SwarmPort: swarmPort,
ipfsNode: ipfsNode,
api: coreapi.NewCoreAPI(ipfsNode),
ctx: ctx,
cancel: cancel,
bootstrapAddrs: bootstrapAddrs,
}, nil
}
// IsOnline returns true when the ipfs node is online.
func (nd *Node) IsOnline() bool {
nd.mu.Lock()
defer nd.mu.Unlock()
return nd.isOnline()
}
func (nd *Node) isOnline() bool {
return nd.ipfsNode.OnlineMode()
}
// Connect will connect to the ipfs network.
// This is the default anyways.
func (nd *Node) Connect() error {
nd.mu.Lock()
defer nd.mu.Unlock()
if nd.isOnline() {
return nil
}
var err error
nd.ipfsNode, err = createNode(nd.ctx, nd.Path, nd.SwarmPort, true, nd.bootstrapAddrs)
if err != nil {
return err
}
nd.api = coreapi.NewCoreAPI(nd.ipfsNode)
return nil
}
// Disconnect disconnects from the ipfs network.
func (nd *Node) Disconnect() error {
nd.mu.Lock()
defer nd.mu.Unlock()
if !nd.isOnline() {
return ErrIsOffline
}
var err error
nd.ipfsNode, err = createNode(nd.ctx, nd.Path, nd.SwarmPort, false, nd.bootstrapAddrs)
if err != nil {
return err
}
nd.api = coreapi.NewCoreAPI(nd.ipfsNode)
return nil
}
// Close shuts down the ipfs node.
// It may not be used afterwards.
func (nd *Node) Close() error {
nd.cancel()
return nd.ipfsNode.Close()
}
// Name returns "ipfs" as name of the backend.
func (nd *Node) Name() string {
return "ipfs"
}