client.go 15.9 KB
Newer Older
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
1
// Copyright (C) 2017-2021  Nexedi SA and Contributors.
2
//                          Kirill Smelkov <kirr@nexedi.com>
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
3 4 5 6 7 8
//
// This program is free software: you can Use, Study, Modify and Redistribute
// it under the terms of the GNU General Public License version 3, or (at your
// option) any later version, as published by the Free Software Foundation.
//
// You can also Link and Combine this program with other software covered by
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
9 10 11 12
// the terms of any of the Free Software licenses or any of the Open Source
// Initiative approved licenses and Convey the resulting work. Corresponding
// source of such a combination shall include the source code for all other
// software used.
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
13 14 15 16 17
//
// This program is distributed WITHOUT ANY WARRANTY; without even the implied
// warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
//
// See COPYING file for full licensing terms.
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
18
// See https://www.nexedi.com/licensing for rationale and options.
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
19

20
package neo
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
21
// client node with ZODB storage interface for accessing NEO cluster.
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
22 23

import (
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
24
	"context"
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
25
	"fmt"
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
26
	"math/rand"
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
27
	"net/url"
28
	"os"
29
	"strconv"
30
	"strings"
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
31
	"sync"
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
32

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
33
	"github.com/golang/glog"
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
34
	"github.com/pkg/errors"
35
	"lab.nexedi.com/kirr/go123/mem"
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
36
	"lab.nexedi.com/kirr/go123/xerr"
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
37
	"lab.nexedi.com/kirr/go123/xcontext"
38
	"lab.nexedi.com/kirr/go123/xnet"
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
39
	"lab.nexedi.com/kirr/go123/xsync"
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
40

41
	"lab.nexedi.com/kirr/neo/go/internal/log"
Kirill Smelkov's avatar
Kirill Smelkov committed
42
	"lab.nexedi.com/kirr/neo/go/internal/task"
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
43
	taskctx "lab.nexedi.com/kirr/neo/go/internal/xcontext/task"
Kirill Smelkov's avatar
Kirill Smelkov committed
44
	"lab.nexedi.com/kirr/neo/go/internal/xurl"
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
45
	"lab.nexedi.com/kirr/neo/go/internal/xzlib"
Kirill Smelkov's avatar
Kirill Smelkov committed
46
	"lab.nexedi.com/kirr/neo/go/internal/xzodb"
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
47
	"lab.nexedi.com/kirr/neo/go/neo/internal/xsha1"
48
	"lab.nexedi.com/kirr/neo/go/neo/neonet"
49
	"lab.nexedi.com/kirr/neo/go/neo/proto"
50
	"lab.nexedi.com/kirr/neo/go/neo/xneo"
51
	"lab.nexedi.com/kirr/neo/go/zodb"
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
52 53
)

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
54
// Client is NEO node that talks to NEO cluster and exposes access to it via ZODB interfaces.
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
55
type Client struct {
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
56
	node *_MasteredNode
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
57

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
58
	// Run is run under:
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
59
	runWG     *xsync.WorkGroup
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
60
	runCancel func()
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
61

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
62
	// driver client <- watcher: database commits | errors.
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
63 64
	watchq chan<- zodb.Event
	head   zodb.Tid          // last invalidation received from server
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
65
	head0  zodb.Tid          // .head state on start of every (re)connection to master
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
66 67 68 69 70

	at0Mu          sync.Mutex
	at0            zodb.Tid            // at0 obtained when initially connecting to server
	eventq0        []*zodb.EventCommit // buffer for initial messages, until .at0 is initialized
	at0Initialized bool                // true after .at0 is initialized
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
71
	at0Ready       chan(struct{})      // ready after .at0 is initialized
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
72

73 74 75
	closeOnce sync.Once
	closed    chan struct{} // ready when Closed

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
76
	ownNet bool // true if Client "owns" networker and should release it on Close
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
77 78
}

79
var _ zodb.IStorageDriver = (*Client)(nil)
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
80

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
81
// NewClient creates new client node.
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
82
//
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
83
// It will connect to master @masterAddr and identify with specified cluster name.
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
84
// Use Run to actually start running the node.
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
85
func NewClient(clusterName, masterAddr string, net xnet.Networker) *Client {
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
86
	c := &Client{
87
		node:     newMasteredNode(proto.CLIENT, clusterName, net, masterAddr),
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
88
		at0Ready: make(chan struct{}),
89
		closed:   make(chan struct{}),
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
90
	}
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
91 92 93 94 95

	var runCtx context.Context
	runCtx, c.runCancel = context.WithCancel(context.Background())
	c.runWG = xsync.NewWorkGroup(runCtx)
	return c
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
96
}
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
97

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
98 99
// Close implements zodb.IStorageDriver.
func (c *Client) Close() (err error) {
100 101 102
	c.closeOnce.Do(func() {
		close(c.closed)
	})
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
103 104 105 106 107 108 109 110
	c.runCancel()
	err = c.runWG.Wait()
	if errors.Is(err, context.Canceled) {
		err = nil // we canceled it
	}

	// close networker if configured to do so
	if c.ownNet {
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
111 112
		__ := c.node.Net.Close()
		err = xerr.First(err, __)
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
113 114 115 116
	}
	return err
}

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
117
// Run starts client node and runs it until either ctx is canceled or master
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
118
// commands it to shutdown.
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
119
func (c *Client) Run(ctx context.Context) (err error) {
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
120
	ctx, cancel := context.WithCancel(ctx)
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
121 122
	c.runCancel = cancel

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
123
	c.runWG.Go(func(runCtx context.Context) error {
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
124
		ctx, cancel := xcontext.Merge/*Cancel*/(ctx, runCtx)
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
125
		defer cancel()
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
126

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
127
		return c.node.TalkMaster(ctx, func(ctx context.Context, mlink *_MasterLink) error {
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
128 129 130 131 132
			c.head0 = c.head
			wg := xsync.NewWorkGroup(ctx)

			// launch master notifications receiver
			wg.Go(func(ctx context.Context) error {
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
133
				return c.recvMaster(ctx, mlink)
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
134
			})
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
135

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
136
			// sync lastTid with master
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
137
			// TODO better change protocol for master to send us head right after accept
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
138 139 140 141 142 143 144
			// channel right after identification.
			wg.Go(func(ctx context.Context) error {
				return c.syncMaster(ctx, mlink)
			})

			return wg.Wait()
		})
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
145 146
	})

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
147
	return c.runWG.Wait()
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
148 149
}

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
150
// recvMaster receives and handles notifications from master.
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
151
func (c *Client) recvMaster(ctx context.Context, mlink *_MasterLink) (err error) {
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
152
	defer task.Running(&ctx, "rx")(&err)
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
153

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
154
	for {
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
155
		req, err := mlink.Recv1(ctx)
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
156
		if err != nil {
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
157
			return err
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
158
		}
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
159

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
160
		err = c.recvMaster1(req.Msg)
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
161
		req.Close()
162 163 164 165 166
		if err != nil {
			return err
		}
	}
}
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
167

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
168
// recvMaster1 handles 1 message from master.
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
169 170
func (c *Client) recvMaster1(msg proto.Msg) error {
	switch msg := msg.(type) {
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
171 172 173
	// <- committed txn
	case *proto.InvalidateObjects:
		return c.invalidateObjects(msg)
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
174 175
	default:
		return fmt.Errorf("unexpected message: %T", msg)
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
176
	}
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
177 178
}

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
// invalidateObjects is called by recvMaster1 on receiving invalidateObjects notification.
func (c *Client) invalidateObjects(msg *proto.InvalidateObjects) error {
	tid := msg.Tid

	// likely no need to verify for tid↑ because IStorage watcher does it.
	// However until .at0 is initialized we do not send events to IStorage,
	// so double check for monotonicity here as well.
	if tid <= c.head {
		return fmt.Errorf("bad invalidation from master: tid not ↑: %s -> %s", c.head, tid)
	}
	c.head = tid

	if c.watchq == nil {
		return nil
	}

	// invalidation event received and we have to send it to .watchq
	event := &zodb.EventCommit{Tid: tid, Changev: msg.OidList}

	c.at0Mu.Lock()
	defer c.at0Mu.Unlock()

	// queue initial events until .at0 is initialized after register
202
	// queued events will be sent to watchq by syncMaster after initializing .at0
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
203 204 205 206 207 208 209
	if !c.at0Initialized {
		c.eventq0 = append(c.eventq0, event)
		return nil
	}

	// at0 is initialized - ok to send current event if it goes > at0
	if tid > c.at0 {
210 211 212 213 214 215 216
		select {
		case <-c.closed:
			// closed - client does not read watchq anymore

		case c.watchq <- event:
			// ok
		}
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
217 218 219 220
	}
	return nil
}

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
221
// syncMaster asks M for DB head right after identification.
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
222
func (c *Client) syncMaster(ctx context.Context, mlink *_MasterLink) (err error) {
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
223
	defer task.Running(&ctx, "sync0")(&err) // TODO try to unify with Sync
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
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 252 253 254 255 256 257 258

	// query last_tid
	lastTxn := proto.AnswerLastTransaction{}
	err = mlink.Ask1(&proto.LastTransaction{}, &lastTxn)
	if err != nil {
		return err
	}

	if c.at0Initialized {
		if lastTxn.Tid != c.head0 {
			return fmt.Errorf("new transactions were committed while we were disconnected from master (%s -> %s)", c.head0, lastTxn.Tid)
		}
	} else {
		// since we read lastTid, in separate protocol exchange there is a
		// chance, that by the time when lastTid was read, some new transactions
		// were committed. This way lastTid will be > than some first
		// transactions received by watcher via "invalidateObjects" server
		// notification.
		//
		// filter-out first < at0 messages for this reason.
		//
		// TODO change NEO protocol so that when C connects to M, M sends it
		// current head and guarantees to send only followup invalidation
		// updates.
		c.at0Mu.Lock()
		c.at0 = lastTxn.Tid
		c.at0Initialized = true
		c.flushEventq0()
		c.at0Mu.Unlock()
		close(c.at0Ready)
	}

	return nil
}

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
259 260 261 262 263 264 265 266 267
// flushEventq0 flushes events queued in c.eventq0.
// must be called under .at0Mu
func (c *Client) flushEventq0() {
	if !c.at0Initialized {
		panic("flush, but .at0 not yet initialized")
	}
	if c.watchq != nil {
		for _, e := range c.eventq0 {
			if e.Tid > c.at0 {
268 269 270 271 272 273 274
				select {
				case <-c.closed:
					// closed - client does not read watchq anymore

				case c.watchq <- e:
					// ok
				}
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
275 276 277 278 279 280 281
			}
		}
	}
	c.eventq0 = nil
}


Kirill Smelkov's avatar
.  
Kirill Smelkov committed
282 283
// --- user API calls ---

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
284
// Sync implements zodb.IStorageDriver.
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
285
func (c *Client) Sync(ctx context.Context) (head zodb.Tid, err error) {
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
286
	ctx = taskctx.Runningf(ctx, "%s: zsync", c.node.MyInfo.NID) // XXX mynid locking
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
287 288 289 290
	if glog.V(2) {
		task.TraceBegin(ctx)
		defer func() { task.TraceEnd(ctx, err) }()
	}
291 292
	defer func() {
		if err != nil {
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
293
			err = &zodb.OpError{URL: c.URL(), Op: "sync", Args: nil, Err: err}
294 295
		}
	}()
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
296

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
297
	err = c.node.WithOperational(ctx, func(mlink *neonet.NodeLink, _ *xneo.ClusterState) error {
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
298 299 300
		// XXX mlink can become down while we are making the call.
		// XXX do we want to return error or retry?
		reply := proto.AnswerLastTransaction{}
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
301
		err = mlink.Ask1(&proto.LastTransaction{}, &reply) // XXX ctx cancel
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
302
		if err != nil {
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
303
			return err // NOTE no need for ZODBErrDecode
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
304 305 306 307 308
		}
		head = reply.Tid
		return nil
	})
	return
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
309 310
}

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
311
// Load implements zodb.IStorageDriver.
312
func (c *Client) Load(ctx context.Context, xid zodb.Xid) (buf *mem.Buf, serial zodb.Tid, err error) {
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
313
	ctx = taskctx.Runningf(ctx, "%s: zload %s", c.node.MyInfo.NID, xid) // XXX mynid locking
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
314 315 316 317
	if glog.V(2) {
		task.TraceBegin(ctx)
		defer func() { task.TraceEnd(ctx, err) }()
	}
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
318 319 320 321 322
	defer func() {
		if err != nil {
			err = &zodb.OpError{URL: c.URL(), Op: "load", Args: xid, Err: err}
		}
	}()
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
323

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
324
	// Retrieve storages we might need to access.
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
325
	storv := make([]*xneo.PeerNode, 0, 1)
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
326
	err = c.node.WithOperational(ctx, func(mlink *neonet.NodeLink, cs *xneo.ClusterState) error {
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
		for _, cell := range cs.PartTab.Get(xid.Oid) {
			if cell.Readable() {
				stor := cs.NodeTab.Get(cell.NID)
				// this storage might not yet come up
				if stor != nil && stor.State == proto.RUNNING {
					storv = append(storv, stor)
				}
			}
		}
		return nil
	})
	if err != nil {
		return nil, 0, err
	}

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
342
	if len(storv) == 0 {
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
343
		// XXX add our Bugf which always forces +v (traceback) on such error print ?
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
344
		return nil, 0, errors.Errorf("internal inconsistency: cluster is operational, but no storages alive for oid %s", xid.Oid)
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
345
	}
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
346

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
347 348 349
	// TODO pick up 3 random storages and send load requests to them all,
	// getting the first who is the fastest to reply; retry from the
	// beginning if all are found to fail.
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
350
	stor := storv[rand.Intn(len(storv))]
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
351

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
352
	slink, err := stor.Dial(ctx)
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
353
	if err != nil {
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
354
		return nil, 0, err
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
355
	}
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
356 357
	// close accept after dialed (not to deadlock if S decides to send us
	// something).
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
358
	slink.CloseAccept() // NOTE need to close only after first real dial
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
359

360
	// on the wire it comes as "before", not "at"
361
	req := proto.GetObject{
362
		Oid:    xid.Oid,
Kirill Smelkov's avatar
Kirill Smelkov committed
363
		Before: xzodb.At2Before(xid.At),
364
		At:     proto.INVALID_TID,
365 366
	}

367
	resp := proto.AnswerObject{}
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
368
	err = slink.Ask1(&req, &resp)
369
	if err != nil {
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
370 371 372
		if e, ok := err.(*proto.Error); ok {
			err = proto.ZODBErrDecode(e)
		}
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
373
		return nil, 0, err
374 375
	}

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
376
	buf = resp.Data
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
377

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
378
	if !xsha1.Skip {
379
		checksum := xsha1.NEOSum(buf.Data)
380 381 382 383
		if checksum != resp.Checksum {
			return nil, 0, fmt.Errorf("data corrupt: checksum mismatch")
		}
	}
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
384

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
385
	if resp.Compression {
386 387
		buf2 := &mem.Buf{Data: nil}
		udata, err := xzlib.Decompress(buf.Data)
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
388
		buf.Release()
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
389
		if err != nil {
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
390
			return nil, 0, fmt.Errorf("data corrupt: %s", err)
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
391
		}
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
392 393
		buf2.Data = udata
		buf = buf2
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
394
	}
395

396 397 398 399 400 401 402
	// deletion is returned as empty data
	// https://lab.nexedi.com/nexedi/neoppod/blob/c1c26894/neo/client/app.py#L464-471
	if len(buf.Data) == 0 {
		buf.Release()
		return nil, 0, &zodb.NoDataError{Oid: xid.Oid, DeletedAt: resp.Serial}
	}

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
403 404
	// reply.NextSerial
	// reply.DataSerial
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
405
	return buf, resp.Serial, nil
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
406 407
}

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
408
// Iterate implements zodb.IStorageDriver.
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
409
func (c *Client) Iterate(ctx context.Context, tidMin, tidMax zodb.Tid) zodb.ITxnIterator {
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
410
	// see notes in ../NOTES:"On iteration"
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
411 412
	panic("TODO")
}
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
413 414


415 416 417
// ---- ZODB open/url support ----


Kirill Smelkov's avatar
.  
Kirill Smelkov committed
418
func openClientByURL(ctx context.Context, u *url.URL, opt *zodb.DriverOptions) (_ zodb.IStorageDriver, _ zodb.Tid, err error) {
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
419
	defer task.Runningf(&ctx, "neo: open %s", u)(&err)
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
420

421
	urlinfo, err := parseURL(ctx, u, opt)
422 423 424 425
	if err != nil {
		return nil, zodb.InvalidTid, err
	}

426
	net, err := neonet.Join(ctx, urlinfo.netcfg)
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
427 428
	if err != nil {
		return nil, zodb.InvalidTid, err
Kirill Smelkov's avatar
Kirill Smelkov committed
429
	}
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
430

431
	c := NewClient(urlinfo.name, urlinfo.masterAddr, net)
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
432
	c.ownNet = true
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
433
	c.watchq = opt.Watchq
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
434 435 436 437 438
	defer func() {
		if err != nil {
			c.Close()
		}
	}()
439

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
440 441 442 443
	// start client node serve loop
	errq := make(chan error, 1)
	go func() {
		err := c.Run(context.Background()) // NOTE not ctx
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
444 445
		// Client.Close cancels talkMaster which makes Run to return
		// `client: talk master(M): context canceled`
446
		// do not propagate this error to ZODB-level user.
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
447 448 449
		if errors.Is(err, context.Canceled) {
			err = nil
		}
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
450

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
451 452 453 454
		// close .watchq after serve is over
		c.at0Mu.Lock()
		defer c.at0Mu.Unlock()
		if c.watchq != nil {
455 456 457 458 459 460 461 462
			if err != nil && /* already flushed .eventq0 */c.at0Initialized {
				select {
				case <-c.closed:
					// closed - client does not read watchq anymore

				case c.watchq <- &zodb.EventError{Err: err}:
					// ok
				}
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
463 464
			}
			close(c.watchq)
465
			c.watchq = nil // prevent flushEventq0 to send to closed chan
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
466
		}
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
467

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
468 469
		errq <- err
	}()
470

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
471 472 473 474 475 476 477 478
	select {
	case <-ctx.Done():
		return nil, zodb.InvalidTid, ctx.Err()
	case <-errq:
		return nil, zodb.InvalidTid, err
	case <-c.at0Ready:
		return c, c.at0, nil
	}
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
479 480
}

481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
// parseURL extracts information from a NEO URI and puts this information into
// a urlInfo and the DriverOptions. If anything fails within this process
// an error and nil are returned.
func parseURL(ctx context.Context, u *url.URL, opt *zodb.DriverOptions) (urlinfo urlInfo, err error) {
	// neo(s)://[credentials@]master1,master2,...,masterN/name?options

	var ssl bool
	switch u.Scheme {
	case "neo":  ssl = false
	case "neos": ssl = true
	default:     return nil, fmt.Errorf("invalid scheme")
	}

	cred := u.User.String()
	// ca=ca.crt;cert=my.crt;key=my.key
	cred = strings.ReplaceAll(cred, ";", "&") // ; is no longer in default separators set https://github.com/golang/go/issues/25192
	x, err := xurl.ParseQuery(cred)
	if err != nil {
		return nil, fmt.Errorf("credentials: %s", err)
	}
	// xpop pops k from credentials, defaulting to $NEO_<K> if envok.
	xpop := func(k string, envok bool) string {
		v, ok := x[k]
		if !ok && envok {
			v = os.Getenv("NEO_"+strings.ToUpper(k))
		}
		delete(x, k)
		return v
	}

	netcfg := neonet.Config{}
	netcfg.LoNode = xpop("lonode", false)

	if !ssl {
		if len(x) != 0 {
			return nil, fmt.Errorf("credentials can be specified only with neos:// scheme")
		}
	} else {
		netcfg.CA   = xpop("ca",   true)
		netcfg.Cert = xpop("cert", true)
		netcfg.Key  = xpop("key",  true)

		if len(x) != 0 {
			return nil, fmt.Errorf("invalid credentials: %v", x)
		}
	}

	name := u.Path
	name = strings.TrimPrefix(name, "/")
	if name == "" {
		return nil, fmt.Errorf("cluster name not specified")
	}

	q, err := xurl.ParseQuery(u.RawQuery)
	if err != nil {
		return nil, err
	}

539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559
	// mv readonly from URL => driver opts
	readOnly, ok := q["read-only"]
	if ok {
		delete(q, "read-only")
		r, err := strconv.ParseBool(readOnly)
		if err != nil {
			return NEOUrlInfo{}, err
		}
		opt.ReadOnly = r
	}

	// pop not yet used client options
	// (our neo client doesn't apply their effect yet)
	for _, k := range []string {"compress", "cache-size", "logfile"} {
		_, ok := q[k]
		if ok {
			delete(q, k)
			log.Warningf(ctx, "TODO client doesn't support option '%q' yet", k)
		}
	}

560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579
	if len(q) != 0 {
		return nil, fmt.Errorf("invalid query: %v", q)
	}

	if !opt.ReadOnly {
		return nil, fmt.Errorf("TODO write mode not implemented")
	}

    masterAddr := u.Host

    return urlInfo{masterAddr, name, netcfg}, nil
}

// urlInfo encapsulates data extracted from a NEO URI.
type urlInfo struct {
	masterAddr string
	name string
	netcfg neonet.Config
}

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
580
// URL implements zodb.IStorageDriver.
581 582
func (c *Client) URL() string {
	// XXX options if such were given to open are discarded
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
583
	//     (but we need to be able to construct URL if Client was created via NewClient directly)
584 585

	zurl := "neo"
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
586
	if strings.Contains(c.node.Net.Network(), "+tls") {
587 588
		zurl += "s"
	}
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
589
	zurl += fmt.Sprintf("://%s/%s", c.node.MasterAddr, c.node.ClusterName)
590
	return zurl
591 592
}

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
593
func init() {
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
594 595
	zodb.RegisterDriver("neo",  openClientByURL)
	zodb.RegisterDriver("neos", openClientByURL)
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
596
}