File: developer_guide.rst

package info (click to toggle)
receptor 1.5.5-2
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 2,772 kB
  • sloc: python: 1,643; makefile: 305; sh: 174
file content (392 lines) | stat: -rw-r--r-- 12,881 bytes parent folder | download | duplicates (2)
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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
.. _dev_guide:

===============
Developer guide
===============

Receptor is an open source project that lives at `ansible/receptor repository <https://github.com/ansible/receptor/>`

.. contents::
   :local:

See the :ref:`contributing:contributing` for more general details.

---------
Debugging
---------

^^^^^^^^^^^
Unix Socket
^^^^^^^^^^^
If you don't want to use receptorctl to control nodes, `socat <https://www.redhat.com/en/blog/getting-started-socat>` can be used to interact with unix sockets directly.

Example:

.. code-block:: bash

   echo -e '{"command": "work", "subcommand": "submit", "node": "execution", "worktype": "cat", }\n"Hi"' | socat - UNIX-CONNECT:/tmp/control.sock  

-------
Linters
-------

All code must pass a suite of Go linters.
There is a pre-commit yaml file in the Receptor repository that points to the linter suite.
It is strongly recommmended to install the pre-commit yaml so that the linters run locally on each commit.

.. code-block:: bash

    cd $HOME
    go get github.com/golangci/golangci-lint/cmd/golangci-lint
    pip install pre-commit
    cd receptor
    pre-commit install

See `Pre commit <https://pre-commit.com/>`_ and `Golangci-lint <https://golangci-lint.run/>`_ for more details on installing and using these tools.

-------
Testing
-------

^^^^^^^^^^^
Development
^^^^^^^^^^^

Write unit tests for new features or functionality.
Add/Update tests for bug fixes.

^^^^^^^
Mocking
^^^^^^^

We are using gomock to generate mocks for our unit tests. The mocks are living inside of a package under the real implementation, prefixed by ``mock_``. An example is the package mock_workceptor under pkg/workceptor.

In order to genenerate a mock for a particular file, run:

.. code-block:: bash

    mockgen -source=pkg/filename.go -destination=pkg/mock_pkg/mock_filename.go

For example, to create/update mocks for Workceptor, we can run:

.. code-block:: bash

    mockgen -source=pkg/workceptor/workceptor.go -destination=pkg/workceptor/mock_workceptor/workceptor.go

^^^^^^^^^^
Kubernetes
^^^^^^^^^^

Some of the tests require access to a Kubernetes cluster; these tests will load in the kubeconfig file located at ``$HOME/.kube/config``. One simple way to make these tests work is to start minikube locally before running ``make test``. See https://minikube.sigs.k8s.io/docs/start/ for more information about minikube.

To skip tests that depend on Kubernetes, set environment variable ``export SKIP_KUBE=1``.

^^^^^^^^^
Execution
^^^^^^^^^

Pull requests must pass a suite of unit and integration tests before being merged into ``devel``.

``make test`` will run the full test suite locally.

-----------
Source code
-----------

The following sections help orient developers to the Receptor code base and provide a starting point for understanding how Receptor works.

^^^^^^^^^^^^^^^^^^^^^
Parsing receptor.conf
^^^^^^^^^^^^^^^^^^^^^

Let's see how items in the config file are mapped to Golang internals.

As an example, in tcp.go

.. code-block:: go

    cmdline.RegisterConfigTypeForApp("receptor-backends",
      "tcp-peer", "Make an outbound backend connection to a TCP peer", TCPDialerCfg{}, cmdline.Section(backendSection))


"tcp-peer" is a top-level key (action item) in receptor.conf

.. code-block:: yaml

    tcp-peers:
      - address: localhost:2222

``RegisterConfigTypeForApp`` tells the cmdline parser that "tcp-peer" is mapped to the ``TCPDialerCfg{}`` structure.

``main()`` in ``receptor.go`` is the entry point for a running Receptor process.

In ``receptor.go`` (modified for clarity):

.. code-block:: go

    cl.ParseAndRun("receptor.conf", []string{"Init", "Prepare", "Run"})

A Receptor config file has many action items, such as ```node``, ``work-command``, and ``tcp-peer``. ``ParseAndRun`` is how each of these items are instantiated when Receptor starts.

Specifically, ParseAndRun will run the Init, Prepare, and Run methods associated with each action item.

Here is the Prepare method for ``TCPDialerCfg``. By the time this code executes, the cfg structure has already been populated with the data provided in the config file.

.. code-block:: go

    // Prepare verifies the parameters are correct.
    func (cfg TCPDialerCfg) Prepare() error {
        if cfg.Cost <= 0.0 {
            return fmt.Errorf("connection cost must be positive")
        }

        return nil
    }

This simply does a check to make sure the provided Cost is valid.

The Run method for the ``TCPDialerCfg`` object:

.. code-block:: go

    // Run runs the action.
    func (cfg TCPDialerCfg) Run() error {
        logger.Debug("Running TCP peer connection %s\n", cfg.Address)
        host, _, err := net.SplitHostPort(cfg.Address)
        if err != nil {
            return err
        }
        tlscfg, err := netceptor.MainInstance.GetClientTLSConfig(cfg.TLS, host, "dns")
        if err != nil {
            return err
        }
        b, err := NewTCPDialer(cfg.Address, cfg.Redial, tlscfg)
        if err != nil {
            logger.Error("Error creating peer %s: %s\n", cfg.Address, err)

            return err
        }
        err = netceptor.MainInstance.AddBackend(b, cfg.Cost, nil)
        if err != nil {
            return err
        }

        return nil
    }

This gets a new TCP dialer object and passes it to the netceptor ``AddBackend`` method, so that it can be processed further.
``AddBackend`` will start proper Go routines that periodically dial the address defined in the TCP dialer structure, which will lead to a proper TCP connection to another Receptor node.

In general, when studying how the start up process works in Receptor, take a look at the ``Init``, ``Prepare``, and ``Run`` methods throughout the code, as these are the entry points to running those specific components of Receptor.

^^^^
Ping
^^^^

Studying how pings work in Receptor will provide a useful glimpse into the internal workings of netceptor -- the main component of Receptor that handles connections and data traffic over the mesh.

``receptorctl --socket /tmp/foo.sock ping bar``

The control-service on `foo` will receive this command and subsequently call the following,

**ping.go::ping**

.. code-block:: go

    func ping(nc *netceptor.Netceptor, target string, hopsToLive byte) (time.Duration, string, error) {
        pc, err := nc.ListenPacket("")

``target`` is the target node, "bar" in this case.

``nc.ListenPacket("")`` starts a new ephemeral service and returns a ``PacketConn`` object. This is a datagram connection that has a WriteTo() and ReadFrom() method for sending and receiving data to other nodes on the mesh.

**packetconn.go::ListenPacket**

.. code-block:: go

    pc := &PacketConn{
        s:            s,
        localService: service,
        recvChan:     make(chan *messageData),
        advertise:    false,
        adTags:       nil,
        connType:     ConnTypeDatagram,
        hopsToLive:   s.maxForwardingHops,
    }

    s.listenerRegistry[service] = pc

    return pc, nil

``s`` is the main netceptor object, and a reference to the PacketConn object is stored in netceptor's ``listenerRegistry`` map.


**ping.go::ping**

.. code-block:: go

    _, err = pc.WriteTo([]byte{}, nc.NewAddr(target, "ping"))

Sends an empty message to the address "bar:ping" on the mesh. Recall that nodes are analogous to DNS names, and services are like port numbers.

``WriteTo`` calls ``sendMessageWithHopsToLive``

**netceptor.go::sendMessageWithHopsToLive**

.. code-block:: go

    md := &messageData{
        FromNode:    s.nodeID,
        FromService: fromService,
        ToNode:      toNode,
        ToService:   toService,
        HopsToLive:  hopsToLive,
        Data:        data,
    }

    return s.handleMessageData(md)

Here the message is constructed with essential information such as the source node and service, and the destination node and service. The Data field contains the actual message, which is empty in this case.

``handleMessageData`` calls ``forwardMessage`` with the ``md`` object.

**netceptor.go::forwardMessage**

.. code-block:: go

    nextHop, ok := s.routingTable[md.ToNode]

The current node might not be directly connected to the target node, and thus netceptor needs to determine what is the next hop to pass the data to. ``s.routingTable`` is a map where the key is a destination ("bar"), and the value is the next hop along the path to that node. In a simple two-node setup with `foo` and `bar`, ``s.routingTable["bar"] == "bar"``.

**netceptor.go::forwardMessage**

.. code-block:: go

    c, ok := s.connections[nextHop]

    c.WriteChan <- message

``c`` here is a ``ConnInfo`` object, which interacts with the various backend connections (UDP, TCP, websockets).

``WriteChan`` is a golang channel. Channels allows communication between separate threads (Go routines) running in the application. When `foo` and `bar` had first started, they established a backend connection. Each node runs the netceptor runProtocol go routine, which in turn starts a protoWriter go routine.

**netceptor.go::protoWriter**

.. code-block:: go

    case message, more := <-ci.WriteChan:
      err := sess.Send(message)

So before the "ping" command was issued, this protoWriter Go routine was already running and waiting to read messages from WriteChan.

``sess`` is a BackendSession object. BackendSession is an abstraction over the various available backends. If `foo` and `bar` are connected via TCP, then ``sess.Send(message)`` will pass along data to the already established TCP session.

**tcp.go::Send**

.. code-block:: go

    func (ns *TCPSession) Send(data []byte) error {
        buf := ns.framer.SendData(data)
        n, err := ns.conn.Write(buf)

``ns.conn`` is net.Conn object, which is part of the Golang standard library.

At this point the message has left the node via a backend connection, where it will be received by `bar`.

Let's review the code from `bar`'s perspective and how it handles the incoming message that is targeting its "ping" service.

On the receiving side, the data will first be read here

**tcp.go::Recv**

.. code-block:: go

    n, err := ns.conn.Read(buf)

    ns.framer.RecvData(buf[:n])


Recv was called in protoReader Go routine, similar to the protoWriter when the message sent from `foo`.

Note that ``ns.conn.Read(buf)`` might not contain the full message, so the data is buffered until the ``messageReady()`` returns true. The size of the message is tagged in the message itself, so when Recv has received N bytes, and the message is N bytes, Recv will return.

**netceptor.go::protoReader**

.. code-block:: go

    buf, err := sess.Recv(1 * time.Second)
    ci.ReadChan <- buf

The data is passed to a ReadChan channel.

**netceptor.go::runProtocol**

.. code-block:: go

    case data := <-ci.ReadChan:

      message, err := s.translateDataToMessage(data)

      err = s.handleMessageData(message)

The data is read from the channel, and deserialized into an actual message format in ``translateDataToMessage``.

**netceptor.go::handleMessageData**

.. code-block:: go

    if md.ToNode == s.nodeID {
      handled, err := s.dispatchReservedService(md)

This checks whether the destination node indicated in the message is the current node. If so, the message can be dispatched to the service.

"ping" is a reserved service in the netceptor instance.

.. code-block:: go

    s.reservedServices = map[string]func(*messageData) error{
      "ping":    s.handlePing,
    }

**netceptor.go::handlePing**

.. code-block:: go

    func (s *Netceptor) handlePing(md *messageData) error {
        return s.sendMessage("ping", md.FromNode, md.FromService, []byte{})
    }

This is the ping reply handler. It sends an empty message to the FromNode (`foo`).

The FromService here is not "ping", but rather the ephemeral service that was created from ``ListenPacket("")`` in ping.go on `foo`.

With ``trace`` enabled in the Receptor configuration, the following log statements show the reply from ``bar``,

.. code-block:: bash

    TRACE --- Received data length 0 from foo:h73opPEh to bar:ping via foo
    TRACE --- Sending data length 0 from bar:ping to foo:h73opPEh

So the ephemeral service on `foo` is called h73opPEh (randomly generated string).


From here, the message from `bar` will passed along in a very similar fashion as the original ping message sent from `foo`.

Back on node `foo`, the message is received receive the message where it is finally handled in ping.go

**ping.go::ping**

.. code-block:: go

    _, addr, err := pc.ReadFrom(buf)

.. code-block:: go

    case replyChan <- fromNode:

.. code-block:: go

    case remote := <-replyChan:
      return time.Since(startTime), remote, nil

The data is read from the PacketConn object, written to a channel, where it is read later by the ping() function, and ping() returns with the roundtrip delay, ``time.Since(startTime)``.