1
0
mirror of https://github.com/ohwgiles/laminar.git synced 2026-10-14 15:11:36 +00:00

115 Commits
0.9 ... master

Author SHA1 Message Date
Wesley Hershberger
e62148b5f5 Fix buffer overflow in readEnvPipe
readEnvPipe writes a null terminator to buffer[sz] without a bounds
check; if a write was >1024 the write overflows the buffer.

Signed-off-by: Wesley Hershberger <wesley.hershberger@gmail.com>
2026-09-27 11:37:50 +13:00
Wesley Hershberger
d25b7a46bb Fix memory leak in handleBadgeRequest
Signed-off-by: Wesley Hershberger <wesley.hershberger@gmail.com>
2026-09-25 13:28:28 +12:00
Oliver Giles
23abdd2712 Update packaging scripts, support for armv7a and cmake < 4.3 2026-08-17 10:17:38 +12:00
Benoit
ffe473b082 Add sticky auto-scroll for build output
Implements #220 - if the page is scrolled to the very bottom while a
build log is streaming, the scroll position "sticks" there and follows
new output as it is rendered, like tail -f. Any upward scroll
disengages this behaviour, and scrolling back to the bottom re-engages
it, so no toggle button is needed.

The sticky state is tracked with wheel/scroll event listeners rather
than sampled from window.scrollY at render time, because scrolling is
handled outside the main thread: while the main thread is busy
rendering a large log chunk, window.scrollY may still report the old
(bottom) position, which would wrongly yank the page back down and
swallow the user's upward scroll.

AI-assisted implementation.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-25 07:56:31 +12:00
Oliver Giles
b1ae75e259 Minor modernizations
resolves #235
2026-07-06 08:31:33 +12:00
jarkad
3392b899b2 feat(pkg): add debian14-amd64 packaging script 2026-02-26 09:12:43 +13:00
Dmitry Shachnev
03c5aca663 Add underline dotted style for hyperlinks 2025-07-31 09:21:53 +12:00
Dmitry Shachnev
8206dc3735 Update ansi_up.js to a newer version
To get OSC 8 hyperlinks support.
2025-07-31 09:21:53 +12:00
feiloo
e7cb501689 opensuse leap rpm spec file (#227)
* add rpm package build script for opensuse leap 15.6

* add more fields to opensuse rpm spec file
2025-02-14 13:28:26 +13:00
Jakob Zahn
f2bd292398 Fix typo 2025-01-22 09:55:23 +13:00
Jakob Zahn
22742d9747 Add run directory to LAMINAR_HOME directory scheme 2025-01-22 09:55:23 +13:00
Jakob Zahn
c9faf3d1ae Thoughts on User Manual (#224)
* Change wording for official package availability
* Explicitly state laminar and user group to be in the system scope
* Expand hello-world-example for saving compiled binary in the archive
* Name variables consistently
* Quote bash variables
* Mention LAMINAR_REASON in the reference section again for completeness
* Add LAMINAR_HOME directory structure
* Reposition explanation for LAMINAR_REASON
* Change more variable names
* Rephrase reference section for LAMINAR_HOME directory scheme
* Refine description of permissions on files in LAMINAR_HOME
* Include `custom` directory in the description of permissions
* Reword instructions for upstream packages
* Fix  archive path being labelled as absolute
* Remove dollars from bash signatures
2025-01-10 11:13:47 +13:00
Hubert Lobit
9da39ed3f7 Fix version of libcapnp in pkg/debian12-amd64.sh
Debian 12 includes libcapnp-0.9.2, not libcapnp-1.0.1:

https://packages.debian.org/bookworm/libcapnp-0.9.2
2024-11-07 10:08:16 +13:00
Oliver Giles
cfa995f8b9 build from source: include make
Resolves #213
2024-08-16 13:05:03 +12:00
Oliver Giles
0a340f9b0b Debian bullseye -> bookworm 2024-08-16 13:04:38 +12:00
Benoit
d259dff604 Add pkg script for Ubuntu 24.04.
This adds a pkg script to build a deb package for Ubuntu 24.04.
2024-08-16 12:55:02 +12:00
Benoit
44aea1fc06 Update ansi-red by following base16-default-dark
base16-default-dark: https://base16.netlify.app/previews/base16-default-dark.html
2024-05-23 10:38:51 +12:00
Benoit
27d2a760fd Fix wrong ANSI red color in the CSS 2024-05-23 10:38:51 +12:00
Michael F. Lamb
fc6343bd19 add .deb package build scripts for debian 12 and 13 2024-05-01 10:04:23 +12:00
Benoit
736c95ff57 Fix mix of tabs/spaces
The bash code block to install packages were mixing spaces and tabs in
the breaking lines.

Removed tabs and spaces, to only use 2 spaces.

Also wrap at 80 characters.
2024-05-01 10:03:45 +12:00
Benoit
5ea394c610 Add pkg script for Ubuntu 22.04 2024-05-01 10:03:33 +12:00
Oliver Giles
8c3d7f62a9 cmake: fix install path of /etc/laminar.conf 2024-03-29 12:21:54 +13:00
Mike Swierczek
a1a95c8e7f README.md: add pkg-config
The project was updated to require
pkg-config for builds.
2024-02-27 12:48:28 +13:00
marian cingel
277a59f1cb Support Clang/LLVM build on FBSD
- Update CMakeList to support installation to PREFIX directory
- FreeBSD does not support abstract sockets (unix-abstract:laminar),
  so explicit 'LAMINAR_BIND_RPC=IP:port' is required
- ld.lld requires explicit emulation for binary blobs, add a new
  variable LINKER_EMULATION_FLAGS for this purpose
2023-11-07 09:17:52 +13:00
mapperr
97b9f6b1ae database: fix missing import 2023-10-25 10:01:35 +13:00
Ferenc Erki
d2c58f0bcd Fix author warning about cmake command order
CMake 3.26.0 introduced an author warning when the top-level project()
call precedes a cmake_minimum_required() call [1].

[1]: https://cmake.org/cmake/help/latest/release/3.26.html#other-changes
2023-07-24 08:27:46 +12:00
Oliver Giles
dab620b01e Http::cleanupPeers: check fulfiller is non-null
resolves #185
2023-03-17 09:51:51 +13:00
Jan-Benedict Glaw
1e7e9319c3 Have at least some minimal logging 2023-03-01 11:25:46 +13:00
Jan-Benedict Glaw
af4b51b3e9 Add a link from any run to its job 2023-03-01 11:25:10 +13:00
Dmitry Shachnev
458ec26943 Optimize query which is used on /jobs page
By replacing the primary key index and simplifying the query.
2023-02-08 15:01:58 +13:00
Lucki
6a20291dc4 Fix wrong example path extension 2023-01-27 20:30:22 +13:00
Oliver Giles
3cc01bc45d Better average line in Build time graph
The technique to display the average line in the old Chart.js
does not look so great in the new version. Take a different
approach using a plugin instead.
2022-11-18 19:47:59 +13:00
Guilherme Lima
e25b58944d Minor tweaks to charts appearance
Some charts had a more 'curvy' look to it. Adjusted this by using the
'tension' parameter.
Adjusted 'Utilization' pie chart aspect ratio so it is not so big.
2022-11-18 19:47:59 +13:00
Guilherme Lima
1be755e323 Update Chart.js to version 3.9
Fixes #175

Following 3.x Migration Guide, here is a list of the changes:

https://www.chartjs.org/docs/latest/getting-started/v3-migration.html#specific-changes
- Chart.scaleService was replaced with Chart.registry. Scale defaults are now in Chart.defaults.scales[type].
- scales.[x/y]Axes arrays were removed. Scales are now configured directly to options.scales object with the object key being the scale Id.
- scales.[x/y]Axes.barPercentage was moved to dataset option barPercentages
- scales.[x/y]Axes.barThickness was moved to dataset option barThickness
- scales.[x/y]Axes.scaleLabel was renamed to scales[id].title
- scales.[x/y]Axes.scaleLabel.labelString was renamed to scales[id].title.text
- scales.[x/y]Axes.ticks.userCallback was renamed to scales[id].ticks.callback
- tooltips namespace was renamed to tooltip to match the plugin name
- legend, title and tooltip namespaces were moved from options to options.plugins

https://www.chartjs.org/docs/latest/getting-started/v3-migration.html#defaults
- legend, title and tooltip namespaces were moved from Chart.defaults to Chart.defaults.plugins.
- elements.line.fill default changed from true to false

https://www.chartjs.org/docs/latest/getting-started/v3-migration.html#chart-types
- horizontalBar chart type was removed. Horizontal bar charts can be configured using the new indexAxis option

https://www.chartjs.org/docs/latest/getting-started/v3-migration.html#tooltip
- xLabel and yLabel were removed. Please use label and formattedValue
- The callbacks no longer are given a data parameter. The tooltip item parameter contains the chart and dataset instead
- The tooltip item's index parameter was renamed to dataIndex and value was renamed to formattedValue

https://www.chartjs.org/docs/latest/getting-started/v3-migration.html#ticks
- options.gridLines was renamed to options.gridLines
2022-11-18 19:47:59 +13:00
Oliver Giles
e9fc547a72 wallboard: correctly tag running build for css
also on page refresh, not just via SSE.
2022-09-03 19:54:10 +12:00
Oliver Giles
01183a3c25 wallboard: fix stuck page without filter query
if no filter param is provided, use a copy of the jobs array
to avoid an infinite sort loop in the frontend

resolves #174
2022-09-03 19:53:14 +12:00
Oliver Giles
e7defa9f15 fe: fix display of first run of job
if it is still running and is the first known of its
name to the frontend, special handling is needed
2022-09-03 19:51:29 +12:00
Dmitry Bogatov
99e2e62906 laminard: ignore SIGHUP
Many daemons reload config file on SIGHUP; laminar don't have config file, so
signal is ignored (with informative message on stdout). Previously, default
handler for SIGHUP was used that terminates process.

Closes: #166
2022-01-30 08:21:14 +13:00
Oliver Giles
261c08d2fe test: assert on >= 5 rather than strictly ==
due to process scheduling, we may even receive job_completed
messages before the test continues. The assert only needs to
check that there are enough messages to prevent invalid indexing.
This fixes a flakey test.
2022-01-28 19:44:40 +13:00
Oliver Giles
48c0e9340e pkg: move to debian 11 (bullseye) 2022-01-28 19:28:30 +13:00
Oliver Giles
7303e4d592 fe perf: insertAdjacentHTML is faster than innerHTML+= 2022-01-22 20:08:23 +13:00
Oliver Giles
23cb30fc0c fe perf: throttle log rendering
as a further enhancement to efafda16f, schedule a render immediately if
500ms have passed without one, and cap the max delay to 500ms.
This removes delay for short logs, and prevents an issue where output that
is produced reasonably quickly will not be rendered for a long time.
2022-01-22 20:07:23 +13:00
Oliver Giles
7eb19ce8c4 fe: fix home icon link under subdir
when hosting laminar under a subdir, href=/ will break out of
the application. Use href=. instead (relative to base href)
2022-01-22 15:18:43 +13:00
Oliver Giles
7c4e1108ae nginx example: trailing slash on proxy_pass argument
this causes nginx to substitute the location directive. Makes no
difference if hosted at toplevel, but if using a subdirectory,
omitting the trailing slash will prevent laminar's http server
from finding the resources.
2022-01-22 15:18:43 +13:00
Oliver Giles
5607a93cc1 manpage: fix synopsis queue/start/run 2022-01-22 15:18:43 +13:00
Oliver Giles
41ddd8fe4f allow adding job to front of queue
laminarc now supports {queue,start,run} --next to place the job at the
front of the queue instead of at the end.

resolves #162
2022-01-22 15:18:43 +13:00
Oliver Giles
e581a0cf5d tests: add setNumExecutors method 2022-01-22 15:18:43 +13:00
Oliver Giles
4a6f99a203 tests: reinstantiate laminar for each unit
reinstantiate Laminar and Server classes and clean the temporary
LAMINAR_HOME directory for each unit test via SetUp and TearDown.
2022-01-22 15:18:43 +13:00
Oliver Giles
efafda16ff improve frontend performance with large logs
frontend would furiously try to render as fast as it received data
chunks from the server. This causes a lot of extra load on the browser
renderer if the logs are large. Buffer and batch calls to rerender
to improve performance.

resolves #165
2022-01-01 21:30:38 +13:00
Oliver Giles
bb087b72ee Revert "make taskFailed non-fatal"
Originally reverted to prevent a crash when reading from an http
client raised ECONNRESET. Although this prevented a crash, laminar
stopped listening for http connections. That issue was resolved in
37bbf6ade4 (see #164), so make all exceptions fatal again.

This reverts commit 02810309fc.
2021-12-24 13:46:57 +13:00
Oliver Giles
37bbf6ade4 server: handle ECONNRESET in http connections
In real deployments, sometimes http connections break with ECONNRESET.
This causes the kj::HttpServer listener promise to break, which means
no more connections are accepted. Catch this exception and restart
the listener.

resolves #164
2021-12-24 13:46:54 +13:00
Oliver Giles
e1686d454b display run number for queued jobs
in the frontend and in laminarc queue/show-queued. This makes
it much easier to abort/unqueue runs which have not yet started.

resolves #155
2021-12-05 13:42:27 +13:00
Oliver Giles
549f49052a create unix sockets with 660 permissions
Realistically this is probably the permission mask you
want if you are using a unix socket for LAMINAR_BIND_RPC
or LAMINAR_BIND_HTTP.

resolves #160
2021-11-12 20:06:35 +13:00
Oliver Giles
d913d04c4a UserManual: correct Debian version name
resolves #163
2021-11-07 13:56:52 +13:00
Oliver Giles
78ceeec3e8 frontend: fix double-escaped link
do not escape links to downstream jobs generated with a private
ANSI CSI escape sequence, because the newer ansi_up escapes HTML.
Work around its dropping of unknown sequences, and have the link
use the Vue routing mechanism rather than a page reload.

resolves #161
2021-09-25 19:07:36 +12:00
Oliver Giles
ded13ed9fe docs: update references to current distro versions 2021-08-04 12:03:38 +12:00
Oliver Giles
15dbed4cac pkg: move centos8 to rocky8 2021-08-04 12:02:09 +12:00
Oliver Giles
e67e0bc453 examples: add git post-receive hook example 2021-07-30 19:59:13 +12:00
Oliver Giles
2de8b91ad2 examples: consistently omit extension for scripts 2021-07-30 19:58:44 +12:00
Oliver Giles
399f07cf3a add example config for nginx reverse proxy 2021-07-24 20:08:23 +12:00
Chl
2941a5abdd Fix typos and formulation in UserManual.md 2021-07-21 08:41:22 +12:00
Oliver Giles
a50514a135 frontend: better dynamic update of graphs
react to jobCompletion messages by updating graphs in
more cases so manual refresh is not necessary to see
most up to date representation.
2021-07-09 10:04:20 +12:00
Oliver Giles
60f7ee5402 make cmake 3.6 the minimum supported version
All packaged distros have this for a long time now.
2021-07-09 10:04:20 +12:00
Oliver Giles
7f1c293588 pkg: centos8 has cmake not cmake3 2021-07-09 10:04:20 +12:00
Starbeamrainbowlabs
fe4caa155b README: Use nproc to get cpu core count
This way, make will always use all the available cpu cores.
2021-06-24 11:05:12 +12:00
Oliver Giles
f3a6ba2f4b console log: improve color scheme
based on base16 default/bright palette
2021-06-11 15:41:16 +12:00
Oliver Giles
dff4c93e15 cmake: GTEST_LIBRARIES not GTEST_LIBRARY
Seems this used to be OK but now not always...
2021-06-09 20:39:01 +12:00
Oliver Giles
747ae3ada8 abort test: use "sleep inf" instead of "yes"
Sometimes yes can produce too much output too quickly and
overwhelm the host. It is not relevant to testing the abort
functionaliy.

resolves #143
2021-06-04 15:26:23 +12:00
Oliver Giles
9a5ccc70e3 add example script for docker builds 2021-06-04 10:12:59 +12:00
Oliver Giles
d01cf1c9b0 failure to remove rundir should not abort the jobrunner
kj::Directory::remove will throw if it fails to remove some files, e.g. in
case of insufficient permissions. Catch this and move right along.

resolves #156
2021-05-23 14:42:06 +12:00
Oliver Giles
02810309fc make taskFailed non-fatal
turns out we can end up here when an http client unexpectedly
drops the connection, so it must not cause an exit()
2021-05-03 09:18:06 +12:00
Oliver Giles
b16991b17a fix race in http log output
Creating of LogWatcher makes it automatically receive new log
chunks as it is part of logWatchers. But we cannot be sure that
stream->write().then() will have already completed, so there is
a chance that a null fulfiller will be caused, causing a crash.
We cannot defer the creation of the LogWatcher until after
stream->write() because in the meantime we may lose new messages,
so call writeLogChunk to make sure we have a fulfiller before
entering stream->write().

Also, pending chunks of log output were std::move()'d to the first
interested client in the loop, they need to be copied if there
is more than one client.
2021-03-19 21:11:22 +13:00
Paolo Greppi
c7c586167c use relative paths to support LAMINAR_BASE_URL option 2021-03-19 20:47:56 +13:00
Jan-Benedict Glaw
7e77ec1211 Allow subdirs in artifacts directory
Extend populateArtifacts() with a subdir parameter (default initialized to ".")
to allow for recursive calls. With subdirs encountered, call recursively.
2021-03-08 20:30:59 +13:00
Oliver Giles
9b8c3762ec fe: do not html entity encode angle braces
in log output, ansi_up does it already.

resolves #148
2021-03-07 21:02:42 +13:00
vrein
c42b6d4207 Pass reason and queuedAt to Home page 2021-02-22 08:53:05 +13:00
Oliver Giles
8df882b273 remove debug logging in app.js 2021-01-09 21:52:02 +13:00
Oliver Giles
14ea1f0f43 move ansi_up to latest version: 4.0.4
this is also the version in debian libjs-ansi-up
2021-01-09 21:51:12 +13:00
meskio
381fd8b55e Remove vue-router in the build process (#141) 2021-01-07 09:32:14 +13:00
Oliver Giles
9f969ae847 remove deprecated href to custom style.css 2021-01-02 21:26:50 +13:00
Oliver Giles
907f3926ce remove dependency on vue-router
only a small subset of vue-router is used, and integration is
complicated by each route having its own EventSource request.
Implementing the routing directly allows simplification of
the EventSource logic.

Another motivating factor is that the vue-router packages in
debian have been unreliable, making the dependence on vue-router
a hinderance for packaging laminar in debian.
2021-01-02 21:26:13 +13:00
meskio
c140fb51eb Add Documentation links to the systemd service (#139) 2020-12-09 07:51:10 +13:00
meskio
63bbb8a6e7 Fix errors on the man page (#138) 2020-12-09 07:50:37 +13:00
Alex Myczko
882978fa77 Update client.cpp (#137)
fix typo
2020-12-09 07:48:29 +13:00
Oliver Giles
1a5292f141 remove old trigger command
it has been deprecated for a while now
2020-12-05 13:55:11 +13:00
Oliver Giles
ec237f475e deprecate custom css
replaced by custom index html page
2020-12-05 13:54:35 +13:00
Oliver Giles
5e64844440 frontend: "builds" -> "runs"
use consistent naming
2020-12-05 13:52:40 +13:00
Oliver Giles
c274e321df fetch average runtime as double, not int
only makes a difference for very short jobs, but nice
to have more accurate graphs
2020-12-05 13:51:25 +13:00
Oliver Giles
e442652e0a rpm packaging: list man pages 2020-12-05 13:49:13 +13:00
Oliver Giles
212cfaf8ab UserManual: laminard env vars with docker
explain how laminard uses environment variables and
recommend how to set them when using docker

resolves #136
2020-12-05 13:24:12 +13:00
Oliver Giles
b755a2ef9e edit manpages and cmakeize them
so that they will be installed in the correct place as part of
a normal build or packaging process.
2020-11-27 21:25:48 +13:00
Dmitry Bogatov
cafd0ddaee Write and install manpage for laminarc 2020-11-25 13:36:34 +13:00
Dmitry Bogatov
69df17d7bf Write and install manpage for laminard 2020-11-25 13:35:25 +13:00
Oliver Giles
308d679ea4 update vue and vue-router
to 2.6.12 and 3.4.8 respectively, as they are the versions available
in Debian. fix an exposed issue where the status handler attempted
to manipulate the DOM before vue had rendered it - such manipulations
need to be deferred with $nextTick().
2020-11-20 14:34:26 +13:00
Oliver Giles
b851c72d53 progress bar: fix initial delayed update
when the displayed frontend state changes, any progress bar
should begin in the initial correct state before smoothly
transitioning with time.
2020-11-20 14:08:02 +13:00
Oliver Giles
3e993d35a0 no badges for unfinished runs
do not attempt to generate badges for runs which have not
yet finished.

resolves #134
2020-11-13 14:02:00 +13:00
Oliver Giles
579c192d89 builds per day: fix dynamic update to wrong result
the wrong dataset was updated, causing the graph to increase
the number of failed builds when a build succeeded and vice-versa.
2020-11-13 14:00:59 +13:00
Oliver Giles
4fb95fcb4f allow contexts to specify accepted jobs
using a glob expression, the same way jobs can specify
contexts. This allows more flexibility in situations where
there are many jobs sharing limited contexts because it
may obviate the need to create a conf file for each job.

resolves #124
2020-11-13 13:47:02 +13:00
Oliver Giles
bd489bdbb0 frontend refactor
use a more modern style, reduce variable scopes where possible,
fix several minor bugs such as pagination and scales in chart
tooltips
2020-10-16 21:19:12 +13:00
Oliver Giles
c6b60646f6 rewrite gtest result formatting example 2020-10-09 20:17:33 +13:00
Oliver Giles
1ea9713536 implement wallboard view
resolves #51
2020-10-09 13:06:03 +13:00
Oliver Giles
746ab24676 move buildTimeDist chart to examples
too esoteric for the front page, converting it to an example
of querying laminar db directly and using gnuplot should provide
more value to those needing deeper insights into job behaviour.
2020-09-26 15:12:02 +12:00
Oliver Giles
9862affd98 fix warnings under clang++ 2020-09-26 11:33:36 +12:00
Oliver Giles
9974df21ce add example telegram notification 2020-09-26 09:03:21 +12:00
Oliver Giles
c774acbb98 add example email notification scripts 2020-09-26 08:53:17 +12:00
Oliver Giles
06a5f3d8ef assign run numbers at queue time
This allows build chains to be traced in the common case where
an upstream job calls `laminarc queue' instead of `laminarc start'.
Incomplete job runs now have database entries, which requires
some adjustments in queries. Queued jobs can now be viewed in
the frontend and there is a corresponding status icon.
2020-09-25 15:29:30 +12:00
Oliver Giles
6d2c0b208b fix LAST_RESULT env var
the variable was set too late to be passed to the forked
process.

resolves #131
2020-09-20 09:15:03 +12:00
Oliver Giles
4b62e6dbf3 fix colours of per-job build time graph 2020-09-19 15:22:01 +12:00
Oliver Giles
dc3e41fb28 prettier graphs 2020-09-04 13:21:29 +12:00
Oliver Giles
e74332595e build time graph: simplify success/failed color logic 2020-09-04 13:15:30 +12:00
Oliver Giles
a793a97424 fix time scales in graphs
these were not correct at all
2020-09-04 13:12:52 +12:00
Oliver Giles
4e9c4bfb04 run page: switch progress bar and nav buttons
the navigation buttons are more usable next to other
navigation elements. This is especially noticeable on
large monitors.
2020-09-04 13:10:09 +12:00
Oliver Giles
e29568f627 improve layout on large screens 2020-09-04 13:08:34 +12:00
Oliver Giles
4316eb8a00 sse endpoint: hint to reverse-proxy not to buffer
Similarly to 210787a3, and as discussed in #88 and #130, nginx
will buffer chunked transfer-encoding unless proxy_buffering
is turned off or the X-Accel-Buffering header is set to no.

resolves #130
2020-08-11 06:54:03 +12:00
Oliver Giles
8a4992e6af more aggressive, recursive kill on abort
some jobs may spawn child processes which change their process group
or session id, making the existing abort behavior of HUP-then-KILL to
the process group ineffective. Instead, if HUP to the process group
fails, recursively walk /proc and KILL anything with a ppid corresponding
to the leader process. This should keep working because the leader
process is a subreaper.

resolves #129
2020-08-08 12:03:55 +12:00
56 changed files with 2497 additions and 1161 deletions

View File

@@ -1,5 +1,5 @@
###
### Copyright 2015-2020 Oliver Giles
### Copyright 2015-2026 Oliver Giles
###
### This file is part of Laminar
###
@@ -16,13 +16,50 @@
### You should have received a copy of the GNU General Public License
### along with Laminar. If not, see <http://www.gnu.org/licenses/>
###
cmake_minimum_required(VERSION 3.18)
project(laminar)
cmake_minimum_required(VERSION 2.8)
cmake_policy(SET CMP0058 NEW)
if (${CMAKE_SYSTEM_NAME} STREQUAL "FreeBSD")
# ld.lld is a default option on FreeBSD
set(LLVM_LINKER_IS_LLD ON)
endif()
# ld.lld specific options. There is no sane way in cmake
# to detect if toolchain is actually using ld.lld
if (LLVM_LINKER_IS_LLD)
if (NOT DEFINED LINKER_EMULATION_FLAGS)
if (${CMAKE_SYSTEM_PROCESSOR} STREQUAL "amd64")
set(LINKER_EMULATION_FLAGS "-melf_x86_64")
elseif (${CMAKE_SYSTEM_PROCESSOR} STREQUAL "x86_64")
set(LINKER_EMULATION_FLAGS "-melf_x86_64")
elseif (${CMAKE_SYSTEM_PROCESSOR} STREQUAL "aarch64")
set(LINKER_EMULATION_FLAGS "-maarch64elf")
elseif (${CMAKE_SYSTEM_PROCESSOR} STREQUAL "powerpc64le")
set(LINKER_EMULATION_FLAGS "-melf64lppc")
elseif (${CMAKE_SYSTEM_PROCESSOR} STREQUAL "powerpc64")
set(LINKER_EMULATION_FLAGS "-melf64ppc")
elseif (${CMAKE_SYSTEM_PROCESSOR} STREQUAL "riscv64")
# llvm17 & riscv64 requires extra step, it is necessary to
# patch 'Elf64.e_flags' (48-th byte) in binary-blob object files
# with value 0x5 - to change soft_float ABI to hard_float ABI
# so they can link with rest of the object files.
set(LINKER_EMULATION_FLAGS "-melf64lriscv")
elseif (${CMAKE_SYSTEM_PROCESSOR} STREQUAL "arm")
set(LINKER_EMULATION_FLAGS "-marmelf")
elseif (${CMAKE_SYSTEM_PROCESSOR} STREQUAL "armv7")
set(LINKER_EMULATION_FLAGS "-marmelf")
else()
message(FATAL_ERROR
"Unsupported '${CMAKE_SYSTEM_PROCESSOR}' translation to emulation flag. "
"Please set it explicitly 'cmake -DLINKER_EMULATION_FLAGS=\"-melf_your_arch\" ...'")
endif()
endif()
endif()
set(CMAKE_INCLUDE_CURRENT_DIR ON)
set(CMAKE_CXX_STANDARD 20)
add_definitions("-std=c++17 -Wall -Wextra -Wno-unused-parameter -Wno-sign-compare")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra -Wno-unused-parameter -Wno-sign-compare")
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -Werror -DDEBUG")
# Allow passing in the version string, for e.g. patched/packaged versions
@@ -56,7 +93,7 @@ macro(generate_compressed_bins BASEDIR)
DEPENDS ${BASEDIR}/${FILE}
)
add_custom_command(OUTPUT ${OUTPUT_FILE}
COMMAND ${CMAKE_LINKER} -r -b binary -o ${OUTPUT_FILE} ${COMPRESSED_FILE}
COMMAND ${CMAKE_LINKER} ${LINKER_EMULATION_FLAGS} -r -b binary -o ${OUTPUT_FILE} ${COMPRESSED_FILE}
COMMAND ${CMAKE_OBJCOPY}
--rename-section .data=.rodata.alloc,load,readonly,data,contents
--add-section .note.GNU-stack=/dev/null
@@ -83,16 +120,14 @@ add_custom_command(OUTPUT index_html_size.h
DEPENDS src/resources/index.html)
# Download 3rd-party frontend JS libs...
file(DOWNLOAD https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.min.js
js/vue.min.js EXPECTED_MD5 ae2fca1cfa0e31377819b1b0ffef704c)
file(DOWNLOAD https://cdnjs.cloudflare.com/ajax/libs/vue-router/2.7.0/vue-router.min.js
js/vue-router.min.js EXPECTED_MD5 5d3e35710dbe02de78c39e3e439b8d4e)
file(DOWNLOAD https://raw.githubusercontent.com/drudru/ansi_up/v1.3.0/ansi_up.js
js/ansi_up.js EXPECTED_MD5 158566dc1ff8f2804de972f7e841e2f6)
file(DOWNLOAD https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js
js/Chart.min.js EXPECTED_MD5 f6c8efa65711e0cbbc99ba72997ecd0e)
file(DOWNLOAD https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.12/vue.min.js
${CMAKE_BINARY_DIR}/js/vue.min.js EXPECTED_MD5 fb192338844efe86ec759a40152fcb8e)
file(DOWNLOAD https://raw.githubusercontent.com/drudru/ansi_up/v5.2.1/ansi_up.js
${CMAKE_BINARY_DIR}/js/ansi_up.js EXPECTED_MD5 77202f7815d9d7f7764793d93598ba88)
file(DOWNLOAD https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.9.1/chart.min.js
${CMAKE_BINARY_DIR}/js/Chart.min.js EXPECTED_MD5 7dd5ea7d2cf22a1c42b43c40093d2669)
# ...and compile them
generate_compressed_bins(${CMAKE_BINARY_DIR} js/vue-router.min.js js/vue.min.js
generate_compressed_bins(${CMAKE_BINARY_DIR} js/vue.min.js
js/ansi_up.js js/Chart.min.js)
# (see resources.cpp where these are fetched)
@@ -111,13 +146,48 @@ set(LAMINARD_CORE_SOURCES
index_html_size.h
)
find_package(CapnProto REQUIRED)
include_directories(${CAPNP_INCLUDE_DIRS})
find_package(SQLite3 REQUIRED)
include_directories(${SQLite3_INCLUDE_DIRS})
if(NOT TARGET SQLite3::SQLite3) # CMake < 4.3
add_library(SQLite3::SQLite3 ALIAS SQLite::SQLite3)
endif()
find_package(ZLIB REQUIRED)
include_directories(${ZLIB_INCLUDE_DIRS})
find_package(Threads REQUIRED)
include_directories(${Threads_INCLUDE_DIRS})
## Server
add_executable(laminard ${LAMINARD_CORE_SOURCES} src/main.cpp ${COMPRESSED_BINS})
target_link_libraries(laminard capnp-rpc capnp kj-http kj-async kj pthread sqlite3 z)
target_link_libraries(laminard CapnProto::capnp-rpc CapnProto::capnp CapnProto::kj-http CapnProto::kj-async
CapnProto::kj Threads::Threads SQLite3::SQLite3 ZLIB::ZLIB)
if (${CMAKE_SYSTEM_NAME} STREQUAL "FreeBSD")
pkg_check_modules(INOTIFY REQUIRED libinotify)
target_link_libraries(laminard ${INOTIFY_LINK_LIBRARIES})
endif()
## Client
add_executable(laminarc src/client.cpp src/version.cpp laminar.capnp.c++)
target_link_libraries(laminarc capnp-rpc capnp kj-async kj pthread)
target_link_libraries(laminarc CapnProto::capnp-rpc CapnProto::capnp CapnProto::kj-async CapnProto::kj Threads::Threads)
## Manpages
macro(gzip SOURCE)
get_filename_component(OUT_FILE ${SOURCE} NAME)
add_custom_command(OUTPUT ${OUT_FILE}.gz
COMMAND gzip < ${CMAKE_CURRENT_SOURCE_DIR}/${SOURCE} > ${OUT_FILE}.gz
DEPENDS ${SOURCE})
endmacro()
add_custom_target(laminar-manpages ALL DEPENDS laminard.8.gz laminarc.1.gz)
gzip(etc/laminard.8)
gzip(etc/laminarc.1)
install(FILES ${CMAKE_CURRENT_BINARY_DIR}/laminard.8.gz DESTINATION share/man/man8)
install(FILES ${CMAKE_CURRENT_BINARY_DIR}/laminarc.1.gz DESTINATION share/man/man1)
## Tests
set(BUILD_TESTS FALSE CACHE BOOL "Build tests")
@@ -125,10 +195,10 @@ if(BUILD_TESTS)
find_package(GTest REQUIRED)
include_directories(${GTEST_INCLUDE_DIRS} src)
add_executable(laminar-tests ${LAMINARD_CORE_SOURCES} ${COMPRESSED_BINS} test/main.cpp test/laminar-functional.cpp test/unit-conf.cpp test/unit-database.cpp)
target_link_libraries(laminar-tests ${GTEST_LIBRARY} capnp-rpc capnp kj-http kj-async kj pthread sqlite3 z)
target_link_libraries(laminar-tests ${GTEST_LIBRARIES} CapnProto::capnp-rpc CapnProto::capnp CapnProto::kj-http CapnProto::kj-async CapnProto::kj
Threads::Threads SQLite3::SQLite3 ZLIB::ZLIB)
endif()
set(SYSTEMD_UNITDIR /lib/systemd/system CACHE PATH "Path to systemd unit files")
set(BASH_COMPLETIONS_DIR /usr/share/bash-completion/completions CACHE PATH "Path to bash completions directory")
set(ZSH_COMPLETIONS_DIR /usr/share/zsh/site-functions CACHE PATH "Path to zsh completions directory")
install(TARGETS laminard RUNTIME DESTINATION sbin)
@@ -137,5 +207,8 @@ install(FILES etc/laminar.conf DESTINATION /etc)
install(FILES etc/laminarc-completion.bash DESTINATION ${BASH_COMPLETIONS_DIR} RENAME laminarc)
install(FILES etc/laminarc-completion.zsh DESTINATION ${ZSH_COMPLETIONS_DIR} RENAME _laminarc)
configure_file(etc/laminar.service.in laminar.service @ONLY)
install(FILES ${CMAKE_CURRENT_BINARY_DIR}/laminar.service DESTINATION ${SYSTEMD_UNITDIR})
if (${CMAKE_SYSTEM_NAME} STREQUAL "Linux")
set(SYSTEMD_UNITDIR /lib/systemd/system CACHE PATH "Path to systemd unit files")
configure_file(etc/laminar.service.in laminar.service @ONLY)
install(FILES ${CMAKE_CURRENT_BINARY_DIR}/laminar.service DESTINATION ${SYSTEMD_UNITDIR})
endif()

View File

@@ -12,11 +12,11 @@ See [the website](https://laminar.ohwg.net) and the [documentation](https://lami
First install development packages for `capnproto (version 0.7.0 or newer)`, `rapidjson`, `sqlite` and `boost` (for the header-only `multi_index_container` library) from your distribution's repository or other source.
On Debian Buster, this can be done with:
On Debian 13 (Trixie), this can be done with:
```bash
sudo apt install \
capnproto cmake g++ libboost-dev libcapnp-dev libsqlite-dev libsqlite3-dev make rapidjson-dev zlib1g-dev
sudo apt install capnproto cmake g++ libboost-dev libcapnp-dev libsqlite3-dev \
make rapidjson-dev zlib1g-dev pkg-config
```
Then compile and install laminar with:
@@ -25,7 +25,7 @@ Then compile and install laminar with:
git clone https://github.com/ohwgiles/laminar.git
cd laminar
cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/usr
make -j4
make -j "$(nproc)"
# Warning: the following will overwrite an existing /etc/laminar.conf
sudo make install
```

View File

@@ -17,27 +17,28 @@ Throughout this document, the fixed base path `/var/lib/laminar` is used. This i
# Installing Laminar
Pre-built packages are available for Debian 9 (Stretch) and CentOS 7 on x86_64. Alternatively, Laminar may be built from source for any Linux distribution.
Pre-built upstream packages are available for Debian on x86_64 and armhf, and for Rocky/CentOS/RHEL on x86_64.
Please see the [GitHub releases page](https://github.com/ohwgiles/laminar/releases) for the latest versions.
## Installation from binaries
Also, Laminar may be built from source for any Linux distribution.
Alternatively to the source-based approach shown above, precompiled packages are supplied for x86_64 Debian 9 (Stretch) and CentOS 7
## Installation from upstream packages
Under Debian:
```bash
wget https://github.com/ohwgiles/laminar/releases/download/0.6/laminar-0.6-1-amd64.deb
sudo apt install laminar-0.6-1-amd64.deb
wget https://github.com/ohwgiles/laminar/releases/download/1.3/laminar_1.3-1.upstream-debian11_amd64.deb
sudo apt install ./laminar_1.3-1.upstream-debian11_amd64.deb
```
Under CentOS:
Under Rocky/CentOS/RHEL:
```bash
wget https://github.com/ohwgiles/laminar/releases/download/0.5/laminar-0.6-1.x86_64.rpm
sudo yum install laminar-0.6-1.x86_64.rpm
wget https://github.com/ohwgiles/laminar/releases/download/1.3/laminar-1.3.upstream_rocky8-1.x86_64.rpm
sudo dnf install ./laminar-1.3.upstream_rocky8-1.x86_64.rpm
```
Both install packages will create a new `laminar` user and install (but not activate) a systemd service for launching the laminar daemon.
Both install packages will create a new `laminar` system user and install (but not activate) a systemd service for launching the laminar daemon.
## Building from source
@@ -52,15 +53,17 @@ You can build an image that runs `laminard` by default, and contains `laminarc`
docker build [-t image:tag] -f docker/Dockerfile .
```
Keep in mind that this is meant to be used as a base image to build from, so it contains only the minimum packages required to run laminar. The only shell available by default is sh and it does not even have ssh or git. You can use this image to run a basic build server, but it is recommended that you build a custom image from this base to better suit your needs.
Keep in mind that this is meant to be used as a base image to build from, so it contains only the minimum packages required to run laminar. The only shell available by default is sh (so scripts with `#!/bin/bash` will fail to execute) and it does not have `ssh` or `git`. You can use this image to run a basic build server, but it is recommended that you build a custom image from this base to better suit your needs.
The container will execute `laminard` by default. To start a laminar server with docker you can simply run the image as a daemon.
The container will execute `laminard` by default. To start a laminar server with docker you can simply run the image as a daemon, for example:
```bash
docker run -d --name laminar_server -p 8080:8080 [-v laminardir|laminar.conf] laminar:latest
docker run -d --name laminar_server -p 8080:8080 -v path/to/laminardir:/var/lib/laminar --env-file path/to/laminar.conf laminar:latest
```
You can customize laminar and persist your data by mounting your laminar directory to `/var/lib/laminar` and/or mounting a custom configuration file to `/etc/laminar.conf`.
The [`-v` flag](https://docs.docker.com/storage/volumes/#choose-the--v-or---mount-flag) is necessary to persist job scripts and artefacts beyond the container lifetime.
The [`--env-file` flag](https://docs.docker.com/engine/reference/commandline/run/#set-environment-variables--e---env---env-file) is necessary to pass configuration from `laminar.conf` to `laminard` because `laminard` does not read `/etc/laminar.conf` directly but expects variables within to be exported by `systemd` or other process supervisor.
Executing `laminarc` may be done in any of the usual ways, for example:
@@ -84,7 +87,7 @@ Laminar's configuration file may be found at `/etc/laminar.conf`. Laminar will s
Edit `/etc/laminar.conf` and change `LAMINAR_BIND_HTTP` to `IPADDR:PORT`, `unix:PATH/TO/SOCKET` or `unix-abstract:SOCKETNAME`. `IPADDR` may be `*` to bind on all interfaces. The default is `*:8080`.
Do not attempt to run laminar on port 80. This requires running as `root`, and Laminar will not drop privileges when executing job scripts! For a more complete integrated solution (including SSL), run laminar as a reverse proxy behind a regular webserver.
Do not attempt to run laminar on port 80. This requires running as `root`, and Laminar will not drop privileges when executing job scripts! For a more complete integrated solution (including SSL), run laminar behind a regular webserver acting as a reverse proxy.
## Running behind a reverse proxy
@@ -92,10 +95,12 @@ A reverse proxy is required if you want Laminar to share a port with other web s
If you use [artefacts](#Archiving-artefacts), note that Laminar is not designed as a file server, and better performance will be achieved by allowing the frontend web server to serve the archive directory directly (e.g. using a `Location` directive).
Laminar uses Sever Sent Events to provide a responsive, auto-updating display without polling. Most frontend webservers should handle this without any extra configuration.
Laminar uses Server Sent Events to provide a responsive, auto-updating display without polling. Most frontend webservers should handle this without any extra configuration.
If you use a reverse proxy to host Laminar at a subfolder instead of a subdomain root, the `<base href>` needs to be updated to ensure all links point to their proper targets. This can be done by setting `LAMINAR_BASE_URL` in `/etc/laminar.conf`.
See [this example configuration file for nginx](https://github.com/ohwgiles/laminar/blob/master/examples/nginx-ssl-reverse-proxy.conf).
## More configuration options
See the [reference section](#Service-configuration-file)
@@ -113,8 +118,17 @@ tar xzf hello-2.10.tar.gz
cd hello-2.10
./configure
make
# save permanently to the job's run archive directory
mv ./hello "$ARCHIVE/"
```
If everything went well, the path to the freshly compiled `hello` binary is `$LAMINAR_HOME/archive/hello/latest/hello`, which prints
```
Hello, world!
```
upon execution.
Laminar uses your script's exit code to determine whether to mark the run as successful or failed. If your script is written in bash, the [`-e` option](http://tldp.org/LDP/abs/html/options.html) is helpful for this. See also [Exit and Exit Status](http://tldp.org/LDP/abs/html/exit-status.html).
Don't forget to mark the script executable:
@@ -127,30 +141,30 @@ chmod +x /var/lib/laminar/cfg/jobs/hello.run
# Triggering a run
When triggering a run, the job is first added to a queue of upcoming tasks. If the server is busy, the job may wait in this queue for a while. It will only be assigned a job number when it leaves this queue and starts executing. The job number may be useful to the client that triggers the run, so there are a few ways to trigger a run.
To add the `hello` job to the queue ("fire-and-forget"), execute
To queue execution of the `hello` job, run
```bash
laminarc queue hello
```
In this case, laminarc returns immediately, with its error code indicating whether adding the job to the queue was sucessful.
In this case, `laminarc` returns immediately, with its error code indicating whether adding the job to the queue was sucessful. The run number will be printed to standard output.
To queue the job and wait until it leaves the queue and starts executing, use
If the server is busy, a run may wait in the queue for some time. To have `laminarc` instead block until the run leaves the queue and starts executing, use
```bash
laminarc start hello
```
In this case, laminarc blocks until the job starts executing, or returns immediately if queueing failed. The run number will be printed to standard output.
In this case, `laminarc` blocks until the job starts executing, or returns immediately if queueing failed. The run number will be printed to standard output.
To launch and run the `hello` job to completion, execute
Finally, to launch and run the `hello` job to completion, execute
```bash
laminarc run hello
```
In this case, laminarc's return value indicates whether the run completed successfully.
In all cases, a started run means the `/var/lib/laminar/cfg/jobs/hello.run` script will be executed, with a working directory of `/var/lib/laminar/run/hello/1` (or current run number)
The result and log output should be visible in the Web UI at http://localhost:8080/jobs/hello/1
@@ -161,6 +175,13 @@ Also note that all the above commands can simultaneously trigger multiple differ
laminarc queue test-host test-target
```
A human-readable reason for the trigger can be set using the environment variable `LAMINAR_REASON`, which will be stored in the database and displayed in the web UI:
```bash
LAMINAR_REASON="Smoke detected" laminarc run activate-sprinklers
```
## Isn't there a "Build Now" button I can click?
This is against the design principles of Laminar and was deliberately excluded. Laminar's web UI is strictly read-only, making it simple to deploy in mixed-permission or public environments without an authentication layer. Furthermore, Laminar tries to encourage ideal continuous integration, where manual triggering is an anti-pattern. Want to make a release? Push a git tag and implement a post-receive hook. Want to re-run a build due to sporadic failure/flaky tests? Fix the tests locally and push a patch. Experience shows that a manual trigger such as a "Build Now" button is often used as a crutch to avoid doing the correct thing, negatively impacting traceability and quality.
@@ -183,7 +204,6 @@ This is what `cron` is for. To trigger a build of `hello` every day at 0300, add
to `laminar`'s crontab. For more information about `cron`, see `man crontab`.
`LAMINAR_REASON` is an optional human-readable string that will be displayed in the web UI as the cause of the build.
## Triggering on a git commit
@@ -194,6 +214,8 @@ This is what [git hooks](https://git-scm.com/book/gr/v2/Customizing-Git-Git-Hook
LAMINAR_REASON="Push to git repository" laminarc queue example-build
```
For a more advanced example, see [examples/git-post-receive-hook-notes](https://github.com/ohwgiles/laminar/blob/master/examples/git-post-receive-hook-notes)
What if your git server is not the same machine as the laminar instance?
## Triggering on a remote laminar instance
@@ -214,13 +236,13 @@ Then, point `laminarc` to the new location using an environment variable:
LAMINAR_HOST=192.168.1.1:9997 laminarc queue example
```
If you need more flexibility, consider running the communication channel as a regular unix socket and applying user and group permissions to the file. To achieve this, set
If you need more flexibility, consider running the communication channel as a regular unix socket. Setting
```
LAMINAR_BIND_RPC=unix:/var/run/laminar.sock
```
or similar path in `/etc/laminar.conf`.
or similar path in `/etc/laminar.conf` will result in a socket with group read/write permissions (`660`), so any user in the `laminar` system group can queue a job.
This can be securely and flexibly combined with remote triggering using `ssh`. There is no need to allow the client full shell access to the server machine, the ssh server can restrict certain users to certain commands (in this case `laminarc`). See [the authorized_keys section of the sshd man page](https://man.openbsd.org/sshd#AUTHORIZED_KEYS_FILE_FORMAT) for further information.
@@ -230,15 +252,15 @@ Consider using [webhook](https://github.com/adnanh/webhook) or a similar applica
## Viewing job logs
A job's console output can be viewed on the Web UI at http://localhost:8080/jobs/$NAME/$NUMBER.
A job's console output can be viewed on the Web UI at http://localhost:8080/jobs/$JOB/$RUN.
Additionally, the raw log output may be fetched over a plain HTTP request to http://localhost:8080/log/$NAME/$NUMBER. The response will be chunked, allowing this mechanism to also be used for in-progress jobs. Furthermore, the special endpoint http://localhost:8080/log/$NAME/latest will redirect to the most recent log output. Be aware that the use of this endpoint may be subject to races when new jobs start.
Additionally, the raw log output may be fetched over a plain HTTP request to http://localhost:8080/log/$JOB/$RUN. The response will be chunked, allowing this mechanism to also be used for in-progress jobs. Furthermore, the special endpoint http://localhost:8080/log/$JOB/latest will redirect to the most recent log output. Be aware that the use of this endpoint may be subject to races when new jobs start.
---
# Job chains
A typical pipeline may involve several steps, such as build, test and deploy. Depending on the project, these may be broken up into seperate laminar jobs for maximal flexibility.
A typical pipeline may involve several steps, such as build, test and deploy. Depending on the project, these may be broken up into separate laminar jobs for maximal flexibility.
The preferred way to accomplish this in Laminar is to use the same method as [regular run triggering](#Triggering-a-run), that is, calling `laminarc` directly in your `example.run` scripts.
@@ -259,7 +281,7 @@ else
laminarc run example-downstream-regular
fi
laminarc run example-test-$TARGET_PLATFORM
laminarc run "example-test-$TARGET_PLATFORM"
```
`laminarc` reads the `$JOB` and `$RUN` variables set by `laminard` and passes them as part of the queue/start/run request so the dependency chain can always be traced back.
@@ -268,7 +290,7 @@ laminarc run example-test-$TARGET_PLATFORM
# Parameterized runs
Any argument passed to `laminarc` of the form `var=value` will be exposed as an environment variable in the corresponding build scripts. For example:
Any argument passed to `laminarc` of the form `KEY=VALUE` will be exposed as an environment variable in the corresponding build scripts. For example:
```bash
laminarc queue example foo=bar
@@ -320,20 +342,20 @@ Then in `example.run`
```bash
#!/bin/bash
echo $foo # prints "bar"
echo "$foo" # prints "bar"
```
---
# Archiving artefacts
Laminar's default behaviour is to remove the run directory `/var/lib/laminar/run/JOB/RUN` after its completion. This prevents the typical CI disk usage explosion and encourages the user to judiciously select artefacts for archive.
Laminar's default behaviour is to remove the run directory `/var/lib/laminar/run/$JOB/$RUN` after its completion. This prevents the typical CI disk usage explosion and encourages the user to judiciously select artefacts for archive.
Laminar provides an archive directory `/var/lib/laminar/archive/JOB/RUN` and exposes its path in `$ARCHIVE`. `example-build.after` might look like this:
Laminar provides an archive directory `/var/lib/laminar/archive/$JOB/$RUN` and exposes its path in `$ARCHIVE`. `example-build.after` might look like this:
```bash
#!/bin/bash -xe
cp example.out $ARCHIVE/
cp example.out "$ARCHIVE/"
```
This folder structure has been chosen to make it easy for system administrators to host the archive on a separate partition or network drive.
@@ -364,15 +386,17 @@ fi
Of course, you can make this as pretty as you like. A [helper script](#Helper-scripts) can be a good choice here.
If you want to send to different addresses dependending on the job, replace `engineering@company.com` above with a variable, e.g. `$RECIPIENTS`, and set `RECIPIENTS=nora@company.com,joe@company.com` in `/var/lib/laminar/cfg/jobs/JOB.env`. See [Environment variables](#Environment-variables).
If you want to send to different addresses depending on the job, replace `engineering@company.com` above with a variable, e.g. `$RECIPIENTS`, and set `RECIPIENTS=nora@company.com,joe@company.com` in `/var/lib/laminar/cfg/jobs/$JOB.env`. See [Environment variables](#Environment-variables).
You could also update the `$RECIPIENTS` variable dynamically based on the build itself. For example, if your run script accepts a parameter `$rev` which is a git commit id, as part of your job's `.after` script you could do the following:
```bash
author_email=$(git show -s --format='%ae' $rev)
laminarc set RECIPIENTS $author_email
author_email=$(git show -s --format='%ae' "$rev")
laminarc set RECIPIENTS "$author_email"
```
See [examples/notify-email-pretty](https://github.com/ohwgiles/laminar/blob/master/examples/notify-email-pretty) and [examples/notify-email-text-log](https://github.com/ohwgiles/laminar/blob/master/examples/notify-email-text-log).
---
# Helper scripts
@@ -407,25 +431,25 @@ For example, the following script creates a tarball containing both compiled out
git clone /path/to/sources .
make
# Use a hardlink so the arguments to tar will be relative to the CWD
ln $WORKSPACE/StaticAsset.bin ./
ln "$WORKSPACE/StaticAsset.bin" ./
tar zc a.out StaticAsset.bin > MyProject.tar.gz
# Archive the artefact (consider moving this to the .after script)
mv MyProject.tar.gz $ARCHIVE/
mv MyProject.tar.gz "$ARCHIVE/"
```
For a project with a large git history, it can be more efficient to store the sources in the workspace:
```bash
#!/bin/bash -ex
cd $WORKSPACE/myproject
cd "$WORKSPACE/myproject"
git pull
cd -
cmake $WORKSPACE/myproject
cmake "$WORKSPACE/myproject"
make -j4
```
Laminar will automatically create the workspace for a job if it doesn't exist when a job is executed. In this case, the `/var/lib/laminar/cfg/jobs/JOBNAME.init` will be executed if it exists. This is an excellent place to prepare the workspace to a state where subsequent builds can rely on its content:
Laminar will automatically create the workspace for a job if it doesn't exist when a job is executed. In this case, the `/var/lib/laminar/cfg/jobs/$JOB.init` will be executed if it exists. This is an excellent place to prepare the workspace to a state where subsequent builds can rely on its content:
```bash
#!/bin/bash -e
@@ -451,16 +475,16 @@ The following example uses [flock](https://linux.die.net/man/1/flock) to efficie
# Locked subshell for modifying the workspace
(
flock 200
cd $WORKSPACE
cd "$WORKSPACE"
# Download all the latest commits
git fetch
git checkout $rev
git checkout "$rev"
cd -
# Fast copy (hard-link) the source from the specific checkout
# to the build dir. This relies on the fact that git unlinks
# during checkout, effectively implementing copy-on-write.
cp -al $WORKSPACE/src src
) 200>$WORKSPACE
cp -al "$WORKSPACE/src" src
) 200>"$WORKSPACE"
# run the (much longer) regular build process
make -C src
@@ -472,7 +496,7 @@ make -C src
## After a timeout
To configure a maximum execution time in seconds for a job, add a line to `/var/lib/laminar/cfg/jobs/JOBNAME.conf`:
To configure a maximum execution time in seconds for a job, add a line to `/var/lib/laminar/cfg/jobs/$JOB.conf`:
```
TIMEOUT=120
@@ -480,7 +504,7 @@ TIMEOUT=120
## Manually
`laminarc abort $JOBNAME $NUMBER`
`laminarc abort $JOB $RUN`
---
@@ -502,19 +526,29 @@ EXECUTORS=1
## Associating a job with a context
When trying to start a job, laminar will wait until the job can be matched to a context which has at least one free executor. You can define which contexts the job will associate with by setting, for example,
When trying to start a job, laminar will wait until the job can be matched to a context which has at least one free executor. There are two ways to associate jobs and contexts. You can specify a comma-separated list of patterns `JOBS` in the context configuration file `/var/lib/laminar/cfg/contexts/$CONTEXT.conf`:
```
JOBS=amd64-target-*,usage-monitor
```
This approach is often preferred when you have many jobs that need to share limited resources.
Alternatively, you can set
```
CONTEXTS=my-env-*,special_context
```
in `/var/lib/laminar/cfg/jobs/JOB.conf`. For each of the patterns in the comma-separated list `CONTEXTS`, Laminar will iterate over the known contexts and associate the run with the first context with free executors. Patterns are [glob expressions](http://man7.org/linux/man-pages/man7/glob.7.html).
in `/var/lib/laminar/cfg/jobs/$JOB.conf`. This approach is often preferred when you have a small number of jobs that require exclusive access to an environment and you can supply alternative environments (e.g. target devices), because new contexts can be added without modifying the job configuration.
If `CONTEXTS` is empty or absent (or if `JOB.conf` doesn't exist), laminar will behave as if `CONTEXTS=default` were defined.
In both cases, Laminar will iterate over the known contexts and associate the run with the first matching context with free executors. Patterns are [glob expressions](http://man7.org/linux/man-pages/man7/glob.7.html).
If `CONTEXTS` is empty or absent (or if `$JOB.conf` doesn't exist), laminar will behave as if `CONTEXTS=default` were defined.
## Adding environment to a context
Append desired environment variables to `/var/lib/laminar/cfg/contexts/CONTEXT_NAME.conf`:
Append desired environment variables to `/var/lib/laminar/cfg/contexts/$CONTEXT.env`:
```
DUT_IP=192.168.3.2
@@ -550,11 +584,11 @@ This means the job script `/var/lib/laminar/cfg/jobs/myproject-test.run` can be
```bash
#!/bin/bash -e
ssh root@$TARGET_IP /bin/bash -xe <<"EOF"
ssh "root@$TARGET_IP" /bin/bash -xe <<"EOF"
uname -a
...
EOF
scp root@$TARGET_IP:result.xml "$ARCHIVE/"
scp "root@$TARGET_IP:result.xml" "$ARCHIVE/"
```
Don't forget to add the `laminar` user's public ssh key to the remote's `authorized_keys`.
@@ -574,6 +608,8 @@ docker run --rm -ti -v $PWD:/root ubuntu /bin/bash -xe <<EOF
EOF
```
For more advanced usage, see [examples/docker-advanced](https://github.com/ohwgiles/laminar/blob/master/examples/docker-advanced)
---
# Colours in log output
@@ -606,7 +642,7 @@ Changes to this file are detected immediately and will be visible on next page r
## Adding a description to a job
Edit `/var/lib/laminar/cfg/jobs/$JOBNAME.conf`:
Edit `/var/lib/laminar/cfg/jobs/$JOB.conf`:
```
DESCRIPTION=Anything here will appear on the job page in the frontend <em>unescaped</em>.
@@ -626,7 +662,7 @@ An example customization can be found at [cweagans/semantic-laminar-theme](https
# Badges
Laminar will serve a job's current status as a pretty badge at the url `/badge/JOBNAME.svg`. This can be used as a link to your server instance from your Github README.md file or cat blog:
Laminar will serve a job's current status as a pretty badge at the url `/badge/$JOB.svg`. This can be used as a link to your server instance from your Github README.md file or cat blog:
```
<a href="https://my-example-laminar-server.com/jobs/my-project">
@@ -638,6 +674,45 @@ Laminar will serve a job's current status as a pretty badge at the url `/badge/J
# Reference
## LAMINAR_HOME directory scheme
```
$LAMINAR_HOME/
├── cfg/
│ ├── before
│ ├── jobs/
│ │ ├── $JOB.init
│ │ ├── $JOB.env
│ │ ├── $JOB.before
│ │ ├── $JOB.run
│ │ ├── $JOB.after
│ │ └── $JOB.conf
│ ├── after
│ │ scripts/
│ │ ├── foo
│ │ └── bar
│ ├── env
│ ├── contexts/
│ │ ├── $CONTEXT.env
│ │ └── $CONTEXT.conf
│ └── groups.conf
├── archive/
│ └── $JOB/
│ └── $RUN/ # $ARCHIVE
├── run/
│ └── $JOB/
│ └── $RUN/ # run directory (ephemeral)
│ └── workspace/ # $WORKSPACE
├── custom/
│ └── index.html
└── laminar.sqlite
```
The user running `laminard` (by default the system user `laminar`)
- must have read/write access to `laminar.sqlite`,
- read/execute access to the contents of `cfg` and `custom` and
- write access to `archive` and `run` if the running jobs are to have the ability to archive artefacts or utilize the workspace, respectively.
## Service configuration file
`laminard` reads the following variables from the environment, which are expected to be sourced by `systemd` from `/etc/laminar.conf`:
@@ -691,12 +766,15 @@ Finally, variables supplied on the command-line call to `laminarc queue`, `lamin
- `queue [JOB [PARAMS...]]...` adds one or more jobs to the queue with optional parameters, returning immediately.
- `start [JOB [PARAMS...]]...` starts one or more jobs with optional parameters, returning when the jobs begin execution.
- `run [JOB [PARAMS...]]...` triggers one or more jobs with optional parameters and waits for the completion of all jobs.
- `set [VARIABLE=VALUE]...` sets one or more variables to be exported in subsequent scripts for the run identified by the `$JOB` and `$RUN` environment variables
- `--next` may be passed before `JOB` in order to place the job at the front of the queue instead of at the end.
- `set [KEY=VALUE]...` sets one or more variables to be exported in subsequent scripts for the run identified by the `JOB` and `RUN` environment variables
- `show-jobs` shows the known jobs on the server (`$LAMINAR_HOME/cfg/jobs/*.run`).
- `show-running` shows the currently running jobs with their numbers.
- `show-queued` shows the names of the jobs waiting in the queue.
- `abort JOB NUMBER` manually aborts a currently running job by name and number.
- `abort JOB RUN` manually aborts a currently running job by name and number.
`laminarc` connects to `laminard` using the address supplied by the `LAMINAR_HOST` environment variable. If it is not set, `laminarc` will first attempt to use `LAMINAR_BIND_RPC`, which will be available if `laminarc` is executed from a script within `laminard`. If neither `LAMINAR_HOST` nor `LAMINAR_BIND_RPC` is set, `laminarc` will assume a default host of `unix-abstract:laminar`.
`laminarc` reads the environment variable `LAMINAR_REASON` for a human-readable reason. See [Triggering a run](#Triggering-a-run).
All commands return zero on success or a non-zero code if the command could not be executed. `laminarc run` will return a non-zero exit status if any executed job failed.

View File

@@ -1,11 +1,13 @@
[Unit]
Description=Laminar continuous integration service
After=network.target
Documentation=man:laminard(8)
Documentation=https://laminar.ohwg.net/docs.html
[Service]
User=laminar
EnvironmentFile=-/etc/laminar.conf
ExecStart=@CMAKE_INSTALL_PREFIX@/sbin/laminard
ExecStart=@CMAKE_INSTALL_PREFIX@/sbin/laminard -v
[Install]
WantedBy=multi-user.target

74
etc/laminarc.1 Normal file
View File

@@ -0,0 +1,74 @@
.Dd Apr 04, 2019
.Dt LAMINARC 1
.Sh NAME
.Nm laminarc
\-
Laminar CI client application
.Sh SYNOPSIS
.Nm laminarc Li queue \fIJOB\fR [\fIPARAM=VALUE...\fR] ...
.Nm laminarc Li start \fIJOB\fR [\fIPARAM=VALUE...\fR] ...
.Nm laminarc Li run \fIJOB\fR [\fIPARAM=VALUE...\fR] ...
.Nm laminarc Li set \fIPARAM=VALUE...\fR
.Nm laminarc Li show-jobs
.Nm laminarc Li show-running
.Nm laminarc Li show-queued
.Nm laminarc Li abort \fIJOB\fR \fINUMBER\fR
.Sh DESCRIPTION
The
.Nm laminarc
program connects to a Laminar server and perform one of following operations:
.Bl -tag
.It Sy queue
adds job(s) (with optional parameters) to the queue and returns immediately.
.It Sy start
adds job(s) (with optional parameters) to the queue and returns when the jobs
begin execution.
.It Sy run
adds job(s) (with optional parameters) to the queue and returns when the jobs
complete execution. The exit code will be non-zero if any of the runs does
not complete successfully.
.It \t
\fB--next\fR may be passed to \fBqueue\fR, \fBstart\fR or \fBrun\fR in order
to place the job at the front of the queue instead of at the end.
.It Sy set
sets one or more parameters to be exported as environment variables in subsequent
scripts for the run identified by the $JOB and $RUN environment variables.
This is primarily intended for use from within a job execution, where those
variables are already set by the server.
.It Sy show-jobs
list jobs known to the server.
.It Sy show-running
list the currently running jobs with their numbers.
.It Sy show-queued
list the names and numbers of the jobs waiting in the queue.
.It Sy abort
manually abort a currently running job by name and number.
.El
.Pp
The laminar server to connect to is read from the
.Ev LAMINAR_HOST
environment variable. If empty, it falls back to
.Ev LAMINAR_BIND_RPC
and finally defaults to
.Ad unix-abstract:laminar
.Sh ENVIRONMENT
.Bl -tag
.It Ev LAMINAR_HOST
address of server to connect. May be of the form
.Ad IP:PORT,
.Ad unix:PATH/TO/SOCKET
or
.Ad unix-abstract:NAME
.It Ev LAMINAR_BIND_RPC
fallback server address variable. It is set by
.Nm laminard
during execution of scripts.
.El
.Sh SEE ALSO
.Xr laminard 8
.Sh AUTHORS
.An Oliver Giles
created Laminar CI.
.An Dmitry Bogatov
created this manual page for the Debian project (but it can be used
by others).

56
etc/laminard.8 Normal file
View File

@@ -0,0 +1,56 @@
.Dd Apr 03, 2019
.Dt LAMINARD 1
.Sh NAME
.Nm laminard
\-
Laminar CI server
.Sh SYNOPSIS
.Nm laminard Op Fl v
.Sh DESCRIPTION
Start Laminar CI server in the foreground. If option
.Fl v
is specified, verbose logging is enabled. Other aspects of
operation are controlled by environment variables.
.Sh ENVIRONMENT
.Bl -tag
.It Ev LAMINAR_HOME
Root location containing laminar configuration, database, build
workspaces and archive.
.Pp
Default: /var/lib/laminar
.It Ev LAMINAR_BIND_HTTP
Interface on which laminard will bind to serve the Web UI.
May be of the form IP:PORT, unix:PATH/TO/SOCKET or unix-abstract:NAME
.Pp
Default: *:8080
.It Ev LAMINAR_BIND_HRPC
Interface on which laminard will bind to accept RPC from laminarc.
May be of the form IP:PORT, unix:PATH/TO/SOCKET or unix-abstract:NAME
.Pp
Default: unix-abstract:laminar
.It Ev LAMINAR_TITLE
Page title to show in web frontend
.It Ev LAMINAR_KEEP_RUNDIRS
Setting this prevents the immediate deletion of job rundirs
$LAMINAR_HOME/run/$JOB/$RUN. Value should be an integer represeting
the number of rundirs to keep.
.Pp
Default: 0
.It Ev LAMINAR_ARCHIVE_URL
Base url used to request artifacts. Laminar can serve build artifacts
(and it will if you leave this unset), but it uses a very naive and
inefficient method. Best to let a real webserver handle serving those
requests.
.El
.Sh FILES
.Bl -tag
.It Pa /etc/laminar.conf
Variable assignments in this file are exported by systemd or other
init system before launching the system-wide installation of Laminar.
.El
.Sh AUTHORS
.An Oliver Giles
created Laminar CI.
.An Dmitry Bogatov
created this manual page for Debian project (but it can be used
by others).

View File

@@ -1,21 +0,0 @@
#!/bin/bash
cat <<EOF
<!doctype html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Laminar</title>
<link href="/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="col-xs-12">
<h2>Test report for $lJobName #$lBuildNum</h2>
EOF
xsltproc "$(dirname ${BASH_SOURCE[0]})/testreport.xsl" "$1";
cat <<EOF
</div>
</body>
</html>
EOF

View File

@@ -1,42 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" indent="no"/>
<xsl:template match="testsuite">
<h3>Test Suite: <xsl:value-of select="@name" /></h3>
<dl class="dl-horizontal">
<dt>Tests run:</dt><dd><xsl:value-of select="@tests" /></dd>
<dt>Failures:</dt><dd><xsl:value-of select="@failures" /></dd>
<dt>Errors:</dt><dd><xsl:value-of select="@errors" /></dd>
<dt>Elapsed time:</dt><dd><xsl:value-of select="@time" /></dd>
</dl>
<ul class="list-group">
<xsl:apply-templates select="testcase" />
</ul>
<xsl:apply-templates select="system-out" />
<xsl:apply-templates select="system-err" />
</xsl:template>
<xsl:template match="testcase">
<xsl:choose>
<xsl:when test="*">
<li class="list-group-item list-group-item-danger"><xsl:value-of select="@name" />
<xsl:apply-templates select="failure" />
</li>
</xsl:when>
<xsl:otherwise>
<li class="list-group-item list-group-item-success"><xsl:value-of select="@name" /></li>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<xsl:template match="failure">
<pre>
<xsl:value-of select="@message"/>
</pre>
</xsl:template>
<xsl:template match="system-out"><h5>Standard output:</h5><pre><xsl:value-of select="." /></pre></xsl:template>
<xsl:template match="system-err"><h5>Standard error:</h5><pre><xsl:value-of select="." /></pre></xsl:template>
</xsl:stylesheet>

53
examples/docker-advanced Executable file
View File

@@ -0,0 +1,53 @@
#!/bin/bash -eu
# Any failing command in a pipe will cause an error, instead
# of just an error in the last command in the pipe
set -o pipefail
# Log commands executed
set -x
# Simple way of getting the docker build tag:
tag=$(docker build -q - <<\EOF
FROM debian:bookworm
RUN apt-get update && apt-get install -y build-essential
EOF
)
# But -q suppresses the log output. If you want to keep it,
# you could use the following fancier way:
exec {pfd}<><(:) # get a new pipe
docker build - <<\EOF |
FROM debian:bookworm
RUN apt-get update && apt-get install -y build-essential
EOF
tee >(awk '/Successfully built/{print $3}' >&$pfd) # parse output to pipe
read tag <&$pfd # read tag back from pipe
exec {pfd}<&- # close pipe
# Alternatively, you can use the -t option to docker build
# to give the built image a name to refer to later. But then
# you need to ensure that it does not conflict with any other
# images, and handle cases where multiple instances of the
# job attempt to update the tagged image.
# If you want the image to be cleaned up on exit:
trap "docker rmi $tag" EXIT
# Now use the image to build something:
docker run -i --rm \
-v "$PWD:$PWD" \
-w "$PWD" \
-u $(id -u):$(id -g) \
$tag /bin/bash -eux \
<<EOF
# The passed options mean we keep our current working
# directory and user, so no permission problems on the
# artifacts produced within the container.
echo 'main(){puts("hello world");}' | gcc -x c -static -o hello -
EOF
# Test the result
./hello

117
examples/format-test-results Executable file
View File

@@ -0,0 +1,117 @@
#!/bin/bash
# This example script takes the XML output of a gtest run and formats
# it as HTML. It can easily be adapted to other XML test output formats
# such as JUnit or CTest
# Prepare xml with ./path/to/test --gtest_output=xml:path/to/output.xml
# Usage: format-test-results test_result.xml > output.html
if [ ! -f "$1" ]; then
echo "File not found: \"$1\""
exit 1
fi
xsltproc --stringparam JOB $JOB --stringparam RUN $RUN <(cat <<\EOF
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" indent="yes" />
<xsl:template match="/">
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Test report for <xsl:value-of select="$JOB" /> #<xsl:value-of select="$RUN" /></title>
<style>
body { font-family: Helvetica Neue, Helvetica, Arial, sans-serif; }
label:hover { cursor: pointer; }
label:before { content: '+ ' }
input[type=checkbox].toggle-collapse { display: none; }
input[type=checkbox].toggle-collapse~.collapsible { display: none; }
input[type=checkbox].toggle-collapse:checked~.collapsible { display: block; }
code { white-space: pre-wrap; color: white; }
.failure { background-color: #c73030; color: white; }
table { min-width: 720px; border-collapse: collapse; }
td, th { padding: 5px; }
tr:nth-child(even) td { padding: 0; }
tr:nth-child(even) { border-bottom: 1px solid #b3abab; }
.testcase { padding: 5px; }
.testcase.success:before { content: '✔ '; color: green; }
</style>
</head>
<body>
<h1><xsl:value-of select="$JOB" /> #<xsl:value-of select="$RUN" /></h1>
<h2>Test Report</h2>
<table>
<thead>
<tr>
<th>Suite</th>
<th>Tests run</th>
<th>Failures</th>
<th>Errors</th>
<th>Elapsed time</th>
</tr>
</thead>
<xsl:apply-templates select="testsuites" />
</table>
</body>
</html>
</xsl:template>
<xsl:template match="testsuite">
<xsl:variable name="result">
<xsl:choose>
<xsl:when test="(@failures &gt; 0) or (@errors &gt; 0)">failure</xsl:when>
<xsl:otherwise>success</xsl:otherwise>
</xsl:choose>
</xsl:variable>
<tr class="{$result}">
<td>
<label for="suite-{@name}"><xsl:value-of select="@name" /></label>
</td>
<td><xsl:value-of select="@tests" /></td>
<td><xsl:value-of select="@failures" /></td>
<td><xsl:value-of select="@errors" /></td>
<td><xsl:value-of select="@time" /></td>
</tr>
<tr class="toggle-target">
<td colspan="5">
<input class="toggle-collapse" id="suite-{@name}" type="checkbox" />
<div class="collapsible" style="padding-left: 15px;">
<xsl:apply-templates select="testcase" />
</div>
</td>
</tr>
</xsl:template>
<xsl:template match="testcase">
<xsl:choose>
<!-- has child nodes? -->
<xsl:when test="*">
<div class="testcase failure">
<xsl:value-of select="@name" /><br />
<xsl:apply-templates select="failure" />
</div>
</xsl:when>
<xsl:otherwise>
<div class="testcase success">
<xsl:value-of select="@name" />
</div>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<xsl:template match="failure">
<div style="padding: 5px; background-color: #313235">
<code>
<xsl:value-of select="@message"/>
</code>
</div>
</xsl:template>
</xsl:stylesheet>
EOF
) "$1"

View File

@@ -0,0 +1,42 @@
#!/bin/bash -e
# Simple post-receive hook that triggers a laminar run
# for every commit pushed to every branch, and annotates
# the commit with the run number using a git note.
# On the cloned repository, useful config is
# git config --add remote.origin.fetch "+refs/notes/*:refs/notes/*"
# to automatically fetch all notes from the origin, and
# git config --add notes.displayRef "refs/notes/*"
# to display all notes in the git log by default
# The laminar job to trigger
LAMINAR_JOB=my-project
# Default notes ref is refs/notes/commits
NOTES_REF=refs/notes/ci
# For each ref pushed...
while read old new ref; do
# Skip tags, notes, etc. Only do heads.
# Extend this to only trigger on specific branches.
if [[ $ref != refs/heads/* ]]; then
continue
fi
# Otherwise, for each new commit in the ref...
# (to only trigger on the newest, set commit=$new and delete the loop)
git rev-list $([[ $old =~ ^0+$ ]] && echo $new || echo $old..$new) | while read commit; do
# Queue the laminar run
run=$(laminarc queue $LAMINAR_JOB commit=$commit ref=$ref)
echo "Started Laminar $run for commit $commit to ref $ref"
# Add a git note about the run
blob=$(echo -n "Laminar-Run: $run" | git hash-object -w --stdin)
if last_note=$(git show-ref -s $NOTES_REF); then
git read-tree $last_note
p_arg=-p
fi
git update-index --add --cacheinfo 100644 $blob $commit
tree=$(git write-tree)
new_note=$(echo "Notes added by post-receive hook" | git commit-tree $tree $p_arg $last_note)
git update-ref $NOTES_REF $new_note $last_note
done
done

View File

@@ -0,0 +1,52 @@
server {
listen [::]:80;
listen 80;
server_name laminar.example.com;
# rule for letsencrypt ACME challenge requests
location ^~ /.well-known/acme-challenge/ {
default_type "text/plain";
alias /srv/www/acme-challenge/;
}
# redirect all other http to https
return 301 https://$server_name$request_uri;
}
server {
# http2 is recommended because browsers will only open a small number of concurrent SSE streams over http1
listen [::]:443 ssl http2;
listen 443 ssl http2;
server_name laminar.example.com;
# modern tls only, see https://syslink.pl/cipherlist/ for a more complete example
ssl_protocols TLSv1.3;
ssl_ciphers EECDH+AESGCM:EDH+AESGCM;
# set according to ACME/letsencrypt client
ssl_certificate /path/to/certificate.crt;
ssl_certificate_key /path/to/private.key;
# use "location /" if laminar is to be accessible at the (sub)domain root.
# alteratively, use a subdirectory such as "location /my-laminar/" and ensure that
# LAMINAR_BASE_URL=/my-laminar/ accordingly.
location / {
# set proxy_pass according to LAMINAR_BIND_HTTP.
# note that the laminar default for LAMINAR_BIND_HTTP is *:8080, which binds on all interfaces
# instead of just the loopback device and is almost certainly not what you want if you are using
# a reverse proxy. It should be set to 127.0.0.1:8080 at a minimum, or use unix sockets for more
# fine-grained control of permissions.
# see http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_pass
# and https://laminar.ohwg.net/docs.html#Running-on-a-different-HTTP-port-or-Unix-socket
proxy_pass http://127.0.0.1:8080/;
# required to allow laminar's SSE stream to pass correctly
proxy_http_version 1.1;
proxy_set_header Connection "";
}
# have nginx serve artefacts directly rather than having laminard do it
location /archive/ {
alias /var/lib/laminar/archive/;
}
}

55
examples/notify-email-pretty Executable file
View File

@@ -0,0 +1,55 @@
#!/bin/bash -e
# IMPORTANT: change these to appropriate values, or fetch them, for example
# from the environment or from $(git show -s --format='%ae' $rev)
TO_EMAIL=engineering@example.com
FROM_EMAIL=laminar@example.com
LAMINAR_URL=${LAMINAR_BASE_URL:-http://localhost:8080}
LAMINAR_TITLE=${LAMINAR_TITLE:-Laminar CI}
if [[ $RESULT = "success" ]]; then
SVGICON=$(cat <<-EOF
<svg viewBox="0 0 100 100" width="24px">
<path fill="#74af77" d="m 23,46 c -6,0 -17,3 -17,11 0,8 9,30 12,32 3,2 14,5 20,-2 6,-6 24,-36
56,-71 5,-3 -9,-8 -23,-2 -13,6 -33,42 -41,47 -6,-3 -5,-12 -8,-15 z" />
</svg>
EOF
)
else
SVGICON=$(cat <<-EOF
<svg viewBox="0 0 100 100" width="24px">
<path fill="#883d3d" d="m 19,20 c 2,8 12,29 15,32 -5,5 -18,21 -21,26 2,3 8,15 11,18 4,-6 17,-21
21,-26 5,5 11,15 15,20 8,-2 15,-9 20,-15 -3,-3 -17,-18 -20,-24 3,-5 23,-26 30,-33 -3,-5 -8,-9
-12,-12 -6,5 -26,26 -29,30 -6,-8 -11,-15 -15,-23 -3,0 -12,5 -15,7 z" />
</svg>
EOF
)
fi
sendmail -t <<EOF
From: $FROM_EMAIL
To: $TO_EMAIL
Subject: $JOB #$RUN: $RESULT
Mime-Version: 1.0
Content-Type: text/html; charset=utf-8
<html lang="en">
<body bgcolor="#efefef" style="margin: 0; font-family: Helvetica Neue, Helvetica, Arial, sans-serif">
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr><td align="center">
<table border="0" cellspacing="0" cellpadding="15" bgcolor="#ffffff">
<tr bgcolor="#2f3340">
<td style="font-size: 28px; color: #ffffff;">$LAMINAR_TITLE</td></tr>
<tr>
<td style="font-size: 26px">
$SVGICON
<a href="$LAMINAR_URL/jobs/$JOB/$RUN">$JOB #$RUN</a>
</td>
</tr>
</table>
</td></tr>
</table>
</body>
</html>
EOF

18
examples/notify-email-text-log Executable file
View File

@@ -0,0 +1,18 @@
#!/bin/bash -e
# IMPORTANT: change these to appropriate values, or fetch them, for example
# from the environment or from $(git show -s --format='%ae' $rev)
TO_EMAIL=engineering@example.com
FROM_EMAIL=laminar@example.com
LAMINAR_URL=${LAMINAR_BASE_URL:-http://localhost:8080}
sendmail -t <<EOF
From: $FROM_EMAIL
To: $TO_EMAIL
Subject: $JOB #$RUN: $RESULT
Mime-Version: 1.0
Content-Type: text/plain; charset=utf-8
$(curl -s $LAMINAR_URL/log/$JOB/$RUN)
EOF

18
examples/notify-telegram Executable file
View File

@@ -0,0 +1,18 @@
#!/bin/bash -e
# Sends a message from a specified bot to a specific telegram chat ID.
# See https://core.telegram.org/bots
# IMPORTANT: modify this to your real bot token and chat ID
BOT_TOKEN=123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11
CHAT_ID=10000000
LAMINAR_URL=${LAMINAR_BASE_URL:-http://localhost:8080}
[[ $(curl -sS https://api.telegram.org/bot$BOT_TOKEN/sendMessage \
-d chat_id=$CHAT_ID \
-d parse_mode=HTML \
-d text="<a href=\"$LAMINAR_URL/jobs/$JOB/$RUN\">$JOB #$RUN</a> $RESULT" \
| jq .ok) == true ]]

46
examples/plot-build-time-dist Executable file
View File

@@ -0,0 +1,46 @@
#!/usr/bin/env gnuplot
# Deeper insights can be obtained by querying Laminar's database directly.
# This example uses gnuplot to create a graph of the distribution of the
# average run time of jobs.
# The following will output a png...
set terminal pngcairo size 800,580 enhanced font 'Helvetica,10'
set output 'build-time-distribution.png'
# ..comment it out to use an interactive widget
# plot style
set tics font "Helvetica,10"
set title font "Helvetica,11"
set xtics nomirror
set ytics nomirror
set border 3 back lt 1 lc rgb "#808080"
set grid back lt 0 lc rgb "#d0d0d0" lw 0.5
set style line 1 lt 1 lc rgb "#7483af" lw 2
# Fetch the path to Laminar's sqlite database
db = system("echo $LAMINAR_HOME") . '/laminar.sqlite'
# Label the axes
set xtics ("<30s" 0, "30s-1m" 1, "1m-5m" 2, "5m-10m" 3, "10m-20m" 4, "20m-40m" 5, "40m-60m" 6, ">60m" 7)
set ylabel "Number of jobs"
set xlabel "Average run time"
set title "Distribution of average run times"
plot '< sqlite3 -separator $''\n'' ' . db . ' \
"WITH ba AS (SELECT name,AVG(completedAt-startedAt) a FROM builds GROUP BY name) SELECT \
COUNT(CASE WHEN a < 30 THEN 1 END), \
COUNT(CASE WHEN a >= 30 AND a < 60 THEN 1 END), \
COUNT(CASE WHEN a >= 60 AND a < 300 THEN 1 END), \
COUNT(CASE WHEN a >= 300 AND a < 600 THEN 1 END), \
COUNT(CASE WHEN a >= 600 AND a < 1200 THEN 1 END), \
COUNT(CASE WHEN a >= 1200 AND a < 2400 THEN 1 END), \
COUNT(CASE WHEN a >= 2400 AND a < 3600 THEN 1 END), \
COUNT(CASE WHEN a >= 3600 THEN 1 END) FROM ba;"' \
using 0:1 with linespoints title '' ls 1
# uncomment this if using an interactive window
#pause mouse close
# Release the output
set output

View File

@@ -1,81 +0,0 @@
#!/bin/bash -e
OUTPUT_DIR=$PWD
SOURCE_DIR=$(readlink -f $(dirname ${BASH_SOURCE[0]})/..)
VERSION=$(cd "$SOURCE_DIR" && git describe --tags --abbrev=8 --dirty | tr - .)~upstream_centos7
DOCKER_TAG=$(docker build -q - <<EOS
FROM centos:7
RUN yum -y install epel-release centos-release-scl && yum-config-manager --enable rhel-server-rhscl-7-rpms && yum -y install rpm-build cmake3 make devtoolset-7-gcc-c++ wget sqlite-devel boost-devel zlib-devel
EOS
)
docker run --rm -i -v $SOURCE_DIR:/root/rpmbuild/SOURCES/laminar-$VERSION:ro -v $OUTPUT_DIR:/output $DOCKER_TAG bash -xe <<EOS
# for new gcc
export PATH=/opt/rh/devtoolset-7/root/usr/bin:\$PATH
mkdir /build
cd /build
wget -O capnproto.tar.gz https://github.com/capnproto/capnproto/archive/v0.7.0.tar.gz
wget -O rapidjson.tar.gz https://github.com/miloyip/rapidjson/archive/v1.1.0.tar.gz
md5sum -c <<EOF
a9de5f042f4cf05515c2d7dfc7f5df21 capnproto.tar.gz
badd12c511e081fec6c89c43a7027bce rapidjson.tar.gz
EOF
tar xzf capnproto.tar.gz
tar xzf rapidjson.tar.gz
cd /build/capnproto-0.7.0/c++/
cmake3 -DCMAKE_BUILD_TYPE=Release -DBUILD_TESTING=off .
make -j4
make install
cd /build/rapidjson-1.1.0/
cmake3 -DRAPIDJSON_BUILD_EXAMPLES=off .
make install
cd
cat <<EOF > laminar.spec
Summary: Lightweight Continuous Integration Service
Name: laminar
Version: $VERSION
Release: 1
License: GPL
BuildRequires: systemd-units
Requires: sqlite zlib
%description
Lightweight Continuous Integration Service
%prep
%build
cmake3 -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/usr -DLAMINAR_VERSION=$VERSION -DSYSTEMD_UNITDIR=%{_unitdir} %{_sourcedir}/laminar-$VERSION
pwd
make
%install
%make_install
%files
%{_bindir}/laminarc
%{_sbindir}/laminard
%{_unitdir}/laminar.service
%config(noreplace) %{_sysconfdir}/laminar.conf
%{_datarootdir}/bash-completion/completions/laminarc
%{_datarootdir}/zsh/site-functions/_laminarc
%post
echo Creating laminar user with home in %{_sharedstatedir}/laminar
useradd -r -d %{_sharedstatedir}/laminar -s %{_sbindir}/nologin laminar
mkdir -p %{_sharedstatedir}/laminar/cfg/{jobs,contexts,scripts}
chown -R laminar: %{_sharedstatedir}/laminar
EOF
rpmbuild -ba laminar.spec
mv rpmbuild/RPMS/x86_64/laminar-$VERSION-1.x86_64.rpm /output/
EOS

View File

@@ -4,11 +4,11 @@ OUTPUT_DIR=$PWD
SOURCE_DIR=$(readlink -f $(dirname ${BASH_SOURCE[0]})/..)
VERSION=$(cd "$SOURCE_DIR" && git describe --tags --abbrev=8 --dirty)-1~upstream-debian10
VERSION=$(cd "$SOURCE_DIR" && git describe --tags --abbrev=8 --dirty)-1~upstream-debian13
DOCKER_TAG=$(docker build -q - <<EOS
FROM debian:10-slim
RUN apt-get update && apt-get install -y wget cmake g++ capnproto libcapnp-dev rapidjson-dev libsqlite3-dev libboost-dev zlib1g-dev
FROM debian:13-slim
RUN apt-get update && apt-get install -y wget cmake g++ capnproto libcapnp-dev rapidjson-dev libsqlite3-dev libboost-dev zlib1g-dev pkg-config
EOS
)
@@ -30,7 +30,7 @@ Section:
Priority: optional
Architecture: amd64
Maintainer: Oliver Giles <web ohwg net>
Depends: libcapnp-0.7.0, libsqlite3-0, zlib1g
Depends: libcapnp-1.0.1, libsqlite3-0, zlib1g
Description: Lightweight Continuous Integration Service
EOF
echo /etc/laminar.conf > laminar/DEBIAN/conffiles

View File

@@ -4,11 +4,11 @@ OUTPUT_DIR=$PWD
SOURCE_DIR=$(readlink -f $(dirname ${BASH_SOURCE[0]})/..)
VERSION=$(cd "$SOURCE_DIR" && git describe --tags --abbrev=8 --dirty)-1~upstream-debian10
VERSION=$(cd "$SOURCE_DIR" && git describe --tags --abbrev=8 --dirty)-1~upstream-debian13
DOCKER_TAG=$(docker build -q - <<EOS
FROM debian:10-slim
RUN dpkg --add-architecture armhf && apt-get update && apt-get install -y wget cmake crossbuild-essential-armhf capnproto libcapnp-dev:armhf rapidjson-dev libsqlite3-dev:armhf libboost-dev:armhf zlib1g-dev:armhf
FROM debian:13-slim
RUN dpkg --add-architecture armhf && apt-get update && apt-get install -y wget cmake pkg-config crossbuild-essential-armhf capnproto libcapnp-dev:armhf rapidjson-dev:armhf libsqlite3-dev:armhf libboost-dev:armhf zlib1g-dev:armhf
EOS
)
@@ -17,18 +17,19 @@ docker run --rm -i -v $SOURCE_DIR:/laminar:ro -v $OUTPUT_DIR:/output $DOCKER_TAG
mkdir /build
cd /build
cat > toolchain.cmake <<EOF
SET(CMAKE_C_COMPILER arm-linux-gnueabihf-gcc)
SET(CMAKE_CXX_COMPILER arm-linux-gnueabihf-g++)
set(CMAKE_LIBRARY_ARCHITECTURE arm-linux-gnueabihf)
cat > toolchain.cmake <<\EOF
set(CMAKE_C_COMPILER arm-linux-gnueabihf-gcc)
set(CMAKE_CXX_COMPILER arm-linux-gnueabihf-g++)
set(CMAKE_PREFIX_PATH /usr/lib/arm-linux-gnueabihf)
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
set(ENV{PKG_CONFIG_PATH} "/usr/lib/arm-linux-gnueabihf/pkgconfig")
EOF
cd /build
cmake \
-DCMAKE_TOOLCHAIN_FILE=toolchain.cmake \
-DCMAKE_LINKER=/usr/bin/arm-linux-gnueabihf-ld \
-DCMAKE_OBJCOPY=/usr/bin/arm-linux-gnueabihf-objcopy \
-DCMAKE_STRIP=/usr/bin/arm-linux-gnueabihf-strip \
-DCMAKE_BUILD_TYPE=Release \
-DCMAKE_INSTALL_PREFIX=/usr \
-DLAMINAR_VERSION=$VERSION \
@@ -46,7 +47,7 @@ Section:
Priority: optional
Architecture: armhf
Maintainer: Oliver Giles <web ohwg net>
Depends: libcapnp-0.7.0, libsqlite3-0, zlib1g
Depends: libcapnp-1.0.1, libsqlite3-0, zlib1g
Description: Lightweight Continuous Integration Service
EOF
echo /etc/laminar.conf > laminar/DEBIAN/conffiles

48
pkg/debian14-amd64.sh Executable file
View File

@@ -0,0 +1,48 @@
#!/bin/bash -e
OUTPUT_DIR=$PWD
SOURCE_DIR=$(readlink -f $(dirname ${BASH_SOURCE[0]})/..)
VERSION=$(cd "$SOURCE_DIR" && git describe --tags --abbrev=8 --dirty)-1~upstream-debian14
DOCKER_TAG=$(docker build -q - <<EOS
FROM debian:forky-slim
RUN apt-get update && apt-get install -y wget cmake g++ capnproto libcapnp-dev rapidjson-dev libsqlite3-dev libboost-dev zlib1g-dev pkg-config
EOS
)
docker run --rm -i -v $SOURCE_DIR:/laminar:ro -v $OUTPUT_DIR:/output $DOCKER_TAG bash -xe <<EOS
mkdir /build
cd /build
cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/usr -DLAMINAR_VERSION=$VERSION -DZSH_COMPLETIONS_DIR=/usr/share/zsh/functions/Completion/Unix /laminar
make -j4
mkdir laminar
make DESTDIR=laminar install/strip
mkdir laminar/DEBIAN
cat <<EOF > laminar/DEBIAN/control
Package: laminar
Version: $VERSION
Section:
Priority: optional
Architecture: amd64
Maintainer: Oliver Giles <web ohwg net>
Depends: libcapnp-1.1.0, libsqlite3-0, zlib1g
Description: Lightweight Continuous Integration Service
EOF
echo /etc/laminar.conf > laminar/DEBIAN/conffiles
cat <<EOF > laminar/DEBIAN/postinst
#!/bin/bash
echo Creating laminar user with home in /var/lib/laminar
useradd -r -d /var/lib/laminar -s /usr/sbin/nologin laminar
mkdir -p /var/lib/laminar/cfg/{jobs,contexts,scripts}
chown -R laminar: /var/lib/laminar
EOF
chmod +x laminar/DEBIAN/postinst
dpkg-deb --build laminar
mv laminar.deb /output/laminar_${VERSION}_amd64.deb
EOS

65
pkg/debian14-armhf.sh Executable file
View File

@@ -0,0 +1,65 @@
#!/bin/bash -e
OUTPUT_DIR=$PWD
SOURCE_DIR=$(readlink -f $(dirname ${BASH_SOURCE[0]})/..)
VERSION=$(cd "$SOURCE_DIR" && git describe --tags --abbrev=8 --dirty)-1~upstream-debian14
DOCKER_TAG=$(docker build -q - <<EOS
FROM debian:forky-slim
RUN dpkg --add-architecture armhf && apt-get update && apt-get install -y wget cmake pkg-config crossbuild-essential-armhf capnproto libcapnp-dev:armhf rapidjson-dev:armhf libsqlite3-dev:armhf libboost-dev:armhf zlib1g-dev:armhf
EOS
)
docker run --rm -i -v $SOURCE_DIR:/laminar:ro -v $OUTPUT_DIR:/output $DOCKER_TAG bash -xe <<EOS
mkdir /build
cd /build
cat > toolchain.cmake <<\EOF
set(CMAKE_C_COMPILER arm-linux-gnueabihf-gcc)
set(CMAKE_CXX_COMPILER arm-linux-gnueabihf-g++)
set(CMAKE_PREFIX_PATH /usr/lib/arm-linux-gnueabihf)
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
set(ENV{PKG_CONFIG_PATH} "/usr/lib/arm-linux-gnueabihf/pkgconfig")
EOF
cd /build
cmake \
-DCMAKE_TOOLCHAIN_FILE=toolchain.cmake \
-DCMAKE_BUILD_TYPE=Release \
-DCMAKE_INSTALL_PREFIX=/usr \
-DLAMINAR_VERSION=$VERSION \
-DZSH_COMPLETIONS_DIR=/usr/share/zsh/functions/Completion/Unix \
/laminar
make -j4
mkdir laminar
make DESTDIR=laminar install/strip
mkdir laminar/DEBIAN
cat <<EOF > laminar/DEBIAN/control
Package: laminar
Version: $VERSION
Section:
Priority: optional
Architecture: armhf
Maintainer: Oliver Giles <web ohwg net>
Depends: libcapnp-1.1.0, libsqlite3-0, zlib1g
Description: Lightweight Continuous Integration Service
EOF
echo /etc/laminar.conf > laminar/DEBIAN/conffiles
cat <<EOF > laminar/DEBIAN/postinst
#!/bin/bash
echo Creating laminar user with home in /var/lib/laminar
useradd -r -d /var/lib/laminar -s /usr/sbin/nologin laminar
mkdir -p /var/lib/laminar/cfg/{jobs,contexts,scripts}
chown -R laminar: /var/lib/laminar
EOF
chmod +x laminar/DEBIAN/postinst
dpkg-deb --build laminar
mv laminar.deb /output/laminar_${VERSION}_armhf.deb
EOS

62
pkg/opensuse16.0-x86_64.sh Executable file
View File

@@ -0,0 +1,62 @@
#!/bin/bash -e
OUTPUT_DIR=$PWD
SOURCE_DIR=$(readlink -f $(dirname ${BASH_SOURCE[0]})/..)
VERSION=$(cd "$SOURCE_DIR" && git describe --tags --abbrev=8 --dirty | tr - .)~upstream_opensuse16
DOCKER_TAG=$(docker build -q - <<EOS
FROM opensuse/leap:16
RUN zypper --non-interactive refresh && zypper --non-interactive update && zypper --non-interactive install -y rpm-build cmake make gcc-c++ wget sqlite3-devel boost-devel zlib-devel capnproto libcapnp-devel rapidjson-devel
EOS
)
# use /usr/sr/packages for opensuse instead of /root/rpmbuild
docker run --rm -i -v $SOURCE_DIR:/usr/src/packages/SOURCES/laminar-$VERSION:ro -v $OUTPUT_DIR:/output $DOCKER_TAG bash -xe <<EOS
mkdir /build
cd /build
cat <<EOF > laminar.spec
Summary: Lightweight Continuous Integration Service
Name: laminar
Version: $VERSION
Release: 1
License: GPL
URL: https://laminar.ohwg.net/
BuildArch: x86_64
BuildRequires: cmake make gcc-c++ sqlite3-devel boost-devel zlib-devel capnproto libcapnp-devel rapidjson-devel
%description
Lightweight Continuous Integration Service
%prep
%build
cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/usr -DLAMINAR_VERSION=$VERSION -DSYSTEMD_UNITDIR=%{_unitdir} %{_sourcedir}/laminar-$VERSION
pwd
make %{?_smp_mflags}
%install
%make_install
%files
%{_bindir}/laminarc
%{_sbindir}/laminard
%{_unitdir}/laminar.service
%config(noreplace) %{_sysconfdir}/laminar.conf
%{_datarootdir}/bash-completion/completions/laminarc
%{_datarootdir}/zsh/site-functions/_laminarc
%{_mandir}/man8/laminard.8.gz
%{_mandir}/man1/laminarc.1.gz
%post
echo Creating laminar user with home in %{_sharedstatedir}/laminar
useradd -r -d %{_sharedstatedir}/laminar -s %{_sbindir}/nologin laminar
mkdir -p %{_sharedstatedir}/laminar/cfg/{jobs,contexts,scripts}
chown -R laminar: %{_sharedstatedir}/laminar
EOF
rpmbuild -ba laminar.spec
mv /usr/src/packages/RPMS/x86_64/laminar-$VERSION-1.x86_64.rpm /output/
EOS

75
pkg/rocky10-x86_64.sh Executable file
View File

@@ -0,0 +1,75 @@
#!/bin/bash -e
OUTPUT_DIR=$PWD
SOURCE_DIR=$(readlink -f $(dirname ${BASH_SOURCE[0]})/..)
VERSION=$(cd "$SOURCE_DIR" && git describe --tags --abbrev=8 --dirty | tr - .)~upstream_rocky10
DOCKER_TAG=$(docker build -q - <<EOS
FROM rockylinux/rockylinux:10
RUN dnf -y update && dnf -y install rpm-build cmake make gcc-c++ wget sqlite-devel boost-devel zlib-devel systemd-units
RUN mkdir /rapidjson && pushd /rapidjson && \
wget -O rapidjson.tar.gz https://github.com/miloyip/rapidjson/archive/v1.1.0.tar.gz && \
echo "badd12c511e081fec6c89c43a7027bce rapidjson.tar.gz" | md5sum -c && \
tar xzf rapidjson.tar.gz && \
cd rapidjson-1.1.0 && \
cmake -DRAPIDJSON_BUILD_EXAMPLES=off . && \
make install && \
popd && rm -rf /rapidjson
RUN mkdir /capnproto && pushd /capnproto && \
wget -O capnproto.tar.gz https://github.com/capnproto/capnproto/archive/v1.5.0.tar.gz && \
echo "cd64102577a89714b9d58494a7e34cee capnproto.tar.gz" | md5sum -c && \
tar xzf capnproto.tar.gz && \
cd capnproto-1.5.0/c++ && \
cmake -DCMAKE_CXX_FLAGS=-fPIE -DCMAKE_BUILD_TYPE=Release -DBUILD_TESTING=off . && \
make -j4 && \
make install && \
popd && rm -rf /capnproto
EOS
)
docker run --rm -i -v $SOURCE_DIR:/root/rpmbuild/SOURCES/laminar-$VERSION:ro -v $OUTPUT_DIR:/output $DOCKER_TAG bash -xe <<EOS
cd
cat <<EOF > laminar.spec
Summary: Lightweight Continuous Integration Service
Name: laminar
Version: $VERSION
Release: 1
License: GPL
BuildRequires: systemd-units
Requires: sqlite-libs zlib
%description
Lightweight Continuous Integration Service
%prep
%build
cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/usr -DLAMINAR_VERSION=$VERSION -DSYSTEMD_UNITDIR=%{_unitdir} %{_sourcedir}/laminar-$VERSION
pwd
make
%install
%make_install
%files
%{_bindir}/laminarc
%{_sbindir}/laminard
%{_unitdir}/laminar.service
%config(noreplace) %{_sysconfdir}/laminar.conf
%{_datarootdir}/bash-completion/completions/laminarc
%{_datarootdir}/zsh/site-functions/_laminarc
%{_mandir}/man8/laminard.8.gz
%{_mandir}/man1/laminarc.1.gz
%post
echo Creating laminar user with home in %{_sharedstatedir}/laminar
useradd -r -d %{_sharedstatedir}/laminar -s %{_sbindir}/nologin laminar
mkdir -p %{_sharedstatedir}/laminar/cfg/{jobs,contexts,scripts}
chown -R laminar: %{_sharedstatedir}/laminar
EOF
rpmbuild -ba laminar.spec
mv rpmbuild/RPMS/x86_64/laminar-$VERSION-1.x86_64.rpm /output/
EOS

View File

@@ -4,37 +4,32 @@ OUTPUT_DIR=$PWD
SOURCE_DIR=$(readlink -f $(dirname ${BASH_SOURCE[0]})/..)
VERSION=$(cd "$SOURCE_DIR" && git describe --tags --abbrev=8 --dirty | tr - .)~upstream_centos8
VERSION=$(cd "$SOURCE_DIR" && git describe --tags --abbrev=8 --dirty | tr - .)~upstream_rocky9
DOCKER_TAG=$(docker build -q - <<EOS
FROM centos:8
RUN dnf -y install rpm-build cmake make gcc-c++ wget sqlite-devel boost-devel zlib-devel
FROM rockylinux/rockylinux:9
RUN dnf -y update && dnf -y install rpm-build cmake make gcc-c++ wget sqlite-devel boost-devel zlib-devel systemd-units
RUN mkdir /rapidjson && pushd /rapidjson && \
wget -O rapidjson.tar.gz https://github.com/miloyip/rapidjson/archive/v1.1.0.tar.gz && \
echo "badd12c511e081fec6c89c43a7027bce rapidjson.tar.gz" | md5sum -c && \
tar xzf rapidjson.tar.gz && \
cd rapidjson-1.1.0 && \
cmake -DRAPIDJSON_BUILD_EXAMPLES=off . && \
make install && \
popd && rm -rf /rapidjson
RUN mkdir /capnproto && pushd /capnproto && \
wget -O capnproto.tar.gz https://github.com/capnproto/capnproto/archive/v1.5.0.tar.gz && \
echo "cd64102577a89714b9d58494a7e34cee capnproto.tar.gz" | md5sum -c && \
tar xzf capnproto.tar.gz && \
cd capnproto-1.5.0/c++ && \
cmake -DCMAKE_BUILD_TYPE=Release -DBUILD_TESTING=off . && \
make -j4 && \
make install && \
popd && rm -rf /capnproto
EOS
)
docker run --rm -i -v $SOURCE_DIR:/root/rpmbuild/SOURCES/laminar-$VERSION:ro -v $OUTPUT_DIR:/output $DOCKER_TAG bash -xe <<EOS
mkdir /build
cd /build
wget -O capnproto.tar.gz https://github.com/capnproto/capnproto/archive/v0.7.0.tar.gz
wget -O rapidjson.tar.gz https://github.com/miloyip/rapidjson/archive/v1.1.0.tar.gz
md5sum -c <<EOF
a9de5f042f4cf05515c2d7dfc7f5df21 capnproto.tar.gz
badd12c511e081fec6c89c43a7027bce rapidjson.tar.gz
EOF
tar xzf capnproto.tar.gz
tar xzf rapidjson.tar.gz
cd /build/capnproto-0.7.0/c++/
cmake3 -DCMAKE_BUILD_TYPE=Release -DBUILD_TESTING=off .
make -j4
make install
cd /build/rapidjson-1.1.0/
cmake -DRAPIDJSON_BUILD_EXAMPLES=off .
make install
cd
cat <<EOF > laminar.spec
Summary: Lightweight Continuous Integration Service
@@ -65,6 +60,8 @@ make
%config(noreplace) %{_sysconfdir}/laminar.conf
%{_datarootdir}/bash-completion/completions/laminarc
%{_datarootdir}/zsh/site-functions/_laminarc
%{_mandir}/man8/laminard.8.gz
%{_mandir}/man1/laminarc.1.gz
%post
echo Creating laminar user with home in %{_sharedstatedir}/laminar

49
pkg/ubuntu2204-amd64.sh Executable file
View File

@@ -0,0 +1,49 @@
#!/bin/bash -e
OUTPUT_DIR=$PWD
SOURCE_DIR=$(readlink -f $(dirname ${BASH_SOURCE[0]})/..)
VERSION=$(cd "$SOURCE_DIR" && git describe --tags --abbrev=8 --dirty)-1~upstream-ubuntu2204
DOCKER_TAG=$(docker build -q - <<EOS
FROM ubuntu:22.04
RUN apt-get update && apt-get install -y wget cmake g++ capnproto libcapnp-dev rapidjson-dev libsqlite3-dev libboost-dev zlib1g-dev pkg-config
EOS
)
docker run --rm -i -v $SOURCE_DIR:/laminar:ro -v $OUTPUT_DIR:/output $DOCKER_TAG bash -xe <<EOS
mkdir /build
cd /build
cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/usr -DLAMINAR_VERSION=$VERSION -DZSH_COMPLETIONS_DIR=/usr/share/zsh/functions/Completion/Unix /laminar
make -j4
mkdir laminar
make DESTDIR=laminar install/strip
mkdir laminar/DEBIAN
cat <<EOF > laminar/DEBIAN/control
Package: laminar
Version: $VERSION
Section:
Priority: optional
Architecture: amd64
Maintainer: Oliver Giles <web ohwg net>
Depends: libcapnp-0.8.0, libsqlite3-0, zlib1g
Description: Lightweight Continuous Integration Service
EOF
echo /etc/laminar.conf > laminar/DEBIAN/conffiles
cat <<EOF > laminar/DEBIAN/postinst
#!/bin/bash
echo Creating laminar user with home in /var/lib/laminar
useradd -r -d /var/lib/laminar -s /usr/sbin/nologin laminar
mkdir -p /var/lib/laminar/cfg/{jobs,contexts,scripts}
chown -R laminar: /var/lib/laminar
EOF
chmod +x laminar/DEBIAN/postinst
dpkg-deb --build laminar
mv laminar.deb /output/laminar_${VERSION}_amd64.deb
EOS

49
pkg/ubuntu2404-amd64.sh Executable file
View File

@@ -0,0 +1,49 @@
#!/bin/bash -e
OUTPUT_DIR=$PWD
SOURCE_DIR=$(readlink -f $(dirname ${BASH_SOURCE[0]})/..)
VERSION=$(cd "$SOURCE_DIR" && git describe --tags --abbrev=8 --dirty)-1~upstream-ubuntu2404
DOCKER_TAG=$(docker build -q - <<EOS
FROM ubuntu:24.04
RUN apt-get update && apt-get install -y wget cmake g++ capnproto libcapnp-dev rapidjson-dev libsqlite3-dev libboost-dev zlib1g-dev pkg-config
EOS
)
docker run --rm -i -v $SOURCE_DIR:/laminar:ro -v $OUTPUT_DIR:/output $DOCKER_TAG bash -xe <<EOS
mkdir /build
cd /build
cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/usr -DLAMINAR_VERSION=$VERSION -DZSH_COMPLETIONS_DIR=/usr/share/zsh/functions/Completion/Unix /laminar
make -j4
mkdir laminar
make DESTDIR=laminar install/strip
mkdir laminar/DEBIAN
cat <<EOF > laminar/DEBIAN/control
Package: laminar
Version: $VERSION
Section:
Priority: optional
Architecture: amd64
Maintainer: Oliver Giles <web ohwg net>
Depends: libcapnp-1.0.1, libsqlite3-0, zlib1g
Description: Lightweight Continuous Integration Service
EOF
echo /etc/laminar.conf > laminar/DEBIAN/conffiles
cat <<EOF > laminar/DEBIAN/postinst
#!/bin/bash
echo Creating laminar user with home in /var/lib/laminar
useradd -r -d /var/lib/laminar -s /usr/sbin/nologin laminar
mkdir -p /var/lib/laminar/cfg/{jobs,contexts,scripts}
chown -R laminar: /var/lib/laminar
EOF
chmod +x laminar/DEBIAN/postinst
dpkg-deb --build laminar
mv laminar.deb /output/laminar_${VERSION}_amd64.deb
EOS

View File

@@ -1,5 +1,5 @@
///
/// Copyright 2015-2020 Oliver Giles
/// Copyright 2015-2022 Oliver Giles
///
/// This file is part of Laminar
///
@@ -87,14 +87,16 @@ static void printTriggerLink(const char* job, uint run) {
static void usage(std::ostream& out) {
out << "laminarc version " << laminar_version() << "\n";
out << "Usage: laminarc [-h|--help] COMMAND [PARAMETERS...]]\n";
out << "Usage: laminarc [-h|--help] COMMAND\n";
out << " -h|--help show this help message\n";
out << "where COMMAND is:\n";
out << " queue JOB_LIST... queues one or more jobs for execution and returns immediately.\n";
out << " start JOB_LIST... queues one or more jobs for execution and blocks until it starts.\n";
out << " run JOB_LIST... queues one or more jobs for execution and blocks until it finishes.\n";
out << " JOB_LIST may be prepended with --next, in this case the job will\n";
out << " be pushed to the front of the queue instead of the end.\n";
out << " set PARAMETER_LIST... sets the given parameters as environment variables in the currently\n";
out << " runing job. Fails if run outside of a job context.\n";
out << " running job. Fails if run outside of a job context.\n";
out << " abort NAME NUMBER aborts the run identified by NAME and NUMBER.\n";
out << " show-jobs lists all known jobs.\n";
out << " show-queued lists currently queued jobs.\n";
@@ -132,38 +134,40 @@ int main(int argc, char** argv) {
auto& waitScope = client.getWaitScope();
if(strcmp(argv[1], "queue") == 0) {
if(argc < 3) {
fprintf(stderr, "Usage %s queue <jobName>\n", argv[0]);
int jobNameIndex = 2;
bool frontOfQueue = false;
if(strcmp(argv[1], "queue") == 0 || strcmp(argv[1], "start") == 0 || strcmp(argv[1], "run") == 0) {
if(argc < 3 || (strcmp(argv[2], "--next") == 0 && argc < 4)) {
fprintf(stderr, "Usage %s %s JOB_LIST...\n", argv[0], argv[1]);
return EXIT_BAD_ARGUMENT;
}
int jobNameIndex = 2;
// make a request for each job specified on the commandline
if(strcmp(argv[2], "--next") == 0) {
frontOfQueue = true;
jobNameIndex++;
}
}
if(strcmp(argv[1], "queue") == 0) {
do {
auto req = laminar.queueRequest();
req.setJobName(argv[jobNameIndex]);
req.setFrontOfQueue(frontOfQueue);
int n = setParams(argc - jobNameIndex - 1, &argv[jobNameIndex + 1], req);
ts.add(req.send().then([&ret,argv,jobNameIndex](capnp::Response<LaminarCi::QueueResults> resp){
if(resp.getResult() != LaminarCi::MethodResult::SUCCESS) {
fprintf(stderr, "Failed to queue job '%s'\n", argv[jobNameIndex]);
ret = EXIT_OPERATION_FAILED;
}
} else
printTriggerLink(argv[jobNameIndex], resp.getBuildNum());
}));
jobNameIndex += n + 1;
} while(jobNameIndex < argc);
} else if(strcmp(argv[1], "start") == 0 || strcmp(argv[1], "trigger") == 0) {
if(strcmp(argv[1], "trigger") == 0)
fprintf(stderr, "Warning: 'trigger' is deprecated, use 'queue' for the old behavior\n");
if(argc < 3) {
fprintf(stderr, "Usage %s queue <jobName>\n", argv[0]);
return EXIT_BAD_ARGUMENT;
}
kj::Vector<capnp::RemotePromise<LaminarCi::StartResults>> promises;
int jobNameIndex = 2;
// make a request for each job specified on the commandline
} else if(strcmp(argv[1], "start") == 0) {
do {
auto req = laminar.startRequest();
req.setJobName(argv[jobNameIndex]);
req.setFrontOfQueue(frontOfQueue);
int n = setParams(argc - jobNameIndex - 1, &argv[jobNameIndex + 1], req);
ts.add(req.send().then([&ret,argv,jobNameIndex](capnp::Response<LaminarCi::StartResults> resp){
if(resp.getResult() != LaminarCi::MethodResult::SUCCESS) {
@@ -175,21 +179,16 @@ int main(int argc, char** argv) {
jobNameIndex += n + 1;
} while(jobNameIndex < argc);
} else if(strcmp(argv[1], "run") == 0) {
if(argc < 3) {
fprintf(stderr, "Usage %s run <jobName>\n", argv[0]);
return EXIT_BAD_ARGUMENT;
}
int jobNameIndex = 2;
// make a request for each job specified on the commandline
do {
auto req = laminar.runRequest();
req.setJobName(argv[jobNameIndex]);
req.setFrontOfQueue(frontOfQueue);
int n = setParams(argc - jobNameIndex - 1, &argv[jobNameIndex + 1], req);
ts.add(req.send().then([&ret,argv,jobNameIndex](capnp::Response<LaminarCi::RunResults> resp){
if(resp.getResult() == LaminarCi::JobResult::UNKNOWN)
fprintf(stderr, "Failed to start job '%s'\n", argv[2]);
else
printTriggerLink(argv[jobNameIndex], resp.getBuildNum());
else
printTriggerLink(argv[jobNameIndex], resp.getBuildNum());
if(resp.getResult() != LaminarCi::JobResult::SUCCESS)
ret = EXIT_RUN_FAILED;
}));
@@ -234,7 +233,7 @@ int main(int argc, char** argv) {
}
auto queued = laminar.listQueuedRequest().send().wait(waitScope);
for(auto it : queued.getResult()) {
printf("%s\n", it.cStr());
printf("%s:%d\n", it.getJob().cStr(), it.getBuildNum());
}
} else if(strcmp(argv[1], "show-running") == 0) {
if(argc != 2) {

View File

@@ -1,5 +1,5 @@
///
/// Copyright 2015 Oliver Giles
/// Copyright 2015-2026 Oliver Giles
///
/// This file is part of Laminar
///
@@ -16,8 +16,7 @@
/// You should have received a copy of the GNU General Public License
/// along with Laminar. If not, see <http://www.gnu.org/licenses/>
///
#ifndef LAMINAR_CONF_H_
#define LAMINAR_CONF_H_
#pragma once
#include <string>
#include <unordered_map>
@@ -41,5 +40,3 @@ int StringMap::convert(std::string e);
// beginning with '#'
StringMap parseConfFile(const char* path);
#endif // LAMINAR_CONF_H_

View File

@@ -1,5 +1,5 @@
///
/// Copyright 2015-2019 Oliver Giles
/// Copyright 2015-2026 Oliver Giles
///
/// This file is part of Laminar
///
@@ -16,19 +16,12 @@
/// You should have received a copy of the GNU General Public License
/// along with Laminar. If not, see <http://www.gnu.org/licenses/>
///
#ifndef LAMINAR_CONTEXT_H_
#define LAMINAR_CONTEXT_H_
#pragma once
#include <fnmatch.h>
#include <string>
#include <set>
class Run;
// FNM_EXTMATCH isn't supported under musl
#if !defined(FNM_EXTMATCH)
#define FNM_EXTMATCH 0
#endif
// Represents a context within which a Run will be executed. Allows applying
// a certain environment to a set of Jobs, or setting a limit on the number
// of parallel Runs
@@ -39,18 +32,6 @@ public:
std::string name;
int numExecutors;
int busyExecutors = 0;
bool canQueue(std::set<std::string>& patterns) {
if(busyExecutors >= numExecutors)
return false;
for(std::string pattern : patterns) {
if(fnmatch(pattern.c_str(), name.c_str(), FNM_EXTMATCH) == 0)
return true;
}
return false;
}
std::set<std::string> jobPatterns;
};
#endif // LAMINAR_CONTEXT_H_

View File

@@ -21,6 +21,7 @@
#include <sqlite3.h>
#include <string.h>
#include <math.h>
#include <cstdint>
struct StdevCtx {
double mean;
@@ -93,6 +94,10 @@ void Database::Statement::bindValue(int i, ulong e) {
sqlite3_bind_int64(stmt, i, static_cast<int64_t>(e));
}
void Database::Statement::bindValue(int i, long long e) {
sqlite3_bind_int64(stmt, i, static_cast<int64_t>(e));
}
void Database::Statement::bindValue(int i, const char* e) {
sqlite3_bind_text(stmt, i, e, -1, nullptr);
}
@@ -129,6 +134,10 @@ template<> ulong Database::Statement::fetchColumn(int col) {
return static_cast<ulong>(sqlite3_column_int64(stmt, col));
}
template<> long long Database::Statement::fetchColumn(int col) {
return sqlite3_column_int64(stmt, col);
}
template<> double Database::Statement::fetchColumn(int col) {
return sqlite3_column_double(stmt, col);
}

View File

@@ -1,5 +1,5 @@
///
/// Copyright 2015-2018 Oliver Giles
/// Copyright 2015-2026 Oliver Giles
///
/// This file is part of Laminar
///
@@ -16,8 +16,7 @@
/// You should have received a copy of the GNU General Public License
/// along with Laminar. If not, see <http://www.gnu.org/licenses/>
///
#ifndef LAMINAR_DATABASE_H_
#define LAMINAR_DATABASE_H_
#pragma once
#include <string>
#include <functional>
@@ -126,6 +125,7 @@ private:
void bindValue(int i, uint e);
void bindValue(int i, long e);
void bindValue(int i, unsigned long e);
void bindValue(int i, long long e);
void bindValue(int i, const char* e);
void bindValue(int i, const std::string& e);
@@ -157,4 +157,3 @@ template<> long Database::Statement::fetchColumn(int col);
template<> ulong Database::Statement::fetchColumn(int col);
template<> double Database::Statement::fetchColumn(int col);
#endif // LAMINAR_DATABASE_H_

View File

@@ -78,14 +78,14 @@ kj::Maybe<MonitorScope> fromUrl(std::string resource, char* query) {
return kj::mv(scope);
}
if(resource.substr(0, 5) != "/jobs")
return nullptr;
if(resource.length() == 5) {
if(resource == "/jobs" || resource == "/wallboard") {
scope.type = MonitorScope::ALL;
return kj::mv(scope);
}
if(resource.substr(0, 5) != "/jobs")
return nullptr;
resource = resource.substr(5);
size_t split = resource.find('/',1);
std::string job = resource.substr(1,split-1);
@@ -131,9 +131,16 @@ kj::Promise<void> Http::cleanupPeers(kj::Timer& timer)
{
return timer.afterDelay(15 * kj::SECONDS).then([&]{
for(EventPeer* p : eventPeers) {
// an empty SSE message is a colon followed by two newlines
p->pendingOutput.push_back(":\n\n");
p->fulfiller->fulfill();
// Even single threaded, if load causes this timeout to be serviced
// before writeEvents has created a fulfiller, or if an exception
// caused the destruction of the promise but attach(peer) hasn't yet
// removed it from the eventPeers list, we will see a null fulfiller
// here
if(p->fulfiller) {
// an empty SSE message is a colon followed by two newlines
p->pendingOutput.push_back(":\n\n");
p->fulfiller->fulfill();
}
}
return cleanupPeers(timer);
}).eagerlyEvaluate(nullptr);
@@ -203,6 +210,8 @@ kj::Promise<void> Http::request(kj::HttpMethod method, kj::StringPtr url, const
if(is_sse) {
KJ_IF_MAYBE(s, fromUrl(url.cStr(), queryString)) {
responseHeaders.set(kj::HttpHeaderId::CONTENT_TYPE, "text/event-stream");
// Disables nginx reverse-proxy's buffering. Necessary for streamed events.
responseHeaders.add("X-Accel-Buffering", "no");
auto peer = kj::heap<WithSetRef<EventPeer>>(eventPeers);
peer->scope = *s;
std::string st = "data: " + laminar.getStatus(peer->scope) + "\n\n";
@@ -219,9 +228,6 @@ kj::Promise<void> Http::request(kj::HttpMethod method, kj::StringPtr url, const
return stream->write(array.begin(), array.size()).attach(kj::mv(array)).attach(kj::mv(file)).attach(kj::mv(stream));
}
} else if(parseLogEndpoint(url, name, num)) {
auto lw = kj::heap<WithSetRef<LogWatcher>>(logWatchers);
lw->job = name;
lw->run = num;
bool complete;
std::string output;
if(laminar.handleLogRequest(name, num, output, complete)) {
@@ -230,18 +236,17 @@ kj::Promise<void> Http::request(kj::HttpMethod method, kj::StringPtr url, const
// Disables nginx reverse-proxy's buffering. Necessary for dynamic log output.
responseHeaders.add("X-Accel-Buffering", "no");
auto stream = response.send(200, "OK", responseHeaders, nullptr);
return stream->write(output.data(), output.size()).then([=,s=stream.get(),c=lw.get()]{
auto s = stream.get();
auto lw = kj::heap<WithSetRef<LogWatcher>>(logWatchers);
lw->job = name;
lw->run = num;
auto promise = writeLogChunk(lw.get(), stream.get()).attach(kj::mv(stream)).attach(kj::mv(lw));
return s->write(output.data(), output.size()).attach(kj::mv(output)).then([p=kj::mv(promise),complete]() mutable {
if(complete)
return kj::Promise<void>(kj::READY_NOW);
return writeLogChunk(c, s);
}).attach(kj::mv(output)).attach(kj::mv(stream)).attach(kj::mv(lw));
return kj::mv(p);
});
}
} else if(url == "/custom/style.css") {
responseHeaders.set(kj::HttpHeaderId::CONTENT_TYPE, "text/css; charset=utf-8");
responseHeaders.add("Content-Transfer-Encoding", "binary");
std::string css = laminar.getCustomCss();
auto stream = response.send(200, "OK", responseHeaders, css.size());
return stream->write(css.data(), css.size()).attach(kj::mv(css)).attach(kj::mv(stream));
} else if(resources->handleRequest(url.cStr(), &start, &end, &content_type)) {
responseHeaders.set(kj::HttpHeaderId::CONTENT_TYPE, content_type);
responseHeaders.add("Content-Encoding", "gzip");
@@ -292,7 +297,7 @@ void Http::notifyLog(std::string job, uint run, std::string log_chunk, bool eot)
{
for(LogWatcher* lw : logWatchers) {
if(lw->job == job && lw->run == run) {
lw->pendingOutput.push_back(kj::mv(log_chunk));
lw->pendingOutput.push_back(log_chunk);
lw->fulfiller->fulfill(kj::mv(eot));
}
}

View File

@@ -1,5 +1,5 @@
///
/// Copyright 2019 Oliver Giles
/// Copyright 2019-2026 Oliver Giles
///
/// This file is part of Laminar
///
@@ -16,8 +16,7 @@
/// You should have received a copy of the GNU General Public License
/// along with Laminar. If not, see <http://www.gnu.org/licenses/>
///
#ifndef LAMINAR_HTTP_H_
#define LAMINAR_HTTP_H_
#pragma once
#include <kj/memory.h>
#include <kj/compat/http.h>
@@ -28,8 +27,8 @@
typedef unsigned int uint;
typedef unsigned long ulong;
struct Laminar;
struct Resources;
class Laminar;
class Resources;
struct LogWatcher;
struct EventPeer;
@@ -66,4 +65,3 @@ private:
kj::HttpHeaderId ACCEPT;
};
#endif //LAMINAR_HTTP_H_

View File

@@ -2,10 +2,10 @@
interface LaminarCi {
queue @0 (jobName :Text, params :List(JobParam)) -> (result :MethodResult);
start @1 (jobName :Text, params :List(JobParam)) -> (result :MethodResult, buildNum :UInt32);
run @2 (jobName :Text, params :List(JobParam)) -> (result :JobResult, buildNum :UInt32);
listQueued @3 () -> (result :List(Text));
queue @0 (jobName :Text, params :List(JobParam), frontOfQueue :Bool) -> (result :MethodResult, buildNum :UInt32);
start @1 (jobName :Text, params :List(JobParam), frontOfQueue :Bool) -> (result :MethodResult, buildNum :UInt32);
run @2 (jobName :Text, params :List(JobParam), frontOfQueue :Bool) -> (result :JobResult, buildNum :UInt32);
listQueued @3 () -> (result :List(Run));
listRunning @4 () -> (result :List(Run));
listKnown @5 () -> (result :List(Text));
abort @6 (run :Run) -> (result :MethodResult);

View File

@@ -1,5 +1,5 @@
///
/// Copyright 2015-2020 Oliver Giles
/// Copyright 2015-2022 Oliver Giles
///
/// This file is part of Laminar
///
@@ -28,7 +28,9 @@
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <fnmatch.h>
#include <fstream>
#include <cstdlib>
#include <zlib.h>
#define COMPRESS_LOG_MIN_SIZE 1024
@@ -36,6 +38,11 @@
#include <rapidjson/stringbuffer.h>
#include <rapidjson/writer.h>
// FNM_EXTMATCH isn't supported under musl
#if !defined(FNM_EXTMATCH)
#define FNM_EXTMATCH 0
#endif
// rapidjson::Writer with a StringBuffer is used a lot in Laminar for
// preparing JSON messages to send to HTTP clients. A small wrapper
// class here reduces verbosity later for this common use case.
@@ -67,7 +74,6 @@ inline kj::Path operator/(const std::string& p, const T& ext) {
typedef std::string str;
Laminar::Laminar(Server &server, Settings settings) :
settings(settings),
srv(server),
homePath(kj::Path::parse(&settings.home[1])),
fsHome(kj::newDiskFilesystem()->getRoot().openSubdir(homePath, kj::WriteMode::MODIFY)),
@@ -90,11 +96,31 @@ Laminar::Laminar(Server &server, Settings settings) :
db = new Database((homePath/"laminar.sqlite").toString(true).cStr());
// Prepare database for first use
// TODO: error handling
db->exec("CREATE TABLE IF NOT EXISTS builds("
"name TEXT, number INT UNSIGNED, node TEXT, queuedAt INT, "
"startedAt INT, completedAt INT, result INT, output TEXT, "
"outputLen INT, parentJob TEXT, parentBuild INT, reason TEXT, "
"PRIMARY KEY (name, number))");
const char *create_table_stmt =
"CREATE TABLE IF NOT EXISTS builds("
"name TEXT, number INT UNSIGNED, node TEXT, queuedAt INT, "
"startedAt INT, completedAt INT, result INT, output TEXT, "
"outputLen INT, parentJob TEXT, parentBuild INT, reason TEXT, "
"PRIMARY KEY (name, number DESC))";
db->exec(create_table_stmt);
// Migrate from (name, number) primary key to (name, number DESC).
// SQLite does not allow to alter primary key of existing table, so
// we have to create a new table.
db->stmt("SELECT sql LIKE '%, PRIMARY KEY (name, number))' "
"FROM sqlite_master WHERE type = 'table' AND name = 'builds'")
.fetch<int>([&](int has_old_index) {
if (has_old_index) {
LLOG(INFO, "Migrating table to the new primary key");
db->exec("BEGIN TRANSACTION");
db->exec("ALTER TABLE builds RENAME TO builds_old");
db->exec(create_table_stmt);
db->exec("INSERT INTO builds SELECT * FROM builds_old");
db->exec("DROP TABLE builds_old");
db->exec("COMMIT");
}
});
db->exec("CREATE INDEX IF NOT EXISTS idx_completion_time ON builds("
"completedAt DESC)");
@@ -136,18 +162,9 @@ void Laminar::loadCustomizations() {
}
uint Laminar::latestRun(std::string job) {
auto it = activeJobs.byJobName().equal_range(job);
if(it.first == it.second) {
uint result = 0;
db->stmt("SELECT MAX(number) FROM builds WHERE name = ?")
.bind(job)
.fetch<uint>([&](uint x){
result = x;
});
return result;
} else {
return (*--it.second)->build;
}
if(auto it = buildNums.find(job); it != buildNums.end())
return it->second;
return 0;
}
bool Laminar::handleLogRequest(std::string name, uint num, std::string& output, bool& complete) {
@@ -207,18 +224,21 @@ std::list<std::string> Laminar::listKnownJobs() {
return res;
}
void Laminar::populateArtifacts(Json &j, std::string job, uint num) const {
void Laminar::populateArtifacts(Json &j, std::string job, uint num, kj::Path subdir) const {
kj::Path runArchive{job,std::to_string(num)};
runArchive = runArchive.append(subdir);
KJ_IF_MAYBE(dir, fsHome->tryOpenSubdir("archive"/runArchive)) {
for(kj::StringPtr file : (*dir)->listNames()) {
kj::FsNode::Metadata meta = (*dir)->lstat(kj::Path{file});
if(meta.type != kj::FsNode::Type::FILE)
continue;
j.StartObject();
j.set("url", archiveUrl + (runArchive/file).toString().cStr());
j.set("filename", file.cStr());
j.set("size", meta.size);
j.EndObject();
if(meta.type == kj::FsNode::Type::FILE) {
j.StartObject();
j.set("url", archiveUrl + (runArchive/file).toString().cStr());
j.set("filename", (subdir/file).toString().cStr());
j.set("size", meta.size);
j.EndObject();
} else if(meta.type == kj::FsNode::Type::DIRECTORY) {
populateArtifacts(j, job, num, subdir/file);
}
}
}
}
@@ -231,35 +251,29 @@ std::string Laminar::getStatus(MonitorScope scope) {
j.set("time", time(nullptr));
j.startObject("data");
if(scope.type == MonitorScope::RUN) {
db->stmt("SELECT queuedAt,startedAt,completedAt,result,reason,parentJob,parentBuild FROM builds WHERE name = ? AND number = ?")
db->stmt("SELECT queuedAt,startedAt,completedAt,result,reason,parentJob,parentBuild,q.lr IS NOT NULL,q.lr FROM builds "
"LEFT JOIN (SELECT name n, MAX(number), completedAt-startedAt lr FROM builds WHERE result IS NOT NULL GROUP BY n) q ON q.n = name "
"WHERE name = ? AND number = ?")
.bind(scope.job, scope.num)
.fetch<time_t, time_t, time_t, int, std::string, std::string, uint>([&](time_t queued, time_t started, time_t completed, int result, std::string reason, std::string parentJob, uint parentBuild) {
j.set("queued", started-queued);
.fetch<time_t, time_t, time_t, int, std::string, std::string, uint, uint, uint>([&](time_t queued, time_t started, time_t completed, int result, std::string reason, std::string parentJob, uint parentBuild, uint lastRuntimeKnown, uint lastRuntime) {
j.set("queued", queued);
j.set("started", started);
j.set("completed", completed);
j.set("result", to_string(RunState(result)));
if(completed)
j.set("completed", completed);
j.set("result", to_string(completed ? RunState(result) : started ? RunState::RUNNING : RunState::QUEUED));
j.set("reason", reason);
j.startObject("upstream").set("name", parentJob).set("num", parentBuild).EndObject(2);
if(lastRuntimeKnown)
j.set("etc", started + lastRuntime);
});
if(const Run* run = activeRun(scope.job, scope.num)) {
j.set("queued", run->startedAt - run->queuedAt);
j.set("started", run->startedAt);
j.set("result", to_string(RunState::RUNNING));
j.set("reason", run->reason());
j.startObject("upstream").set("name", run->parentName).set("num", run->parentBuild).EndObject(2);
db->stmt("SELECT completedAt - startedAt FROM builds WHERE name = ? ORDER BY completedAt DESC LIMIT 1")
.bind(run->name)
.fetch<uint>([&](uint lastRuntime){
j.set("etc", run->startedAt + lastRuntime);
});
}
if(auto it = buildNums.find(scope.job); it != buildNums.end())
j.set("latestNum", int(it->second));
j.startArray("artifacts");
populateArtifacts(j, scope.job, scope.num);
j.EndArray();
} else if(scope.type == MonitorScope::JOB) {
const uint runsPerPage = 10;
const uint runsPerPage = 20;
j.startArray("recent");
// ORDER BY param cannot be bound
std::string order_by;
@@ -274,7 +288,8 @@ std::string Laminar::getStatus(MonitorScope scope) {
order_by = "(completedAt-startedAt) " + direction + ", number DESC";
else
order_by = "number DESC";
std::string stmt = "SELECT number,startedAt,completedAt,result,reason FROM builds WHERE name = ? ORDER BY "
std::string stmt = "SELECT number,startedAt,completedAt,result,reason FROM builds "
"WHERE name = ? AND result IS NOT NULL ORDER BY "
+ order_by + " LIMIT ?,?";
db->stmt(stmt.c_str())
.bind(scope.job, scope.page * runsPerPage, runsPerPage)
@@ -288,7 +303,7 @@ std::string Laminar::getStatus(MonitorScope scope) {
.EndObject();
});
j.EndArray();
db->stmt("SELECT COUNT(*),AVG(completedAt-startedAt) FROM builds WHERE name = ?")
db->stmt("SELECT COUNT(*),AVG(completedAt-startedAt) FROM builds WHERE name = ? AND result IS NOT NULL")
.bind(scope.job)
.fetch<uint,uint>([&](uint nRuns, uint averageRuntime){
j.set("averageRuntime", averageRuntime);
@@ -312,21 +327,28 @@ std::string Laminar::getStatus(MonitorScope scope) {
j.EndObject();
}
j.EndArray();
int nQueued = 0;
j.startArray("queued");
for(const auto& run : queuedJobs) {
if (run->name == scope.job) {
nQueued++;
j.StartObject();
j.set("number", run->build);
j.set("result", to_string(RunState::QUEUED));
j.set("reason", run->reason());
j.EndObject();
}
}
j.set("nQueued", nQueued);
db->stmt("SELECT number,startedAt FROM builds WHERE name = ? AND result = ? ORDER BY completedAt DESC LIMIT 1")
j.EndArray();
db->stmt("SELECT number,startedAt FROM builds WHERE name = ? AND result = ? "
"ORDER BY completedAt DESC LIMIT 1")
.bind(scope.job, int(RunState::SUCCESS))
.fetch<int,time_t>([&](int build, time_t started){
j.startObject("lastSuccess");
j.set("number", build).set("started", started);
j.EndObject();
});
db->stmt("SELECT number,startedAt FROM builds WHERE name = ? AND result <> ? ORDER BY completedAt DESC LIMIT 1")
db->stmt("SELECT number,startedAt FROM builds "
"WHERE name = ? AND result <> ? "
"ORDER BY completedAt DESC LIMIT 1")
.bind(scope.job, int(RunState::SUCCESS))
.fetch<int,time_t>([&](int build, time_t started){
j.startObject("lastFailed");
@@ -337,14 +359,16 @@ std::string Laminar::getStatus(MonitorScope scope) {
j.set("description", desc == jobDescriptions.end() ? "" : desc->second);
} else if(scope.type == MonitorScope::ALL) {
j.startArray("jobs");
db->stmt("SELECT name,number,startedAt,completedAt,result FROM builds b JOIN (SELECT name n,MAX(number) l FROM builds GROUP BY n) q ON b.name = q.n AND b.number = q.l")
.fetch<str,uint,time_t,time_t,int>([&](str name,uint number, time_t started, time_t completed, int result){
db->stmt("SELECT name, number, startedAt, completedAt, result, reason "
"FROM builds GROUP BY name HAVING number = MAX(number)")
.fetch<str,uint,time_t,time_t,int,str>([&](str name,uint number, time_t started, time_t completed, int result, str reason){
j.StartObject();
j.set("name", name);
j.set("number", number);
j.set("result", to_string(RunState(result)));
j.set("started", started);
j.set("completed", completed);
j.set("reason", reason);
j.EndObject();
});
j.EndArray();
@@ -364,15 +388,17 @@ std::string Laminar::getStatus(MonitorScope scope) {
j.EndObject();
} else { // Home page
j.startArray("recent");
db->stmt("SELECT * FROM builds ORDER BY completedAt DESC LIMIT 15")
.fetch<str,uint,str,time_t,time_t,time_t,int>([&](str name,uint build,str context,time_t,time_t started,time_t completed,int result){
db->stmt("SELECT name,number,node,queuedAt,startedAt,completedAt,result,reason FROM builds WHERE completedAt IS NOT NULL ORDER BY completedAt DESC LIMIT 20")
.fetch<str,uint,str,time_t,time_t,time_t,int,str>([&](str name,uint build,str context,time_t queued,time_t started,time_t completed,int result,str reason){
j.StartObject();
j.set("name", name)
.set("number", build)
.set("context", context)
.set("queued", queued)
.set("started", started)
.set("completed", completed)
.set("result", to_string(RunState(result)))
.set("reason", reason)
.EndObject();
});
j.EndArray();
@@ -383,7 +409,9 @@ std::string Laminar::getStatus(MonitorScope scope) {
j.set("number", run->build);
j.set("context", run->context->name);
j.set("started", run->startedAt);
db->stmt("SELECT completedAt - startedAt FROM builds WHERE name = ? ORDER BY completedAt DESC LIMIT 1")
db->stmt("SELECT completedAt - startedAt FROM builds "
"WHERE completedAt IS NOT NULL AND name = ? "
"ORDER BY completedAt DESC LIMIT 1")
.bind(run->name)
.fetch<uint>([&](uint lastRuntime){
j.set("etc", run->startedAt + lastRuntime);
@@ -395,6 +423,8 @@ std::string Laminar::getStatus(MonitorScope scope) {
for(const auto& run : queuedJobs) {
j.StartObject();
j.set("name", run->name);
j.set("number", run->build);
j.set("result", to_string(RunState::QUEUED));
j.EndObject();
}
j.EndArray();
@@ -428,7 +458,7 @@ std::string Laminar::getStatus(MonitorScope scope) {
j.startObject("timePerJob");
db->stmt("SELECT name, AVG(completedAt-startedAt) av FROM builds WHERE completedAt > ? GROUP BY name ORDER BY av DESC LIMIT 8")
.bind(time(nullptr) - 7 * 86400)
.fetch<str, uint>([&](str job, uint time){
.fetch<str, double>([&](str job, double time){
j.set(job.c_str(), time);
});
j.EndObject();
@@ -466,29 +496,12 @@ std::string Laminar::getStatus(MonitorScope scope) {
j.EndObject();
});
j.EndArray();
j.startArray("buildTimeDist");
db->stmt("WITH ba AS (SELECT name,AVG(completedAt-startedAt) a FROM builds GROUP BY name) SELECT "
"COUNT(CASE WHEN a < 30 THEN 1 END),"
"COUNT(CASE WHEN a >= 30 AND a < 60 THEN 1 END),"
"COUNT(CASE WHEN a >= 60 AND a < 300 THEN 1 END),"
"COUNT(CASE WHEN a >= 300 AND a < 600 THEN 1 END),"
"COUNT(CASE WHEN a >= 600 AND a < 1200 THEN 1 END),"
"COUNT(CASE WHEN a >= 1200 AND a < 2400 THEN 1 END),"
"COUNT(CASE WHEN a >= 2400 AND a < 3600 THEN 1 END),"
"COUNT(CASE WHEN a >= 3600 THEN 1 END) FROM ba")
.fetch<uint,uint,uint,uint,uint,uint,uint,uint>([&](uint c1, uint c2, uint c3, uint c4, uint c5, uint c6, uint c7, uint c8){
j.Int(c1);
j.Int(c2);
j.Int(c3);
j.Int(c4);
j.Int(c5);
j.Int(c6);
j.Int(c7);
j.Int(c8);
j.startObject("completedCounts");
db->stmt("SELECT name, COUNT(*) FROM builds WHERE result IS NOT NULL GROUP BY name")
.fetch<str, uint>([&](str job, uint count){
j.set(job.c_str(), count);
});
j.EndArray();
j.EndObject();
}
j.EndObject();
return j.str();
@@ -520,6 +533,16 @@ bool Laminar::loadConfiguration() {
context->name = name;
context->numExecutors = conf.get<int>("EXECUTORS", 6);
std::string jobPtns = conf.get<std::string>("JOBS");
std::set<std::string> jobPtnsList;
if(!jobPtns.empty()) {
std::istringstream iss(jobPtns);
std::string job;
while(std::getline(iss, job, ','))
jobPtnsList.insert(job);
}
context->jobPatterns.swap(jobPtnsList);
knownContexts.insert(name);
}
}
@@ -552,14 +575,20 @@ bool Laminar::loadConfiguration() {
std::string ctxPtns = conf.get<std::string>("CONTEXTS");
std::set<std::string> ctxPtnList;
if(!ctxPtns.empty()) {
std::istringstream iss(ctxPtns);
std::set<std::string> ctxPtnList;
std::string ctx;
while(std::getline(iss, ctx, ','))
ctxPtnList.insert(ctx);
jobContexts[jobName].swap(ctxPtnList);
}
// Must be present both here and in queueJob because otherwise if a context
// were created while a job is already queued, the default context would be
// dropped when the set of contexts is updated here.
if(ctxPtnList.empty())
ctxPtnList.insert("default");
jobContexts[jobName].swap(ctxPtnList);
std::string desc = conf.get<std::string>("DESCRIPTION");
if(!desc.empty()) {
jobDescriptions[jobName] = desc;
@@ -576,24 +605,35 @@ bool Laminar::loadConfiguration() {
return true;
}
std::shared_ptr<Run> Laminar::queueJob(std::string name, ParamMap params) {
std::shared_ptr<Run> Laminar::queueJob(std::string name, ParamMap params, bool frontOfQueue) {
if(!fsHome->exists(kj::Path{"cfg","jobs",name+".run"})) {
LLOG(ERROR, "Non-existent job", name);
return nullptr;
}
// If the job has no contexts (maybe there is no .conf file at all), add the default context
// jobContexts[name] can be empty if there is no .conf file at all
if(jobContexts[name].empty())
jobContexts.at(name).insert("default");
std::shared_ptr<Run> run = std::make_shared<Run>(name, kj::mv(params), homePath.clone());
queuedJobs.push_back(run);
std::shared_ptr<Run> run = std::make_shared<Run>(name, ++buildNums[name], kj::mv(params), homePath.clone());
if(frontOfQueue)
queuedJobs.push_front(run);
else
queuedJobs.push_back(run);
db->stmt("INSERT INTO builds(name,number,queuedAt,parentJob,parentBuild,reason) VALUES(?,?,?,?,?,?)")
.bind(run->name, run->build, run->queuedAt, run->parentName, run->parentBuild, run->reason())
.exec();
// notify clients
Json j;
j.set("type", "job_queued")
.startObject("data")
.set("name", name)
.set("number", run->build)
.set("result", to_string(RunState::QUEUED))
.set("queueIndex", frontOfQueue ? 0 : (queuedJobs.size() - 1))
.set("reason", run->reason())
.EndObject();
http->notifyEvent(j.str(), name.c_str());
@@ -613,21 +653,48 @@ void Laminar::abortAll() {
}
}
bool Laminar::canQueue(const Context& ctx, const Run& run) const {
if(ctx.busyExecutors >= ctx.numExecutors)
return false;
// match may be jobs as defined by the context...
for(std::string p : ctx.jobPatterns) {
if(fnmatch(p.c_str(), run.name.c_str(), FNM_EXTMATCH) == 0)
return true;
}
// ...or context as defined by the job.
for(std::string p : jobContexts.at(run.name)) {
if(fnmatch(p.c_str(), ctx.name.c_str(), FNM_EXTMATCH) == 0)
return true;
}
return false;
}
bool Laminar::tryStartRun(std::shared_ptr<Run> run, int queueIndex) {
for(auto& sc : contexts) {
std::shared_ptr<Context> ctx = sc.second;
if(ctx->canQueue(jobContexts.at(run->name))) {
kj::Promise<RunState> onRunFinished = run->start(buildNums[run->name] + 1, ctx, *fsHome,[this](kj::Maybe<pid_t>& pid){return srv.onChildExit(pid);});
if(canQueue(*ctx, *run)) {
RunState lastResult = RunState::UNKNOWN;
ctx->busyExecutors++;
// set the last known result if exists
// set the last known result if exists. Runs which haven't started yet should
// have completedAt == NULL and thus be at the end of a DESC ordered query
db->stmt("SELECT result FROM builds WHERE name = ? ORDER BY completedAt DESC LIMIT 1")
.bind(run->name)
.fetch<int>([=](int result){
run->lastResult = RunState(result);
.fetch<int>([&](int result){
lastResult = RunState(result);
});
kj::Promise<RunState> onRunFinished = run->start(lastResult, ctx, *fsHome,[this](kj::Maybe<pid_t>& pid){return srv.onChildExit(pid);});
db->stmt("UPDATE builds SET node = ?, startedAt = ? WHERE name = ? AND number = ?")
.bind(ctx->name, run->startedAt, run->name, run->build)
.exec();
ctx->busyExecutors++;
kj::Promise<void> exec = srv.readDescriptor(run->output_fd, [this, run](const char*b, size_t n){
// handle log output
std::string s(b, n);
@@ -647,16 +714,13 @@ bool Laminar::tryStartRun(std::shared_ptr<Run> run, int queueIndex) {
srv.addTask(kj::mv(exec));
LLOG(INFO, "Started job", run->name, run->build, ctx->name);
// update next build number
buildNums[run->name]++;
// notify clients
Json j;
j.set("type", "job_started")
.startObject("data")
.set("queueIndex", queueIndex)
.set("name", run->name)
.set("queued", run->startedAt - run->queuedAt)
.set("queued", run->queuedAt)
.set("started", run->startedAt)
.set("number", run->build)
.set("reason", run->reason());
@@ -705,10 +769,8 @@ void Laminar::handleRunFinished(Run * r) {
}
}
std::string reason = r->reason();
db->stmt("INSERT INTO builds VALUES(?,?,?,?,?,?,?,?,?,?,?,?)")
.bind(r->name, r->build, ctx->name, r->queuedAt, r->startedAt, completedAt, int(r->result),
maybeZipped, logsize, r->parentName, r->parentBuild, reason)
db->stmt("UPDATE builds SET completedAt = ?, result = ?, output = ?, outputLen = ? WHERE name = ? AND number = ?")
.bind(completedAt, int(r->result), maybeZipped, logsize, r->name, r->build)
.exec();
// notify clients
@@ -717,7 +779,7 @@ void Laminar::handleRunFinished(Run * r) {
.startObject("data")
.set("name", r->name)
.set("number", r->build)
.set("queued", r->startedAt - r->queuedAt)
.set("queued", r->queuedAt)
.set("completed", completedAt)
.set("started", r->startedAt)
.set("result", to_string(r->result))
@@ -750,7 +812,14 @@ void Laminar::handleRunFinished(Run * r) {
// anyway so hence this (admittedly debatable) optimization.
if(!fsHome->exists(d))
break;
fsHome->remove(d);
// must use a try/catch because remove will throw if deletion fails. Using
// tryRemove does not help because it still throws an exception for some
// errors such as EACCES
try {
fsHome->remove(d);
} catch(kj::Exception& e) {
LLOG(ERROR, "Could not remove directory", e.getDescription());
}
}
fsHome->symlink(kj::Path{"archive", r->name, "latest"}, std::to_string(r->build), kj::WriteMode::CREATE|kj::WriteMode::MODIFY);
@@ -765,7 +834,7 @@ kj::Maybe<kj::Own<const kj::ReadableFile>> Laminar::getArtefact(std::string path
bool Laminar::handleBadgeRequest(std::string job, std::string &badge) {
RunState rs = RunState::UNKNOWN;
db->stmt("SELECT result FROM builds WHERE name = ? ORDER BY number DESC LIMIT 1")
db->stmt("SELECT result FROM builds WHERE name = ? AND result IS NOT NULL ORDER BY number DESC LIMIT 1")
.bind(job)
.fetch<int>([&](int result){
rs = RunState(result);
@@ -804,19 +873,7 @@ R"x(
return false;
badge = svg;
std::free(svg);
return true;
}
// TODO: deprecate
std::string Laminar::getCustomCss() {
KJ_IF_MAYBE(cssFile, fsHome->tryOpenFile(kj::Path{"custom","style.css"})) {
static bool warningShown = false;
if(!warningShown) {
LLOG(WARNING, "Custom CSS has been deprecated and will be removed from a future release. Use a custom HTML template instead.");
warningShown = true;
}
return (*cssFile)->readAllText().cStr();
} else {
return std::string();
}
}

View File

@@ -1,5 +1,5 @@
///
/// Copyright 2015-2019 Oliver Giles
/// Copyright 2015-2026 Oliver Giles
///
/// This file is part of Laminar
///
@@ -16,14 +16,14 @@
/// You should have received a copy of the GNU General Public License
/// along with Laminar. If not, see <http://www.gnu.org/licenses/>
///
#ifndef LAMINAR_LAMINAR_H_
#define LAMINAR_LAMINAR_H_
#pragma once
#include "run.h"
#include "monitorscope.h"
#include "context.h"
#include "database.h"
#include <list>
#include <unordered_map>
#include <kj/filesystem.h>
#include <kj/async-io.h>
@@ -31,7 +31,7 @@
// Context name to context object map
typedef std::unordered_map<std::string, std::shared_ptr<Context>> ContextMap;
struct Server;
class Server;
class Json;
class Http;
@@ -52,7 +52,7 @@ public:
// Queues a job, returns immediately. Return value will be nullptr if
// the supplied name is not a known job.
std::shared_ptr<Run> queueJob(std::string name, ParamMap params = ParamMap());
std::shared_ptr<Run> queueJob(std::string name, ParamMap params = ParamMap(), bool frontOfQueue = false);
// Return the latest known number of the named job
uint latestRun(std::string job);
@@ -90,11 +90,6 @@ public:
// if the job is unknown.
bool handleBadgeRequest(std::string job, std::string& badge);
// Fetches the content of $LAMINAR_HOME/custom/style.css or an empty
// string. Ideally, this would instead be served by a proper web server
// which handles this url.
std::string getCustomCss();
// Aborts a single job
bool abort(std::string job, uint buildNum);
@@ -105,10 +100,11 @@ private:
bool loadConfiguration();
void loadCustomizations();
void assignNewJobs();
bool canQueue(const Context& ctx, const Run& run) const;
bool tryStartRun(std::shared_ptr<Run> run, int queueIndex);
void handleRunFinished(Run*);
// expects that Json has started an array
void populateArtifacts(Json& out, std::string job, uint num) const;
void populateArtifacts(Json& out, std::string job, uint num, kj::Path subdir = kj::Path::parse(".")) const;
Run* activeRun(const std::string name, uint num) {
auto it = activeJobs.byNameNumber().find(boost::make_tuple(name, num));
@@ -125,7 +121,6 @@ private:
std::unordered_map<std::string, std::string> jobGroups;
Settings settings;
RunSet activeJobs;
Database* db;
Server& srv;
@@ -139,4 +134,3 @@ private:
kj::Own<Rpc> rpc;
};
#endif // LAMINAR_LAMINAR_H_

View File

@@ -20,7 +20,12 @@
#include <string>
#include <unistd.h>
#include <queue>
#include <dirent.h>
#if defined(__FreeBSD__)
#include <sys/procctl.h>
#else
#include <sys/prctl.h>
#endif
#include <sys/types.h>
#include <sys/wait.h>
#include <kj/async-io.h>
@@ -29,6 +34,8 @@
#include "run.h"
const int SET_ENV_BUF_SIZE = 1024;
// short syntax helper for kj::Path
template<typename T>
inline kj::Path operator/(const kj::Path& p, const T& ext) {
@@ -45,6 +52,39 @@ struct Script {
bool runOnAbort;
};
static void aggressive_recursive_kill(pid_t parent) {
DIR* proc = opendir("/proc");
if(!proc)
return;
while(struct dirent* de = readdir(proc)) {
if(!isdigit(*de->d_name))
continue;
char status_file[640];
sprintf(status_file, "/proc/%s/status", de->d_name);
FILE* status_fp = fopen(status_file, "rb");
if(!status_fp)
continue;
char status_buffer[512];
int n = fread(status_buffer, 1, 512, status_fp);
if(char* p = (char*)memmem(status_buffer, n, "PPid:\t", 6)) {
pid_t ppid = strtol(p + 6, NULL, 10);
if(ppid == parent) {
pid_t pid = atoi(de->d_name);
aggressive_recursive_kill(pid);
fprintf(stderr, "[laminar] sending SIGKILL to pid %d\n", pid);
kill(pid, SIGKILL);
}
}
fclose(status_fp);
}
closedir(proc);
}
class Leader final : public kj::TaskSet::ErrorHandler {
public:
Leader(kj::AsyncIoContext& ioContext, kj::Filesystem& fs, const char* jobName, uint runNumber);
@@ -67,6 +107,7 @@ private:
pid_t currentScriptPid;
std::queue<Script> scripts;
int setEnvPipe[2];
bool aborting;
};
Leader::Leader(kj::AsyncIoContext &ioContext, kj::Filesystem &fs, const char *jobName, uint runNumber) :
@@ -76,7 +117,8 @@ Leader::Leader(kj::AsyncIoContext &ioContext, kj::Filesystem &fs, const char *jo
home(fs.getCurrent()),
rootPath(fs.getCurrentPath()),
jobName(jobName),
runNumber(runNumber)
runNumber(runNumber),
aborting(false)
{
tasks.add(ioContext.unixEventPort.onSignal(SIGTERM).then([this](siginfo_t) {
while(scripts.size() && (!scripts.front().runOnAbort))
@@ -84,14 +126,14 @@ Leader::Leader(kj::AsyncIoContext &ioContext, kj::Filesystem &fs, const char *jo
// TODO: probably shouldn't do this if we are already in a runOnAbort script
kill(-currentGroupId, SIGTERM);
return this->ioContext.provider->getTimer().afterDelay(2*kj::SECONDS).then([this]{
fprintf(stderr, "[laminar] sending SIGKILL to process group %d\n", currentGroupId);
kill(-currentGroupId, SIGKILL);
aborting = true;
aggressive_recursive_kill(getpid());
});
}));
LSYSCALL(pipe(setEnvPipe));
auto event = ioContext.lowLevelProvider->wrapInputFd(setEnvPipe[0], kj::LowLevelAsyncIoProvider::TAKE_OWNERSHIP);
auto buffer = kj::heapArrayBuilder<char>(1024);
auto buffer = kj::heapArrayBuilder<char>(SET_ENV_BUF_SIZE);
tasks.add(readEnvPipe(event, buffer.asPtr().begin()).attach(kj::mv(event), kj::mv(buffer)));
}
@@ -223,14 +265,18 @@ kj::Promise<void> Leader::reapChildProcesses()
// waiting for is done
return reapChildProcesses();
}
// we were aborted by the primary process already, just wait until all
// SIGKILLs are processed
if(aborting) {
return reapChildProcesses();
}
// Otherwise, reparented orphans are on borrowed time
// TODO list wayward processes?
fprintf(stderr, "[laminar] sending SIGHUP to adopted child processes\n");
kill(-currentGroupId, SIGHUP);
return ioContext.provider->getTimer().afterDelay(5*kj::SECONDS).then([this]{
fprintf(stderr, "[laminar] sending SIGKILL to process group %d\n", currentGroupId);
// TODO: should we mark the job as failed if we had to kill reparented processes?
kill(-currentGroupId, SIGKILL);
aggressive_recursive_kill(getpid());
return reapChildProcesses();
}).exclusiveJoin(reapChildProcesses());
} else if(pid == currentScriptPid) {
@@ -251,7 +297,7 @@ kj::Promise<void> Leader::reapChildProcesses()
}
kj::Promise<void> Leader::readEnvPipe(kj::AsyncInputStream *stream, char *buffer) {
return stream->tryRead(buffer, 1, 1024).then([this,stream,buffer](size_t sz) {
return stream->tryRead(buffer, 1, SET_ENV_BUF_SIZE - 1).then([this,stream,buffer](size_t sz) {
if(sz > 0) {
buffer[sz] = '\0';
if(char* eq = strchr(buffer, '=')) {
@@ -277,7 +323,11 @@ int leader_main(void) {
// will be reparented to this one instead of init (or higher layer subreaper).
// We do this so that the run will wait until all descedents exit before executing
// the next step.
#if defined(__FreeBSD__)
procctl(P_PID, 0, PROC_REAP_ACQUIRE, NULL);
#else
prctl(PR_SET_CHILD_SUBREAPER, 1, NULL, NULL, NULL);
#endif
// Become the leader of a new process group. This is so that all child processes
// will also get a kill signal when the run is aborted

View File

@@ -1,5 +1,5 @@
///
/// Copyright 2019 Oliver Giles
/// Copyright 2019-2026 Oliver Giles
///
/// This file is part of Laminar
///
@@ -16,8 +16,7 @@
/// You should have received a copy of the GNU General Public License
/// along with Laminar. If not, see <http://www.gnu.org/licenses/>
///
#ifndef LAMINAR_LEADER_H_
#define LAMINAR_LEADER_H_
#pragma once
// Main function for the leader process which is responsible for
// executing all the scripts which make up a Run. Separating this
@@ -33,4 +32,3 @@
int leader_main(void);
#endif // LAMINAR_LEADER_H_

View File

@@ -1,5 +1,5 @@
///
/// Copyright 2015-2020 Oliver Giles
/// Copyright 2015-2026 Oliver Giles
///
/// This file is part of Laminar
///
@@ -16,8 +16,7 @@
/// You should have received a copy of the GNU General Public License
/// along with Laminar. If not, see <http://www.gnu.org/licenses/>
///
#ifndef LAMINAR_LOG_H_
#define LAMINAR_LOG_H_
#pragma once
#include <kj/debug.h>
#include <utility>
@@ -69,5 +68,3 @@ namespace _ {
const char* laminar_version();
#endif // LAMINAR_LOG_H_

View File

@@ -26,6 +26,7 @@
#include <kj/async-unix.h>
#include <kj/filesystem.h>
#include <signal.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
@@ -53,6 +54,13 @@ static void usage(std::ostream& out) {
out << " -v enable verbose output\n";
}
static void on_sighup(int)
{
constexpr const char msg[] = "Laminar received and ignored SIGHUP\n";
// write(2) is safe to call inside signal handler.
write(STDERR_FILENO, msg, sizeof(msg) - 1);
}
int main(int argc, char** argv) {
if(argv[0][0] == '{')
return leader_main();
@@ -92,6 +100,7 @@ int main(int argc, char** argv) {
signal(SIGINT, &laminar_quit);
signal(SIGTERM, &laminar_quit);
signal(SIGHUP, &on_sighup);
printf("laminard version %s started\n", laminar_version());

View File

@@ -1,5 +1,5 @@
///
/// Copyright 2015-2019 Oliver Giles
/// Copyright 2015-2026 Oliver Giles
///
/// This file is part of Laminar
///
@@ -16,8 +16,7 @@
/// You should have received a copy of the GNU General Public License
/// along with Laminar. If not, see <http://www.gnu.org/licenses/>
///
#ifndef LAMINAR_MONITORSCOPE_H_
#define LAMINAR_MONITORSCOPE_H_
#pragma once
#include <string>
@@ -59,5 +58,3 @@ struct MonitorScope {
bool order_desc;
};
#endif // LAMINAR_MONITORSCOPE_H_

View File

@@ -44,7 +44,6 @@ Resources::Resources()
INIT_RESOURCE("/js/app.js", js_app_js, CONTENT_TYPE_JS);
INIT_RESOURCE("/js/ansi_up.js", js_ansi_up_js, CONTENT_TYPE_JS);
INIT_RESOURCE("/js/vue.min.js", js_vue_min_js, CONTENT_TYPE_JS);
INIT_RESOURCE("/js/vue-router.min.js", js_vue_router_min_js, CONTENT_TYPE_JS);
INIT_RESOURCE("/js/ansi_up.js", js_ansi_up_js, CONTENT_TYPE_JS);
INIT_RESOURCE("/js/Chart.min.js", js_Chart_min_js, CONTENT_TYPE_JS);
INIT_RESOURCE("/style.css", style_css, CONTENT_TYPE_CSS);
@@ -122,7 +121,7 @@ inline bool beginsWith(std::string haystack, const char* needle) {
bool Resources::handleRequest(std::string path, const char** start, const char** end, const char** content_type) {
// need to keep the list of "application links" synchronised with the angular
// application. We cannot return a 404 for any of these
auto it = beginsWith(path,"/jobs")
auto it = beginsWith(path,"/jobs") || path == "/wallboard"
? resources.find("/")
: resources.find(path);

View File

@@ -1,5 +1,5 @@
///
/// Copyright 2015-2019 Oliver Giles
/// Copyright 2015-2026 Oliver Giles
///
/// This file is part of Laminar
///
@@ -16,8 +16,7 @@
/// You should have received a copy of the GNU General Public License
/// along with Laminar. If not, see <http://www.gnu.org/licenses/>
///
#ifndef LAMINAR_RESOURCES_H_
#define LAMINAR_RESOURCES_H_
#pragma once
#include <unordered_map>
#include <utility>
@@ -47,4 +46,3 @@ private:
std::string index_html;
};
#endif // LAMINAR_RESOURCES_H_

View File

@@ -11,26 +11,29 @@
<link rel="manifest" href="/manifest.webmanifest">
<title>Laminar</title>
<script src="js/vue.min.js"></script>
<script src="js/vue-router.min.js"></script>
<script src="js/ansi_up.js"></script>
<script src="js/Chart.min.js"></script>
<script src="js/app.js" defer></script>
<link href="style.css" rel="stylesheet">
<link href="custom/style.css" rel="stylesheet">
</head>
<body>
<template id="home"><div id="page-home-main">
<nav>
<table class="table striped">
<tr v-for="job in jobsQueued">
<td><router-link :to="'/jobs/'+job.name">{{job.name}}</router-link> <i>queued</i></td>
<td>
<span v-html="runIcon(job.result)"></span>
<router-link :to="'jobs/'+job.name">{{job.name}}</router-link>
<router-link :to="'jobs/'+job.name+'/'+job.number">#{{job.number}}</router-link>
<i>queued</i>
</td>
</tr>
<tr v-for="job in jobsRunning">
<td>
<span v-html="runIcon(job.result)"></span>
<router-link :to="'/jobs/'+job.name">{{job.name}}</router-link>
<router-link :to="'/jobs/'+job.name+'/'+job.number">#{{job.number}}</router-link>
<router-link :to="'jobs/'+job.name">{{job.name}}</router-link>
<router-link :to="'jobs/'+job.name+'/'+job.number">#{{job.number}}</router-link>
<small style="float:right;">{{formatDuration(job.started, job.completed)}}</small>
<div class="progress" style="margin-top: 5px;">
<div class="progress-bar" :class="{overtime:job.overtime,indeterminate:!job.etc}" :style="job.etc && {width:job.progress+'%'}"></div>
@@ -40,8 +43,8 @@
<tr v-for="job in jobsRecent">
<td>
<span v-html="runIcon(job.result)"></span>
<router-link :to="'/jobs/'+job.name">{{job.name}}</router-link>
<router-link :to="'/jobs/'+job.name+'/'+job.number">#{{job.number}}</router-link><br>
<router-link :to="'jobs/'+job.name">{{job.name}}</router-link>
<router-link :to="'jobs/'+job.name+'/'+job.number">#{{job.number}}</router-link><br>
<small>Took {{formatDuration(job.started, job.completed)}} at {{formatDate(job.started)}}</small>
</td>
</tr>
@@ -52,13 +55,13 @@
<div>
<h3>Recent regressions</h3>
<table>
<tr v-for="job in resultChanged" v-if="job.lastFailure>job.lastSuccess"><td><router-link :to="'/jobs/'+job.name+'/'+job.lastFailure">{{job.name}} #{{job.lastFailure}}</router-link> since <router-link :to="'/jobs/'+job.name+'/'+job.lastSuccess">#{{job.lastSuccess}}</router-link></tr>
<tr v-for="job in resultChanged" v-if="job.lastFailure>job.lastSuccess"><td><router-link :to="'jobs/'+job.name+'/'+job.lastFailure">{{job.name}} #{{job.lastFailure}}</router-link> since <router-link :to="'jobs/'+job.name+'/'+job.lastSuccess">#{{job.lastSuccess}}</router-link></tr>
</table>
</div>
<div>
<h3>Low pass rates</h3>
<table>
<tr v-for="job in lowPassRates"><td><router-link :to="'/jobs/'+job.name">{{job.name}}</router-link></td><td>{{Math.round(job.passRate*100)}}&nbsp;%</td></tr>
<tr v-for="job in lowPassRates"><td><router-link :to="'jobs/'+job.name">{{job.name}}</router-link></td><td>{{Math.round(job.passRate*100)}}&nbsp;%</td></tr>
</table>
</div>
<div>
@@ -66,14 +69,11 @@
<div><canvas id="chartUtil"></canvas></div>
</div>
</div>
<div>
<div style="display: grid; grid-template-columns: repeat(auto-fill, minmax(380px, 1fr)); gap: 5px; padding: 5px;">
<div><canvas id="chartBpd"></canvas></div>
<div><canvas id="chartBpj"></canvas></div>
<div><canvas id="chartTpj"></canvas></div>
<div><canvas id="chartBuildTimeChanges"></canvas></div>
<div><canvas id="chartBuildTimeDist"></canvas></div>
</div>
<div id="page-home-plots">
<div><canvas id="chartBpd"></canvas></div>
<div><canvas id="chartBpj"></canvas></div>
<div><canvas id="chartTpj"></canvas></div>
<div><canvas id="chartBuildTimeChanges"></canvas></div>
</div>
</section>
</div></template>
@@ -84,27 +84,47 @@
<a v-show="ungrouped.length" :class="{'active':group==null}" href v-on:click.prevent="group = null">Ungrouped Jobs</a>
<a v-for="g in Object.keys(groups)" :class="{'active':g==group}" href v-on:click.prevent="group = g">{{g}}</a>
</div>
<input class="form-control" id="jobFilter" v-model="search" placeholder="Filter...">
<div style="display: grid; grid-auto-flow: column; align-items: center; gap: 15px">
<router-link :to="wallboardLink()" style="display: inherit;" title="Wallboard">
<svg width="18" viewBox="0 0 13 13">
<g fill="#728494">
<rect x="0" y="2" width="6" height="4" />
<rect x="0" y="7" width="6" height="4" />
<rect x="7" y="2" width="6" height="4" />
<rect x="7" y="7" width="6" height="4" />
</g>
</svg>
</router-link>
<input class="form-control" id="jobFilter" v-model="search" placeholder="Filter...">
</div>
</nav>
<table class="striped" id="job-list">
<tr v-for="job in filteredJobs()">
<td><router-link :to="'/jobs/'+job.name">{{job.name}}</router-link></td>
<td style="white-space: nowrap;"><span v-html="runIcon(job.result)"></span> <router-link :to="'/jobs/'+job.name+'/'+job.number">#{{job.number}}</router-link></td>
<td><router-link :to="'jobs/'+job.name">{{job.name}}</router-link></td>
<td style="white-space: nowrap;"><span v-html="runIcon(job.result)"></span> <router-link :to="'jobs/'+job.name+'/'+job.number">#{{job.number}}</router-link></td>
<td>{{formatDate(job.started)}}</td>
<td>{{formatDuration(job.started,job.completed)}}</td>
</tr>
</table>
</div></template>
<template id="wallboard"><div class="wallboard">
<router-link :to="'jobs/'+job.name+'/'+job.number" tag="div" v-for="job in wallboardJobs()" :data-result="job.result">
<span style="font-size: 36px; font-weight: bold;">{{job.name}} #{{job.number}}</span><br>
<span style="font-size: 30px;">{{formatDate(job.started)}}</span><br>
<span style="font-size: 26px;">{{job.reason}}</span>
</router-link>
</div></template>
<template id="job"><div id="page-job-main">
<div style="padding: 15px;">
<h2>{{$route.params.name}}</h2>
<h2>{{route.params.name}}</h2>
<div v-html="description"></div>
<dl>
<dt>Last Successful Run</dt>
<dd><router-link v-if="lastSuccess" :to="'/jobs/'+$route.params.name+'/'+lastSuccess.number">#{{lastSuccess.number}}</router-link> {{lastSuccess?' - at '+formatDate(lastSuccess.started):'never'}}</dd>
<dd><router-link v-if="lastSuccess" :to="'jobs/'+route.params.name+'/'+lastSuccess.number">#{{lastSuccess.number}}</router-link> {{lastSuccess?' - at '+formatDate(lastSuccess.started):'never'}}</dd>
<dt>Last Failed Run</dt>
<dd><router-link v-if="lastFailed" :to="'/jobs/'+$route.params.name+'/'+lastFailed.number">#{{lastFailed.number}}</router-link> {{lastFailed?' - at '+formatDate(lastFailed.started):'never'}}</dd>
<dd><router-link v-if="lastFailed" :to="'jobs/'+route.params.name+'/'+lastFailed.number">#{{lastFailed.number}}</router-link> {{lastFailed?' - at '+formatDate(lastFailed.started):'never'}}</dd>
</dl>
</div>
<div style="display: grid; justify-content: center; padding: 15px;">
@@ -119,14 +139,11 @@
<th class="text-center">Duration <a class="sort" :class="(sort.field=='duration'?sort.order:'')" v-on:click="do_sort('duration')">&nbsp;</a></th>
<th class="text-center vp-sm-hide">Reason <a class="sort" :class="(sort.field=='reason'?sort.order:'')" v-on:click="do_sort('reason')">&nbsp;</a></th>
</tr></thead>
<tr v-show="nQueued">
<td colspan="5"><i>{{nQueued}} run(s) queued</i></td>
</tr>
<tr v-for="job in jobsRunning.concat(jobsRecent)" track-by="$index">
<tr v-for="job in jobsQueued.concat(jobsRunning).concat(jobsRecent)" track-by="$index">
<td style="width:1px"><span v-html="runIcon(job.result)"></span></td>
<td><router-link :to="'/jobs/'+$route.params.name+'/'+job.number">#{{job.number}}</router-link></td>
<td class="text-center">{{formatDate(job.started)}}</td>
<td class="text-center">{{formatDuration(job.started, job.completed)}}</td>
<td><router-link :to="'jobs/'+route.params.name+'/'+job.number">#{{job.number}}</router-link></td>
<td class="text-center"><span v-if="job.result!='queued'">{{formatDate(job.started)}}</span></td>
<td class="text-center"><span v-if="job.result!='queued'">{{formatDuration(job.started, job.completed)}}</span></td>
<td class="text-center vp-sm-hide">{{job.reason}}</td>
</tr>
</table>
@@ -140,25 +157,24 @@
<template id="run"><div style="display: grid; grid-template-rows: auto 1fr">
<div style="padding: 15px">
<div style="display: grid; grid-template-columns: auto 1fr 400px auto auto; gap: 5px; align-items: center">
<h2 style="white-space: nowrap"><span v-html="runIcon(job.result)"></span> {{$route.params.name}} #{{$route.params.number}}</h2>
<div style="display: grid; grid-template-columns: auto 25px auto auto 1fr 400px; gap: 5px; align-items: center">
<h2 style="white-space: nowrap"><span v-html="runIcon(job.result)"></span> <router-link :to="'jobs/'+route.params.name">{{route.params.name}}</router-link> #{{route.params.number}}</h2>
<span></span>
<div><!-- extra div to preserve grid columns when v-show hides the progress bar -->
<div class="progress" v-show="job.result == 'running'">
<div class="progress-bar" :class="{overtime:job.overtime,indeterminate:!job.etc}" :style="job.etc && {width:job.progress+'%'}"></div>
</div>
<router-link :disabled="route.params.number == 1" :to="'jobs/'+route.params.name+'/'+(route.params.number-1)" tag="button">&laquo;</router-link>
<router-link :disabled="route.params.number == latestNum" :to="'jobs/'+route.params.name+'/'+(parseInt(route.params.number)+1)" tag="button">&raquo;</router-link>
<span></span>
<div class="progress" v-show="job.result == 'running'">
<div class="progress-bar" :class="{overtime:job.overtime,indeterminate:!job.etc}" :style="job.etc && {width:job.progress+'%'}"></div>
</div>
<router-link :disabled="$route.params.number == 1" :to="'/jobs/'+$route.params.name+'/'+($route.params.number-1)" tag="button">&laquo;</router-link>
<router-link :disabled="$route.params.number == latestNum" :to="'/jobs/'+$route.params.name+'/'+(parseInt($route.params.number)+1)" tag="button">&raquo;</router-link>
</div>
<div id="page-run-detail">
<dl>
<dt>Reason</dt><dd>{{job.reason}}</dd>
<dt v-show="job.upstream.num > 0">Upstream</dt><dd v-show="job.upstream.num > 0"><router-link :to="'/jobs/'+job.upstream.name">{{job.upstream.name}}</router-link> <router-link :to="'/jobs/'+job.upstream.name+'/'+job.upstream.num">#{{job.upstream.num}}</router-link></li></dd>
<dt>Queued for</dt><dd>{{job.queued}}s</dd>
<dt>Started</dt><dd>{{formatDate(job.started)}}</dd>
<dt v-show="job.upstream.num > 0">Upstream</dt><dd v-show="job.upstream.num > 0"><router-link :to="'jobs/'+job.upstream.name">{{job.upstream.name}}</router-link> <router-link :to="'jobs/'+job.upstream.name+'/'+job.upstream.num">#{{job.upstream.num}}</router-link></li></dd>
<dt>Queued for</dt><dd>{{formatDuration(job.queued, job.started ? job.started : Math.floor(Date.now()/1000))}}</dd>
<dt v-show="job.started">Started</dt><dd v-show="job.started">{{formatDate(job.started)}}</dd>
<dt v-show="runComplete(job)">Completed</dt><dd v-show="job.completed">{{formatDate(job.completed)}}</dd>
<dt>Duration</dt><dd>{{formatDuration(job.started, job.completed)}}</dd>
<dt v-show="job.started">Duration</dt><dd v-show="job.started">{{formatDuration(job.started, job.completed)}}</dd>
</dl>
<dl v-show="job.artifacts.length">
<dt>Artifacts</dt>
@@ -171,19 +187,19 @@
</div>
</div>
<div class="console-log">
<code v-html="log"></code>
<span v-show="job.result == 'running'" v-html="runIcon('running')" style="display: block;"></span>
<code></code>
<span v-show="!logComplete" v-html="runIcon('running')" style="display: block;"></span>
</div>
</div></template>
<main id="app" style="display: grid; grid-template-rows: auto 1fr auto; height: 100%;">
<nav id="nav-top" style="display: grid; grid-template-columns: auto auto 1fr auto auto; grid-gap: 15px;">
<router-link to="/" style="display: grid; grid-auto-flow: column; align-items: center; margin: 5px; font-size: 20px;">
<router-link to="." style="display: grid; grid-auto-flow: column; align-items: center; margin: 5px; font-size: 20px;">
<img src="icon.png"> {{title}}
</router-link>
<div id="nav-top-links" style="display: grid; grid-auto-flow: column; justify-content: start; gap: 15px; padding: 0 15px; align-items: center; font-size: 16px;">
<router-link to="/jobs">Jobs</router-link>
<router-link v-for="(crumb,i) in _route.path.slice(1).split('/').slice(1,-1)" :to="_route.path.split('/').slice(0,i+3).join('/')">{{crumb}}</router-link>
<router-link to="jobs">Jobs</router-link>
<router-link v-for="(crumb,i) in route.path.slice(1).split('/').slice(1,-1)" :to="route.path.split('/').slice(0,i+3).join('/')">{{crumb}}</router-link>
</div>
<div></div>
<span class="version">{{version}}</span>

File diff suppressed because it is too large Load Diff

View File

@@ -12,8 +12,6 @@
--running: #4786ab;
--warning: #de9a34;
--link-fg: #2f4579;
--console-bg: #313235;
--console-fg: #fff;
--alt-row-bg: #fafafa;
--border-grey: #d0d0d0;
}
@@ -84,7 +82,9 @@ canvas {
}
svg.success path { fill: var(--success); }
svg.failed path { fill: var(--failure); }
svg.running circle { stroke: var(--running); }
svg.running circle { stroke: var(--running); }
svg.queued circle { fill: var(--nav-fg); }
svg.queued path { stroke: white; }
/* sort indicators */
a.sort {
@@ -119,10 +119,46 @@ a.sort:not(.dsc):hover:after { border-top-color: var(--main-fg); }
a.active { color: var(--main-fg); }
a.active:hover { text-decoration: none; }
/* run console output */
.console-log { padding: 15px; background-color: var(--console-bg); }
.console-log code { white-space: pre-wrap; color: var(--console-fg); }
.console-log a { color: var(--console-fg); }
/* run console ansi colors (based on base16-default-dark and base16-bright) */
:root {
--ansi-black: #181818;
--ansi-red: #ab4642;
--ansi-green: #a1b56c;
--ansi-yellow: #f7ca88;
--ansi-blue: #7cafc2;
--ansi-magenta: #ba8baf;
--ansi-cyan: #86c1b9;
--ansi-white: #d8d8d8;
--ansi-brightblack: #000000;
--ansi-brightred: #fb0120;
--ansi-brightgreen: #a1c659;
--ansi-brightyellow: #fda331;
--ansi-brightblue: #6fb3d2;
--ansi-brightmagenta: #d381c3;
--ansi-brightcyan: #76c7b7;
--ansi-brightwhite: #e0e0e0;
}
.ansi-black-fg { color: var(--ansi-black); } .ansi-black-bg { background-color: var(--ansi-black); }
.ansi-red-fg { color: var(--ansi-red); } .ansi-red-bg { background-color: var(--ansi-red); }
.ansi-green-fg { color: var(--ansi-green); } .ansi-green-bg { background-color: var(--ansi-green); }
.ansi-yellow-fg { color: var(--ansi-yellow); } .ansi-yellow-bg { background-color: var(--ansi-yellow); }
.ansi-blue-fg { color: var(--ansi-blue); } .ansi-blue-bg { background-color: var(--ansi-blue); }
.ansi-magenta-fg { color: var(--ansi-magenta); } .ansi-magenta-bg { background-color: var(--ansi-magenta); }
.ansi-cyan-fg { color: var(--ansi-cyan); } .ansi-cyan-bg { background-color: var(--ansi-cyan); }
.ansi-white-fg { color: var(--ansi-white); } .ansi-white-bg { background-color: var(--ansi-white); }
.ansi-bright-black-fg { color: var(--ansi-brightblack); } .ansi-bright-black-bg { background-color: var(--ansi-brightblack); }
.ansi-bright-red-fg { color: var(--ansi-brightred); } .ansi-bright-red-bg { background-color: var(--ansi-brightred); }
.ansi-bright-green-fg { color: var(--ansi-brightgreen); } .ansi-bright-green-bg { background-color: var(--ansi-brightgreen); }
.ansi-bright-yellow-fg { color: var(--ansi-brightyellow); } .ansi-bright-yellow-bg { background-color: var(--ansi-brightyellow); }
.ansi-bright-blue-fg { color: var(--ansi-brightblue); } .ansi-bright-blue-bg { background-color: var(--ansi-brightblue); }
.ansi-bright-magenta-fg { color: var(--ansi-brightmagenta); } .ansi-bright-magenta-bg { background-color: var(--ansi-brightmagenta); }
.ansi-bright-cyan-fg { color: var(--ansi-brightcyan); } .ansi-bright-cyan-bg { background-color: var(--ansi-brightcyan); }
.ansi-bright-white-fg { color: var(--ansi-brightwhite); } .ansi-bright-white-bg { background-color: var(--ansi-brightwhite); }
/* run console */
.console-log { padding: 15px; background-color: var(--ansi-black); }
.console-log code { white-space: pre-wrap; color: var(--ansi-white); }
.console-log a { color: var(--ansi-brightwhite); text-decoration: underline dotted; }
/* text input (job filtering) */
input { padding: 5px 8px; }
@@ -163,7 +199,6 @@ button:not([disabled]) { cursor: pointer; color: var(--main-fg); }
}
.progress-bar {
height: 100%;
width: 100%;
background-color: var(--running);
background-image: linear-gradient(45deg, transparent 35%, rgba(255,255,255,0.18) 35% 65%, transparent 65%);
background-size: 1rem;
@@ -177,6 +212,41 @@ button:not([disabled]) { cursor: pointer; color: var(--main-fg); }
from { background-position: 1rem 0; } to { background-position: 0 0; }
}
/* wallboard */
.wallboard {
display: flex;
flex-wrap: wrap-reverse;
flex-direction: row-reverse;
gap: 20px;
padding: 20px;
position: fixed;
height: 100%;
width: 100%;
overflow: auto;
background-color: #000
}
.wallboard > div {
padding: 30px;
flex-grow: 1;
background-color: var(--failure);
color: var(--nav-fg-light);
}
.wallboard > div:hover {
cursor: pointer;
}
.wallboard > div[data-result="running"] {
animation: wallboard-bg-fade 2s ease infinite;
}
@keyframes wallboard-bg-fade {
from { background-color: #4786ab; }
50% { background-color: #446597; }
to { background-color: #4786ab; }
}
.wallboard > div[data-result="success"] {
background-color: var(--success);
color: var(--main-fg);
}
/* connecting overlay */
#connecting-overlay {
position: fixed;
@@ -214,6 +284,8 @@ button:not([disabled]) { cursor: pointer; color: var(--main-fg); }
grid-template-columns: 1fr 1fr 1fr;
padding: 15px;
gap: 15px;
max-width: 1600px;
margin: auto;
text-align: center;
}
@media (max-width: 650px) {
@@ -221,6 +293,19 @@ button:not([disabled]) { cursor: pointer; color: var(--main-fg); }
grid-template-columns: 1fr;
}
}
#page-home-plots {
display: grid;
grid-template-columns: 1fr 1fr;
padding: 5px;
gap: 5px;
max-width: 1600px;
margin: auto;
}
@media (max-width: 1095px) {
#page-home-plots {
grid-template-columns: 1fr;
}
}
#page-job-main {
display: grid;
grid-template: auto 1fr / minmax(550px, 1fr) 1fr;

View File

@@ -1,5 +1,5 @@
///
/// Copyright 2015-2019 Oliver Giles
/// Copyright 2015-2022 Oliver Giles
///
/// This file is part of Laminar
///
@@ -53,10 +53,13 @@ public:
kj::Promise<void> queue(QueueContext context) override {
std::string jobName = context.getParams().getJobName();
LLOG(INFO, "RPC queue", jobName);
LaminarCi::MethodResult result = laminar.queueJob(jobName, params(context.getParams().getParams()))
? LaminarCi::MethodResult::SUCCESS
: LaminarCi::MethodResult::FAILED;
context.getResults().setResult(result);
std::shared_ptr<Run> run = laminar.queueJob(jobName, params(context.getParams().getParams()), context.getParams().getFrontOfQueue());
if(Run* r = run.get()) {
context.getResults().setResult(LaminarCi::MethodResult::SUCCESS);
context.getResults().setBuildNum(r->build);
} else {
context.getResults().setResult(LaminarCi::MethodResult::FAILED);
}
return kj::READY_NOW;
}
@@ -64,7 +67,7 @@ public:
kj::Promise<void> start(StartContext context) override {
std::string jobName = context.getParams().getJobName();
LLOG(INFO, "RPC start", jobName);
std::shared_ptr<Run> run = laminar.queueJob(jobName, params(context.getParams().getParams()));
std::shared_ptr<Run> run = laminar.queueJob(jobName, params(context.getParams().getParams()), context.getParams().getFrontOfQueue());
if(Run* r = run.get()) {
return r->whenStarted().then([context,r]() mutable {
context.getResults().setResult(LaminarCi::MethodResult::SUCCESS);
@@ -80,7 +83,7 @@ public:
kj::Promise<void> run(RunContext context) override {
std::string jobName = context.getParams().getJobName();
LLOG(INFO, "RPC run", jobName);
std::shared_ptr<Run> run = laminar.queueJob(jobName, params(context.getParams().getParams()));
std::shared_ptr<Run> run = laminar.queueJob(jobName, params(context.getParams().getParams()), context.getParams().getFrontOfQueue());
if(run) {
return run->whenFinished().then([context,run](RunState state) mutable {
context.getResults().setResult(fromRunState(state));
@@ -98,7 +101,9 @@ public:
auto res = context.getResults().initResult(queue.size());
int i = 0;
for(auto it : queue) {
res.set(i++, it->name);
res[i].setJob(it->name);
res[i].setBuildNum(it->build);
i++;
}
return kj::READY_NOW;
}

View File

@@ -1,5 +1,5 @@
///
/// Copyright 2019 Oliver Giles
/// Copyright 2019-2026 Oliver Giles
///
/// This file is part of Laminar
///
@@ -16,14 +16,13 @@
/// You should have received a copy of the GNU General Public License
/// along with Laminar. If not, see <http://www.gnu.org/licenses/>
///
#ifndef LAMINAR_RPC_H_
#define LAMINAR_RPC_H_
#pragma once
#include <capnp/ez-rpc.h>
#include <capnp/rpc-twoparty.h>
#include <capnp/rpc.capnp.h>
struct Laminar;
class Laminar;
class Rpc {
public:
@@ -33,4 +32,3 @@ public:
capnp::Capability::Client rpcInterface;
};
#endif //LAMINAR_RPC_H_

View File

@@ -21,10 +21,16 @@
#include "conf.h"
#include "log.h"
#include <sys/wait.h>
#include <iostream>
#include <unistd.h>
#include <signal.h>
#if defined(__FreeBSD__)
#include <sys/sysctl.h>
#include <sys/limits.h>
#endif
// short syntax helper for kj::Path
template<typename T>
inline kj::Path operator/(const kj::Path& p, const T& ext) {
@@ -33,7 +39,7 @@ inline kj::Path operator/(const kj::Path& p, const T& ext) {
std::string to_string(const RunState& rs) {
switch(rs) {
case RunState::PENDING: return "pending";
case RunState::QUEUED: return "queued";
case RunState::RUNNING: return "running";
case RunState::ABORTED: return "aborted";
case RunState::FAILED: return "failed";
@@ -44,10 +50,10 @@ std::string to_string(const RunState& rs) {
}
Run::Run(std::string name, ParamMap pm, kj::Path&& rootPath) :
Run::Run(std::string name, uint num, ParamMap pm, kj::Path&& rootPath) :
result(RunState::SUCCESS),
lastResult(RunState::UNKNOWN),
name(name),
build(num),
params(kj::mv(pm)),
queuedAt(time(nullptr)),
rootPath(kj::mv(rootPath)),
@@ -84,7 +90,7 @@ static void setEnvFromFile(const kj::Path& rootPath, kj::Path file) {
}
}
kj::Promise<RunState> Run::start(uint buildNum, std::shared_ptr<Context> ctx, const kj::Directory &fsHome, std::function<kj::Promise<int>(kj::Maybe<pid_t>&)> getPromise)
kj::Promise<RunState> Run::start(RunState lastResult, std::shared_ptr<Context> ctx, const kj::Directory &fsHome, std::function<kj::Promise<int>(kj::Maybe<pid_t>&)> getPromise)
{
kj::Path cfgDir{"cfg"};
@@ -131,7 +137,7 @@ kj::Promise<RunState> Run::start(uint buildNum, std::shared_ptr<Context> ctx, co
PATH.append(p);
}
std::string runNumStr = std::to_string(buildNum);
std::string runNumStr = std::to_string(build);
setenv("PATH", PATH.c_str(), true);
setenv("RUN", runNumStr.c_str(), true);
@@ -152,14 +158,26 @@ kj::Promise<RunState> Run::start(uint buildNum, std::shared_ptr<Context> ctx, co
// enough. Instead, we'll just exec ourselves and handle that in laminard's
// main() by calling leader_main()
char* procName;
if(asprintf(&procName, "{laminar} %s:%d", name.data(), buildNum) > 0)
if(asprintf(&procName, "{laminar} %s:%d", name.data(), build) > 0)
#if defined(__FreeBSD__)
{
int sysctl_rq[] = {CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1};
size_t self_exe_len = PATH_MAX;
char self_exe[PATH_MAX];
if (sysctl(sysctl_rq, 4, self_exe, &self_exe_len, NULL, 0))
_exit(EXIT_FAILURE);
execl(self_exe, procName, NULL); // does not return
}
#else
execl("/proc/self/exe", procName, NULL); // does not return
#endif
_exit(EXIT_FAILURE);
}
// All good, we've "started"
startedAt = time(nullptr);
build = buildNum;
context = ctx;
output_fd = plog[0];

View File

@@ -1,5 +1,5 @@
///
/// Copyright 2015-2018 Oliver Giles
/// Copyright 2015-2026 Oliver Giles
///
/// This file is part of Laminar
///
@@ -16,14 +16,10 @@
/// You should have received a copy of the GNU General Public License
/// along with Laminar. If not, see <http://www.gnu.org/licenses/>
///
#ifndef LAMINAR_RUN_H_
#define LAMINAR_RUN_H_
#pragma once
#include <string>
#include <queue>
#include <list>
#include <functional>
#include <ostream>
#include <unordered_map>
#include <memory>
#include <kj/async.h>
@@ -34,7 +30,7 @@ typedef unsigned int uint;
enum class RunState {
UNKNOWN,
PENDING,
QUEUED,
RUNNING,
ABORTED,
FAILED,
@@ -50,14 +46,14 @@ typedef std::unordered_map<std::string, std::string> ParamMap;
// Represents an execution of a job.
class Run {
public:
Run(std::string name, ParamMap params, kj::Path&& rootPath);
Run(std::string name, uint num, ParamMap params, kj::Path&& rootPath);
~Run();
// copying this class would be asking for trouble...
Run(const Run&) = delete;
Run& operator=(const Run&) = delete;
kj::Promise<RunState> start(uint buildNum, std::shared_ptr<Context> ctx, const kj::Directory &fsHome, std::function<kj::Promise<int>(kj::Maybe<pid_t>&)> getPromise);
kj::Promise<RunState> start(RunState lastResult, std::shared_ptr<Context> ctx, const kj::Directory &fsHome, std::function<kj::Promise<int>(kj::Maybe<pid_t>&)> getPromise);
// aborts this run
bool abort();
@@ -69,7 +65,6 @@ public:
std::shared_ptr<Context> context;
RunState result;
RunState lastResult;
std::string name;
std::string parentName;
int parentBuild = 0;
@@ -110,6 +105,7 @@ private:
// be executing thousands of builds at the same time
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/hashed_index.hpp>
#include <boost/multi_index/indexed_by.hpp>
#include <boost/multi_index/member.hpp>
#include <boost/multi_index/composite_key.hpp>
#include <boost/multi_index/global_fun.hpp>
@@ -126,7 +122,7 @@ struct _run_same {
};
// A single Run can be fetched by...
struct _run_index : bmi::indexed_by<
typedef bmi::indexed_by<
bmi::hashed_unique<bmi::composite_key<
std::shared_ptr<Run>,
// a combination of their job name and build number
@@ -139,8 +135,7 @@ struct _run_index : bmi::indexed_by<
bmi::ordered_non_unique<bmi::member<Run, time_t, &Run::startedAt>>,
// or by their job name
bmi::ordered_non_unique<bmi::member<Run, std::string, &Run::name>>
>
{};
> _run_index;
struct RunSet: public boost::multi_index_container<
std::shared_ptr<Run>,
@@ -159,4 +154,3 @@ struct RunSet: public boost::multi_index_container<
typename bmi::nth_index<RunSet, 3>::type const& byJobName() const { return get<3>(); }
};
#endif // LAMINAR_RUN_H_

View File

@@ -1,5 +1,5 @@
///
/// Copyright 2015-2019 Oliver Giles
/// Copyright 2015-2026 Oliver Giles
///
/// This file is part of Laminar
///
@@ -26,10 +26,9 @@
#include <kj/async-unix.h>
#include <kj/threadlocal.h>
#include <signal.h>
#include <sys/eventfd.h>
#include <sys/stat.h>
#include <sys/inotify.h>
#include <sys/signalfd.h>
// Size of buffer used to read from file descriptors. Should be
// a multiple of sizeof(struct signalfd_siginfo) == 128
@@ -95,7 +94,7 @@ kj::Promise<int> Server::onChildExit(kj::Maybe<pid_t> &pid) {
Server::PathWatcher& Server::watchPaths(std::function<void()> fn)
{
struct PathWatcherImpl : public PathWatcher {
struct PathWatcherImpl final : public PathWatcher {
PathWatcher& addPath(const char* path) override {
inotify_add_watch(fd, path, IN_ONLYDIR | IN_CLOSE_WRITE | IN_CREATE | IN_DELETE);
return *this;
@@ -117,8 +116,11 @@ void Server::listenRpc(Rpc &rpc, kj::StringPtr rpcBindAddress)
if(rpcBindAddress.startsWith("unix:"))
unlink(rpcBindAddress.slice(strlen("unix:")).cStr());
listeners->add(ioContext.provider->getNetwork().parseAddress(rpcBindAddress)
.then([this,&rpc](kj::Own<kj::NetworkAddress>&& addr) {
return acceptRpcClient(rpc, addr->listen());
.then([this,&rpc,rpcBindAddress](kj::Own<kj::NetworkAddress>&& addr) {
kj::Own<kj::ConnectionReceiver> listener = addr->listen();
if(rpcBindAddress.startsWith("unix:"))
chmod(rpcBindAddress.slice(strlen("unix:")).cStr(), 0660);
return acceptRpcClient(rpc, kj::mv(listener));
}));
}
@@ -128,18 +130,28 @@ void Server::listenHttp(Http &http, kj::StringPtr httpBindAddress)
if(httpBindAddress.startsWith("unix:"))
unlink(httpBindAddress.slice(strlen("unix:")).cStr());
listeners->add(ioContext.provider->getNetwork().parseAddress(httpBindAddress)
.then([this,&http](kj::Own<kj::NetworkAddress>&& addr) {
return http.startServer(ioContext.lowLevelProvider->getTimer(), addr->listen());
.then([this,&http,httpBindAddress](kj::Own<kj::NetworkAddress>&& addr) {
kj::Own<kj::ConnectionReceiver> listener = addr->listen();
if(httpBindAddress.startsWith("unix:"))
chmod(httpBindAddress.slice(strlen("unix:")).cStr(), 0660);
return http.startServer(ioContext.lowLevelProvider->getTimer(), kj::mv(listener));
}).catch_([this,&http,httpBindAddress](kj::Exception&&e) mutable -> kj::Promise<void> {
if(e.getType() == kj::Exception::Type::DISCONNECTED) {
LLOG(ERROR, "HTTP disconnect, restarting server", e.getDescription());
listenHttp(http, httpBindAddress);
return kj::READY_NOW;
}
// otherwise propagate the exception
return kj::mv(e);
}));
}
kj::Promise<void> Server::acceptRpcClient(Rpc& rpc, kj::Own<kj::ConnectionReceiver>&& listener) {
kj::ConnectionReceiver& cr = *listener.get();
return cr.accept().then(kj::mvCapture(kj::mv(listener),
[this, &rpc](kj::Own<kj::ConnectionReceiver>&& listener, kj::Own<kj::AsyncIoStream>&& connection) {
return cr.accept().then([this, &rpc, l = kj::mv(listener)](kj::Own<kj::AsyncIoStream>&& connection) mutable {
addTask(rpc.accept(kj::mv(connection)));
return acceptRpcClient(rpc, kj::mv(listener));
}));
return acceptRpcClient(rpc, kj::mv(l));
});
}
// returns a promise which will read a chunk of data from the file descriptor

View File

@@ -1,5 +1,5 @@
///
/// Copyright 2015-2017 Oliver Giles
/// Copyright 2015-2026 Oliver Giles
///
/// This file is part of Laminar
///
@@ -16,8 +16,7 @@
/// You should have received a copy of the GNU General Public License
/// along with Laminar. If not, see <http://www.gnu.org/licenses/>
///
#ifndef LAMINAR_SERVER_H_
#define LAMINAR_SERVER_H_
#pragma once
#include <kj/async-io.h>
#include <kj/compat/http.h>
@@ -26,9 +25,9 @@
#include <functional>
#include <sys/types.h>
struct Laminar;
struct Http;
struct Rpc;
class Laminar;
class Http;
class Rpc;
// This class manages the program's asynchronous event loop
class Server final : public kj::TaskSet::ErrorHandler {
@@ -72,4 +71,3 @@ private:
kj::Maybe<kj::Promise<void>> reapWatch;
};
#endif // LAMINAR_SERVER_H_

View File

@@ -52,7 +52,7 @@ private:
std::vector<rapidjson::Document> receivedMessages;
kj::Promise<void> waitForMessages(kj::AsyncInputStream* stream, ulong offset) {
return stream->read(buffer.asPtr().begin() + offset, 1, BUFFER_SIZE).then([=](size_t s) {
return stream->read(buffer.asPtr().begin() + offset, 1, BUFFER_SIZE).then([=, this](size_t s) {
ulong end = offset + s;
buffer.asPtr().begin()[end] = '\0';
if(strcmp(&buffer.asPtr().begin()[end - 2], "\n\n") == 0) {

View File

@@ -1,5 +1,5 @@
///
/// Copyright 2019-2020 Oliver Giles
/// Copyright 2019-2022 Oliver Giles
///
/// This file is part of Laminar
///
@@ -33,20 +33,26 @@
class LaminarFixture : public ::testing::Test {
public:
LaminarFixture() {
bind_rpc = std::string("unix:/") + tmp.path.toString(true).cStr() + "/rpc.sock";
bind_http = std::string("unix:/") + tmp.path.toString(true).cStr() + "/http.sock";
home = tmp.path.toString(true).cStr();
tmp.fs->openSubdir(kj::Path{"cfg", "jobs"}, kj::WriteMode::CREATE | kj::WriteMode::CREATE_PARENT);
bind_rpc = std::string("unix:/") + home + "/rpc.sock";
bind_http = std::string("unix:/") + home + "/http.sock";
settings.home = home.c_str();
settings.bind_rpc = bind_rpc.c_str();
settings.bind_http = bind_http.c_str();
settings.archive_url = "/test-archive/";
}
~LaminarFixture() noexcept(true) {}
void SetUp() override {
tmp.init();
server = new Server(*ioContext);
laminar = new Laminar(*server, settings);
}
~LaminarFixture() noexcept(true) {
void TearDown() override {
delete server;
delete laminar;
tmp.clean();
}
kj::Own<EventSource> eventSource(const char* path) {
@@ -92,6 +98,14 @@ public:
return { res.getResult(), kj::mv(log) };
}
void setNumExecutors(int nexec) {
KJ_IF_MAYBE(f, tmp.fs->tryOpenFile(kj::Path{"cfg", "contexts", "default.conf"},
kj::WriteMode::CREATE | kj::WriteMode::MODIFY | kj::WriteMode::CREATE_PARENT)) {
std::string content = "EXECUTORS=" + std::to_string(nexec);
(*f)->writeAll(content);
}
}
kj::String stripLaminarLogLines(const kj::String& str) {
auto out = kj::heapString(str.size());
char *o = out.begin();

View File

@@ -1,5 +1,5 @@
///
/// Copyright 2019 Oliver Giles
/// Copyright 2019-2022 Oliver Giles
///
/// This file is part of Laminar
///
@@ -45,7 +45,6 @@ TEST_F(LaminarFixture, EmptyStatusMessageStructure) {
EXPECT_TRUE(data.HasMember("resultChanged"));
EXPECT_TRUE(data.HasMember("lowPassRates"));
EXPECT_TRUE(data.HasMember("buildTimeChanges"));
EXPECT_TRUE(data.HasMember("buildTimeDist"));
}
TEST_F(LaminarFixture, JobNotifyHomePage) {
@@ -134,7 +133,7 @@ TEST_F(LaminarFixture, ParamsToEnv) {
}
TEST_F(LaminarFixture, Abort) {
defineJob("job1", "yes");
defineJob("job1", "sleep inf");
auto req = client().runRequest();
req.setJobName("job1");
auto res = req.send();
@@ -163,3 +162,27 @@ TEST_F(LaminarFixture, JobDescription) {
ASSERT_TRUE(data.HasMember("description"));
EXPECT_STREQ("bar", data["description"].GetString());
}
TEST_F(LaminarFixture, QueueFront) {
setNumExecutors(0);
defineJob("foo", "true");
defineJob("bar", "true");
auto es = eventSource("/");
auto req1 = client().queueRequest();
req1.setJobName("foo");
auto res1 = req1.send();
auto req2 = client().queueRequest();
req2.setFrontOfQueue(true);
req2.setJobName("bar");
auto res2 = req2.send();
ioContext->waitScope.poll();
setNumExecutors(2);
ioContext->waitScope.poll();
ASSERT_GE(es->messages().size(), 5);
auto started1 = es->messages().at(3).GetObject();
EXPECT_STREQ("job_started", started1["type"].GetString());
EXPECT_STREQ("bar", started1["data"]["name"].GetString());
auto started2 = es->messages().at(4).GetObject();
EXPECT_STREQ("job_started", started2["type"].GetString());
EXPECT_STREQ("foo", started2["data"]["name"].GetString());
}

View File

@@ -1,5 +1,5 @@
///
/// Copyright 2018-2020 Oliver Giles
/// Copyright 2018-2022 Oliver Giles
///
/// This file is part of Laminar
///
@@ -28,12 +28,25 @@ class TempDir {
public:
TempDir() :
path(mkdtemp()),
fs(kj::newDiskFilesystem()->getRoot().openSubdir(path, kj::WriteMode::CREATE|kj::WriteMode::MODIFY))
fs(kj::newDiskFilesystem()->getRoot().openSubdir(path, kj::WriteMode::MODIFY))
{
}
~TempDir() noexcept {
kj::newDiskFilesystem()->getRoot().remove(path);
}
void init() {
// set up empty directory structure
fs->openSubdir(kj::Path{"cfg"}, kj::WriteMode::CREATE);
fs->openSubdir(kj::Path{"cfg", "jobs"}, kj::WriteMode::CREATE);
fs->openSubdir(kj::Path{"cfg", "contexts"}, kj::WriteMode::CREATE);
}
void clean() {
// rm -rf in config folder
for(kj::StringPtr name : fs->listNames()) {
fs->remove(kj::Path{name});
}
}
kj::Path path;
kj::Own<const kj::Directory> fs;
private: