summaryrefslogtreecommitdiffstats
path: root/BUILD.md
blob: 83f7e9945ed4370009a0aae3759e74964d0e257a (plain)
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
<!--
title: "The build system"
custom_edit_url: https://github.com/netdata/netdata/edit/master/BUILD.md
-->

# The build system

We are currently migrating from `autotools` to `CMake` as a build-system. This document 
currently describes how we intend to perform this migration, and will be updated after
the migration to explain how the new `CMake` configuration works.

## Stages during the build

1. The `netdata-installer.sh`, take in arguments and environment settings to control the
   build.
2. The configure step: `autoreconf -ivf ; ./configure` passing arguments into the configure
   script. This becomes `generation-time` in CMake. This includes package / system detection
   and configuration resulting in the `config.h` in the source root.
3. The build step: recurse through the generated Makefiles and build the executable.
4. The first install step: calls `make install` to handle all the install steps put into
   the Makefiles by the configure step (puts binaries / libraries / config into target
   tree structure).
5. The second install step: the rest of the installer after the make install handles
   system-level configuration (privilege setting, user / groups,  fetch/build/install `go.d`
   plugins, telemetry, installing service for startup, uninstaller, auto-updates.

The ideal migration result is to replace all of this with the following steps:
```
mkdir build ; cd build ; cmake .. -D... ; cmake --build . --target install
```

The `-D...` indicates where the command-line arguments for configuration are passed into
`CMake`.

## CMake generation time

At generation time we need to solve the following issues:

### Feature flags

Every command-line switch on the installer and the configure script needs to becomes an
argument to the CMake generation, we can do this with variables in the CMake cache:

CMakeLists.txt:
```
option(ENABLE_DBENGINE "Enable the dbengine storage" ON)
...
if(${ENABLE_DBENGINE})
...
endif()
```

Command-line interface
```
cmake -DENABLE_DBENGINE
```

### Dependency detection

We have a mixture of soft- and hard-dependencies on libraries. For most of these we expect
`pkg-config` information, for some we manually probe for libraries and include files. We
should treat all of the external dependencies consistently:

1. Default to autodetect using `pkg-config` (e.g. the standard `jemalloc` drops a `.pc`
   into the system but we do not check for it.
2. If no `.pc` is found perform a manual search for libraries under known names, and
   check for accessible symbols inside them.
3. Check that include paths work.
4. Allow a command-line override (e.g. `-DWITH_JEMALLOC=/...`).
5. If none of the above work then fail the install if the dependency is hard, otherwise
   indicate it is not present in the `config.h`.

Before doing any dependency detection we need to determine which search paths are 
really in use for the current compiler, after the `project` declaration we can use:
```
execute_process(COMMAND ${CMAKE_C_COMPILER} "--print-search-dirs"
                COMMAND grep "^libraries:"
                COMMAND sed "s/^libraries: =//"
                COMMAND tr ":" " "
                COMMAND tr -d "\n"
                OUTPUT_VARIABLE CC_SEARCH_DIRS
                RESULTS_VARIABLE CC_SEARCH_RES)
string(REGEX MATCH   "^[0-9]+" CC_SEARCH_RES ${CC_SEARCH_RES})
#string(STRIP "${CC_SEARCH_RES}" CC_SEARCH_RES)
if(0 LESS ${CC_SEARCH_RES})
    message(STATUS "Warning - cannot determine standard compiler library paths")
    # Note: we will probably need a different method for Windows...
endif()

```

The output format for this switch works on both `Clang` and `gcc`, it also includes
the include search path, which can be extracted in a similar way. Standard advice here
is to list the `ldconfig` cache or use the `-V` flag to check, but this does not work
consistently across platforms - in particular `gcc` will reconfigure `ld` when it is
called to gcc's internal view of search paths. During experiments each of these 
alternative missed / added unused paths. Dumping the compiler's own estimate of the
search paths seems to work consistently across clang/gcc/linux/freebsd configurations.

The default behaviour in CMake is to search across predefined paths (e.g. `CMAKE_LIBRARY_PATH`)
that are based on heuristics about the current platform. Most projects using CMake seem
to overwrite this with their own estimates.

We can use the extracted paths as a base, add our own heuristics based on OS and then
`set(CMAKE_LIBRARY_PATH ${OUR_OWN_LIB_SEARCH})` to get the best results. Roughly we do
the following for each external dependency:
```
set(WITH_JSONC "Detect" CACHE STRING "Manually set the path to a json-c installation")
...
if(${WITH_JSONC} STREQUAL "Detect")
    pkg_check_modules(JSONC json-c)     # Don't set the REQUIRED flag
    if(JSONC_FOUND)
        message(STATUS "libjsonc found through .pc -> ${JSONC_CFLAGS_OTHER} ${JSONC_LIBRARIES}")
        # ... setup using JSONC_CFLAGS_OTHER JSONC_LIBRARIES and JSONC_INCLUDE_DIRS
    else()
        find_library(LIB_JSONC
                     NAMES json-c libjson-c
                     PATHS ${CMAKE_LIBRARY_PATH})       # Includes our additions by this point
        if(${LIB_JSONC} STREQUAL "LIB_JSONC-NOTFOUND")
            message(STATUS "Library json-c not installed, disabling")
        else()
            check_library_exists(${LIB_JSONC} json_object_get_type "" HAVE_JSONC)
            # ... setup using heuristics for CFLAGS and check include files are available
        endif()
    endif()
else()
    # ... use explicit path as base to check for library and includes ...
endif()

```

For checking the include path we have two options, if we overwrite the `CMAKE_`... variables
to change the internal search path we can use:
```
CHECK_INCLUDE_FILE(json/json.h HAVE_JSONC_H)
```
Or we can build a custom search path and then use:
```
find_file(HAVE_JSONC_H json/json.h PATHS ${OUR_INCLUDE_PATHS})
```

Note: we may have cases where there is no `.pc` but we have access to a `.cmake` (e.g. AWS SDK, mongodb,cmocka) - these need to be checked / pulled inside the repo while building a prototype.

### Compiler compatibility checks

In CMakeLists.txt:

```
CHECK_INCLUDE_FILE(sys/prctl.h HAVE_PRCTL_H)
configure_file(cmake/config.in config.h)
```

In cmake/config.in:

```
#cmakedefine HAVE_PRCTL_H 1
```

If we want to check explicitly if something compiles (e.g. the accept4 check, or the 
`strerror_r` typing issue) then we set the `CMAKE_`... paths and then use:
```
check_c_source_compiles(
    "
    #include <string.h>
    int main() { char x = *strerror_r(0, &x, sizeof(x)); return 0; }
    "
    STRERROR_R_CHAR_P)

```
This produces a bool that we can use inside CMake or propagate into the `config.h`.

We can handle the atomic checks with:
```
check_c_source_compiles(
    "
    int main (int argc, char **argv)
    {
      volatile unsigned long ul1 = 1, ul2 = 0, ul3 = 2;
      __atomic_load_n(&ul1, __ATOMIC_SEQ_CST);
      __atomic_compare_exchange(&ul1, &ul2, &ul3, 1, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST);
      __atomic_fetch_add(&ul1, 1, __ATOMIC_SEQ_CST);
      __atomic_fetch_sub(&ul3, 1, __ATOMIC_SEQ_CST);
      __atomic_or_fetch(&ul1, ul2, __ATOMIC_SEQ_CST);
      __atomic_and_fetch(&ul1, ul2, __ATOMIC_SEQ_CST);
      volatile unsigned long long ull1 = 1, ull2 = 0, ull3 = 2;
      __atomic_load_n(&ull1, __ATOMIC_SEQ_CST);
      __atomic_compare_exchange(&ull1, &ull2, &ull3, 1, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST);
      __atomic_fetch_add(&ull1, 1, __ATOMIC_SEQ_CST);
      __atomic_fetch_sub(&ull3, 1, __ATOMIC_SEQ_CST);
      __atomic_or_fetch(&ull1, ull2, __ATOMIC_SEQ_CST);
      __atomic_and_fetch(&ull1, ull2, __ATOMIC_SEQ_CST);
      return 0;
    }
    "
    HAVE_C__ATOMIC)
```

For the specific problem of getting the correct type signature in log.c for the `strerror_r`
calls we can replicate what we have now, or we can delete this code completely and use a 
better solution that is documented [here](http://www.club.cc.cmu.edu/~cmccabe/blog_strerror.html).
To replicate what we have now:
```
check_c_source_compiles(
    "
    #include <string.h>
    int main() { char x = *strerror_r(0, &x, sizeof(x)); return 0; }
    "
    STRERROR_R_CHAR_P)

check_c_source_compiles(
    "
    #include <string.h>
    int main() { int x = strerror_r(0, &x, sizeof(x)); return 0; }
    "
    STRERROR_R_INT)

if("${STRERROR_R_CHAR_P}" OR "${STRERROR_R_INT}")
    set(HAVE_DECL_STRERROR_R 1)
endif()
message(STATUS "Result was ${HAVE_DECL_STRERROR_R}")

```

Note: I did not find an explicit way to select compiler when both `clang` and `gcc` are
present. We might have an implicit way (like redirecting `cc`) but we should put one in.



### Debugging problems in test compilations

Test compilations attempt to feed a test-input into the targeted compiler and result
in a yes/no decision, this is similar to `AC_LANG_SOURCE(.... if test $ac_...` in .`m4`.
We have two techniques to use in CMake:
```
cmake_minimum_required(VERSION 3.1.0)
include(CheckCCompilerFlag)
project(empty C)

check_c_source_compiles(
    "
    #include <string.h>
    int main() { char x = *strerror_r(0, &x, sizeof(x)); return 0; }
    "
    STRERROR_R_CHAR_P)

try_compile(HAVE_JEMALLOC ${CMAKE_CURRENT_BINARY_DIR}
            ${CMAKE_CURRENT_SOURCE_DIR}/quickdemo.c
            LINK_LIBRARIES jemalloc)
```

The `check_c_source_compiles` is light-weight:

* Inline source for the test, easy to follow.
* Build errors are reported in `CMakeFiles/CMakeErrors.log`

But we cannot alter the include-paths / library-paths / compiler-flags specifically for
the test without overwriting the current CMake settings. The alternative approach is
slightly more heavy-weight:

* Can't inline source for `try_compile` - it requires a `.c` file in the tree.
* Build errors are not shown, the recovery process for them is somewhat difficult.

```
rm -rf * && cmake .. --debug-trycompile
grep jemal CMakeFiles/CMakeTmp/CMakeFiles/*dir/*
cd CMakeFiles/CMakeTmp/CMakeFiles/cmTC_d6f0e.dir  # for example
cmake --build ../..
```

This implies that we can do this to diagnose problems / develop test-programs, but we
have to make them *bullet-proof* as we cannot expose this to end-users. This means that
the results of the compilation must be *crisp* - exactly yes/no if the feature we are
testing is supported.

### System configuration checks

For any system configuration checks that fall outside of the above scope (includes, libraries,
packages, test-compilation checks) we have a fall-back that we can use to glue any holes
that we need, e.g. to pull out the packaging strings, inside the `CMakeLists.h`:
```
execute_process(COMMAND cat ${CMAKE_CURRENT_SOURCE_DIR}/packaging/version
                COMMAND tr -d '\n'
                OUTPUT_VARIABLE VERSION_FROM_FILE)
message(STATUS "Packaging version ${VERSION_FROM_FILE}")
```
and this in the `config.h.in`:
```
#define VERSION_FROM_FILE "@VERSION_FROM_FILE@"
```

## CMake build time

We have a working definition of the targets that is in use with CLion and works on modern
CMake (3.15). It breaks on older CMake version (e.g. 3.7) with an error message (issue#7091).
No PoC yet to fix this, but it looks like changing the target properties should do it (in the
worst case we can drop the separate object completely and merge the sources directly into
the final target).

Steps needed for building a prototype:

1. Pick a reasonable configuration.
2. Use the PoC techniques above to do a full generation of `CMAKE_` variables in the cache
   according to the feature options and dependencies.
3. Push these into the project variables.
4. Work on it until the build succeeds in at least one known configuration.
5. Smoke-test that the output is valid (i.e. the executable loads and runs, and we can
   access the dashboard).
6. Do a full comparison of the `config.h` generated by autotools against the CMake version
   and document / fix any deviations.

## CMake install target

I've only looked at this superficially as we do not have a prototype yet, but each of the
first-stage install steps (in `make install`) and the second-stage (in `netdata-installer.sh`)
look feasible.

## General issues

*   We need to choose a minimum CMake version that is an available package across all of our
    supported environments. There is currently a build issue #7091 that documents a problem 
    in the compilation phase (we cannot link in libnetdata as an object on old CMake versions
    and need to find a different way to express this).

*   The default variable-expansion / comparisons in CMake are awkward, we need this to make it
    sane:
    ```
    cmake_policy(SET CMP0054 "NEW")
    ```
*   Default paths for libs / includes are not comprehensive on most environments, we still need
    some heuristics for common locations, e.g. `/usr/local` on FreeBSD.

# Recommendations

We should follow these steps:

1. Build a prototype.
2. Build a test-environment to check the prototype against environments / configurations that
   the team uses.
3. Perform an "internal" release - merge the new CMake into master, but not announce it or 
   offer to support it.
4. Check it works for the team internally.
5. Do a soft-release: offer it externally as a replacement option for autotools.
6. Gather feedback and usage reports on a wider range of configurations.
7. Do a hard-release: switch over the preferred build-system in the installation instructions.
8. Gather feedback and usage reports on a wider range of configurations (again).
9. Deprecate / remove the autotools build-system completely (so that we can support a single
   build-system).

Some smaller miscellaneous suggestions:

1. Remove the `_Generic` / `strerror_r` config to make the system simpler (use the technique
   on the blog post to make the standard version re-entrant so that it is thread-safe).
2. Pull in jemalloc by source into the repo if it is our preferred malloc implementation.

# Background

* [Stack overflow starting point](https://stackoverflow.com/questions/7132862/how-do-i-convert-an-autotools-project-to-a-cmake-project#7680240)
* [CMake wiki including previous autotools conversions](https://gitlab.kitware.com/cmake/community/wikis/Home)
* [Commands section in old CMake docs](https://cmake.org/cmake/help/v2.8.8/cmake.html#section_Commands)
* [try_compile in newer CMake docs](https://cmake.org/cmake/help/v3.7/command/try_compile.html)
* [configure_file in newer CMake docs](https://cmake.org/cmake/help/v3.7/command/configure_file.html?highlight=configure_file)
* [header checks in CMake](https://stackoverflow.com/questions/647892/how-to-check-header-files-and-library-functions-in-cmake-like-it-is-done-in-auto)
* [how to write platform checks](https://gitlab.kitware.com/cmake/community/wikis/doc/tutorials/How-To-Write-Platform-Checks)
1240'>1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770