mirror of
https://github.com/ohwgiles/laminar.git
synced 2026-10-12 22:20:47 +00:00
Compare commits
140 Commits
feature/co
...
1.4
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
23abdd2712 | ||
|
|
ffe473b082 | ||
|
|
b1ae75e259 | ||
|
|
3392b899b2 | ||
|
|
03c5aca663 | ||
|
|
8206dc3735 | ||
|
|
e7cb501689 | ||
|
|
f2bd292398 | ||
|
|
22742d9747 | ||
|
|
c9faf3d1ae | ||
|
|
9da39ed3f7 | ||
|
|
cfa995f8b9 | ||
|
|
0a340f9b0b | ||
|
|
d259dff604 | ||
|
|
44aea1fc06 | ||
|
|
27d2a760fd | ||
|
|
fc6343bd19 | ||
|
|
736c95ff57 | ||
|
|
5ea394c610 | ||
|
|
8c3d7f62a9 | ||
|
|
a1a95c8e7f | ||
|
|
277a59f1cb | ||
|
|
97b9f6b1ae | ||
|
|
d2c58f0bcd | ||
|
|
dab620b01e | ||
|
|
1e7e9319c3 | ||
|
|
af4b51b3e9 | ||
|
|
458ec26943 | ||
|
|
6a20291dc4 | ||
|
|
3cc01bc45d | ||
|
|
e25b58944d | ||
|
|
1be755e323 | ||
|
|
e9fc547a72 | ||
|
|
01183a3c25 | ||
|
|
e7defa9f15 | ||
|
|
99e2e62906 | ||
|
|
261c08d2fe | ||
|
|
48c0e9340e | ||
|
|
7303e4d592 | ||
|
|
23cb30fc0c | ||
|
|
7eb19ce8c4 | ||
|
|
7c4e1108ae | ||
|
|
5607a93cc1 | ||
|
|
41ddd8fe4f | ||
|
|
e581a0cf5d | ||
|
|
4a6f99a203 | ||
|
|
efafda16ff | ||
|
|
bb087b72ee | ||
|
|
37bbf6ade4 | ||
|
|
e1686d454b | ||
|
|
549f49052a | ||
|
|
d913d04c4a | ||
|
|
78ceeec3e8 | ||
|
|
ded13ed9fe | ||
|
|
15dbed4cac | ||
|
|
e67e0bc453 | ||
|
|
2de8b91ad2 | ||
|
|
399f07cf3a | ||
|
|
2941a5abdd | ||
|
|
a50514a135 | ||
|
|
60f7ee5402 | ||
|
|
7f1c293588 | ||
|
|
fe4caa155b | ||
|
|
f3a6ba2f4b | ||
|
|
dff4c93e15 | ||
|
|
747ae3ada8 | ||
|
|
9a5ccc70e3 | ||
|
|
d01cf1c9b0 | ||
|
|
02810309fc | ||
|
|
b16991b17a | ||
|
|
c7c586167c | ||
|
|
7e77ec1211 | ||
|
|
9b8c3762ec | ||
|
|
c42b6d4207 | ||
|
|
8df882b273 | ||
|
|
14ea1f0f43 | ||
|
|
381fd8b55e | ||
|
|
9f969ae847 | ||
|
|
907f3926ce | ||
|
|
c140fb51eb | ||
|
|
63bbb8a6e7 | ||
|
|
882978fa77 | ||
|
|
1a5292f141 | ||
|
|
ec237f475e | ||
|
|
5e64844440 | ||
|
|
c274e321df | ||
|
|
e442652e0a | ||
|
|
212cfaf8ab | ||
|
|
b755a2ef9e | ||
|
|
cafd0ddaee | ||
|
|
69df17d7bf | ||
|
|
308d679ea4 | ||
|
|
b851c72d53 | ||
|
|
3e993d35a0 | ||
|
|
579c192d89 | ||
|
|
4fb95fcb4f | ||
|
|
bd489bdbb0 | ||
|
|
c6b60646f6 | ||
|
|
1ea9713536 | ||
|
|
746ab24676 | ||
|
|
9862affd98 | ||
|
|
9974df21ce | ||
|
|
c774acbb98 | ||
|
|
06a5f3d8ef | ||
|
|
6d2c0b208b | ||
|
|
4b62e6dbf3 | ||
|
|
dc3e41fb28 | ||
|
|
e74332595e | ||
|
|
a793a97424 | ||
|
|
4e9c4bfb04 | ||
|
|
e29568f627 | ||
|
|
4316eb8a00 | ||
|
|
8a4992e6af | ||
|
|
7f7e8d2455 | ||
|
|
d6be7f5079 | ||
|
|
09a208ebeb | ||
|
|
ae560b9de4 | ||
|
|
4554039703 | ||
|
|
cd64be2cea | ||
|
|
559a6480ee | ||
|
|
1bb545e3f9 | ||
|
|
de948c149e | ||
|
|
0f2e601692 | ||
|
|
c690be3a90 | ||
|
|
1cc6cc6ae9 | ||
|
|
d5cfa3b94e | ||
|
|
081becf23a | ||
|
|
6c61fb3111 | ||
|
|
eadcdbdf9c | ||
|
|
2e54773e83 | ||
|
|
f981491a34 | ||
|
|
a7e6094d01 | ||
|
|
6f366e21cc | ||
|
|
2bf04d8157 | ||
|
|
40b708c594 | ||
|
|
b8ab43b508 | ||
|
|
3fde38c6b8 | ||
|
|
304ef797b8 | ||
|
|
e6f338ceb2 | ||
|
|
0384fc9a0a |
153
CMakeLists.txt
153
CMakeLists.txt
@@ -1,5 +1,5 @@
|
||||
###
|
||||
### Copyright 2015-2019 Oliver Giles
|
||||
### Copyright 2015-2026 Oliver Giles
|
||||
###
|
||||
### This file is part of Laminar
|
||||
###
|
||||
@@ -16,15 +16,65 @@
|
||||
### 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++14 -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
|
||||
if(NOT LAMINAR_VERSION AND EXISTS ${CMAKE_SOURCE_DIR}/.git)
|
||||
execute_process(COMMAND git describe --tags --abbrev=8 --dirty
|
||||
WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
|
||||
OUTPUT_VARIABLE LAMINAR_VERSION
|
||||
OUTPUT_STRIP_TRAILING_WHITESPACE)
|
||||
endif()
|
||||
if(NOT LAMINAR_VERSION)
|
||||
set(LAMINAR_VERSION xx-unversioned)
|
||||
endif()
|
||||
set_source_files_properties(src/version.cpp PROPERTIES COMPILE_DEFINITIONS
|
||||
LAMINAR_VERSION=${LAMINAR_VERSION})
|
||||
|
||||
# This macro takes a list of files, gzips them and converts the output into
|
||||
# object files so they can be linked directly into the application.
|
||||
# ld generates symbols based on the string argument given to its executable,
|
||||
@@ -43,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
|
||||
@@ -62,7 +112,7 @@ add_custom_command(OUTPUT laminar.capnp.c++ laminar.capnp.h
|
||||
|
||||
# Zip and compile statically served resources
|
||||
generate_compressed_bins(${CMAKE_SOURCE_DIR}/src/resources index.html js/app.js
|
||||
favicon.ico favicon-152.png icon.png)
|
||||
style.css manifest.webmanifest favicon.ico favicon-152.png icon.png)
|
||||
|
||||
# The code that allows dynamic modifying of index.html requires knowing its original size
|
||||
add_custom_command(OUTPUT index_html_size.h
|
||||
@@ -70,56 +120,95 @@ 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://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css
|
||||
css/bootstrap.min.css EXPECTED_MD5 5d5357cb3704e1f43a1f5bfed2aebf42)
|
||||
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
|
||||
js/ansi_up.js js/Chart.min.js css/bootstrap.min.css)
|
||||
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)
|
||||
|
||||
set(LAMINARD_CORE_SOURCES
|
||||
src/database.cpp
|
||||
src/server.cpp
|
||||
src/laminar.cpp
|
||||
src/conf.cpp
|
||||
src/database.cpp
|
||||
src/laminar.cpp
|
||||
src/leader.cpp
|
||||
src/http.cpp
|
||||
src/resources.cpp
|
||||
src/rpc.cpp
|
||||
src/run.cpp
|
||||
src/server.cpp
|
||||
src/version.cpp
|
||||
laminar.capnp.c++
|
||||
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 laminar.capnp.c++)
|
||||
target_link_libraries(laminarc capnp-rpc capnp kj-async kj pthread)
|
||||
add_executable(laminarc src/client.cpp src/version.cpp laminar.capnp.c++)
|
||||
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")
|
||||
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 test/unit-run.cpp)
|
||||
target_link_libraries(laminar-tests ${GTEST_LIBRARY} capnp-rpc capnp kj-http kj-async kj pthread sqlite3 z)
|
||||
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_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 laminarc RUNTIME DESTINATION usr/bin)
|
||||
install(FILES etc/laminar.service DESTINATION ${SYSTEMD_UNITDIR})
|
||||
install(FILES etc/laminar.conf DESTINATION etc)
|
||||
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)
|
||||
install(TARGETS laminarc RUNTIME DESTINATION bin)
|
||||
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)
|
||||
|
||||
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()
|
||||
|
||||
15
README.md
15
README.md
@@ -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:
|
||||
@@ -24,8 +24,9 @@ Then compile and install laminar with:
|
||||
```bash
|
||||
git clone https://github.com/ohwgiles/laminar.git
|
||||
cd laminar
|
||||
cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/
|
||||
make -j4
|
||||
cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/usr
|
||||
make -j "$(nproc)"
|
||||
# Warning: the following will overwrite an existing /etc/laminar.conf
|
||||
sudo make install
|
||||
```
|
||||
|
||||
@@ -34,3 +35,7 @@ sudo make install
|
||||
## Packaging for distributions
|
||||
|
||||
The `pkg` directory contains shell scripts which use docker to build native packages (deb,rpm) for common Linux distributions. Note that these are very simple packages which may not completely conform to the distribution's packaging guidelines, however they may serve as a starting point for creating an official package, or may be useful if the official package lags.
|
||||
|
||||
## Contributing
|
||||
|
||||
Issues and pull requests via GitHub are most welcome. All pull requests must adhere to the [Developer Certificate of Origin](https://developercertificate.org/).
|
||||
|
||||
324
UserManual.md
324
UserManual.md
@@ -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,13 +95,11 @@ 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`.
|
||||
|
||||
## Set the page title
|
||||
|
||||
Change `LAMINAR_TITLE` in `/etc/laminar.conf` to your preferred page title. For further WebUI customization, consider using a [custom style sheet](#Customizing-the-WebUI).
|
||||
See [this example configuration file for nginx](https://github.com/ohwgiles/laminar/blob/master/examples/nginx-ssl-reverse-proxy.conf).
|
||||
|
||||
## More configuration options
|
||||
|
||||
@@ -117,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:
|
||||
@@ -131,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
|
||||
@@ -165,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.
|
||||
@@ -187,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
|
||||
|
||||
@@ -198,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
|
||||
@@ -218,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.
|
||||
|
||||
@@ -234,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.
|
||||
|
||||
@@ -263,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.
|
||||
@@ -272,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
|
||||
@@ -324,22 +342,20 @@ Then in `example.run`
|
||||
|
||||
```bash
|
||||
#!/bin/bash
|
||||
echo $foo # prints "bar"
|
||||
echo "$foo" # prints "bar"
|
||||
```
|
||||
|
||||
This works because laminarc reads `$JOB` and `$NUM` and passes them to the laminar daemon as part of the `set` request. (It is thus possible to set environment variables on other jobs by overriding these variables, but this is not very useful).
|
||||
|
||||
---
|
||||
|
||||
# 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.
|
||||
@@ -370,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
|
||||
@@ -413,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
|
||||
@@ -439,7 +457,7 @@ echo Initializing workspace
|
||||
git clone git@example.com:company/project.git .
|
||||
```
|
||||
|
||||
**CAUTION**: By default, laminar permits multiple simultaneous runs of the same job. If a job can **modify** the workspace, this might result in inconsistent builds when simultaneous runs access the same content. This is unlikely to be an issue for nightly builds, but for SCM-triggered builds it will be. To solve this, use [nodes](#Nodes-and-Tags) to restrict simultaneous execution of jobs, or consider [flock](https://linux.die.net/man/1/flock).
|
||||
**CAUTION**: By default, laminar permits multiple simultaneous runs of the same job. If a job can **modify** the workspace, this might result in inconsistent builds when simultaneous runs access the same content. This is unlikely to be an issue for nightly builds, but for SCM-triggered builds it will be. To solve this, use [contexts](#Contexts) to restrict simultaneous execution of jobs, or consider [flock](https://linux.die.net/man/1/flock).
|
||||
|
||||
The following example uses [flock](https://linux.die.net/man/1/flock) to efficiently share a git repository workspace between multiple simultaneous builds:
|
||||
|
||||
@@ -457,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
|
||||
@@ -478,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
|
||||
@@ -486,66 +504,79 @@ TIMEOUT=120
|
||||
|
||||
## Manually
|
||||
|
||||
`laminarc abort $JOBNAME $NUMBER`
|
||||
`laminarc abort $JOB $RUN`
|
||||
|
||||
---
|
||||
|
||||
# Nodes and Tags
|
||||
# Contexts
|
||||
|
||||
In Laminar, a *node* is an abstract concept allowing more fine-grained control over job execution scheduling. Each node can be defined to support an integer number of *executors*, which defines how many runs can be executed simultaneously.
|
||||
In Laminar, each run of a job is associated with a context. The context defines an integer number of *executors*, which is the amount of runs which the context will accept simultaneously. A context may also provide additional environment variables.
|
||||
|
||||
A typical example would be to allow only a few concurrent CPU-intensive jobs (such as compilation), while simultaneously allowing many more less-intensive jobs (such as monitoring or remote jobs). To create a node named `build` with 3 executors, create the file `/var/lib/laminar/cfg/nodes/build.conf` with the following content:
|
||||
Uses for this feature include limiting the amount of concurrent CPU-intensive jobs (such as compilation); and controlling access to jobs [executed remotely](#Remote-jobs).
|
||||
|
||||
```
|
||||
EXECUTORS=3
|
||||
```
|
||||
If no contexts are defined, Laminar will behave as if there is a single context named "default", with `6` executors. This is a reasonable default that allows simple setups to work without any consideration of contexts.
|
||||
|
||||
To associate jobs with nodes, laminar uses *tags*. Tags may be applied to nodes and jobs. If a node has tags, only jobs with a matching tag will be executed on it. If a node has no tags, it will accept any job. To tag a node, add them to `/var/lib/laminar/cfg/nodes/NODENAME.conf`:
|
||||
## Defining a context
|
||||
|
||||
```
|
||||
EXECUTORS=3
|
||||
TAGS=tag1,tag2
|
||||
```
|
||||
|
||||
To add a tag to a job, add the following to `/var/lib/laminar/cfg/jobs/JOBNAME.conf`:
|
||||
|
||||
```
|
||||
TAGS=tag2
|
||||
```
|
||||
|
||||
If Laminar cannot find any node configuration, it will assume a single node with 6 executors and no tags.
|
||||
|
||||
## Grouping jobs with tags
|
||||
|
||||
Tags are also used to group jobs in the web UI. Each tag will presented as a tab in the "Jobs" page.
|
||||
|
||||
## Node scripts
|
||||
|
||||
If `/var/lib/laminar/cfg/nodes/NODENAME.before` exists, it will be executed before the run script of a job scheduled to that node. Similarly, if `/var/lib/laminar/cfg/nodes/NODENAME.after` exists, it will be executed after the run script of a job scheduled to that node.
|
||||
|
||||
## Node environment
|
||||
|
||||
If `/var/lib/laminar/cfg/nodes/NODENAME.env` exists and can be parsed as a list of `KEY=VALUE` pairs, these variables will be exposed as part of the run's environment.
|
||||
|
||||
# Remote jobs
|
||||
|
||||
Laminar provides no specific support, `bash`, `ssh` and possibly NFS are all you need. For example, consider two identical target devices on which test jobs can be run in parallel. You might create a [node](#Nodes-and-Tags) for each, `/var/lib/laminar/cfg/nodes/target{1,2}.conf` with a common tag:
|
||||
To create a context named "my-env" which only allows a single run at once, create `/var/lib/laminar/cfg/contexts/my-env.conf` with the content:
|
||||
|
||||
```
|
||||
EXECUTORS=1
|
||||
TAGS=remote-target
|
||||
```
|
||||
|
||||
In each node's `.env` file, set the individual device's IP address:
|
||||
## 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. 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`. 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.
|
||||
|
||||
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.env`:
|
||||
|
||||
```
|
||||
DUT_IP=192.168.3.2
|
||||
FOO=bar
|
||||
```
|
||||
|
||||
This environment will then be available the run script of jobs associated with this context. Note that these definitions are not expanded by a shell, so `FOO="bar"` would result in a variable `FOO` whose contents *include* double-quotes.
|
||||
|
||||
---
|
||||
|
||||
# Remote jobs
|
||||
|
||||
Laminar provides no specific support, `bash`, `ssh` and possibly NFS are all you need. For example, consider two identical target devices on which test jobs can be run in parallel. You might create a [context](#Contexts) for each, `/var/lib/laminar/cfg/contexts/target{1,2}.conf`:
|
||||
|
||||
```
|
||||
EXECUTORS=1
|
||||
```
|
||||
|
||||
In each context's `.env` file, set the individual device's IP address:
|
||||
|
||||
```
|
||||
TARGET_IP=192.168.0.123
|
||||
```
|
||||
|
||||
And tag the job accordingly in `/var/lib/laminar/cfg/jobs/myproject-test.conf`:
|
||||
And mark the job accordingly in `/var/lib/laminar/cfg/jobs/myproject-test.conf`:
|
||||
|
||||
```
|
||||
TAGS=remote-target
|
||||
CONTEXTS=target*
|
||||
```
|
||||
|
||||
This means the job script `/var/lib/laminar/cfg/jobs/myproject-test.run` can be generic:
|
||||
@@ -553,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`.
|
||||
@@ -577,19 +608,61 @@ 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
|
||||
|
||||
Laminar's frontend supports ANSI colours using the [ansi-up library](https://github.com/drudru/ansi_up). Unfortunately, there is no standard way of convincing applications to output colours when not connected to a tty. It is recommended to set [CLICOLOR_FORCE=1](https://bixense.com/clicolors/) in Laminar's [global environment file](#Environment-variables), plus any of the following environment variables that may be relevant (please submit more):
|
||||
|
||||
* git: `GIT_CONFIG_PARAMETERS='color.status=always' 'color.ui=always'`
|
||||
* google test: `GTEST_COLOR=1`
|
||||
* grep: `GREP_OPTIONS=--color=always`
|
||||
|
||||
More intrusive options for other common tools which do not support enabling colours via environment variable:
|
||||
|
||||
* gcc and clang: Add `-fdiagnostics-color=always` to compile flags
|
||||
|
||||
---
|
||||
|
||||
# Customizing the WebUI
|
||||
|
||||
If it exists, the file `/var/lib/laminar/custom/style.css` will be served by laminar and may be used to change the appearance of Laminar's WebUI.
|
||||
## Organising jobs into groups
|
||||
|
||||
This directory is also a good place to add any extra assets needed for this customization, but note that in this case you will need to serve this directory directly from your [HTTP reverse proxy](#Service-configuration) (highly recommended).
|
||||
*Groups* may be used to organise the "Jobs" page into tabs. Edit `/var/lib/laminar/cfg/groups.conf` and define the matched jobs as a [javascript regular expression](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), for example:
|
||||
|
||||
```
|
||||
Builds=compile-\w+
|
||||
My Fav Jobs=^(target-foo-(build|deploy)|run-benchmarks)$
|
||||
All=.*
|
||||
```
|
||||
|
||||
Changes to this file are detected immediately and will be visible on next page refresh.
|
||||
|
||||
## Adding a description to a job
|
||||
|
||||
Edit `/var/lib/laminar/cfg/jobs/$JOB.conf`:
|
||||
|
||||
```
|
||||
DESCRIPTION=Anything here will appear on the job page in the frontend <em>unescaped</em>.
|
||||
```
|
||||
|
||||
## Setting the page title
|
||||
|
||||
Change `LAMINAR_TITLE` in `/etc/laminar.conf` to your preferred page title. Laminar must be restarted for this change to take effect.
|
||||
|
||||
## Custom HTML template
|
||||
|
||||
If it exists, the file `/var/lib/laminar/custom/index.html` will be served by laminar instead of the default markup that is bundled into the Laminar binary. This file can be used to change any aspect of Laminar's WebUI, for example adding menu links or adding a custom stylesheet. Any required assets will need to be served directly from your [HTTP reverse proxy](#Service-configuration) or other HTTP server.
|
||||
|
||||
An example customization can be found at [cweagans/semantic-laminar-theme](https://github.com/cweagans/semantic-laminar-theme).
|
||||
|
||||
---
|
||||
|
||||
# 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">
|
||||
@@ -601,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`:
|
||||
@@ -614,15 +726,13 @@ Laminar will serve a job's current status as a pretty badge at the url `/badge/J
|
||||
|
||||
## Script execution order
|
||||
|
||||
When `$JOB` is triggered on `$NODE`, the following scripts (relative to `$LAMINAR_HOME/cfg`) may be executed:
|
||||
When `$JOB` is triggered, the following scripts (relative to `$LAMINAR_HOME/cfg`) may be executed:
|
||||
|
||||
- `jobs/$JOB.init` if the [workspace](#Data-sharing-and-Workspaces) did not exist
|
||||
- `before`
|
||||
- `nodes/$NODE.before`
|
||||
- `jobs/$JOB.before`
|
||||
- `jobs/$JOB.run`
|
||||
- `jobs/$JOB.after`
|
||||
- `nodes/$NODE.after`
|
||||
- `after`
|
||||
|
||||
## Environment variables
|
||||
@@ -635,15 +745,18 @@ The following variables are available in run scripts:
|
||||
- `LAST_RESULT` string previous run status
|
||||
- `WORKSPACE` path to this job's workspace
|
||||
- `ARCHIVE` path to this run's archive
|
||||
- `CONTEXT` the context of this run
|
||||
|
||||
In addition, `$LAMINAR_HOME/cfg/scripts` is prepended to `$PATH`. See [helper scripts](#Helper-scripts).
|
||||
|
||||
Laminar will also export variables in the form `KEY=VALUE` found in these files:
|
||||
|
||||
- `env`
|
||||
- `nodes/$NODE.env`
|
||||
- `contexts/$CONTEXT.env`
|
||||
- `jobs/$JOB.env`
|
||||
|
||||
Note that definitions in these files are not expanded by a shell, so `FOO="bar"` would result in a variable `FOO` whose contents *include* double-quotes.
|
||||
|
||||
Finally, variables supplied on the command-line call to `laminarc queue`, `laminarc start` or `laminarc run` will be available. See [parameterized runs](#Parameterized-runs)
|
||||
|
||||
## laminarc
|
||||
@@ -653,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.
|
||||
|
||||
@@ -28,7 +28,7 @@ RUN apk add --no-cache --virtual .build -X http://dl-3.alpinelinux.org/alpine/ed
|
||||
zlib-dev \
|
||||
rapidjson-dev && \
|
||||
cd /build/laminar && \
|
||||
cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/ && \
|
||||
cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/usr && \
|
||||
make -j4 && \
|
||||
make install && \
|
||||
apk del .build && \
|
||||
|
||||
@@ -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=/usr/bin/laminard
|
||||
ExecStart=@CMAKE_INSTALL_PREFIX@/sbin/laminard -v
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
74
etc/laminarc.1
Normal file
74
etc/laminarc.1
Normal 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
56
etc/laminard.8
Normal 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).
|
||||
@@ -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
|
||||
@@ -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
53
examples/docker-advanced
Executable 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
117
examples/format-test-results
Executable 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 > 0) or (@errors > 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"
|
||||
42
examples/git-post-receive-hook-notes
Executable file
42
examples/git-post-receive-hook-notes
Executable 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
|
||||
52
examples/nginx-ssl-reverse-proxy.conf
Normal file
52
examples/nginx-ssl-reverse-proxy.conf
Normal 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
55
examples/notify-email-pretty
Executable 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
18
examples/notify-email-text-log
Executable 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
18
examples/notify-telegram
Executable 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
46
examples/plot-build-time-dist
Executable 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
|
||||
@@ -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=/ -DSYSTEMD_UNITDIR=%{_unitdir} %{_sourcedir}/laminar-$VERSION
|
||||
pwd
|
||||
make
|
||||
|
||||
%install
|
||||
%make_install
|
||||
|
||||
%files
|
||||
%{_bindir}/laminarc
|
||||
%{_bindir}/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,nodes,scripts}
|
||||
chown -R laminar: %{_sharedstatedir}/laminar
|
||||
EOF
|
||||
|
||||
rpmbuild -ba laminar.spec
|
||||
mv rpmbuild/RPMS/x86_64/laminar-$VERSION-1.x86_64.rpm /output/
|
||||
EOS
|
||||
@@ -1,78 +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_centos8
|
||||
|
||||
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
|
||||
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
|
||||
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=/ -DSYSTEMD_UNITDIR=%{_unitdir} %{_sourcedir}/laminar-$VERSION
|
||||
pwd
|
||||
make
|
||||
|
||||
%install
|
||||
%make_install
|
||||
|
||||
%files
|
||||
%{_bindir}/laminarc
|
||||
%{_bindir}/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,nodes,scripts}
|
||||
chown -R laminar: %{_sharedstatedir}/laminar
|
||||
EOF
|
||||
|
||||
rpmbuild -ba laminar.spec
|
||||
mv rpmbuild/RPMS/x86_64/laminar-$VERSION-1.x86_64.rpm /output/
|
||||
EOS
|
||||
@@ -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
|
||||
)
|
||||
|
||||
@@ -17,7 +17,7 @@ docker run --rm -i -v $SOURCE_DIR:/laminar:ro -v $OUTPUT_DIR:/output $DOCKER_TAG
|
||||
mkdir /build
|
||||
cd /build
|
||||
|
||||
cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/ -DZSH_COMPLETIONS_DIR=/usr/share/zsh/functions/Completion/Unix /laminar
|
||||
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
|
||||
@@ -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
|
||||
@@ -38,7 +38,7 @@ 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,nodes,scripts}
|
||||
mkdir -p /var/lib/laminar/cfg/{jobs,contexts,scripts}
|
||||
chown -R laminar: /var/lib/laminar
|
||||
EOF
|
||||
chmod +x laminar/DEBIAN/postinst
|
||||
@@ -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,20 +17,22 @@ 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=/ \
|
||||
-DCMAKE_INSTALL_PREFIX=/usr \
|
||||
-DLAMINAR_VERSION=$VERSION \
|
||||
-DZSH_COMPLETIONS_DIR=/usr/share/zsh/functions/Completion/Unix \
|
||||
/laminar
|
||||
make -j4
|
||||
@@ -45,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
|
||||
@@ -53,7 +55,7 @@ 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,nodes,scripts}
|
||||
mkdir -p /var/lib/laminar/cfg/{jobs,contexts,scripts}
|
||||
chown -R laminar: /var/lib/laminar
|
||||
EOF
|
||||
chmod +x laminar/DEBIAN/postinst
|
||||
48
pkg/debian14-amd64.sh
Executable file
48
pkg/debian14-amd64.sh
Executable 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
65
pkg/debian14-armhf.sh
Executable 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
|
||||
@@ -1,88 +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)-1~upstream-debian9
|
||||
|
||||
DOCKER_TAG=$(docker build -q - <<EOS
|
||||
FROM debian:9-slim
|
||||
RUN dpkg --add-architecture armhf && apt-get update && apt-get install -y wget cmake crossbuild-essential-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_LIBRARY_ARCHITECTURE arm-linux-gnueabihf)
|
||||
EOF
|
||||
|
||||
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
|
||||
|
||||
mkdir capnproto-host
|
||||
cd capnproto-host
|
||||
cmake -DCMAKE_BUILD_TYPE=Release -DBUILD_TESTING=off /build/capnproto-0.7.0/c++/
|
||||
make -j4
|
||||
make install
|
||||
|
||||
cd /build/capnproto-0.7.0/c++/
|
||||
cmake -DCMAKE_TOOLCHAIN_FILE=../../toolchain.cmake -DCMAKE_BUILD_TYPE=Release -DBUILD_TESTING=OFF -DCMAKE_INSTALL_PREFIX=/usr/arm-linux-gnueabihf/ .
|
||||
make -j4
|
||||
make install
|
||||
|
||||
cd /build/rapidjson-1.1.0/
|
||||
cmake -DRAPIDJSON_BUILD_EXAMPLES=off -DCMAKE_INSTALL_PREFIX=/usr/arm-linux-gnueabihf/ .
|
||||
make install
|
||||
|
||||
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=/ \
|
||||
-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: 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,nodes,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
62
pkg/opensuse16.0-x86_64.sh
Executable 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
75
pkg/rocky10-x86_64.sh
Executable 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
|
||||
75
pkg/rocky9-x86_64.sh
Executable file
75
pkg/rocky9-x86_64.sh
Executable 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_rocky9
|
||||
|
||||
DOCKER_TAG=$(docker build -q - <<EOS
|
||||
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
|
||||
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
|
||||
@@ -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-debian9
|
||||
VERSION=$(cd "$SOURCE_DIR" && git describe --tags --abbrev=8 --dirty)-1~upstream-ubuntu2204
|
||||
|
||||
DOCKER_TAG=$(docker build -q - <<EOS
|
||||
FROM debian:9-slim
|
||||
RUN apt-get update && apt-get install -y wget cmake g++ libsqlite3-dev libboost-dev zlib1g-dev
|
||||
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
|
||||
)
|
||||
|
||||
@@ -17,27 +17,7 @@ docker run --rm -i -v $SOURCE_DIR:/laminar:ro -v $OUTPUT_DIR:/output $DOCKER_TAG
|
||||
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++/
|
||||
cmake -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 /build
|
||||
cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/ -DZSH_COMPLETIONS_DIR=/usr/share/zsh/functions/Completion/Unix /laminar
|
||||
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
|
||||
@@ -50,7 +30,7 @@ Section:
|
||||
Priority: optional
|
||||
Architecture: amd64
|
||||
Maintainer: Oliver Giles <web ohwg net>
|
||||
Depends: libsqlite3-0, zlib1g
|
||||
Depends: libcapnp-0.8.0, libsqlite3-0, zlib1g
|
||||
Description: Lightweight Continuous Integration Service
|
||||
EOF
|
||||
echo /etc/laminar.conf > laminar/DEBIAN/conffiles
|
||||
@@ -58,7 +38,7 @@ 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,nodes,scripts}
|
||||
mkdir -p /var/lib/laminar/cfg/{jobs,contexts,scripts}
|
||||
chown -R laminar: /var/lib/laminar
|
||||
EOF
|
||||
chmod +x laminar/DEBIAN/postinst
|
||||
@@ -66,3 +46,4 @@ 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
49
pkg/ubuntu2404-amd64.sh
Executable 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
|
||||
|
||||
174
src/client.cpp
174
src/client.cpp
@@ -1,5 +1,5 @@
|
||||
///
|
||||
/// Copyright 2015-2018 Oliver Giles
|
||||
/// Copyright 2015-2022 Oliver Giles
|
||||
///
|
||||
/// This file is part of Laminar
|
||||
///
|
||||
@@ -17,12 +17,15 @@
|
||||
/// along with Laminar. If not, see <http://www.gnu.org/licenses/>
|
||||
///
|
||||
#include "laminar.capnp.h"
|
||||
#include "log.h"
|
||||
|
||||
#include <capnp/ez-rpc.h>
|
||||
#include <kj/vector.h>
|
||||
|
||||
#include <iostream>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#define EXIT_BAD_ARGUMENT 1
|
||||
#define EXIT_OPERATION_FAILED 2
|
||||
@@ -71,18 +74,59 @@ static int setParams(int argc, char** argv, T& request) {
|
||||
}
|
||||
|
||||
static void printTriggerLink(const char* job, uint run) {
|
||||
// use a private ANSI CSI sequence to mark the JOB:NUM so the
|
||||
// frontend can recognise it and generate a hyperlink.
|
||||
printf("\033[{%s:%d\033\\\n", job, run);
|
||||
if(getenv("__LAMINAR_SETENV_PIPE")) {
|
||||
// use a private ANSI CSI sequence to mark the JOB:NUM so the
|
||||
// frontend can recognise it and generate a hyperlink.
|
||||
printf("\033[{%s:%d\033\\\n", job, run);
|
||||
} else {
|
||||
// not called from within a laminar job, let's not confuse
|
||||
// scripts with ANSI sequences.
|
||||
printf("%s:%d\n", job, run);
|
||||
}
|
||||
}
|
||||
|
||||
static void usage(std::ostream& out) {
|
||||
out << "laminarc version " << laminar_version() << "\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 << " 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";
|
||||
out << " show-running lists currently running jobs.\n";
|
||||
out << "JOB_LIST is of the form:\n";
|
||||
out << " [JOB_NAME [PARAMETER_LIST...]]...\n";
|
||||
out << "PARAMETER_LIST is of the form:\n";
|
||||
out << " [KEY=VALUE]...\n";
|
||||
out << "Example:\n";
|
||||
out << " laminarc start \\\n";
|
||||
out << " nightly-build branch=master type=release \\\n";
|
||||
out << " nightly-build branch=master type=debug\n";
|
||||
}
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
if(argc < 2) {
|
||||
fprintf(stderr, "Usage: %s <command> [parameters...]\n", argv[0]);
|
||||
return EXIT_BAD_ARGUMENT;
|
||||
}
|
||||
if(argc < 2)
|
||||
return usage(std::cerr), EXIT_BAD_ARGUMENT;
|
||||
else if(strcmp("-h", argv[1]) == 0 || strcmp("--help", argv[1]) == 0)
|
||||
return usage(std::cout), EXIT_SUCCESS;
|
||||
|
||||
struct: public kj::TaskSet::ErrorHandler {
|
||||
void taskFailed(kj::Exception&& e) override {
|
||||
fprintf(stderr, "%s\n", e.getDescription().cStr());
|
||||
ret = EXIT_OPERATION_FAILED;
|
||||
}
|
||||
int ret = 0;
|
||||
} errorHandler;
|
||||
kj::TaskSet ts(errorHandler);
|
||||
int& ret = errorHandler.ret;
|
||||
|
||||
int ret = 0;
|
||||
const char* address = getenv("LAMINAR_HOST") ?: getenv("LAMINAR_BIND_RPC") ?: "unix-abstract:laminar";
|
||||
|
||||
capnp::EzRpcClient client(address);
|
||||
@@ -90,100 +134,75 @@ 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;
|
||||
}
|
||||
kj::Vector<capnp::RemotePromise<LaminarCi::QueueResults>> promises;
|
||||
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);
|
||||
promises.add(req.send());
|
||||
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);
|
||||
// pend on the promises
|
||||
for(auto& p : promises) {
|
||||
if(p.wait(waitScope).getResult() != LaminarCi::MethodResult::SUCCESS) {
|
||||
fprintf(stderr, "Failed to queue job '%s'\n", argv[2]);
|
||||
return EXIT_OPERATION_FAILED;
|
||||
}
|
||||
}
|
||||
} 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;
|
||||
struct: public kj::TaskSet::ErrorHandler {
|
||||
void taskFailed(kj::Exception&&) override {}
|
||||
} ignoreFailed;
|
||||
kj::TaskSet ts(ignoreFailed);
|
||||
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) {
|
||||
fprintf(stderr, "Failed to start job '%s'\n", argv[2]);
|
||||
ret = EXIT_OPERATION_FAILED;
|
||||
}
|
||||
printTriggerLink(argv[jobNameIndex], resp.getBuildNum());
|
||||
} else
|
||||
printTriggerLink(argv[jobNameIndex], resp.getBuildNum());
|
||||
}));
|
||||
jobNameIndex += n + 1;
|
||||
} while(jobNameIndex < argc);
|
||||
ts.onEmpty().wait(waitScope);
|
||||
} else if(strcmp(argv[1], "run") == 0) {
|
||||
if(argc < 3) {
|
||||
fprintf(stderr, "Usage %s run <jobName>\n", argv[0]);
|
||||
return EXIT_BAD_ARGUMENT;
|
||||
}
|
||||
struct: public kj::TaskSet::ErrorHandler {
|
||||
void taskFailed(kj::Exception&&) override {}
|
||||
} ignoreFailed;
|
||||
kj::TaskSet ts(ignoreFailed);
|
||||
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){
|
||||
printTriggerLink(argv[jobNameIndex], resp.getBuildNum());
|
||||
if(resp.getResult() != LaminarCi::JobResult::SUCCESS) {
|
||||
if(resp.getResult() == LaminarCi::JobResult::UNKNOWN)
|
||||
fprintf(stderr, "Failed to start job '%s'\n", argv[2]);
|
||||
else
|
||||
printTriggerLink(argv[jobNameIndex], resp.getBuildNum());
|
||||
if(resp.getResult() != LaminarCi::JobResult::SUCCESS)
|
||||
ret = EXIT_RUN_FAILED;
|
||||
}
|
||||
}));
|
||||
jobNameIndex += n + 1;
|
||||
} while(jobNameIndex < argc);
|
||||
ts.onEmpty().wait(waitScope);
|
||||
} else if(strcmp(argv[1], "set") == 0) {
|
||||
if(argc < 3) {
|
||||
fprintf(stderr, "Usage %s set param=value\n", argv[0]);
|
||||
return EXIT_BAD_ARGUMENT;
|
||||
}
|
||||
auto req = laminar.setRequest();
|
||||
char* eq = strchr(argv[2], '=');
|
||||
char* job = getenv("JOB");
|
||||
char* num = getenv("RUN");
|
||||
if(job && num && eq) {
|
||||
char* name = argv[2];
|
||||
*eq++ = '\0';
|
||||
char* val = eq;
|
||||
req.getRun().setJob(job);
|
||||
req.getRun().setBuildNum(atoi(num));
|
||||
req.getParam().setName(name);
|
||||
req.getParam().setValue(val);
|
||||
req.send().wait(waitScope);
|
||||
if(char* pipeNum = getenv("__LAMINAR_SETENV_PIPE")) {
|
||||
LSYSCALL(write(atoi(pipeNum), argv[2], strlen(argv[2])));
|
||||
} else {
|
||||
fprintf(stderr, "Missing $JOB or $RUN or param is not in the format key=value\n");
|
||||
fprintf(stderr, "Must be run from within a laminar job\n");
|
||||
return EXIT_BAD_ARGUMENT;
|
||||
}
|
||||
} else if(strcmp(argv[1], "abort") == 0) {
|
||||
@@ -194,14 +213,17 @@ int main(int argc, char** argv) {
|
||||
auto req = laminar.abortRequest();
|
||||
req.getRun().setJob(argv[2]);
|
||||
req.getRun().setBuildNum(atoi(argv[3]));
|
||||
if(req.send().wait(waitScope).getResult() != LaminarCi::MethodResult::SUCCESS)
|
||||
ret = EXIT_OPERATION_FAILED;
|
||||
ts.add(req.send().then([&ret](capnp::Response<LaminarCi::AbortResults> resp){
|
||||
if(resp.getResult() != LaminarCi::MethodResult::SUCCESS)
|
||||
ret = EXIT_OPERATION_FAILED;
|
||||
}));
|
||||
} else if(strcmp(argv[1], "show-jobs") == 0) {
|
||||
if(argc != 2) {
|
||||
fprintf(stderr, "Usage: %s show-jobs\n", argv[0]);
|
||||
return EXIT_BAD_ARGUMENT;
|
||||
}
|
||||
for(auto it : laminar.listKnownRequest().send().wait(waitScope).getResult()) {
|
||||
auto jobs = laminar.listKnownRequest().send().wait(waitScope);
|
||||
for(auto it : jobs.getResult()) {
|
||||
printf("%s\n", it.cStr());
|
||||
}
|
||||
} else if(strcmp(argv[1], "show-queued") == 0) {
|
||||
@@ -209,15 +231,17 @@ int main(int argc, char** argv) {
|
||||
fprintf(stderr, "Usage: %s show-queued\n", argv[0]);
|
||||
return EXIT_BAD_ARGUMENT;
|
||||
}
|
||||
for(auto it : laminar.listQueuedRequest().send().wait(waitScope).getResult()) {
|
||||
printf("%s\n", it.cStr());
|
||||
auto queued = laminar.listQueuedRequest().send().wait(waitScope);
|
||||
for(auto it : queued.getResult()) {
|
||||
printf("%s:%d\n", it.getJob().cStr(), it.getBuildNum());
|
||||
}
|
||||
} else if(strcmp(argv[1], "show-running") == 0) {
|
||||
if(argc != 2) {
|
||||
fprintf(stderr, "Usage: %s show-running\n", argv[0]);
|
||||
return EXIT_BAD_ARGUMENT;
|
||||
}
|
||||
for(auto it : laminar.listRunningRequest().send().wait(waitScope).getResult()) {
|
||||
auto running = laminar.listRunningRequest().send().wait(waitScope);
|
||||
for(auto it : running.getResult()) {
|
||||
printf("%s:%d\n", it.getJob().cStr(), it.getBuildNum());
|
||||
}
|
||||
} else {
|
||||
@@ -225,5 +249,7 @@ int main(int argc, char** argv) {
|
||||
return EXIT_BAD_ARGUMENT;
|
||||
}
|
||||
|
||||
ts.onEmpty().wait(waitScope);
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
///
|
||||
/// Copyright 2015 Oliver Giles
|
||||
/// Copyright 2015-2026 Oliver Giles
|
||||
///
|
||||
/// This file is part of Laminar
|
||||
///
|
||||
@@ -16,9 +16,9 @@
|
||||
/// 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>
|
||||
|
||||
class StringMap : public std::unordered_map<std::string, std::string> {
|
||||
@@ -40,5 +40,3 @@ int StringMap::convert(std::string e);
|
||||
// beginning with '#'
|
||||
StringMap parseConfFile(const char* path);
|
||||
|
||||
|
||||
#endif // LAMINAR_CONF_H_
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
///
|
||||
/// Copyright 2015 Oliver Giles
|
||||
/// Copyright 2015-2026 Oliver Giles
|
||||
///
|
||||
/// This file is part of Laminar
|
||||
///
|
||||
@@ -16,28 +16,22 @@
|
||||
/// 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_NODE_H_
|
||||
#define LAMINAR_NODE_H_
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
#include <set>
|
||||
|
||||
class Run;
|
||||
|
||||
// Represents a group of executors. Currently almost unnecessary POD
|
||||
// abstraction, but may be enhanced in the future to support e.g. tags
|
||||
class Node {
|
||||
// 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
|
||||
class Context {
|
||||
public:
|
||||
Node() {}
|
||||
Context() {}
|
||||
|
||||
std::string name;
|
||||
int numExecutors;
|
||||
int busyExecutors = 0;
|
||||
std::set<std::string> tags;
|
||||
|
||||
// Attempts to queue the given run to this node. Returns true if succeeded.
|
||||
bool queue(const Run& run);
|
||||
std::set<std::string> jobPatterns;
|
||||
};
|
||||
|
||||
|
||||
#endif // LAMINAR_NODE_H_
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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_
|
||||
|
||||
54
src/http.cpp
54
src/http.cpp
@@ -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");
|
||||
@@ -268,8 +273,8 @@ Http::Http(Laminar &li) :
|
||||
|
||||
Http::~Http()
|
||||
{
|
||||
KJ_ASSERT(logWatchers.size() == 0);
|
||||
KJ_ASSERT(eventPeers.size() == 0);
|
||||
LASSERT(logWatchers.size() == 0);
|
||||
LASSERT(eventPeers.size() == 0);
|
||||
}
|
||||
|
||||
kj::Promise<void> Http::startServer(kj::Timer& timer, kj::Own<kj::ConnectionReceiver>&& listener)
|
||||
@@ -292,8 +297,13 @@ 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));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void Http::setHtmlTemplate(std::string tmpl)
|
||||
{
|
||||
resources->setHtmlTemplate(tmpl);
|
||||
}
|
||||
|
||||
13
src/http.h
13
src/http.h
@@ -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;
|
||||
|
||||
@@ -43,6 +42,9 @@ public:
|
||||
void notifyEvent(const char* data, std::string job = nullptr);
|
||||
void notifyLog(std::string job, uint run, std::string log_chunk, bool eot);
|
||||
|
||||
// Allows supplying a custom HTML template. Pass an empty string to use the default.
|
||||
void setHtmlTemplate(std::string tmpl = std::string());
|
||||
|
||||
private:
|
||||
virtual kj::Promise<void> request(kj::HttpMethod method, kj::StringPtr url, const kj::HttpHeaders& headers,
|
||||
kj::AsyncInputStream& requestBody, Response& response) override;
|
||||
@@ -63,4 +65,3 @@ private:
|
||||
kj::HttpHeaderId ACCEPT;
|
||||
};
|
||||
|
||||
#endif //LAMINAR_HTTP_H_
|
||||
|
||||
@@ -2,14 +2,13 @@
|
||||
|
||||
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);
|
||||
set @3 (run :Run, param :JobParam) -> (result :MethodResult);
|
||||
listQueued @4 () -> (result :List(Text));
|
||||
listRunning @5 () -> (result :List(Run));
|
||||
listKnown @6 () -> (result :List(Text));
|
||||
abort @7 (run :Run) -> (result :MethodResult);
|
||||
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);
|
||||
|
||||
struct Run {
|
||||
job @0 :Text;
|
||||
|
||||
496
src/laminar.cpp
496
src/laminar.cpp
@@ -1,5 +1,5 @@
|
||||
///
|
||||
/// Copyright 2015-2019 Oliver Giles
|
||||
/// Copyright 2015-2022 Oliver Giles
|
||||
///
|
||||
/// This file is part of Laminar
|
||||
///
|
||||
@@ -28,6 +28,7 @@
|
||||
#include <sys/types.h>
|
||||
#include <sys/stat.h>
|
||||
#include <fcntl.h>
|
||||
#include <fnmatch.h>
|
||||
#include <fstream>
|
||||
#include <zlib.h>
|
||||
|
||||
@@ -36,6 +37,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 +73,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)),
|
||||
@@ -76,6 +81,11 @@ Laminar::Laminar(Server &server, Settings settings) :
|
||||
{
|
||||
LASSERT(settings.home[0] == '/');
|
||||
|
||||
if(fsHome->exists(homePath/"cfg"/"nodes")) {
|
||||
LLOG(ERROR, "Found node configuration directory cfg/nodes. Nodes have been deprecated, please migrate to contexts. Laminar will now exit.");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
archiveUrl = settings.archive_url;
|
||||
if(archiveUrl.back() != '/')
|
||||
archiveUrl.append("/");
|
||||
@@ -85,11 +95,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)");
|
||||
|
||||
@@ -104,8 +134,15 @@ Laminar::Laminar(Server &server, Settings settings) :
|
||||
loadConfiguration();
|
||||
// config change may allow stuck jobs to dequeue
|
||||
assignNewJobs();
|
||||
}).addPath((homePath/"cfg"/"nodes").toString(true).cStr())
|
||||
.addPath((homePath/"cfg"/"jobs").toString(true).cStr());
|
||||
}).addPath((homePath/"cfg"/"contexts").toString(true).cStr())
|
||||
.addPath((homePath/"cfg"/"jobs").toString(true).cStr())
|
||||
.addPath((homePath/"cfg").toString(true).cStr()); // for groups.conf
|
||||
|
||||
loadCustomizations();
|
||||
srv.watchPaths([this]{
|
||||
LLOG(INFO, "Reloading customizations");
|
||||
loadCustomizations();
|
||||
}).addPath((homePath/"custom").toString(true).cStr());
|
||||
|
||||
srv.listenRpc(*rpc, settings.bind_rpc);
|
||||
srv.listenHttp(*http, settings.bind_http);
|
||||
@@ -115,21 +152,20 @@ Laminar::Laminar(Server &server, Settings settings) :
|
||||
loadConfiguration();
|
||||
}
|
||||
|
||||
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;
|
||||
void Laminar::loadCustomizations() {
|
||||
KJ_IF_MAYBE(templ, fsHome->tryOpenFile(kj::Path{"custom","index.html"})) {
|
||||
http->setHtmlTemplate((*templ)->readAllText().cStr());
|
||||
} else {
|
||||
return (*--it.second)->build;
|
||||
http->setHtmlTemplate();
|
||||
}
|
||||
}
|
||||
|
||||
uint Laminar::latestRun(std::string job) {
|
||||
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) {
|
||||
if(Run* run = activeRun(name, num)) {
|
||||
output = run->log;
|
||||
@@ -187,18 +223,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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -207,37 +246,33 @@ std::string Laminar::getStatus(MonitorScope scope) {
|
||||
Json j;
|
||||
j.set("type", "status");
|
||||
j.set("title", getenv("LAMINAR_TITLE") ?: "Laminar");
|
||||
j.set("version", laminar_version());
|
||||
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);
|
||||
});
|
||||
}
|
||||
j.set("latestNum", int(buildNums[scope.job]));
|
||||
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;
|
||||
@@ -252,7 +287,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)
|
||||
@@ -266,7 +302,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);
|
||||
@@ -283,50 +319,55 @@ std::string Laminar::getStatus(MonitorScope scope) {
|
||||
const std::shared_ptr<Run> run = *it;
|
||||
j.StartObject();
|
||||
j.set("number", run->build);
|
||||
j.set("node", run->node->name);
|
||||
j.set("context", run->context->name);
|
||||
j.set("started", run->startedAt);
|
||||
j.set("result", to_string(RunState::RUNNING));
|
||||
j.set("reason", run->reason());
|
||||
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");
|
||||
j.set("number", build).set("started", started);
|
||||
j.EndObject();
|
||||
});
|
||||
|
||||
auto desc = jobDescriptions.find(scope.job);
|
||||
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.startArray("tags");
|
||||
for(const str& t: jobTags[name]) {
|
||||
j.String(t.c_str());
|
||||
}
|
||||
j.EndArray();
|
||||
j.set("reason", reason);
|
||||
j.EndObject();
|
||||
});
|
||||
j.EndArray();
|
||||
@@ -335,27 +376,28 @@ std::string Laminar::getStatus(MonitorScope scope) {
|
||||
j.StartObject();
|
||||
j.set("name", run->name);
|
||||
j.set("number", run->build);
|
||||
j.set("node", run->node->name);
|
||||
j.set("context", run->context->name);
|
||||
j.set("started", run->startedAt);
|
||||
j.startArray("tags");
|
||||
for(const str& t: jobTags[run->name]) {
|
||||
j.String(t.c_str());
|
||||
}
|
||||
j.EndArray();
|
||||
j.EndObject();
|
||||
}
|
||||
j.EndArray();
|
||||
j.startObject("groups");
|
||||
for(const auto& group : jobGroups)
|
||||
j.set(group.first.c_str(), group.second);
|
||||
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 node,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("node", node)
|
||||
.set("context", context)
|
||||
.set("queued", queued)
|
||||
.set("started", started)
|
||||
.set("completed", completed)
|
||||
.set("result", to_string(RunState(result)))
|
||||
.set("reason", reason)
|
||||
.EndObject();
|
||||
});
|
||||
j.EndArray();
|
||||
@@ -364,9 +406,11 @@ std::string Laminar::getStatus(MonitorScope scope) {
|
||||
j.StartObject();
|
||||
j.set("name", run->name);
|
||||
j.set("number", run->build);
|
||||
j.set("node", run->node->name);
|
||||
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);
|
||||
@@ -378,15 +422,17 @@ 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();
|
||||
int execTotal = 0;
|
||||
int execBusy = 0;
|
||||
for(const auto& it : nodes) {
|
||||
const std::shared_ptr<Node>& node = it.second;
|
||||
execTotal += node->numExecutors;
|
||||
execBusy += node->busyExecutors;
|
||||
for(const auto& it : contexts) {
|
||||
const std::shared_ptr<Context>& context = it.second;
|
||||
execTotal += context->numExecutors;
|
||||
execBusy += context->busyExecutors;
|
||||
}
|
||||
j.set("executorsTotal", execTotal);
|
||||
j.set("executorsBusy", execBusy);
|
||||
@@ -411,7 +457,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();
|
||||
@@ -449,29 +495,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();
|
||||
@@ -488,51 +517,51 @@ bool Laminar::loadConfiguration() {
|
||||
if(const char* ndirs = getenv("LAMINAR_KEEP_RUNDIRS"))
|
||||
numKeepRunDirs = static_cast<uint>(atoi(ndirs));
|
||||
|
||||
std::set<std::string> knownNodes;
|
||||
std::set<std::string> knownContexts;
|
||||
|
||||
KJ_IF_MAYBE(nodeDir, fsHome->tryOpenSubdir(kj::Path{"cfg","nodes"})) {
|
||||
for(kj::Directory::Entry& entry : (*nodeDir)->listEntries()) {
|
||||
KJ_IF_MAYBE(contextsDir, fsHome->tryOpenSubdir(kj::Path{"cfg","contexts"})) {
|
||||
for(kj::Directory::Entry& entry : (*contextsDir)->listEntries()) {
|
||||
if(!entry.name.endsWith(".conf"))
|
||||
continue;
|
||||
|
||||
StringMap conf = parseConfFile((homePath/"cfg"/"nodes"/entry.name).toString(true).cStr());
|
||||
StringMap conf = parseConfFile((homePath/"cfg"/"contexts"/entry.name).toString(true).cStr());
|
||||
|
||||
std::string nodeName(entry.name.cStr(), entry.name.findLast('.').orDefault(0));
|
||||
auto existingNode = nodes.find(nodeName);
|
||||
std::shared_ptr<Node> node = existingNode == nodes.end() ? nodes.emplace(nodeName, std::shared_ptr<Node>(new Node)).first->second : existingNode->second;
|
||||
node->name = nodeName;
|
||||
node->numExecutors = conf.get<int>("EXECUTORS", 6);
|
||||
std::string name(entry.name.cStr(), entry.name.findLast('.').orDefault(0));
|
||||
auto existing = contexts.find(name);
|
||||
std::shared_ptr<Context> context = existing == contexts.end() ? contexts.emplace(name, std::shared_ptr<Context>(new Context)).first->second : existing->second;
|
||||
context->name = name;
|
||||
context->numExecutors = conf.get<int>("EXECUTORS", 6);
|
||||
|
||||
std::string tagString = conf.get<std::string>("TAGS");
|
||||
std::set<std::string> tagList;
|
||||
if(!tagString.empty()) {
|
||||
std::istringstream iss(tagString);
|
||||
std::string tag;
|
||||
while(std::getline(iss, tag, ','))
|
||||
tagList.insert(tag);
|
||||
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);
|
||||
}
|
||||
std::swap(node->tags, tagList);
|
||||
context->jobPatterns.swap(jobPtnsList);
|
||||
|
||||
knownNodes.insert(nodeName);
|
||||
knownContexts.insert(name);
|
||||
}
|
||||
}
|
||||
|
||||
// remove any nodes whose config files disappeared.
|
||||
// if there are no known nodes, take care not to remove and re-add the default node
|
||||
for(auto it = nodes.begin(); it != nodes.end();) {
|
||||
if((it->first == "" && knownNodes.size() == 0) || knownNodes.find(it->first) != knownNodes.end())
|
||||
// remove any contexts whose config files disappeared.
|
||||
// if there are no known contexts, take care not to remove and re-add the default context.
|
||||
for(auto it = contexts.begin(); it != contexts.end();) {
|
||||
if((it->first == "default" && knownContexts.size() == 0) || knownContexts.find(it->first) != knownContexts.end())
|
||||
it++;
|
||||
else
|
||||
it = nodes.erase(it);
|
||||
it = contexts.erase(it);
|
||||
}
|
||||
|
||||
// add a default node
|
||||
if(nodes.empty()) {
|
||||
LLOG(INFO, "Creating a default node with 6 executors");
|
||||
std::shared_ptr<Node> node(new Node);
|
||||
node->name = "";
|
||||
node->numExecutors = 6;
|
||||
nodes.emplace("", node);
|
||||
// add a default context
|
||||
if(contexts.empty()) {
|
||||
LLOG(INFO, "Creating a default context with 6 executors");
|
||||
std::shared_ptr<Context> context(new Context);
|
||||
context->name = "default";
|
||||
context->numExecutors = 6;
|
||||
contexts.emplace("default", context);
|
||||
}
|
||||
|
||||
KJ_IF_MAYBE(jobsDir, fsHome->tryOpenSubdir(kj::Path{"cfg","jobs"})) {
|
||||
@@ -543,36 +572,67 @@ bool Laminar::loadConfiguration() {
|
||||
|
||||
std::string jobName(entry.name.cStr(), entry.name.findLast('.').orDefault(0));
|
||||
|
||||
std::string tags = conf.get<std::string>("TAGS");
|
||||
if(!tags.empty()) {
|
||||
std::istringstream iss(tags);
|
||||
std::set<std::string> tagList;
|
||||
std::string tag;
|
||||
while(std::getline(iss, tag, ','))
|
||||
tagList.insert(tag);
|
||||
jobTags[jobName] = tagList;
|
||||
}
|
||||
std::string ctxPtns = conf.get<std::string>("CONTEXTS");
|
||||
|
||||
std::set<std::string> ctxPtnList;
|
||||
if(!ctxPtns.empty()) {
|
||||
std::istringstream iss(ctxPtns);
|
||||
std::string ctx;
|
||||
while(std::getline(iss, ctx, ','))
|
||||
ctxPtnList.insert(ctx);
|
||||
}
|
||||
// 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
jobGroups.clear();
|
||||
KJ_IF_MAYBE(groupsConf, fsHome->tryOpenFile(kj::Path{"cfg","groups.conf"}))
|
||||
jobGroups = parseConfFile((homePath/"cfg"/"groups.conf").toString(true).cStr());
|
||||
if(jobGroups.empty())
|
||||
jobGroups["All Jobs"] = ".*";
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
std::shared_ptr<Run> run = std::make_shared<Run>(name, kj::mv(params), homePath.clone());
|
||||
queuedJobs.push_back(run);
|
||||
// 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, ++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());
|
||||
|
||||
@@ -581,36 +641,30 @@ std::shared_ptr<Run> Laminar::queueJob(std::string name, ParamMap params) {
|
||||
}
|
||||
|
||||
bool Laminar::abort(std::string job, uint buildNum) {
|
||||
if(Run* run = activeRun(job, buildNum)) {
|
||||
run->abort(true);
|
||||
return true;
|
||||
}
|
||||
if(Run* run = activeRun(job, buildNum))
|
||||
return run->abort();
|
||||
return false;
|
||||
}
|
||||
|
||||
void Laminar::abortAll() {
|
||||
for(std::shared_ptr<Run> run : activeJobs) {
|
||||
run->abort(false);
|
||||
run->abort();
|
||||
}
|
||||
}
|
||||
|
||||
bool Laminar::nodeCanQueue(const Node& node, std::string jobName) const {
|
||||
// if a node is too busy, it can't take the job
|
||||
if(node.busyExecutors >= node.numExecutors)
|
||||
bool Laminar::canQueue(const Context& ctx, const Run& run) const {
|
||||
if(ctx.busyExecutors >= ctx.numExecutors)
|
||||
return false;
|
||||
|
||||
// if the node has no tags, allow the build
|
||||
if(node.tags.size() == 0)
|
||||
return true;
|
||||
// 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;
|
||||
}
|
||||
|
||||
auto it = jobTags.find(jobName);
|
||||
// if the job has no tags, it cannot be run on this node
|
||||
if(it == jobTags.end())
|
||||
return false;
|
||||
|
||||
// otherwise, allow the build if job and node have a tag in common
|
||||
for(const std::string& tag : it->second) {
|
||||
if(node.tags.find(tag) != node.tags.end())
|
||||
// ...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;
|
||||
}
|
||||
|
||||
@@ -618,32 +672,46 @@ bool Laminar::nodeCanQueue(const Node& node, std::string jobName) const {
|
||||
}
|
||||
|
||||
bool Laminar::tryStartRun(std::shared_ptr<Run> run, int queueIndex) {
|
||||
for(auto& sn : nodes) {
|
||||
std::shared_ptr<Node> node = sn.second;
|
||||
for(auto& sc : contexts) {
|
||||
std::shared_ptr<Context> ctx = sc.second;
|
||||
|
||||
if(nodeCanQueue(*node.get(), run->name) && run->configure(buildNums[run->name] + 1, node, *fsHome)) {
|
||||
node->busyExecutors++;
|
||||
// set the last known result if exists
|
||||
if(canQueue(*ctx, *run)) {
|
||||
RunState lastResult = RunState::UNKNOWN;
|
||||
|
||||
// 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);
|
||||
});
|
||||
|
||||
// Actually schedules the Run steps
|
||||
kj::Promise<void> exec = handleRunStep(run.get()).then([=]{
|
||||
runFinished(run.get());
|
||||
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);
|
||||
run->log += s;
|
||||
http->notifyLog(run->name, run->build, s, false);
|
||||
}).then([run, p = kj::mv(onRunFinished)]() mutable {
|
||||
// wait until leader reaped
|
||||
return kj::mv(p);
|
||||
}).then([this, run](RunState){
|
||||
handleRunFinished(run.get());
|
||||
});
|
||||
if(run->timeout > 0) {
|
||||
exec = exec.attach(srv.addTimeout(run->timeout, [r=run.get()](){
|
||||
r->abort(true);
|
||||
r->abort();
|
||||
}));
|
||||
}
|
||||
srv.addTask(kj::mv(exec));
|
||||
LLOG(INFO, "Started job on node", run->name, run->build, node->name);
|
||||
|
||||
// update next build number
|
||||
buildNums[run->name]++;
|
||||
LLOG(INFO, "Started job", run->name, run->build, ctx->name);
|
||||
|
||||
// notify clients
|
||||
Json j;
|
||||
@@ -651,7 +719,7 @@ bool Laminar::tryStartRun(std::shared_ptr<Run> run, int queueIndex) {
|
||||
.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());
|
||||
@@ -660,11 +728,6 @@ bool Laminar::tryStartRun(std::shared_ptr<Run> run, int queueIndex) {
|
||||
.fetch<uint>([&](uint etc){
|
||||
j.set("etc", time(nullptr) + etc);
|
||||
});
|
||||
j.startArray("tags");
|
||||
for(const str& t: jobTags[run->name]) {
|
||||
j.String(t.c_str());
|
||||
}
|
||||
j.EndArray();
|
||||
j.EndObject();
|
||||
http->notifyEvent(j.str(), run->name.c_str());
|
||||
return true;
|
||||
@@ -685,34 +748,10 @@ void Laminar::assignNewJobs() {
|
||||
}
|
||||
}
|
||||
|
||||
kj::Promise<void> Laminar::handleRunStep(Run* run) {
|
||||
if(run->step()) {
|
||||
// no more steps
|
||||
return kj::READY_NOW;
|
||||
}
|
||||
void Laminar::handleRunFinished(Run * r) {
|
||||
std::shared_ptr<Context> ctx = r->context;
|
||||
|
||||
kj::Promise<int> exited = srv.onChildExit(run->current_pid);
|
||||
// promise is fulfilled when the process is reaped. But first we wait for all
|
||||
// output from the pipe (Run::output_fd) to be consumed.
|
||||
return srv.readDescriptor(run->output_fd, [this,run](const char*b,size_t n){
|
||||
// handle log output
|
||||
std::string s(b, n);
|
||||
run->log += s;
|
||||
http->notifyLog(run->name, run->build, s, false);
|
||||
}).then([p = std::move(exited)]() mutable {
|
||||
// wait until the process is reaped
|
||||
return kj::mv(p);
|
||||
}).then([this, run](int status){
|
||||
run->reaped(status);
|
||||
// next step in Run
|
||||
return handleRunStep(run);
|
||||
});
|
||||
}
|
||||
|
||||
void Laminar::runFinished(Run * r) {
|
||||
std::shared_ptr<Node> node = r->node;
|
||||
|
||||
node->busyExecutors--;
|
||||
ctx->busyExecutors--;
|
||||
LLOG(INFO, "Run completed", r->name, to_string(r->result));
|
||||
time_t completedAt = time(nullptr);
|
||||
|
||||
@@ -729,10 +768,8 @@ void Laminar::runFinished(Run * r) {
|
||||
}
|
||||
}
|
||||
|
||||
std::string reason = r->reason();
|
||||
db->stmt("INSERT INTO builds VALUES(?,?,?,?,?,?,?,?,?,?,?,?)")
|
||||
.bind(r->name, r->build, node->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
|
||||
@@ -741,16 +778,11 @@ void Laminar::runFinished(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))
|
||||
.set("reason", r->reason());
|
||||
j.startArray("tags");
|
||||
for(const str& t: jobTags[r->name]) {
|
||||
j.String(t.c_str());
|
||||
}
|
||||
j.EndArray();
|
||||
j.startArray("artifacts");
|
||||
populateArtifacts(j, r->name, r->build);
|
||||
j.EndArray();
|
||||
@@ -779,7 +811,14 @@ void Laminar::runFinished(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);
|
||||
@@ -794,7 +833,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);
|
||||
@@ -809,7 +848,7 @@ bool Laminar::handleBadgeRequest(std::string job, std::string &badge) {
|
||||
const char* gradient1 = (rs == RunState::SUCCESS) ? "#2aff4d" : "#ff2a2a";
|
||||
const char* gradient2 = (rs == RunState::SUCCESS) ? "#24b43c" : "#b42424";
|
||||
char* svg = NULL;
|
||||
asprintf(&svg,
|
||||
if(asprintf(&svg,
|
||||
R"x(
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="%d" height="20">
|
||||
<clipPath id="clip">
|
||||
@@ -829,15 +868,10 @@ R"x(
|
||||
<rect x="%d" width="%d" height="20" fill="url(#status)"/>
|
||||
<text x="%d" y="14" fill="#000">%s</text>
|
||||
</g>
|
||||
</svg>)x", jobNameWidth+statusWidth, jobNameWidth+statusWidth, gradient1, gradient2, jobNameWidth, jobNameWidth/2+1, job.data(), jobNameWidth, statusWidth, jobNameWidth+statusWidth/2, status.data());
|
||||
</svg>)x", jobNameWidth+statusWidth, jobNameWidth+statusWidth, gradient1, gradient2, jobNameWidth, jobNameWidth/2+1, job.data(), jobNameWidth, statusWidth, jobNameWidth+statusWidth/2, status.data()) < 0)
|
||||
return false;
|
||||
|
||||
badge = svg;
|
||||
return true;
|
||||
}
|
||||
|
||||
std::string Laminar::getCustomCss() {
|
||||
KJ_IF_MAYBE(cssFile, fsHome->tryOpenFile(kj::Path{"custom","style.css"})) {
|
||||
return (*cssFile)->readAllText().cStr();
|
||||
} else {
|
||||
return std::string();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
///
|
||||
/// Copyright 2015-2019 Oliver Giles
|
||||
/// Copyright 2015-2026 Oliver Giles
|
||||
///
|
||||
/// This file is part of Laminar
|
||||
///
|
||||
@@ -16,22 +16,22 @@
|
||||
/// 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 "node.h"
|
||||
#include "context.h"
|
||||
#include "database.h"
|
||||
|
||||
#include <list>
|
||||
#include <unordered_map>
|
||||
#include <kj/filesystem.h>
|
||||
#include <kj/async-io.h>
|
||||
|
||||
// Node name to node object map
|
||||
typedef std::unordered_map<std::string, std::shared_ptr<Node>> NodeMap;
|
||||
// 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);
|
||||
|
||||
@@ -103,13 +98,13 @@ public:
|
||||
|
||||
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);
|
||||
kj::Promise<void> handleRunStep(Run *run);
|
||||
void runFinished(Run*);
|
||||
bool nodeCanQueue(const Node&, std::string jobName) const;
|
||||
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));
|
||||
@@ -120,13 +115,16 @@ private:
|
||||
|
||||
std::unordered_map<std::string, uint> buildNums;
|
||||
|
||||
std::unordered_map<std::string, std::set<std::string>> jobTags;
|
||||
std::unordered_map<std::string, std::set<std::string>> jobContexts;
|
||||
|
||||
std::unordered_map<std::string, std::string> jobDescriptions;
|
||||
|
||||
std::unordered_map<std::string, std::string> jobGroups;
|
||||
|
||||
Settings settings;
|
||||
RunSet activeJobs;
|
||||
Database* db;
|
||||
Server& srv;
|
||||
NodeMap nodes;
|
||||
ContextMap contexts;
|
||||
kj::Path homePath;
|
||||
kj::Own<const kj::Directory> fsHome;
|
||||
uint numKeepRunDirs;
|
||||
@@ -136,4 +134,3 @@ private:
|
||||
kj::Own<Rpc> rpc;
|
||||
};
|
||||
|
||||
#endif // LAMINAR_LAMINAR_H_
|
||||
|
||||
346
src/leader.cpp
Normal file
346
src/leader.cpp
Normal file
@@ -0,0 +1,346 @@
|
||||
///
|
||||
/// Copyright 2019-2020 Oliver Giles
|
||||
///
|
||||
/// This file is part of Laminar
|
||||
///
|
||||
/// Laminar is free software: you can redistribute it and/or modify
|
||||
/// it under the terms of the GNU General Public License as published by
|
||||
/// the Free Software Foundation, either version 3 of the License, or
|
||||
/// (at your option) any later version.
|
||||
///
|
||||
/// Laminar is distributed in the hope that it will be useful,
|
||||
/// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
/// GNU General Public License for more details.
|
||||
///
|
||||
/// You should have received a copy of the GNU General Public License
|
||||
/// along with Laminar. If not, see <http://www.gnu.org/licenses/>
|
||||
///
|
||||
#include "log.h"
|
||||
#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>
|
||||
#include <kj/async-unix.h>
|
||||
#include <kj/filesystem.h>
|
||||
|
||||
#include "run.h"
|
||||
|
||||
// short syntax helper for kj::Path
|
||||
template<typename T>
|
||||
inline kj::Path operator/(const kj::Path& p, const T& ext) {
|
||||
return p.append(ext);
|
||||
}
|
||||
template<typename T>
|
||||
inline kj::Path operator/(const kj::PathPtr& p, const T& ext) {
|
||||
return p.append(ext);
|
||||
}
|
||||
|
||||
struct Script {
|
||||
kj::Path path;
|
||||
kj::Path cwd;
|
||||
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);
|
||||
RunState run();
|
||||
|
||||
private:
|
||||
void taskFailed(kj::Exception&& exception) override;
|
||||
kj::Promise<void> step(std::queue<Script>& scripts);
|
||||
kj::Promise<void> reapChildProcesses();
|
||||
kj::Promise<void> readEnvPipe(kj::AsyncInputStream* stream, char* buffer);
|
||||
|
||||
kj::TaskSet tasks;
|
||||
RunState result;
|
||||
kj::AsyncIoContext& ioContext;
|
||||
const kj::Directory& home;
|
||||
kj::PathPtr rootPath;
|
||||
std::string jobName;
|
||||
uint runNumber;
|
||||
pid_t currentGroupId;
|
||||
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) :
|
||||
tasks(*this),
|
||||
result(RunState::SUCCESS),
|
||||
ioContext(ioContext),
|
||||
home(fs.getCurrent()),
|
||||
rootPath(fs.getCurrentPath()),
|
||||
jobName(jobName),
|
||||
runNumber(runNumber),
|
||||
aborting(false)
|
||||
{
|
||||
tasks.add(ioContext.unixEventPort.onSignal(SIGTERM).then([this](siginfo_t) {
|
||||
while(scripts.size() && (!scripts.front().runOnAbort))
|
||||
scripts.pop();
|
||||
// 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]{
|
||||
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);
|
||||
tasks.add(readEnvPipe(event, buffer.asPtr().begin()).attach(kj::mv(event), kj::mv(buffer)));
|
||||
}
|
||||
|
||||
RunState Leader::run()
|
||||
{
|
||||
kj::Path cfgDir{"cfg"};
|
||||
|
||||
// create the run directory
|
||||
kj::Path rd{"run",jobName,std::to_string(runNumber)};
|
||||
bool createWorkdir = true;
|
||||
KJ_IF_MAYBE(ls, home.tryLstat(rd)) {
|
||||
LASSERT(ls->type == kj::FsNode::Type::DIRECTORY);
|
||||
LLOG(WARNING, "Working directory already exists, removing", rd.toString());
|
||||
if(home.tryRemove(rd) == false) {
|
||||
LLOG(WARNING, "Failed to remove working directory");
|
||||
createWorkdir = false;
|
||||
}
|
||||
}
|
||||
if(createWorkdir && home.tryOpenSubdir(rd, kj::WriteMode::CREATE|kj::WriteMode::CREATE_PARENT) == nullptr) {
|
||||
LLOG(ERROR, "Could not create working directory", rd.toString());
|
||||
return RunState::FAILED;
|
||||
}
|
||||
|
||||
// create an archive directory
|
||||
kj::Path archive = kj::Path{"archive",jobName,std::to_string(runNumber)};
|
||||
if(home.exists(archive)) {
|
||||
LLOG(WARNING, "Archive directory already exists", archive.toString());
|
||||
} else if(home.tryOpenSubdir(archive, kj::WriteMode::CREATE|kj::WriteMode::CREATE_PARENT) == nullptr) {
|
||||
LLOG(ERROR, "Could not create archive directory", archive.toString());
|
||||
return RunState::FAILED;
|
||||
}
|
||||
|
||||
// create a workspace for this job if it doesn't exist
|
||||
kj::Path ws{"run",jobName,"workspace"};
|
||||
if(!home.exists(ws)) {
|
||||
home.openSubdir(ws, kj::WriteMode::CREATE|kj::WriteMode::CREATE_PARENT);
|
||||
// prepend the workspace init script
|
||||
if(home.exists(cfgDir/"jobs"/(jobName+".init")))
|
||||
scripts.push({cfgDir/"jobs"/(jobName+".init"), kj::mv(ws), false});
|
||||
}
|
||||
|
||||
// add scripts
|
||||
// global before-run script
|
||||
if(home.exists(cfgDir/"before"))
|
||||
scripts.push({cfgDir/"before", rd.clone(), false});
|
||||
// job before-run script
|
||||
if(home.exists(cfgDir/"jobs"/(jobName+".before")))
|
||||
scripts.push({cfgDir/"jobs"/(jobName+".before"), rd.clone(), false});
|
||||
// main run script. must exist.
|
||||
scripts.push({cfgDir/"jobs"/(jobName+".run"), rd.clone(), false});
|
||||
// job after-run script
|
||||
if(home.exists(cfgDir/"jobs"/(jobName+".after")))
|
||||
scripts.push({cfgDir/"jobs"/(jobName+".after"), rd.clone(), true});
|
||||
// global after-run script
|
||||
if(home.exists(cfgDir/"after"))
|
||||
scripts.push({cfgDir/"after", rd.clone(), true});
|
||||
|
||||
// Start executing scripts
|
||||
return step(scripts).then([this](){
|
||||
return result;
|
||||
}).wait(ioContext.waitScope);
|
||||
}
|
||||
|
||||
void Leader::taskFailed(kj::Exception &&exception)
|
||||
{
|
||||
LLOG(ERROR, exception);
|
||||
}
|
||||
|
||||
kj::Promise<void> Leader::step(std::queue<Script> &scripts)
|
||||
{
|
||||
if(scripts.empty())
|
||||
return kj::READY_NOW;
|
||||
|
||||
Script currentScript = kj::mv(scripts.front());
|
||||
scripts.pop();
|
||||
|
||||
pid_t pid = fork();
|
||||
if(pid == 0) { // child
|
||||
// unblock all signals
|
||||
sigset_t mask;
|
||||
sigfillset(&mask);
|
||||
sigprocmask(SIG_UNBLOCK, &mask, nullptr);
|
||||
|
||||
// create a new process group to help us deal with any wayward forks
|
||||
setpgid(0, 0);
|
||||
|
||||
std::string buildNum = std::to_string(runNumber);
|
||||
|
||||
LSYSCALL(chdir(currentScript.cwd.toString(false).cStr()));
|
||||
|
||||
setenv("RESULT", to_string(result).c_str(), true);
|
||||
|
||||
// pass the pipe through a variable to allow laminarc to send new env back
|
||||
char pipeNum[4];
|
||||
sprintf(pipeNum, "%d", setEnvPipe[1]);
|
||||
setenv("__LAMINAR_SETENV_PIPE", pipeNum, 1);
|
||||
|
||||
fprintf(stderr, "[laminar] Executing %s\n", currentScript.path.toString().cStr());
|
||||
kj::String execPath = (rootPath/currentScript.path).toString(true);
|
||||
|
||||
execl(execPath.cStr(), execPath.cStr(), NULL);
|
||||
fprintf(stderr, "[laminar] Failed to execute %s\n", currentScript.path.toString().cStr());
|
||||
_exit(1);
|
||||
}
|
||||
|
||||
currentScriptPid = pid;
|
||||
currentGroupId = pid;
|
||||
|
||||
return reapChildProcesses().then([&](){
|
||||
return step(scripts);
|
||||
});
|
||||
}
|
||||
|
||||
kj::Promise<void> Leader::reapChildProcesses()
|
||||
{
|
||||
return ioContext.unixEventPort.onSignal(SIGCHLD).then([this](siginfo_t) -> kj::Promise<void> {
|
||||
while(true) {
|
||||
int status;
|
||||
errno = 0;
|
||||
pid_t pid = waitpid(-1, &status, WNOHANG);
|
||||
if(pid == -1 && errno == ECHILD) {
|
||||
// all children exited
|
||||
return kj::READY_NOW;
|
||||
} else if(pid == 0) {
|
||||
// child processes are still running
|
||||
if(currentScriptPid) {
|
||||
// We could get here if a more deeply nested process was reparented to us
|
||||
// before the primary script executed. Quietly wait until the process we're
|
||||
// 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]{
|
||||
// TODO: should we mark the job as failed if we had to kill reparented processes?
|
||||
aggressive_recursive_kill(getpid());
|
||||
return reapChildProcesses();
|
||||
}).exclusiveJoin(reapChildProcesses());
|
||||
} else if(pid == currentScriptPid) {
|
||||
// the script we were waiting for is done
|
||||
// if we already marked as failed, preserve that
|
||||
if(result == RunState::SUCCESS) {
|
||||
if(WIFSIGNALED(status) && (WTERMSIG(status) == SIGTERM || WTERMSIG(status) == SIGKILL))
|
||||
result = RunState::ABORTED;
|
||||
else if(WEXITSTATUS(status) != 0)
|
||||
result = RunState::FAILED;
|
||||
}
|
||||
currentScriptPid = 0;
|
||||
} else {
|
||||
// some reparented process was reaped
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
kj::Promise<void> Leader::readEnvPipe(kj::AsyncInputStream *stream, char *buffer) {
|
||||
return stream->tryRead(buffer, 1, 1024).then([this,stream,buffer](size_t sz) {
|
||||
if(sz > 0) {
|
||||
buffer[sz] = '\0';
|
||||
if(char* eq = strchr(buffer, '=')) {
|
||||
*eq++ = '\0';
|
||||
setenv(buffer, eq, 1);
|
||||
}
|
||||
return readEnvPipe(stream, kj::mv(buffer));
|
||||
}
|
||||
return kj::Promise<void>(kj::READY_NOW);
|
||||
});
|
||||
}
|
||||
|
||||
int leader_main(void) {
|
||||
auto ioContext = kj::setupAsyncIo();
|
||||
auto fs = kj::newDiskFilesystem();
|
||||
|
||||
kj::UnixEventPort::captureSignal(SIGTERM);
|
||||
// Don't use captureChildExit or onChildExit because they don't provide a way to
|
||||
// reap orphaned child processes. Stick with the more fundamental onSignal.
|
||||
kj::UnixEventPort::captureSignal(SIGCHLD);
|
||||
|
||||
// Becoming a subreaper means any descendent process whose parent process disappears
|
||||
// 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
|
||||
setpgid(0, 0);
|
||||
|
||||
// Environment inherited from main laminard process
|
||||
const char* jobName = getenv("JOB");
|
||||
std::string name(jobName);
|
||||
uint runNumber = atoi(getenv("RUN"));
|
||||
|
||||
if(!jobName || !runNumber)
|
||||
return EXIT_FAILURE;
|
||||
|
||||
Leader leader(ioContext, *fs, jobName, runNumber);
|
||||
|
||||
// Parent process will cast back to RunState
|
||||
return int(leader.run());
|
||||
}
|
||||
34
src/leader.h
Normal file
34
src/leader.h
Normal file
@@ -0,0 +1,34 @@
|
||||
///
|
||||
/// Copyright 2019-2026 Oliver Giles
|
||||
///
|
||||
/// This file is part of Laminar
|
||||
///
|
||||
/// Laminar is free software: you can redistribute it and/or modify
|
||||
/// it under the terms of the GNU General Public License as published by
|
||||
/// the Free Software Foundation, either version 3 of the License, or
|
||||
/// (at your option) any later version.
|
||||
///
|
||||
/// Laminar is distributed in the hope that it will be useful,
|
||||
/// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
/// GNU General Public License for more details.
|
||||
///
|
||||
/// You should have received a copy of the GNU General Public License
|
||||
/// along with Laminar. If not, see <http://www.gnu.org/licenses/>
|
||||
///
|
||||
#pragma once
|
||||
|
||||
// Main function for the leader process which is responsible for
|
||||
// executing all the scripts which make up a Run. Separating this
|
||||
// into its own process allows for a cleaner process tree view,
|
||||
// where it's obvious which script belongs to which run of which
|
||||
// job, and allows this leader process to act as a subreaper for
|
||||
// any wayward child processes.
|
||||
|
||||
// This could have been implemented as a separate process, but
|
||||
// instead we just fork & exec /proc/self/exe from the main laminar
|
||||
// daemon, and distinguish based on argv[0]. This saves installing
|
||||
// another binary and avoids some associated pitfalls.
|
||||
|
||||
int leader_main(void);
|
||||
|
||||
@@ -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_LOG_H_
|
||||
#define LAMINAR_LOG_H_
|
||||
#pragma once
|
||||
|
||||
#include <kj/debug.h>
|
||||
#include <utility>
|
||||
@@ -67,5 +66,5 @@ namespace _ {
|
||||
for (::kj::_::Debug::Fault f(__FILE_BASE__, __LINE__, \
|
||||
_kjSyscallResult.getErrorNumber(), #call, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal())
|
||||
|
||||
#endif // LAMINAR_LOG_H_
|
||||
const char* laminar_version();
|
||||
|
||||
|
||||
42
src/main.cpp
42
src/main.cpp
@@ -1,5 +1,5 @@
|
||||
///
|
||||
/// Copyright 2015-2016 Oliver Giles
|
||||
/// Copyright 2015-2020 Oliver Giles
|
||||
///
|
||||
/// This file is part of Laminar
|
||||
///
|
||||
@@ -17,11 +17,18 @@
|
||||
/// along with Laminar. If not, see <http://www.gnu.org/licenses/>
|
||||
///
|
||||
#include "laminar.h"
|
||||
#include "leader.h"
|
||||
#include "server.h"
|
||||
#include "log.h"
|
||||
#include <signal.h>
|
||||
|
||||
#include <fcntl.h>
|
||||
#include <iostream>
|
||||
#include <kj/async-unix.h>
|
||||
#include <kj/filesystem.h>
|
||||
#include <signal.h>
|
||||
#include <unistd.h>
|
||||
#include <sys/types.h>
|
||||
#include <sys/stat.h>
|
||||
|
||||
static Laminar* laminar;
|
||||
static Server* server;
|
||||
@@ -40,15 +47,43 @@ constexpr const char* INTADDR_HTTP_DEFAULT = "*:8080";
|
||||
constexpr const char* ARCHIVE_URL_DEFAULT = "/archive/";
|
||||
}
|
||||
|
||||
static void usage(std::ostream& out) {
|
||||
out << "laminard version " << laminar_version() << "\n";
|
||||
out << "Usage:\n";
|
||||
out << " -h|--help show this help message\n";
|
||||
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();
|
||||
|
||||
for(int i = 1; i < argc; ++i) {
|
||||
if(strcmp(argv[i], "-v") == 0) {
|
||||
kj::_::Debug::setLogLevel(kj::_::Debug::Severity::INFO);
|
||||
} else if(strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--help") == 0) {
|
||||
return usage(std::cout), EXIT_SUCCESS;
|
||||
} else {
|
||||
std::cerr << "Unknown argument " << argv[i] << "\n";
|
||||
return usage(std::cerr), EXIT_FAILURE;
|
||||
}
|
||||
}
|
||||
|
||||
// The parent process hopefully connected stdin to /dev/null, but
|
||||
// do it again here just in case. This is important because stdin
|
||||
// is inherited to job runs via the leader process, and some
|
||||
// processes misbehave if they can successfully block on reading
|
||||
// from stdin.
|
||||
close(STDIN_FILENO);
|
||||
LASSERT(open("/dev/null", O_RDONLY) == STDIN_FILENO);
|
||||
|
||||
auto ioContext = kj::setupAsyncIo();
|
||||
|
||||
Settings settings;
|
||||
@@ -65,6 +100,9 @@ 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());
|
||||
|
||||
server->start();
|
||||
|
||||
|
||||
@@ -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_
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
///
|
||||
/// Copyright 2015-2019 Oliver Giles
|
||||
/// Copyright 2015-2020 Oliver Giles
|
||||
///
|
||||
/// This file is part of Laminar
|
||||
///
|
||||
@@ -27,67 +27,91 @@
|
||||
extern const char _binary_##name##_z_end[]; \
|
||||
resources.emplace(route, Resource{_binary_ ## name ## _z_start, _binary_ ## name ## _z_end, content_type})
|
||||
|
||||
#define CONTENT_TYPE_HTML "text/html; charset=utf-8"
|
||||
#define CONTENT_TYPE_ICO "image/x-icon"
|
||||
#define CONTENT_TYPE_PNG "image/png"
|
||||
#define CONTENT_TYPE_JS "application/javascript; charset=utf-8"
|
||||
#define CONTENT_TYPE_CSS "text/css; charset=utf-8"
|
||||
#define CONTENT_TYPE_HTML "text/html; charset=utf-8"
|
||||
#define CONTENT_TYPE_ICO "image/x-icon"
|
||||
#define CONTENT_TYPE_PNG "image/png"
|
||||
#define CONTENT_TYPE_JS "application/javascript; charset=utf-8"
|
||||
#define CONTENT_TYPE_CSS "text/css; charset=utf-8"
|
||||
#define CONTENT_TYPE_MANIFEST "application/manifest+json; charset=utf-8"
|
||||
|
||||
#define GZIP_FORMAT 16
|
||||
|
||||
Resources::Resources()
|
||||
{
|
||||
INIT_RESOURCE("/", index_html, CONTENT_TYPE_HTML);
|
||||
INIT_RESOURCE("/favicon.ico", favicon_ico, CONTENT_TYPE_ICO);
|
||||
INIT_RESOURCE("/favicon-152.png", favicon_152_png, CONTENT_TYPE_PNG);
|
||||
INIT_RESOURCE("/icon.png", icon_png, CONTENT_TYPE_PNG);
|
||||
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("/css/bootstrap.min.css", css_bootstrap_min_css, CONTENT_TYPE_CSS);
|
||||
INIT_RESOURCE("/style.css", style_css, CONTENT_TYPE_CSS);
|
||||
INIT_RESOURCE("/manifest.webmanifest", manifest_webmanifest, CONTENT_TYPE_MANIFEST);
|
||||
// Configure the default template
|
||||
setHtmlTemplate(std::string());
|
||||
}
|
||||
|
||||
if(const char* baseUrl = getenv("LAMINAR_BASE_URL")) {
|
||||
// The administrator needs to customize the <base href>. Unfortunately this seems
|
||||
// to be the only thing that needs to be customizable but cannot be done via dynamic
|
||||
// DOM manipulation without heavy compromises. So replace the static char array with
|
||||
// a modified buffer accordingly.
|
||||
z_stream strm;
|
||||
memset(&strm, 0, sizeof(z_stream));
|
||||
std::string tmp;
|
||||
tmp.resize(INDEX_HTML_UNCOMPRESSED_SIZE);
|
||||
// inflate
|
||||
inflateInit2(&strm, MAX_WBITS|GZIP_FORMAT);
|
||||
strm.next_in = (unsigned char*) _binary_index_html_z_start;
|
||||
strm.avail_in = _binary_index_html_z_end - _binary_index_html_z_start;
|
||||
strm.next_out = (unsigned char*) tmp.data();
|
||||
strm.avail_out = INDEX_HTML_UNCOMPRESSED_SIZE;
|
||||
if(inflate(&strm, Z_FINISH) != Z_STREAM_END) {
|
||||
LLOG(FATAL, "Failed to uncompress index_html");
|
||||
}
|
||||
// replace
|
||||
// There's no validation on the replacement string, so you can completely mangle
|
||||
// the html if you like. This isn't really an issue because if you can modify laminar's
|
||||
// environment you already have elevated permissions
|
||||
if(auto it = tmp.find("base href=\"/"))
|
||||
tmp.replace(it+11, 1, baseUrl);
|
||||
void Resources::setHtmlTemplate(std::string tmpl) {
|
||||
extern const char _binary_index_html_z_start[];
|
||||
extern const char _binary_index_html_z_end[];
|
||||
|
||||
z_stream strm;
|
||||
memset(&strm, 0, sizeof(z_stream));
|
||||
|
||||
if(!tmpl.empty()) {
|
||||
// deflate
|
||||
index_html.resize(tmp.size());
|
||||
index_html.resize(tmpl.size());
|
||||
deflateInit2(&strm, Z_DEFAULT_COMPRESSION, Z_DEFLATED, MAX_WBITS|GZIP_FORMAT, 8, Z_DEFAULT_STRATEGY);
|
||||
strm.next_in = (unsigned char*) tmp.data();
|
||||
strm.avail_in = tmp.size();
|
||||
strm.next_in = (unsigned char*) tmpl.data();
|
||||
strm.avail_in = tmpl.size();
|
||||
strm.next_out = (unsigned char*) index_html.data();
|
||||
strm.avail_out = tmp.size();
|
||||
strm.avail_out = tmpl.size();
|
||||
if(deflate(&strm, Z_FINISH) != Z_STREAM_END) {
|
||||
LLOG(FATAL, "Failed to compress index.html");
|
||||
}
|
||||
index_html.resize(strm.total_out);
|
||||
// update resource map
|
||||
resources["/"].start = index_html.data();
|
||||
resources["/"].end = index_html.data() + index_html.size();
|
||||
} else {
|
||||
// use the default template from compile-time asset
|
||||
if(const char* baseUrl = getenv("LAMINAR_BASE_URL")) {
|
||||
// The administrator needs to customize the <base href>. Unfortunately this seems
|
||||
// to be the only thing that needs to be customizable but cannot be done via dynamic
|
||||
// DOM manipulation without heavy compromises. So replace the static char array with
|
||||
// a modified buffer accordingly.
|
||||
std::string tmp;
|
||||
tmp.resize(INDEX_HTML_UNCOMPRESSED_SIZE);
|
||||
// inflate
|
||||
inflateInit2(&strm, MAX_WBITS|GZIP_FORMAT);
|
||||
strm.next_in = (unsigned char*) _binary_index_html_z_start;
|
||||
strm.avail_in = _binary_index_html_z_end - _binary_index_html_z_start;
|
||||
strm.next_out = (unsigned char*) tmp.data();
|
||||
strm.avail_out = INDEX_HTML_UNCOMPRESSED_SIZE;
|
||||
if(inflate(&strm, Z_FINISH) != Z_STREAM_END) {
|
||||
LLOG(FATAL, "Failed to uncompress index_html");
|
||||
}
|
||||
// replace
|
||||
// There's no validation on the replacement string, so you can completely mangle
|
||||
// the html if you like. This isn't really an issue because if you can modify laminar's
|
||||
// environment you already have elevated permissions
|
||||
if(auto it = tmp.find("base href=\"/"))
|
||||
tmp.replace(it+11, 1, baseUrl);
|
||||
// deflate
|
||||
index_html.resize(tmp.size());
|
||||
deflateInit2(&strm, Z_DEFAULT_COMPRESSION, Z_DEFLATED, MAX_WBITS|GZIP_FORMAT, 8, Z_DEFAULT_STRATEGY);
|
||||
strm.next_in = (unsigned char*) tmp.data();
|
||||
strm.avail_in = tmp.size();
|
||||
strm.next_out = (unsigned char*) index_html.data();
|
||||
strm.avail_out = tmp.size();
|
||||
if(deflate(&strm, Z_FINISH) != Z_STREAM_END) {
|
||||
LLOG(FATAL, "Failed to compress index.html");
|
||||
}
|
||||
index_html.resize(strm.total_out);
|
||||
} else {
|
||||
index_html = std::string(_binary_index_html_z_start, _binary_index_html_z_end);
|
||||
}
|
||||
}
|
||||
// update resource map
|
||||
resources["/"] = Resource{index_html.data(), index_html.data() + index_html.size(), CONTENT_TYPE_HTML};
|
||||
}
|
||||
|
||||
inline bool beginsWith(std::string haystack, const char* needle) {
|
||||
@@ -97,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);
|
||||
|
||||
|
||||
@@ -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>
|
||||
@@ -34,6 +33,9 @@ public:
|
||||
// type. Function returns false if no resource for the given path exists
|
||||
bool handleRequest(std::string path, const char** start, const char** end, const char** content_type);
|
||||
|
||||
// Allows providing a custom HTML template. Pass an empty string to use the default.
|
||||
void setHtmlTemplate(std::string templ = std::string());
|
||||
|
||||
private:
|
||||
struct Resource {
|
||||
const char* start;
|
||||
@@ -44,4 +46,3 @@ private:
|
||||
std::string index_html;
|
||||
};
|
||||
|
||||
#endif // LAMINAR_RESOURCES_H_
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<!doctype html>
|
||||
<html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<base href="/">
|
||||
<meta charset="utf-8">
|
||||
@@ -8,333 +8,217 @@
|
||||
<meta name="apple-mobile-web-app-capable" content="yes" />
|
||||
<link rel="apple-touch-icon-precomposed" href="favicon-152.png">
|
||||
<link rel="icon" href="favicon.ico">
|
||||
<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>
|
||||
<link href="css/bootstrap.min.css" rel="stylesheet">
|
||||
<link href="custom/style.css" rel="stylesheet">
|
||||
<script src="js/app.js" defer></script>
|
||||
<style>
|
||||
body, html { height: 100%; }
|
||||
.navbar { margin-bottom: 0; border-radius: 0; }
|
||||
.navbar-brand { margin: 0 -15px; padding: 7px 15px }
|
||||
.navbar-brand>img { display: inline; }
|
||||
a.navbar-btn { color: #9d9d9d; }
|
||||
a.navbar-btn.active { color: #fff; }
|
||||
a.navbar-btn:hover { color: #fff; text-decoration: none; }
|
||||
a.navbar-btn:focus { color: #fff; }
|
||||
.bell { margin: 8px 15px; color: #9d9d9d; }
|
||||
.bell:hover { text-decoration: none; color: #9d9d9d; cursor: pointer; }
|
||||
.bell.active { color: #333; }
|
||||
dt,dd { line-height: 2; }
|
||||
canvas {
|
||||
width: 100% !important;
|
||||
max-width: 800px;
|
||||
height: auto !important;
|
||||
}
|
||||
.progress {
|
||||
height: 10px;
|
||||
margin-top: 5px;
|
||||
margin-bottom: 0;
|
||||
}
|
||||
table#joblist tr:first-child td { border-top: 0; }
|
||||
#popup-connecting {
|
||||
position: fixed;
|
||||
background: white;
|
||||
border: 1px solid #ddd;
|
||||
bottom: 10px;
|
||||
right: 10px;
|
||||
padding: 20px;
|
||||
}
|
||||
/* status icons */
|
||||
span.status {
|
||||
display: inline-block;
|
||||
width: 1em;
|
||||
text-align: center;
|
||||
font-family: sans-serif;
|
||||
}
|
||||
span.success { color: forestgreen; }
|
||||
span.failed { color: firebrick; }
|
||||
span.aborted { color: indigo; }
|
||||
span.spin {
|
||||
color: steelblue;
|
||||
animation: 2s linear infinite spin;
|
||||
}
|
||||
@keyframes spin {
|
||||
to { transform: rotate(360deg); }
|
||||
}
|
||||
/* chart overlay */
|
||||
li.chart-overlay {
|
||||
position: absolute;
|
||||
display: inline-block;
|
||||
background: white;
|
||||
border: 1px solid lightgray;
|
||||
padding: 3px;
|
||||
}
|
||||
/* sort indicators */
|
||||
a.sort {
|
||||
position: relative;
|
||||
margin-left: 7px;
|
||||
}
|
||||
a.sort:before, a.sort:after {
|
||||
border: 4px solid transparent;
|
||||
content: "";
|
||||
position: absolute;
|
||||
display: block;
|
||||
height: 0;
|
||||
width: 0;
|
||||
right: 0;
|
||||
top: 50%;
|
||||
}
|
||||
a.sort:before {
|
||||
border-bottom-color: #ccc;
|
||||
margin-top: -9px;
|
||||
}
|
||||
a.sort:after {
|
||||
border-top-color: #ccc;
|
||||
margin-top: 1px;
|
||||
}
|
||||
a.sort.dsc:after { border-top-color: #000; }
|
||||
a.sort.asc:before { border-bottom-color: #000; }
|
||||
a.sort:hover { text-decoration: none; cursor:pointer; }
|
||||
a.sort:not(.asc):hover:before { border-bottom-color: #777; }
|
||||
a.sort:not(.dsc):hover:after { border-top-color: #777; }
|
||||
|
||||
</style>
|
||||
<link href="style.css" rel="stylesheet">
|
||||
</head>
|
||||
<body>
|
||||
<template id="home"><div>
|
||||
<ol class="breadcrumb"><li class="active">Home</li></ol>
|
||||
<div class="container-fluid"><div class="row">
|
||||
<div class="col-sm-5 col-md-4 col-lg-3 dash">
|
||||
<table class="table table-bordered">
|
||||
<tr v-for="job in jobsQueued">
|
||||
<td><router-link :to="'/jobs/'+job.name">{{job.name}}</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>
|
||||
<small class="pull-right">{{formatDuration(job.started, job.completed)}}</small>
|
||||
<div class="progress">
|
||||
<div class="progress-bar progress-bar-striped" :class="'progress-bar-'+(job.overtime?'warning':'info')" :class="job.etc?'':'active'" :style="'width:'+(!job.etc?'100':job.progress)+'%'"></div>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
<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><small>Took {{formatDuration(job.started, job.completed)}} at {{formatDate(job.started)}}</small></td>
|
||||
</tr>
|
||||
</table>
|
||||
<template id="home"><div id="page-home-main">
|
||||
<nav>
|
||||
<table class="table striped">
|
||||
<tr v-for="job in jobsQueued">
|
||||
<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>
|
||||
<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>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
<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>
|
||||
<small>Took {{formatDuration(job.started, job.completed)}} at {{formatDate(job.started)}}</small>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</nav>
|
||||
<section style="border-left: 1px solid #d0d0d0;">
|
||||
<div id="page-home-stats">
|
||||
<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>
|
||||
</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)}} %</td></tr>
|
||||
</table>
|
||||
</div>
|
||||
<div>
|
||||
<h3>Utilization</h3>
|
||||
<div><canvas id="chartUtil"></canvas></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-sm-7 col-md-8 col-lg-9"><div class="row">
|
||||
<div class="col-md-6">
|
||||
<div class="panel panel-default">
|
||||
<div class="panel-heading">Total runs per day this week</div>
|
||||
<div class="panel-body">
|
||||
<canvas id="chartBpd"></canvas>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<div class="panel panel-default">
|
||||
<div class="panel-heading">Most runs per job in the last 24 hours</div>
|
||||
<div class="panel-body" id="chartStatus">
|
||||
<canvas id="chartBpj"></canvas>
|
||||
</div>
|
||||
</div>
|
||||
</div></div><div class="row">
|
||||
<div class="col-md-6">
|
||||
<div class="panel panel-default">
|
||||
<div class="panel-heading">Longest average run time per job this week</div>
|
||||
<div class="panel-body">
|
||||
<canvas id="chartTpj"></canvas>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<div class="panel panel-default">
|
||||
<div class="panel-heading">Current executor utilization</div>
|
||||
<div class="panel-body">
|
||||
<canvas id="chartUtil"></canvas>
|
||||
</div>
|
||||
</div>
|
||||
</div></div><div class="row">
|
||||
<div class="col-md-6">
|
||||
<div class="panel panel-default">
|
||||
<div class="panel-heading">Regressions and recoveries</div>
|
||||
<div class="panel-body"><div style="position:relative">
|
||||
<canvas id="chartResultChanges"></canvas>
|
||||
<ul v-for="job in resultChanged">
|
||||
<li v-if="job.lastFailure>job.lastSuccess" :id="'rcd_'+job.name" class="chart-overlay"><router-link :to="'/jobs/'+job.name">{{job.name}}</router-link>: <span v-html="runIcon('failed')"></span> <router-link :to="'/jobs/'+job.name+'/'+job.lastFailure">#{{job.lastFailure}}</router-link> since <span v-html="runIcon('success')"></span> <router-link :to="'/jobs/'+job.name+'/'+job.lastSuccess">#{{job.lastSuccess}}</router-link></li>
|
||||
<li v-if="job.lastFailure<job.lastSuccess" :id="'rcd_'+job.name" class="chart-overlay"><router-link :to="'/jobs/'+job.name">{{job.name}}</router-link>: <span v-html="runIcon('success')"></span> <router-link :to="'/jobs/'+job.name+'/'+job.lastSuccess">#{{job.lastSuccess}}</router-link> since <span v-html="runIcon('failed')"></span> <router-link :to="'/jobs/'+job.name+'/'+job.lastFailure">#{{job.lastFailure}}</router-link></li>
|
||||
</ul>
|
||||
</div></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<div class="panel panel-default">
|
||||
<div class="panel-heading">Low pass rates</div>
|
||||
<div class="panel-body">
|
||||
<canvas id="chartPassRates"></canvas>
|
||||
</div>
|
||||
</div>
|
||||
</div></div><div class="row">
|
||||
<div class="col-md-6">
|
||||
<div class="panel panel-default">
|
||||
<div class="panel-heading">Run time changes</div>
|
||||
<div class="panel-body">
|
||||
<canvas id="chartBuildTimeChanges"></canvas>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<div class="panel panel-default">
|
||||
<div class="panel-heading">Average run time distribution</div>
|
||||
<div class="panel-body">
|
||||
<canvas id="chartBuildTimeDist"></canvas>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div></div>
|
||||
</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>
|
||||
|
||||
|
||||
<template id="jobs"><div>
|
||||
<ol class="breadcrumb"><li><router-link to="/">Home</router-link></li><li class="active">Jobs</li></ol>
|
||||
<div class="container-fluid"><div class="row">
|
||||
<div class="col-xs-12">
|
||||
<div class="pull-right">
|
||||
<input class="form-control" id="jobFilter" v-model="search" placeholder="Filter...">
|
||||
</div>
|
||||
<ul class="nav nav-tabs">
|
||||
<li :class="{'active':tag==null}"><a href v-on:click.prevent="tag = null">All Jobs</a></li>
|
||||
<li v-for="t in tags" :class="{'active':t==tag}"><a href v-on:click.prevent="tag = t">{{t}}</a></li>
|
||||
</ul>
|
||||
<table class="table table-striped" id="joblist">
|
||||
<tr v-for="job in filteredJobs()">
|
||||
<td><router-link :to="'/jobs/'+job.name">{{job.name}}</router-link></td>
|
||||
<td class="text-center"><span v-html="runIcon(job.result)"></span> <router-link :to="'/jobs/'+job.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>
|
||||
</tr>
|
||||
</table>
|
||||
<nav style="display: grid; grid-auto-flow: column; justify-content: space-between; align-items: end; padding: 10px 15px;">
|
||||
<div style="display:grid; grid-auto-flow: column; grid-gap: 15px; padding: 5px 0;">
|
||||
<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>
|
||||
</div></div>
|
||||
<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>{{formatDate(job.started)}}</td>
|
||||
<td>{{formatDuration(job.started,job.completed)}}</td>
|
||||
</tr>
|
||||
</table>
|
||||
</div></template>
|
||||
|
||||
<template id="job"><div>
|
||||
<ol class="breadcrumb"><li><router-link to="/">Home</router-link></li><li><router-link to="/jobs">Jobs</router-link></li><li class="active">{{$route.params.name}}</li></ol></ol>
|
||||
<div class="container-fluid">
|
||||
<div class="row">
|
||||
<div class="col-sm-5 col-md-6 col-lg-7">
|
||||
<h3>{{$route.params.name}}</h3>
|
||||
<dl class="dl-horizontal">
|
||||
<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>
|
||||
<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>
|
||||
</dl>
|
||||
</div>
|
||||
<div class="col-sm-7 col-md-6 col-lg-5">
|
||||
<div class="panel panel-default">
|
||||
<div class="panel-heading">Build time</div>
|
||||
<div class="panel-body">
|
||||
<canvas id="chartBt"></canvas>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<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>
|
||||
<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>
|
||||
<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>
|
||||
</dl>
|
||||
</div>
|
||||
<div style="display: grid; justify-content: center; padding: 15px;">
|
||||
<canvas id="chartBt"></canvas>
|
||||
</div>
|
||||
<div style="grid-column: 1/-1">
|
||||
<table class="striped">
|
||||
<thead><tr>
|
||||
<th><a class="sort" :class="(sort.field=='result'?sort.order:'')" v-on:click="do_sort('result')"> </a></th>
|
||||
<th>Run <a class="sort" :class="(sort.field=='number'?sort.order:'')" v-on:click="do_sort('number')"> </a></th>
|
||||
<th class="text-center">Started <a class="sort" :class="(sort.field=='started'?sort.order:'')" v-on:click="do_sort('started')"> </a></th>
|
||||
<th class="text-center">Duration <a class="sort" :class="(sort.field=='duration'?sort.order:'')" v-on:click="do_sort('duration')"> </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')"> </a></th>
|
||||
</tr></thead>
|
||||
<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"><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>
|
||||
<div style="float: right; margin: 15px; display: inline-grid; grid-auto-flow: column; gap: 10px; align-items: center">
|
||||
<button v-on:click="page_prev" :disabled="sort.page==0">«</button>
|
||||
<span>Page {{sort.page+1}} of {{pages}}</span>
|
||||
<button class="btn" v-on:click="page_next" :disabled="sort.page==pages-1">»</button>
|
||||
</div>
|
||||
<div class="row"><div class="col-xs-12">
|
||||
<table class="table table-striped">
|
||||
<thead><tr>
|
||||
<th><a class="sort" :class="(sort.field=='result'?sort.order:'')" v-on:click="do_sort('result')"> </a></th>
|
||||
<th>Run <a class="sort" :class="(sort.field=='number'?sort.order:'')" v-on:click="do_sort('number')"> </a></th>
|
||||
<th class="text-center">Started <a class="sort" :class="(sort.field=='started'?sort.order:'')" v-on:click="do_sort('started')"> </a></th>
|
||||
<th class="text-center">Duration <a class="sort" :class="(sort.field=='duration'?sort.order:'')" v-on:click="do_sort('duration')"> </a></th>
|
||||
<th class="text-center hidden-xs">Reason <a class="sort" :class="(sort.field=='reason'?sort.order:'')" v-on:click="do_sort('reason')"> </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" 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 class="text-center hidden-xs">{{job.reason}}</td>
|
||||
</tr>
|
||||
<tr v-for="job in 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 class="text-center hidden-xs">{{job.reason}}</td>
|
||||
</tr>
|
||||
</table>
|
||||
<ul class="pagination pull-right">
|
||||
<li><button class="btn btn-default" v-on:click="page_prev" :disabled="sort.page==0">«</button></li>
|
||||
<li>Page {{sort.page+1}} of {{pages}}</li>
|
||||
<li><button class="btn btn-default" v-on:click="page_next" :disabled="sort.page==pages-1">»</button></li>
|
||||
</ul>
|
||||
</div></div>
|
||||
</div>
|
||||
</div></template>
|
||||
|
||||
<template id="run"><div>
|
||||
<ol class="breadcrumb"><li><router-link to="/">Home</router-link></li><li><router-link to="/jobs">Jobs</router-link></li><li><router-link :to="'/jobs/'+$route.params.name">{{$route.params.name}}</router-link></li><li class="active">#{{$route.params.number}}</li></ol></ol>
|
||||
<div class="container-fluid">
|
||||
<div class="row">
|
||||
<div class="col-sm-5 col-md-6 col-lg-7">
|
||||
<h3 style="float:left"><span v-html="runIcon(job.result)"></span> {{$route.params.name}} #{{$route.params.number}}</h3>
|
||||
<nav class="pull-left">
|
||||
<ul class="pagination" style="margin:15px 20px">
|
||||
<li v-show="$route.params.number > 1"><router-link :to="'/jobs/'+$route.params.name+'/'+($route.params.number-1)">«</router-link></li>
|
||||
<li v-show="latestNum > $route.params.number"><router-link :to="'/jobs/'+$route.params.name+'/'+(parseInt($route.params.number)+1)">»</router-link></li>
|
||||
</ul>
|
||||
</nav>
|
||||
<div style="clear:both;"></div>
|
||||
<dl class="dl-horizontal">
|
||||
<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="runComplete(job)">Completed</dt><dd v-show="job.completed">{{formatDate(job.completed)}}</dd>
|
||||
<dt>Duration</dt><dd>{{formatDuration(job.started, job.completed)}}</dd>
|
||||
</dl>
|
||||
</div>
|
||||
<div class="col-sm-7 col-md-6 col-lg-5">
|
||||
<div class="progress" v-show="job.result == 'running'">
|
||||
<div class="progress-bar progress-bar-striped" :class="'progress-bar-'+(job.overtime?'warning':'info')" :class="job.etc?'':'active'" :style="{width:!job.etc?100:job.progress + '%'}"></div>
|
||||
</div>
|
||||
<div class="panel panel-default" v-show="job.artifacts.length">
|
||||
<div class="panel-heading">Artifacts</div>
|
||||
<div class="panel-body">
|
||||
<ul class="list-unstyled" style="margin-bottom: 0">
|
||||
<li v-for="art in job.artifacts"><a :href="art.url" target="_self">{{art.filename}}</a> [{{ art.size | iecFileSize }}]</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
<template id="run"><div style="display: grid; grid-template-rows: auto 1fr">
|
||||
<div style="padding: 15px">
|
||||
<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>
|
||||
<router-link :disabled="route.params.number == 1" :to="'jobs/'+route.params.name+'/'+(route.params.number-1)" tag="button">«</router-link>
|
||||
<router-link :disabled="route.params.number == latestNum" :to="'jobs/'+route.params.name+'/'+(parseInt(route.params.number)+1)" tag="button">»</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>
|
||||
</div>
|
||||
<div class="row"><div class="col-xs-12">
|
||||
<button type="button" class="btn btn-default btn-xs pull-right" :class="{'active':autoscroll}" v-on:click="autoscroll = !autoscroll" style="margin-top:10px">Autoscroll</button>
|
||||
<h4>Console output</h4>
|
||||
<pre v-html="log"></pre>
|
||||
</div></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>{{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 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>
|
||||
<dd>
|
||||
<ul style="margin-bottom: 0">
|
||||
<li v-for="art in job.artifacts"><a :href="art.url" target="_self">{{art.filename}}</a> [{{ art.size | iecFileSize }}]</li>
|
||||
</ul>
|
||||
</dd>
|
||||
</dl>
|
||||
</div>
|
||||
</div>
|
||||
<div class="console-log">
|
||||
<code></code>
|
||||
<span v-show="!logComplete" v-html="runIcon('running')" style="display: block;"></span>
|
||||
</div>
|
||||
</div></template>
|
||||
|
||||
<div id="app">
|
||||
<nav class="navbar navbar-inverse">
|
||||
<div>
|
||||
<router-link to="/" class="navbar-brand"><img src="icon.png">{{title}}</router-link>
|
||||
<router-link to="/jobs" class="btn navbar-btn pull-right">Jobs</router-link>
|
||||
<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;">
|
||||
<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>
|
||||
</div>
|
||||
<div></div>
|
||||
<span class="version">{{version}}</span>
|
||||
<div style="display: grid; align-items: center; padding: 0 15px">
|
||||
<a v-on:click="toggleNotifications(!notify)" class="nav-icon" :class="{active:notify}" v-show="supportsNotifications" :title="(notify?'Disable':'Enable')+' notifications'">
|
||||
<svg width="18" viewBox="0 0 12 12">
|
||||
<g stroke-width="0.5">
|
||||
<path d="m 6,9 c -1,0 -1,0 -1,1 0,1 2,1 2,0 0,-1 0,-1 -1,-1 z" />
|
||||
<path d="m 1,10 c 3,-3 1,-9 5,-9 4,0 2,6 5,9 1,1 -3,-1 -5,-1 -2,0 -6,2 -5,1 z" />
|
||||
</g>
|
||||
</svg>
|
||||
</a>
|
||||
</div>
|
||||
</nav>
|
||||
<a v-on:click="toggleNotifications(!notify)" v-show="supportsNotifications" class="bell pull-right" :class="{'active':notify}" :title="(notify?'Disable':'Enable')+' notifications'">🔔</a>
|
||||
<router-view></router-view>
|
||||
<div v-show="!connected" id="popup-connecting"><span class="status spin">⚙︎</span> Connecting...</div>
|
||||
</div>
|
||||
<div id="connecting-overlay" :class="{shown:!connected}">
|
||||
<div><span v-html="runIcon('running')"></span> Connecting...</div>
|
||||
</div>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
21
src/resources/manifest.webmanifest
Normal file
21
src/resources/manifest.webmanifest
Normal file
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"short_name": "Laminar",
|
||||
"name": "Laminar",
|
||||
"description": "Lightweight Continuous Integration",
|
||||
"icons": [
|
||||
{
|
||||
"src": "/icon.png",
|
||||
"type": "image/png",
|
||||
"sizes": "36x36"
|
||||
},
|
||||
{
|
||||
"src": "/favicon-152.png",
|
||||
"type": "image/png",
|
||||
"sizes": "152x152"
|
||||
}
|
||||
],
|
||||
"start_url": "/",
|
||||
"background_color": "#2F3340",
|
||||
"display": "standalone",
|
||||
"scope": "/"
|
||||
}
|
||||
327
src/resources/style.css
Normal file
327
src/resources/style.css
Normal file
@@ -0,0 +1,327 @@
|
||||
/* colour scheme */
|
||||
:root {
|
||||
--main-bg: #fff;
|
||||
--main-fg: #333;
|
||||
--nav-bg: #2F3340;
|
||||
--nav-bg-darker: #292b33;
|
||||
--nav-fg: #d0d0d0;
|
||||
--nav-fg-light: #fafafa;
|
||||
--icon-enabled: #d8cb83;
|
||||
--success: #74af77;
|
||||
--failure: #883d3d;
|
||||
--running: #4786ab;
|
||||
--warning: #de9a34;
|
||||
--link-fg: #2f4579;
|
||||
--alt-row-bg: #fafafa;
|
||||
--border-grey: #d0d0d0;
|
||||
}
|
||||
|
||||
/* basic resets */
|
||||
html { box-sizing: border-box; }
|
||||
*, *:before, *:after { box-sizing: inherit; }
|
||||
body, h1, h2, h3, h4, h5, h6, p, ol, ul {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
font-weight: normal;
|
||||
}
|
||||
ol, ul { list-style: none; }
|
||||
body, html { height: 100%; }
|
||||
body {
|
||||
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
|
||||
font-size: 16px;
|
||||
color: var(--main-fg);
|
||||
}
|
||||
|
||||
/* main header bar */
|
||||
#nav-top { background-color: var(--nav-bg); }
|
||||
#nav-top-links { background-color: var(--nav-bg-darker); }
|
||||
#nav-top a { color: var(--nav-fg); }
|
||||
#nav-top a:hover { color: white; text-decoration: none; }
|
||||
|
||||
.version {
|
||||
align-self: center;
|
||||
font-size: x-small;
|
||||
color: rgba(255,255,255,0.3);
|
||||
}
|
||||
|
||||
/* navbar svg icons (enable notifications) */
|
||||
.nav-icon { display: inherit; }
|
||||
.nav-icon svg { fill: var(--nav-fg); stroke: #000; }
|
||||
.nav-icon:hover { cursor: pointer; }
|
||||
.nav-icon:hover svg { fill: var(--nav-fg-light); }
|
||||
.nav-icon.active svg { fill: var(--icon-enabled); }
|
||||
|
||||
/* anchors */
|
||||
a { color: var(--link-fg); text-decoration: none; }
|
||||
a:visited { color: var(--link-fg); }
|
||||
a:active { color: var(--link-fg); }
|
||||
a:hover { text-decoration: underline; }
|
||||
|
||||
/* charts */
|
||||
canvas {
|
||||
width: 100% !important;
|
||||
max-width: 800px;
|
||||
height: auto !important;
|
||||
}
|
||||
|
||||
#popup-connecting {
|
||||
position: fixed;
|
||||
background: white;
|
||||
border: 1px solid #ddd;
|
||||
bottom: 10px;
|
||||
right: 10px;
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
/* status icons */
|
||||
.status {
|
||||
display: inline-block;
|
||||
width: 1em;
|
||||
vertical-align: middle;
|
||||
margin-top: -2px; /* pixel-pushing */
|
||||
}
|
||||
svg.success path { fill: var(--success); }
|
||||
svg.failed path { fill: var(--failure); }
|
||||
svg.running circle { stroke: var(--running); }
|
||||
svg.queued circle { fill: var(--nav-fg); }
|
||||
svg.queued path { stroke: white; }
|
||||
|
||||
/* sort indicators */
|
||||
a.sort {
|
||||
position: relative;
|
||||
margin-left: 7px;
|
||||
}
|
||||
a.sort:before, a.sort:after {
|
||||
border: 4px solid transparent;
|
||||
content: "";
|
||||
position: absolute;
|
||||
display: block;
|
||||
height: 0;
|
||||
width: 0;
|
||||
right: 0;
|
||||
top: 50%;
|
||||
}
|
||||
a.sort:before {
|
||||
border-bottom-color: var(--border-grey);
|
||||
margin-top: -9px;
|
||||
}
|
||||
a.sort:after {
|
||||
border-top-color: var(--border-grey);
|
||||
margin-top: 1px;
|
||||
}
|
||||
a.sort.dsc:after { border-top-color: var(--main-fg); }
|
||||
a.sort.asc:before { border-bottom-color: var(--main-fg); }
|
||||
a.sort:hover { text-decoration: none; cursor:pointer; }
|
||||
a.sort:not(.asc):hover:before { border-bottom-color: var(--main-fg); }
|
||||
a.sort:not(.dsc):hover:after { border-top-color: var(--main-fg); }
|
||||
|
||||
/* job group tabs */
|
||||
a.active { color: var(--main-fg); }
|
||||
a.active:hover { text-decoration: none; }
|
||||
|
||||
/* 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; }
|
||||
|
||||
/* description list (run detail) */
|
||||
dl { display: grid; grid-template-columns: auto 1fr; }
|
||||
dt { text-align: right; font-weight: bold; min-width: 85px; }
|
||||
dt,dd { line-height: 2; }
|
||||
|
||||
/* tables */
|
||||
table { border-spacing: 0; width: 100%; }
|
||||
th { text-align: left; border-bottom: 1px solid var(--border-grey); }
|
||||
td, th { padding: 8px; }
|
||||
table.striped td { border-top: 1px solid var(--border-grey); }
|
||||
table.striped tr:nth-child(even) { background-color: var(--alt-row-bg); }
|
||||
td:first-child, th:first-child { padding-left: 15px; }
|
||||
td:last-child, th:last-child { padding-right: 15px; }
|
||||
|
||||
/* next/prev navigation buttons */
|
||||
button {
|
||||
border: 1px solid var(--border-grey);
|
||||
background-color: var(--alt-row-bg);
|
||||
padding: 6px;
|
||||
min-width: 29px;
|
||||
}
|
||||
button[disabled] { cursor: not-allowed; color: var(--border-grey); }
|
||||
button:not([disabled]) { cursor: pointer; color: var(--main-fg); }
|
||||
|
||||
/* progress bar */
|
||||
.progress {
|
||||
width: 100%;
|
||||
height: 8px;
|
||||
border: 1px solid;
|
||||
border-radius: 4px;
|
||||
overflow: hidden;
|
||||
border-color: var(--border-grey);
|
||||
background-color: var(--alt-row-bg);
|
||||
}
|
||||
.progress-bar {
|
||||
height: 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;
|
||||
transition: width .6s linear;
|
||||
}
|
||||
.progress-bar.overtime { background-color: var(--warning); }
|
||||
.progress-bar.indeterminate {
|
||||
animation: animate-stripes 1s linear infinite;
|
||||
}
|
||||
@keyframes animate-stripes {
|
||||
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;
|
||||
top: 0; right: 0; bottom: 0; left: 0;
|
||||
display: grid;
|
||||
align-content: end; justify-content: end;
|
||||
color: var(--nav-fg-light);
|
||||
font-size: 18px;
|
||||
padding: 30px;
|
||||
visibility: hidden;
|
||||
background-color: rgba(0,0,0,0.75);
|
||||
opacity: 0;
|
||||
transition: opacity 0.5s ease, visibility 0s 0.5s;
|
||||
}
|
||||
#connecting-overlay.shown {
|
||||
visibility: visible;
|
||||
opacity: 1;
|
||||
transition: opacity 0.5s ease 2s;
|
||||
}
|
||||
#connecting-overlay > div { opacity: 1; }
|
||||
|
||||
/* responsive layout */
|
||||
#page-home-main {
|
||||
display: grid;
|
||||
grid-template-columns: auto 1fr;
|
||||
}
|
||||
@media (max-width: 865px) {
|
||||
#page-home-main {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
.vp-sm-hide { display: none; }
|
||||
}
|
||||
#page-home-stats {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr 1fr;
|
||||
padding: 15px;
|
||||
gap: 15px;
|
||||
max-width: 1600px;
|
||||
margin: auto;
|
||||
text-align: center;
|
||||
}
|
||||
@media (max-width: 650px) {
|
||||
#page-home-stats {
|
||||
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;
|
||||
}
|
||||
@media (max-width: 965px) {
|
||||
#page-job-main {
|
||||
grid-template: auto auto 1fr / 1fr;
|
||||
}
|
||||
}
|
||||
#page-run-detail {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(400px, auto) 1fr;
|
||||
gap: 5px;
|
||||
}
|
||||
@media (max-width: 780px) {
|
||||
#page-run-detail {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
41
src/rpc.cpp
41
src/rpc.cpp
@@ -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,11 +83,11 @@ 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()));
|
||||
if(Run* r = run.get()) {
|
||||
return r->whenFinished().then([context,r](RunState state) mutable {
|
||||
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));
|
||||
context.getResults().setBuildNum(r->build);
|
||||
context.getResults().setBuildNum(run->build);
|
||||
});
|
||||
} else {
|
||||
context.getResults().setResult(LaminarCi::JobResult::UNKNOWN);
|
||||
@@ -92,27 +95,15 @@ public:
|
||||
}
|
||||
}
|
||||
|
||||
// Set a parameter on a running build
|
||||
kj::Promise<void> set(SetContext context) override {
|
||||
std::string jobName = context.getParams().getRun().getJob();
|
||||
uint buildNum = context.getParams().getRun().getBuildNum();
|
||||
LLOG(INFO, "RPC set", jobName, buildNum);
|
||||
|
||||
LaminarCi::MethodResult result = laminar.setParam(jobName, buildNum,
|
||||
context.getParams().getParam().getName(), context.getParams().getParam().getValue())
|
||||
? LaminarCi::MethodResult::SUCCESS
|
||||
: LaminarCi::MethodResult::FAILED;
|
||||
context.getResults().setResult(result);
|
||||
return kj::READY_NOW;
|
||||
}
|
||||
|
||||
// List jobs in queue
|
||||
kj::Promise<void> listQueued(ListQueuedContext context) override {
|
||||
const std::list<std::shared_ptr<Run>>& queue = laminar.listQueuedJobs();
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -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_
|
||||
|
||||
273
src/run.cpp
273
src/run.cpp
@@ -1,5 +1,5 @@
|
||||
///
|
||||
/// Copyright 2015-2018 Oliver Giles
|
||||
/// Copyright 2015-2020 Oliver Giles
|
||||
///
|
||||
/// This file is part of Laminar
|
||||
///
|
||||
@@ -17,14 +17,20 @@
|
||||
/// along with Laminar. If not, see <http://www.gnu.org/licenses/>
|
||||
///
|
||||
#include "run.h"
|
||||
#include "node.h"
|
||||
#include "context.h"
|
||||
#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,15 +50,17 @@ 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)),
|
||||
started(kj::newPromiseAndFulfiller<void>()),
|
||||
finished(kj::newPromiseAndFulfiller<RunState>())
|
||||
startedFork(started.promise.fork()),
|
||||
finished(kj::newPromiseAndFulfiller<RunState>()),
|
||||
finishedFork(finished.promise.fork())
|
||||
{
|
||||
for(auto it = params.begin(); it != params.end();) {
|
||||
if(it->first[0] == '=') {
|
||||
@@ -75,119 +83,53 @@ Run::~Run() {
|
||||
LLOG(INFO, "Run destroyed");
|
||||
}
|
||||
|
||||
bool Run::configure(uint buildNum, std::shared_ptr<Node> nd, const kj::Directory& fsHome)
|
||||
static void setEnvFromFile(const kj::Path& rootPath, kj::Path file) {
|
||||
StringMap vars = parseConfFile((rootPath/file).toString(true).cStr());
|
||||
for(auto& it : vars) {
|
||||
setenv(it.first.c_str(), it.second.c_str(), true);
|
||||
}
|
||||
}
|
||||
|
||||
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"};
|
||||
|
||||
// create the run directory
|
||||
kj::Path rd{"run",name,std::to_string(buildNum)};
|
||||
bool createWorkdir = true;
|
||||
KJ_IF_MAYBE(ls, fsHome.tryLstat(rd)) {
|
||||
LASSERT(ls->type == kj::FsNode::Type::DIRECTORY);
|
||||
LLOG(WARNING, "Working directory already exists, removing", rd.toString());
|
||||
if(fsHome.tryRemove(rd) == false) {
|
||||
LLOG(WARNING, "Failed to remove working directory");
|
||||
createWorkdir = false;
|
||||
}
|
||||
}
|
||||
if(createWorkdir && fsHome.tryOpenSubdir(rd, kj::WriteMode::CREATE|kj::WriteMode::CREATE_PARENT) == nullptr) {
|
||||
LLOG(ERROR, "Could not create working directory", rd.toString());
|
||||
return false;
|
||||
}
|
||||
|
||||
// create an archive directory
|
||||
kj::Path archive = kj::Path{"archive",name,std::to_string(buildNum)};
|
||||
if(fsHome.exists(archive)) {
|
||||
LLOG(WARNING, "Archive directory already exists", archive.toString());
|
||||
} else if(fsHome.tryOpenSubdir(archive, kj::WriteMode::CREATE|kj::WriteMode::CREATE_PARENT) == nullptr) {
|
||||
LLOG(ERROR, "Could not create archive directory", archive.toString());
|
||||
return false;
|
||||
}
|
||||
|
||||
// create a workspace for this job if it doesn't exist
|
||||
kj::Path ws{"run",name,"workspace"};
|
||||
if(!fsHome.exists(ws)) {
|
||||
fsHome.openSubdir(ws, kj::WriteMode::CREATE|kj::WriteMode::CREATE_PARENT);
|
||||
// prepend the workspace init script
|
||||
if(fsHome.exists(cfgDir/"jobs"/(name+".init")))
|
||||
addScript(cfgDir/"jobs"/(name+".init"), kj::mv(ws));
|
||||
}
|
||||
|
||||
// add scripts
|
||||
// global before-run script
|
||||
if(fsHome.exists(cfgDir/"before"))
|
||||
addScript(cfgDir/"before", rd.clone());
|
||||
// per-node before-run script
|
||||
if(fsHome.exists(cfgDir/"nodes"/(nd->name+".before")))
|
||||
addScript(cfgDir/"nodes"/(nd->name+".before"), rd.clone());
|
||||
// job before-run script
|
||||
if(fsHome.exists(cfgDir/"jobs"/(name+".before")))
|
||||
addScript(cfgDir/"jobs"/(name+".before"), rd.clone());
|
||||
// main run script. must exist.
|
||||
addScript(cfgDir/"jobs"/(name+".run"), rd.clone());
|
||||
// job after-run script
|
||||
if(fsHome.exists(cfgDir/"jobs"/(name+".after")))
|
||||
addScript(cfgDir/"jobs"/(name+".after"), rd.clone(), true);
|
||||
// per-node after-run script
|
||||
if(fsHome.exists(cfgDir/"nodes"/(nd->name+".after")))
|
||||
addScript(cfgDir/"nodes"/(nd->name+".after"), rd.clone(), true);
|
||||
// global after-run script
|
||||
if(fsHome.exists(cfgDir/"after"))
|
||||
addScript(cfgDir/"after", rd.clone(), true);
|
||||
|
||||
// add environment files
|
||||
if(fsHome.exists(cfgDir/"env"))
|
||||
addEnv(cfgDir/"env");
|
||||
if(fsHome.exists(cfgDir/"nodes"/(nd->name+".env")))
|
||||
addEnv(cfgDir/"nodes"/(nd->name+".env"));
|
||||
if(fsHome.exists(cfgDir/"jobs"/(name+".env")))
|
||||
addEnv(cfgDir/"jobs"/(name+".env"));
|
||||
|
||||
// add job timeout if specified
|
||||
if(fsHome.exists(cfgDir/"jobs"/(name+".conf"))) {
|
||||
timeout = parseConfFile((rootPath/cfgDir/"jobs"/(name+".conf")).toString(true).cStr()).get<int>("TIMEOUT", 0);
|
||||
}
|
||||
|
||||
// All good, we've "started"
|
||||
startedAt = time(nullptr);
|
||||
build = buildNum;
|
||||
node = nd;
|
||||
int plog[2];
|
||||
LSYSCALL(pipe(plog));
|
||||
|
||||
// notifies the rpc client if the start command was used
|
||||
started.fulfiller->fulfill();
|
||||
// Fork a process leader to run all the steps of the job. This gives us a nice
|
||||
// process tree output (job name and number as the process name) and helps
|
||||
// contain any wayward descendent processes.
|
||||
pid_t leader;
|
||||
LSYSCALL(leader = fork());
|
||||
|
||||
return true;
|
||||
}
|
||||
if(leader == 0) {
|
||||
// All output from this process will be captured in the plog pipe
|
||||
close(plog[0]);
|
||||
dup2(plog[1], STDOUT_FILENO);
|
||||
dup2(plog[1], STDERR_FILENO);
|
||||
close(plog[1]);
|
||||
|
||||
std::string Run::reason() const {
|
||||
return reasonMsg;
|
||||
}
|
||||
// All initial/fixed env vars can be set here. Dynamic ones, including
|
||||
// "RESULT" and any set by `laminarc set` have to be handled in the subprocess.
|
||||
|
||||
bool Run::step() {
|
||||
if(!scripts.size())
|
||||
return true;
|
||||
// add environment files
|
||||
if(fsHome.exists(cfgDir/"env"))
|
||||
setEnvFromFile(rootPath, cfgDir/"env");
|
||||
if(fsHome.exists(cfgDir/"contexts"/(ctx->name+".env")))
|
||||
setEnvFromFile(rootPath, cfgDir/"contexts"/(ctx->name+".env"));
|
||||
if(fsHome.exists(cfgDir/"jobs"/(name+".env")))
|
||||
setEnvFromFile(rootPath, cfgDir/"jobs"/(name+".env"));
|
||||
|
||||
Script currentScript = kj::mv(scripts.front());
|
||||
scripts.pop();
|
||||
|
||||
int pfd[2];
|
||||
pipe(pfd);
|
||||
pid_t pid = fork();
|
||||
if(pid == 0) { // child
|
||||
// reset signal mask (SIGCHLD blocked in Laminar::start)
|
||||
sigset_t mask;
|
||||
sigemptyset(&mask);
|
||||
sigaddset(&mask, SIGCHLD);
|
||||
sigprocmask(SIG_UNBLOCK, &mask, nullptr);
|
||||
|
||||
// set pgid == pid for easy killing on abort
|
||||
setpgid(0, 0);
|
||||
|
||||
close(pfd[0]);
|
||||
dup2(pfd[1], 1);
|
||||
dup2(pfd[1], 2);
|
||||
close(pfd[1]);
|
||||
std::string buildNum = std::to_string(build);
|
||||
// parameterized vars
|
||||
for(auto& pair : params) {
|
||||
setenv(pair.first.c_str(), pair.second.c_str(), false);
|
||||
}
|
||||
|
||||
std::string PATH = (rootPath/"cfg"/"scripts").toString(true).cStr();
|
||||
if(const char* p = getenv("PATH")) {
|
||||
@@ -195,73 +137,74 @@ bool Run::step() {
|
||||
PATH.append(p);
|
||||
}
|
||||
|
||||
LSYSCALL(chdir((rootPath/currentScript.cwd).toString(true).cStr()));
|
||||
|
||||
// conf file env vars
|
||||
for(kj::Path& file : env) {
|
||||
StringMap vars = parseConfFile((rootPath/file).toString(true).cStr());
|
||||
for(auto& it : vars) {
|
||||
setenv(it.first.c_str(), it.second.c_str(), true);
|
||||
}
|
||||
}
|
||||
// parameterized vars
|
||||
for(auto& pair : params) {
|
||||
setenv(pair.first.c_str(), pair.second.c_str(), false);
|
||||
}
|
||||
std::string runNumStr = std::to_string(build);
|
||||
|
||||
setenv("PATH", PATH.c_str(), true);
|
||||
setenv("RUN", buildNum.c_str(), true);
|
||||
setenv("RUN", runNumStr.c_str(), true);
|
||||
setenv("JOB", name.c_str(), true);
|
||||
if(!node->name.empty())
|
||||
setenv("NODE", node->name.c_str(), true);
|
||||
setenv("RESULT", to_string(result).c_str(), true);
|
||||
setenv("CONTEXT", ctx->name.c_str(), true);
|
||||
setenv("LAST_RESULT", to_string(lastResult).c_str(), true);
|
||||
setenv("WORKSPACE", (rootPath/"run"/name/"workspace").toString(true).cStr(), true);
|
||||
setenv("ARCHIVE", (rootPath/"archive"/name/buildNum).toString(true).cStr(), true);
|
||||
setenv("ARCHIVE", (rootPath/"archive"/name/runNumStr).toString(true).cStr(), true);
|
||||
// RESULT set in leader process
|
||||
|
||||
fprintf(stderr, "[laminar] Executing %s\n", currentScript.path.toString().cStr());
|
||||
kj::String execPath = (rootPath/currentScript.path).toString(true);
|
||||
execl(execPath.cStr(), execPath.cStr(), NULL);
|
||||
// cannot use LLOG because stdout/stderr are captured
|
||||
fprintf(stderr, "[laminar] Failed to execute %s\n", currentScript.path.toString().cStr());
|
||||
_exit(1);
|
||||
// leader process assumes $LAMINAR_HOME as CWD
|
||||
LSYSCALL(chdir(rootPath.toString(true).cStr()));
|
||||
setenv("PWD", rootPath.toString(true).cStr(), 1);
|
||||
|
||||
// We could just fork/wait over all the steps here directly, but then we
|
||||
// can't set a nice name for the process tree. There is pthread_setname_np,
|
||||
// but it's limited to 16 characters, which most of the time probably isn't
|
||||
// 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(), 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);
|
||||
}
|
||||
|
||||
LLOG(INFO, "Forked", currentScript.path, currentScript.cwd, pid);
|
||||
close(pfd[1]);
|
||||
// All good, we've "started"
|
||||
startedAt = time(nullptr);
|
||||
context = ctx;
|
||||
|
||||
current_pid = pid;
|
||||
output_fd = pfd[0];
|
||||
output_fd = plog[0];
|
||||
close(plog[1]);
|
||||
pid = leader;
|
||||
|
||||
// notifies the rpc client if the start command was used
|
||||
started.fulfiller->fulfill();
|
||||
|
||||
return getPromise(pid).then([this](int status){
|
||||
// The leader process passes a RunState through the return value.
|
||||
// Check it didn't die abnormally, then cast to get it back.
|
||||
result = WIFEXITED(status) ? RunState(WEXITSTATUS(status)) : RunState::ABORTED;
|
||||
finished.fulfiller->fulfill(RunState(result));
|
||||
return result;
|
||||
});
|
||||
}
|
||||
|
||||
std::string Run::reason() const {
|
||||
return reasonMsg;
|
||||
}
|
||||
|
||||
bool Run::abort() {
|
||||
// if the Maybe is empty, wait() was already called on this process
|
||||
KJ_IF_MAYBE(p, pid) {
|
||||
kill(-*p, SIGTERM);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void Run::addScript(kj::Path scriptPath, kj::Path scriptWorkingDir, bool runOnAbort) {
|
||||
scripts.push({kj::mv(scriptPath), kj::mv(scriptWorkingDir), runOnAbort});
|
||||
}
|
||||
|
||||
void Run::addEnv(kj::Path path) {
|
||||
env.push_back(kj::mv(path));
|
||||
}
|
||||
|
||||
void Run::abort(bool respectRunOnAbort) {
|
||||
while(scripts.size() && (!respectRunOnAbort || !scripts.front().runOnAbort))
|
||||
scripts.pop();
|
||||
// if the Maybe is empty, wait() was already called on this process
|
||||
KJ_IF_MAYBE(p, current_pid) {
|
||||
kill(-*p, SIGTERM);
|
||||
}
|
||||
}
|
||||
|
||||
void Run::reaped(int status) {
|
||||
// once state is non-success it cannot change again
|
||||
if(result != RunState::SUCCESS)
|
||||
return;
|
||||
|
||||
if(WIFSIGNALED(status) && (WTERMSIG(status) == SIGTERM || WTERMSIG(status) == SIGKILL))
|
||||
result = RunState::ABORTED;
|
||||
else if(status != 0)
|
||||
result = RunState::FAILED;
|
||||
// otherwise preserve earlier status
|
||||
|
||||
finished.fulfiller->fulfill(RunState(result));
|
||||
}
|
||||
|
||||
53
src/run.h
53
src/run.h
@@ -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,
|
||||
@@ -43,48 +39,38 @@ enum class RunState {
|
||||
|
||||
std::string to_string(const RunState& rs);
|
||||
|
||||
class Node;
|
||||
class Context;
|
||||
|
||||
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;
|
||||
|
||||
// Call this to "start" the run with a specific number and node
|
||||
bool configure(uint buildNum, std::shared_ptr<Node> node, const kj::Directory &fsHome);
|
||||
|
||||
// executes the next script (if any), returning true if there is nothing
|
||||
// more to be done.
|
||||
bool step();
|
||||
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
|
||||
void abort(bool respectRunOnAbort);
|
||||
|
||||
// called when a process owned by this run has been reaped. The status
|
||||
// may be used to set the run's job status
|
||||
void reaped(int status);
|
||||
bool abort();
|
||||
|
||||
std::string reason() const;
|
||||
|
||||
kj::Promise<void>&& whenStarted() { return kj::mv(started.promise); }
|
||||
kj::Promise<RunState>&& whenFinished() { return kj::mv(finished.promise); }
|
||||
kj::Promise<void> whenStarted() { return startedFork.addBranch(); }
|
||||
kj::Promise<RunState> whenFinished() { return finishedFork.addBranch(); }
|
||||
|
||||
std::shared_ptr<Node> node;
|
||||
std::shared_ptr<Context> context;
|
||||
RunState result;
|
||||
RunState lastResult;
|
||||
std::string name;
|
||||
std::string parentName;
|
||||
int parentBuild = 0;
|
||||
uint build = 0;
|
||||
std::string log;
|
||||
kj::Maybe<pid_t> current_pid;
|
||||
kj::Maybe<pid_t> pid;
|
||||
int output_fd;
|
||||
std::unordered_map<std::string, std::string> params;
|
||||
int timeout = 0;
|
||||
@@ -105,13 +91,13 @@ private:
|
||||
};
|
||||
|
||||
kj::Path rootPath;
|
||||
std::queue<Script> scripts;
|
||||
std::list<kj::Path> env;
|
||||
std::string reasonMsg;
|
||||
kj::PromiseFulfillerPair<void> started;
|
||||
kj::PromiseFulfillerPair<RunState> finished;
|
||||
};
|
||||
|
||||
kj::PromiseFulfillerPair<void> started;
|
||||
kj::ForkedPromise<void> startedFork;
|
||||
kj::PromiseFulfillerPair<RunState> finished;
|
||||
kj::ForkedPromise<RunState> finishedFork;
|
||||
};
|
||||
|
||||
// All this below is a somewhat overengineered method of keeping track of
|
||||
// currently executing builds (Run objects). This would probably scale
|
||||
@@ -119,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>
|
||||
@@ -135,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
|
||||
@@ -148,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>,
|
||||
@@ -168,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_
|
||||
|
||||
@@ -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
|
||||
|
||||
13
src/server.h
13
src/server.h
@@ -1,5 +1,5 @@
|
||||
///
|
||||
/// Copyright 2015-2017 Oliver Giles
|
||||
/// Copyright 2015-2026 Oliver Giles
|
||||
///
|
||||
/// This file is part of Laminar
|
||||
///
|
||||
@@ -16,18 +16,18 @@
|
||||
/// 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>
|
||||
#include <capnp/message.h>
|
||||
#include <capnp/capability.h>
|
||||
#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 {
|
||||
@@ -71,4 +71,3 @@ private:
|
||||
kj::Maybe<kj::Promise<void>> reapWatch;
|
||||
};
|
||||
|
||||
#endif // LAMINAR_SERVER_H_
|
||||
|
||||
25
src/version.cpp
Normal file
25
src/version.cpp
Normal file
@@ -0,0 +1,25 @@
|
||||
///
|
||||
/// Copyright 2020 Oliver Giles
|
||||
///
|
||||
/// This file is part of Laminar
|
||||
///
|
||||
/// Laminar is free software: you can redistribute it and/or modify
|
||||
/// it under the terms of the GNU General Public License as published by
|
||||
/// the Free Software Foundation, either version 3 of the License, or
|
||||
/// (at your option) any later version.
|
||||
///
|
||||
/// Laminar is distributed in the hope that it will be useful,
|
||||
/// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
/// GNU General Public License for more details.
|
||||
///
|
||||
/// You should have received a copy of the GNU General Public License
|
||||
/// along with Laminar. If not, see <http://www.gnu.org/licenses/>
|
||||
///
|
||||
|
||||
#define str(x) #x
|
||||
#define xstr(x) str(x)
|
||||
|
||||
const char* laminar_version() {
|
||||
return xstr(LAMINAR_VERSION);
|
||||
}
|
||||
@@ -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) {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
///
|
||||
/// Copyright 2019 Oliver Giles
|
||||
/// Copyright 2019-2022 Oliver Giles
|
||||
///
|
||||
/// This file is part of Laminar
|
||||
///
|
||||
@@ -19,47 +19,121 @@
|
||||
#ifndef LAMINAR_FIXTURE_H_
|
||||
#define LAMINAR_FIXTURE_H_
|
||||
|
||||
#include <capnp/rpc-twoparty.h>
|
||||
#include <gtest/gtest.h>
|
||||
#include "laminar.capnp.h"
|
||||
#include "eventsource.h"
|
||||
#include "tempdir.h"
|
||||
#include "laminar.h"
|
||||
#include "log.h"
|
||||
#include "server.h"
|
||||
#include "conf.h"
|
||||
|
||||
#include <capnp/rpc-twoparty.h>
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
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/";
|
||||
server = new Server(ioContext);
|
||||
}
|
||||
~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) {
|
||||
return kj::heap<EventSource>(ioContext, bind_http.c_str(), path);
|
||||
return kj::heap<EventSource>(*ioContext, bind_http.c_str(), path);
|
||||
}
|
||||
|
||||
void defineJob(const char* name, const char* scriptContent) {
|
||||
void defineJob(const char* name, const char* scriptContent, const char* configContent = nullptr) {
|
||||
KJ_IF_MAYBE(f, tmp.fs->tryOpenFile(kj::Path{"cfg", "jobs", std::string(name) + ".run"},
|
||||
kj::WriteMode::CREATE | kj::WriteMode::CREATE_PARENT | kj::WriteMode::EXECUTABLE)) {
|
||||
(*f)->writeAll(std::string("#!/bin/sh\n") + scriptContent + "\n");
|
||||
}
|
||||
if(configContent) {
|
||||
KJ_IF_MAYBE(f, tmp.fs->tryOpenFile(kj::Path{"cfg", "jobs", std::string(name) + ".conf"}, kj::WriteMode::CREATE)) {
|
||||
(*f)->writeAll(configContent);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct RunExec {
|
||||
LaminarCi::JobResult result;
|
||||
kj::String log;
|
||||
};
|
||||
|
||||
RunExec runJob(const char* name, kj::Maybe<StringMap> params = nullptr) {
|
||||
auto req = client().runRequest();
|
||||
req.setJobName(name);
|
||||
KJ_IF_MAYBE(p, params) {
|
||||
auto params = req.initParams(p->size());
|
||||
int i = 0;
|
||||
for(auto kv : *p) {
|
||||
params[i].setName(kv.first);
|
||||
params[i].setValue(kv.second);
|
||||
i++;
|
||||
}
|
||||
}
|
||||
auto res = req.send().wait(ioContext->waitScope);
|
||||
std::string path = std::string{"/log/"} + name + "/" + std::to_string(res.getBuildNum());
|
||||
kj::HttpHeaderTable headerTable;
|
||||
kj::String log = kj::newHttpClient(ioContext->lowLevelProvider->getTimer(), headerTable,
|
||||
*ioContext->provider->getNetwork().parseAddress(bind_http.c_str()).wait(ioContext->waitScope))
|
||||
->request(kj::HttpMethod::GET, path, kj::HttpHeaders(headerTable)).response.wait(ioContext->waitScope).body
|
||||
->readAllText().wait(ioContext->waitScope);
|
||||
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();
|
||||
for(const char *p = str.cStr(), *e = p + str.size(); p < e;) {
|
||||
const char *nl = strchrnul(p, '\n');
|
||||
if(!kj::StringPtr{p}.startsWith("[laminar]")) {
|
||||
memcpy(o, p, nl - p + 1);
|
||||
o += nl - p + 1;
|
||||
}
|
||||
p = nl + 1;
|
||||
}
|
||||
*o = '\0';
|
||||
return out;
|
||||
}
|
||||
|
||||
StringMap parseFromString(kj::StringPtr content) {
|
||||
char tmp[16] = "/tmp/lt.XXXXXX";
|
||||
int fd = mkstemp(tmp);
|
||||
LSYSCALL(write(fd, content.begin(), content.size()));
|
||||
close(fd);
|
||||
StringMap map = parseConfFile(tmp);
|
||||
unlink(tmp);
|
||||
return map;
|
||||
}
|
||||
|
||||
LaminarCi::Client client() {
|
||||
if(!rpc) {
|
||||
auto stream = ioContext.provider->getNetwork().parseAddress(bind_rpc).wait(ioContext.waitScope)->connect().wait(ioContext.waitScope);
|
||||
auto stream = ioContext->provider->getNetwork().parseAddress(bind_rpc).wait(ioContext->waitScope)->connect().wait(ioContext->waitScope);
|
||||
auto net = kj::heap<capnp::TwoPartyVatNetwork>(*stream, capnp::rpc::twoparty::Side::CLIENT);
|
||||
rpc = kj::heap<capnp::RpcSystem<capnp::rpc::twoparty::VatId>>(*net, nullptr).attach(kj::mv(net), kj::mv(stream));
|
||||
}
|
||||
@@ -76,7 +150,7 @@ public:
|
||||
Settings settings;
|
||||
Server* server;
|
||||
Laminar* laminar;
|
||||
static kj::AsyncIoContext ioContext;
|
||||
static kj::AsyncIoContext* ioContext;
|
||||
};
|
||||
|
||||
#endif // LAMINAR_FIXTURE_H_
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
///
|
||||
/// Copyright 2019 Oliver Giles
|
||||
/// Copyright 2019-2022 Oliver Giles
|
||||
///
|
||||
/// This file is part of Laminar
|
||||
///
|
||||
@@ -18,13 +18,14 @@
|
||||
///
|
||||
#include <kj/async-unix.h>
|
||||
#include "laminar-fixture.h"
|
||||
#include "conf.h"
|
||||
|
||||
// TODO: consider handling this differently
|
||||
kj::AsyncIoContext LaminarFixture::ioContext = kj::setupAsyncIo();
|
||||
kj::AsyncIoContext* LaminarFixture::ioContext;
|
||||
|
||||
TEST_F(LaminarFixture, EmptyStatusMessageStructure) {
|
||||
auto es = eventSource("/");
|
||||
ioContext.waitScope.poll();
|
||||
ioContext->waitScope.poll();
|
||||
ASSERT_EQ(1, es->messages().size());
|
||||
|
||||
auto json = es->messages().front().GetObject();
|
||||
@@ -44,19 +45,13 @@ 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) {
|
||||
defineJob("foo", "true");
|
||||
auto es = eventSource("/");
|
||||
|
||||
auto req = client().runRequest();
|
||||
req.setJobName("foo");
|
||||
ASSERT_EQ(LaminarCi::JobResult::SUCCESS, req.send().wait(ioContext.waitScope).getResult());
|
||||
|
||||
// wait for job completed
|
||||
ioContext.waitScope.poll();
|
||||
runJob("foo");
|
||||
|
||||
ASSERT_EQ(4, es->messages().size());
|
||||
|
||||
@@ -84,13 +79,8 @@ TEST_F(LaminarFixture, OnlyRelevantNotifications) {
|
||||
auto es1Run = eventSource("/jobs/job1/1");
|
||||
auto es2Run = eventSource("/jobs/job2/1");
|
||||
|
||||
auto req1 = client().runRequest();
|
||||
req1.setJobName("job1");
|
||||
ASSERT_EQ(LaminarCi::JobResult::SUCCESS, req1.send().wait(ioContext.waitScope).getResult());
|
||||
auto req2 = client().runRequest();
|
||||
req2.setJobName("job2");
|
||||
ASSERT_EQ(LaminarCi::JobResult::SUCCESS, req2.send().wait(ioContext.waitScope).getResult());
|
||||
ioContext.waitScope.poll();
|
||||
runJob("job1");
|
||||
runJob("job2");
|
||||
|
||||
EXPECT_EQ(7, esHome->messages().size());
|
||||
EXPECT_EQ(7, esJobs->messages().size());
|
||||
@@ -101,3 +91,98 @@ TEST_F(LaminarFixture, OnlyRelevantNotifications) {
|
||||
EXPECT_EQ(4, es1Run->messages().size());
|
||||
EXPECT_EQ(4, es2Run->messages().size());
|
||||
}
|
||||
|
||||
TEST_F(LaminarFixture, FailedStatus) {
|
||||
defineJob("job1", "false");
|
||||
auto run = runJob("job1");
|
||||
ASSERT_EQ(LaminarCi::JobResult::FAILED, run.result);
|
||||
}
|
||||
|
||||
TEST_F(LaminarFixture, WorkingDirectory) {
|
||||
defineJob("job1", "pwd");
|
||||
auto run = runJob("job1");
|
||||
ASSERT_EQ(LaminarCi::JobResult::SUCCESS, run.result);
|
||||
std::string cwd{tmp.path.append(kj::Path{"run","job1","1"}).toString(true).cStr()};
|
||||
EXPECT_EQ(cwd + "\n", stripLaminarLogLines(run.log).cStr());
|
||||
}
|
||||
|
||||
|
||||
TEST_F(LaminarFixture, Environment) {
|
||||
defineJob("foo", "env");
|
||||
auto run = runJob("foo");
|
||||
|
||||
std::string ws{tmp.path.append(kj::Path{"run","foo","workspace"}).toString(true).cStr()};
|
||||
std::string archive{tmp.path.append(kj::Path{"archive","foo","1"}).toString(true).cStr()};
|
||||
|
||||
StringMap map = parseFromString(run.log);
|
||||
EXPECT_EQ("1", map["RUN"]);
|
||||
EXPECT_EQ("foo", map["JOB"]);
|
||||
EXPECT_EQ("success", map["RESULT"]);
|
||||
EXPECT_EQ("unknown", map["LAST_RESULT"]);
|
||||
EXPECT_EQ(ws, map["WORKSPACE"]);
|
||||
EXPECT_EQ(archive, map["ARCHIVE"]);
|
||||
}
|
||||
|
||||
TEST_F(LaminarFixture, ParamsToEnv) {
|
||||
defineJob("foo", "env");
|
||||
StringMap params;
|
||||
params["foo"] = "bar";
|
||||
auto run = runJob("foo", params);
|
||||
StringMap map = parseFromString(run.log);
|
||||
EXPECT_EQ("bar", map["foo"]);
|
||||
}
|
||||
|
||||
TEST_F(LaminarFixture, Abort) {
|
||||
defineJob("job1", "sleep inf");
|
||||
auto req = client().runRequest();
|
||||
req.setJobName("job1");
|
||||
auto res = req.send();
|
||||
// There isn't a nice way of knowing when the leader process is ready to
|
||||
// handle SIGTERM. Just wait until it prints something to the log
|
||||
ioContext->waitScope.poll();
|
||||
kj::HttpHeaderTable headerTable;
|
||||
char _;
|
||||
kj::newHttpClient(ioContext->lowLevelProvider->getTimer(), headerTable,
|
||||
*ioContext->provider->getNetwork().parseAddress(bind_http.c_str()).wait(ioContext->waitScope))
|
||||
->request(kj::HttpMethod::GET, "/log/job1/1", kj::HttpHeaders(headerTable)).response.wait(ioContext->waitScope).body
|
||||
->tryRead(&_, 1, 1).wait(ioContext->waitScope);
|
||||
// now it should be ready to abort
|
||||
ASSERT_TRUE(laminar->abort("job1", 1));
|
||||
EXPECT_EQ(LaminarCi::JobResult::ABORTED, res.wait(ioContext->waitScope).getResult());
|
||||
}
|
||||
|
||||
TEST_F(LaminarFixture, JobDescription) {
|
||||
defineJob("foo", "true", "DESCRIPTION=bar");
|
||||
auto es = eventSource("/jobs/foo");
|
||||
ioContext->waitScope.poll();
|
||||
ASSERT_EQ(1, es->messages().size());
|
||||
auto json = es->messages().front().GetObject();
|
||||
ASSERT_TRUE(json.HasMember("data"));
|
||||
auto data = json["data"].GetObject();
|
||||
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());
|
||||
}
|
||||
|
||||
@@ -18,10 +18,22 @@
|
||||
///
|
||||
#include <kj/async-unix.h>
|
||||
#include <gtest/gtest.h>
|
||||
#include <kj/debug.h>
|
||||
|
||||
// gtest main supplied in order to call captureChildExit
|
||||
#include "laminar-fixture.h"
|
||||
#include "leader.h"
|
||||
|
||||
// gtest main supplied in order to call captureChildExit and handle process leader
|
||||
int main(int argc, char **argv) {
|
||||
if(argv[0][0] == '{')
|
||||
return leader_main();
|
||||
|
||||
// TODO: consider handling this differently
|
||||
auto ioContext = kj::setupAsyncIo();
|
||||
LaminarFixture::ioContext = &ioContext;
|
||||
|
||||
kj::UnixEventPort::captureChildExit();
|
||||
//kj::_::Debug::setLogLevel(kj::_::Debug::Severity::INFO);
|
||||
|
||||
::testing::InitGoogleTest(&argc, argv);
|
||||
return RUN_ALL_TESTS();
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
///
|
||||
/// Copyright 2018 Oliver Giles
|
||||
/// Copyright 2018-2022 Oliver Giles
|
||||
///
|
||||
/// This file is part of Laminar
|
||||
///
|
||||
@@ -19,6 +19,8 @@
|
||||
#ifndef LAMINAR_TEMPDIR_H_
|
||||
#define LAMINAR_TEMPDIR_H_
|
||||
|
||||
#include "log.h"
|
||||
|
||||
#include <kj/filesystem.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
@@ -26,18 +28,31 @@ 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:
|
||||
static kj::Path mkdtemp() {
|
||||
char dir[] = "/tmp/laminar-test-XXXXXX";
|
||||
::mkdtemp(dir);
|
||||
LASSERT(::mkdtemp(dir) != nullptr, "mkdtemp failed");
|
||||
return kj::Path::parse(&dir[1]);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
///
|
||||
/// Copyright 2018 Oliver Giles
|
||||
/// Copyright 2018-2020 Oliver Giles
|
||||
///
|
||||
/// This file is part of Laminar
|
||||
///
|
||||
@@ -16,8 +16,9 @@
|
||||
/// You should have received a copy of the GNU General Public License
|
||||
/// along with Laminar. If not, see <http://www.gnu.org/licenses/>
|
||||
///
|
||||
#include <gtest/gtest.h>
|
||||
#include "conf.h"
|
||||
#include "log.h"
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
class ConfTest : public ::testing::Test {
|
||||
protected:
|
||||
@@ -30,7 +31,7 @@ protected:
|
||||
}
|
||||
void parseConf(std::string conf) {
|
||||
lseek(fd, SEEK_SET, 0);
|
||||
write(fd, conf.data(), conf.size());
|
||||
LSYSCALL(write(fd, conf.data(), conf.size()));
|
||||
cfg = parseConfFile(tmpFile);
|
||||
}
|
||||
StringMap cfg;
|
||||
|
||||
@@ -1,136 +0,0 @@
|
||||
///
|
||||
/// Copyright 2018 Oliver Giles
|
||||
///
|
||||
/// This file is part of Laminar
|
||||
///
|
||||
/// Laminar is free software: you can redistribute it and/or modify
|
||||
/// it under the terms of the GNU General Public License as published by
|
||||
/// the Free Software Foundation, either version 3 of the License, or
|
||||
/// (at your option) any later version.
|
||||
///
|
||||
/// Laminar is distributed in the hope that it will be useful,
|
||||
/// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
/// GNU General Public License for more details.
|
||||
///
|
||||
/// You should have received a copy of the GNU General Public License
|
||||
/// along with Laminar. If not, see <http://www.gnu.org/licenses/>
|
||||
///
|
||||
#include <gtest/gtest.h>
|
||||
#include "run.h"
|
||||
#include "log.h"
|
||||
#include "node.h"
|
||||
#include "conf.h"
|
||||
#include "tempdir.h"
|
||||
|
||||
class RunTest : public testing::Test {
|
||||
protected:
|
||||
RunTest() :
|
||||
testing::Test(),
|
||||
node(std::make_shared<Node>()),
|
||||
tmp(),
|
||||
run("foo", ParamMap{}, tmp.path.clone())
|
||||
{
|
||||
}
|
||||
|
||||
~RunTest() noexcept {}
|
||||
|
||||
void wait() {
|
||||
int state = -1;
|
||||
waitpid(run.current_pid.orDefault(0), &state, 0);
|
||||
run.reaped(state);
|
||||
}
|
||||
|
||||
void runAll() {
|
||||
while(!run.step())
|
||||
wait();
|
||||
}
|
||||
|
||||
std::string readAllOutput() {
|
||||
std::string res;
|
||||
char tmp[64];
|
||||
for(ssize_t n = read(run.output_fd, tmp, 64); n > 0; n = read(run.output_fd, tmp, 64))
|
||||
res += std::string(tmp, n);
|
||||
// strip the first "[laminar] executing.. line
|
||||
return strchr(res.c_str(), '\n') + 1;
|
||||
}
|
||||
StringMap parseFromString(std::string content) {
|
||||
char tmp[16] = "/tmp/lt.XXXXXX";
|
||||
int fd = mkstemp(tmp);
|
||||
write(fd, content.data(), content.size());
|
||||
close(fd);
|
||||
StringMap map = parseConfFile(tmp);
|
||||
unlink(tmp);
|
||||
return map;
|
||||
}
|
||||
|
||||
std::shared_ptr<Node> node;
|
||||
TempDir tmp;
|
||||
class Run run;
|
||||
|
||||
void setRunLink(const char * path) {
|
||||
KJ_IF_MAYBE(f, tmp.fs->tryOpenFile(kj::Path{"cfg", "jobs", run.name + ".run"},
|
||||
kj::WriteMode::CREATE | kj::WriteMode::CREATE_PARENT | kj::WriteMode::EXECUTABLE)) {
|
||||
(f->get())->writeAll(std::string("#!/bin/sh\nexec ") + path + "\n");
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
TEST_F(RunTest, WorkingDirectory) {
|
||||
setRunLink("pwd");
|
||||
run.configure(1, node, *tmp.fs);
|
||||
runAll();
|
||||
std::string cwd{tmp.path.append(kj::Path{"run","foo","1"}).toString(true).cStr()};
|
||||
EXPECT_EQ(cwd + "\n", readAllOutput());
|
||||
}
|
||||
|
||||
TEST_F(RunTest, SuccessStatus) {
|
||||
setRunLink("true");
|
||||
run.configure(1, node, *tmp.fs);
|
||||
runAll();
|
||||
EXPECT_EQ(RunState::SUCCESS, run.result);
|
||||
}
|
||||
|
||||
TEST_F(RunTest, FailedStatus) {
|
||||
setRunLink("false");
|
||||
run.configure(1, node, *tmp.fs);
|
||||
runAll();
|
||||
EXPECT_EQ(RunState::FAILED, run.result);
|
||||
}
|
||||
|
||||
TEST_F(RunTest, Environment) {
|
||||
setRunLink("env");
|
||||
run.configure(1234, node, *tmp.fs);
|
||||
runAll();
|
||||
|
||||
std::string ws{tmp.path.append(kj::Path{"run","foo","workspace"}).toString(true).cStr()};
|
||||
std::string archive{tmp.path.append(kj::Path{"archive","foo","1234"}).toString(true).cStr()};
|
||||
|
||||
StringMap map = parseFromString(readAllOutput());
|
||||
EXPECT_EQ("1234", map["RUN"]);
|
||||
EXPECT_EQ("foo", map["JOB"]);
|
||||
EXPECT_EQ("success", map["RESULT"]);
|
||||
EXPECT_EQ("unknown", map["LAST_RESULT"]);
|
||||
EXPECT_EQ(ws, map["WORKSPACE"]);
|
||||
EXPECT_EQ(archive, map["ARCHIVE"]);
|
||||
}
|
||||
|
||||
TEST_F(RunTest, ParamsToEnv) {
|
||||
setRunLink("env");
|
||||
run.params["foo"] = "bar";
|
||||
run.configure(1, node, *tmp.fs);
|
||||
runAll();
|
||||
StringMap map = parseFromString(readAllOutput());
|
||||
EXPECT_EQ("bar", map["foo"]);
|
||||
}
|
||||
|
||||
TEST_F(RunTest, Abort) {
|
||||
setRunLink("yes");
|
||||
run.configure(1, node, *tmp.fs);
|
||||
run.step();
|
||||
usleep(200); // TODO fix
|
||||
run.abort(false);
|
||||
wait();
|
||||
EXPECT_EQ(RunState::ABORTED, run.result);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user