Auto-merge for PR #592 via VersionBot

Remove the last few parts of Go
This commit is contained in:
resin-io-versionbot[bot] 2018-03-22 16:35:01 +00:00 committed by GitHub
commit ebbe90fd73
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
169 changed files with 118 additions and 23283 deletions

View File

@ -4,6 +4,10 @@ All notable changes to this project will be documented in this file
automatically by Versionist. DO NOT EDIT THIS FILE MANUALLY!
This project adheres to [Semantic Versioning](http://semver.org/).
## v7.1.20 - 2018-03-22
* Replace the gosuper component with a node module that handles communication with systemd, and stop using an init system in the supervisor container #592 [Pablo Carranza Velez]
## v7.1.19 - 2018-03-22
* Remove any leftover knex migrations locks before running migrations #599 [Pablo Carranza Velez]

View File

@ -1,63 +1,4 @@
ARG ARCH=amd64
# Build golang supervisor
FROM debian:jessie-20170723 as gosuper
RUN apt-get update \
&& apt-get install -y \
build-essential \
curl \
rsync \
&& rm -rf /var/lib/apt/lists/
ENV GOLANG_VERSION 1.8.3
ENV GOLANG_DOWNLOAD_URL https://golang.org/dl/go$GOLANG_VERSION.linux-amd64.tar.gz
ENV GOLANG_DOWNLOAD_SHA256 1862f4c3d3907e59b04a757cfda0ea7aa9ef39274af99a784f5be843c80c6772
COPY gosuper/go-${GOLANG_VERSION}-patches /go-${GOLANG_VERSION}-patches
RUN mkdir /usr/src/go \
&& cd /usr/src/go \
&& curl -L -o go.tar.gz $GOLANG_DOWNLOAD_URL \
&& echo "${GOLANG_DOWNLOAD_SHA256} go.tar.gz" | sha256sum -c - \
&& tar xzf go.tar.gz -C /usr/local \
&& cd /usr/src \
&& rm -rf go \
&& export GOROOT_BOOTSTRAP=/usr/local/go-bootstrap \
&& cp -r /usr/local/go /usr/local/go-bootstrap \
&& cd /usr/local/go/src \
&& patch -p2 -i /go-${GOLANG_VERSION}-patches/0001-dont-fail-when-no-mmx.patch \
&& patch -p2 -i /go-${GOLANG_VERSION}-patches/0002-implement-atomic-quadword-ops-with-FILD-FISTP.patch \
&& ./make.bash \
&& rm -rf /usr/local/go-bootstrap
ENV UPX_VERSION 3.94
# UPX doesn't provide fingerprints so I checked this one manually
ENV UPX_SHA256 e1fc0d55c88865ef758c7e4fabbc439e4b5693b9328d219e0b9b3604186abe20
RUN mkdir /usr/src/upx \
&& cd /usr/src/upx \
&& curl -L -o upx.tar.xz https://github.com/upx/upx/releases/download/v$UPX_VERSION/upx-$UPX_VERSION-amd64_linux.tar.xz \
&& echo "${UPX_SHA256} upx.tar.xz" | sha256sum -c - \
&& tar xf upx.tar.xz --strip-components=1 \
&& cp ./upx /usr/bin/ \
&& cd /usr/src \
&& rm -rf upx
ENV GOPATH /go
ENV PATH $GOPATH/bin:/usr/local/go/bin:$PATH
COPY ./gosuper /go/src/resin-supervisor/gosuper
WORKDIR /go/src/resin-supervisor/gosuper
ENV GOOS linux
ENV GO386=387
ARG ARCH
RUN bash ./build.sh
RUN rsync -a --delete /go/bin/gosuper /build/
##############################################################################
# The node version here should match the version of the runtime image which is
# specified in the base-image subdirectory in the project
@ -146,12 +87,7 @@ RUN find . -path '*/coverage/*' -o -path '*/test/*' -o -path '*/.nyc_output/*' \
&& find . -type f -path '*/node_modules/knex/build*' -delete \
&& rm -rf node_modules/sqlite3/node.dtps
# Create /var/run/resin for the gosuper to place its socket in
RUN mkdir -p rootfs-overlay/var/run/resin
COPY entry.sh run.sh package.json rootfs-overlay/usr/src/app/
COPY inittab rootfs-overlay/etc/inittab
COPY entry.sh package.json rootfs-overlay/usr/src/app/
RUN rsync -a --delete node_modules rootfs-overlay /build
@ -171,7 +107,6 @@ WORKDIR /usr/src/app
COPY --from=node-build /usr/src/app/dist ./dist
COPY --from=node-deps /build/node_modules ./node_modules
COPY --from=gosuper /build/gosuper ./gosuper
COPY --from=node-deps /build/rootfs-overlay/ /
VOLUME /data
@ -186,3 +121,5 @@ ENV CONFIG_MOUNT_POINT=/boot/config.json \
HEALTHCHECK --interval=5m --start-period=1m --timeout=30s --retries=3 \
CMD wget -qO- http://127.0.0.1:${LISTEN_PORT:-48484}/v1/healthy || exit 1
CMD [ "./entry.sh" ]

View File

@ -6,7 +6,6 @@
# Build targets (require Docker 17.05 or greater):
# * supervisor (default) - builds a resin-supervisor image
# * deploy - pushes a resin-supervisor image to the registry, retrying up to 3 times
# * gosuper - builds the "gosuper" component (a golang image with the Go supervisor component at /go/bin/gosuper and /build/gosuper)
# * nodedeps, nodebuild - builds the node component, with the node_modules and src at /usr/src/app and /build (also includes a rootfs-overlay there)
# * supervisor-dind: build the development docker-in-docker supervisor that run-supervisor uses (requires a SUPERVISOR_IMAGE to be available locally)
#
@ -19,8 +18,6 @@
#
# Test/development targets:
# * run-supervisor, stop-supervisor - build and start or stop a docker-in-docker resin-supervisor (requires aufs, ability to run privileged containers, and a SUPERVISOR_IMAGE to be available locally)
# * format-gosuper, test-gosuper - build a gosuper image and run formatting or unit tests
# * test-integration - run an integration test (see gosuper/supertest). Requires a docker-in-docker supervisor to be running
#
# Variables for test/dev targets:
# * IMAGE: image to build and run (either for run-supervisor or test-gosuper/integration)
@ -193,33 +190,4 @@ nodedeps:
nodebuild:
$(MAKE) -f $(THIS_FILE) TARGET_COMPONENT=node-build IMAGE=$(IMAGE) ARCH=$(ARCH) supervisor-image
gosuper:
$(MAKE) -f $(THIS_FILE) TARGET_COMPONENT=gosuper IMAGE=$(IMAGE) ARCH=$(ARCH) supervisor-image
test-gosuper: gosuper
docker run \
--rm \
-v /var/run/dbus:/mnt/root/run/dbus \
-e DBUS_SYSTEM_BUS_ADDRESS="/mnt/root/run/dbus/system_bus_socket" \
$(IMAGE) bash -c \
'./test_formatting.sh && go test -v ./gosuper'
format-gosuper: gosuper
docker run \
--rm \
-v $(shell pwd)/gosuper:/go/src/resin-supervisor/gosuper \
$(IMAGE) \
go fmt ./...
test-integration: gosuper
docker run \
--rm \
--net=host \
-e SUPERVISOR_IP="$(shell docker inspect --format '{{ .NetworkSettings.IPAddress }}' resin_supervisor_1)" \
--volumes-from resin_supervisor_1 \
-v /var/run/dbus:/mnt/root/run/dbus \
-e DBUS_SYSTEM_BUS_ADDRESS="/mnt/root/run/dbus/system_bus_socket" \
$(IMAGE) \
go test -v ./supertest
.PHONY: supervisor deploy nodedeps nodebuild gosuper supervisor-dind run-supervisor
.PHONY: supervisor deploy nodedeps nodebuild supervisor-dind run-supervisor

View File

@ -18,7 +18,6 @@
#
# It pulls intermediate images for caching, if available:
# resin/$ARCH-supervisor-node:$TAG
# resin/$ARCH-supervisor-go:$TAG
#
# In all of these cases it will use "master" if $TAG is not found.
#
@ -49,15 +48,12 @@ TARGET_IMAGE=resin/$ARCH-supervisor:$TAG
# Intermediate images and cache
NODE_IMAGE=resin/$ARCH-supervisor-node:$TAG
NODE_BUILD_IMAGE=resin/$ARCH-supervisor-node:$TAG-build
GO_IMAGE=resin/$ARCH-supervisor-go:$TAG
TARGET_CACHE=$TARGET_IMAGE
GO_CACHE=$GO_IMAGE
NODE_CACHE=$NODE_IMAGE
NODE_BUILD_CACHE=$NODE_BUILD_IMAGE
TARGET_CACHE_MASTER=resin/$ARCH-supervisor:master
GO_CACHE_MASTER=resin/$ARCH-supervisor-go:master
NODE_CACHE_MASTER=resin/$ARCH-supervisor-node:master
NODE_BUILD_CACHE_MASTER=resin/$ARCH-supervisor-node:master-build
@ -73,29 +69,17 @@ function tryPullForCache() {
# Only if the pull succeeds we add a --cache-from option
tryPullForCache $TARGET_CACHE
tryPullForCache $TARGET_CACHE_MASTER
tryPullForCache $GO_CACHE
tryPullForCache $GO_CACHE_MASTER
tryPullForCache $NODE_CACHE
tryPullForCache $NODE_CACHE_MASTER
tryPullForCache $NODE_BUILD_CACHE
tryPullForCache $NODE_BUILD_CACHE_MASTER
if [ "$ENABLE_TESTS" = "true" ]; then
make ARCH=$ARCH IMAGE=$GO_IMAGE test-gosuper
fi
export DOCKER_BUILD_OPTIONS=${CACHE_FROM}
export ARCH
export PUBNUB_PUBLISH_KEY
export PUBNUB_SUBSCRIBE_KEY
export MIXPANEL_TOKEN
make IMAGE=$GO_IMAGE gosuper
if [ "$PUSH_IMAGES" = "true" ]; then
make IMAGE=$GO_IMAGE deploy || true
fi
export DOCKER_BUILD_OPTIONS="${DOCKER_BUILD_OPTIONS} --cache-from ${GO_IMAGE}"
make IMAGE=$NODE_BUILD_IMAGE nodebuild
if [ "$PUSH_IMAGES" = "true" ]; then
make IMAGE=$NODE_BUILD_IMAGE deploy || true
@ -123,12 +107,10 @@ fi
if [ "$CLEANUP" = "true" ]; then
tryRemove $TARGET_IMAGE
tryRemove $GO_IMAGE
tryRemove $NODE_IMAGE
tryRemove $NODE_BUILD_IMAGE
tryRemove $TARGET_CACHE
tryRemove $GO_CACHE
tryRemove $NODE_BUILD_CACHE
tryRemove $NODE_CACHE
fi

View File

@ -18,7 +18,7 @@ Alternatively, the Resin API (api.resin.io) has a proxy endpoint at `POST /super
The API is versioned (currently at v1), except for `/ping`.
You might notice that the formats of some responses differ. This is because they were implemented later, and in Go instead of node.js.
You might notice that the formats of some responses differ. This is because they were implemented later, and in Go instead of node.js - even if the Go pieces were later removed, so we kept the response format for backwards compatibility.
Here's the full list of endpoints implemented so far. In all examples, replace everything between `< >` for the corresponding values.
@ -119,7 +119,6 @@ When successful, responds with 202 accepted and a JSON object:
"Error": ""
}
```
(This is implemented in Go)
#### Request body
Can contain a `force` property, which if set to `true` will cause the update lock to be overridden.
@ -158,7 +157,6 @@ When successful, responds with 202 accepted and a JSON object:
"Error": ""
}
```
(This is implemented in Go)
#### Request body
Can contain a `force` property, which if set to `true` will cause the update lock to be overridden.
@ -197,8 +195,6 @@ When successful, responds with 200 and a JSON object:
}
```
(This is implemented in Go)
#### Request body
Has to be a JSON object with an `appId` property, corresponding to the ID of the application the device is running.

View File

@ -2,16 +2,9 @@
set -o errexit
[ -d /dev/net ] ||
mkdir -p /dev/net
[ -c /dev/net/tun ] ||
mknod /dev/net/tun c 10 200
[ -d /mnt/root/tmp/resin-supervisor ] ||
mkdir -p /mnt/root/tmp/resin-supervisor
mkdir -p /var/run/resin
mount -t tmpfs -o size=1m tmpfs /var/run/resin
# If DOCKER_ROOT isn't set then default it
if [ -z "${DOCKER_ROOT}" ]; then
DOCKER_ROOT=/mnt/root/var/lib/rce
@ -23,3 +16,11 @@ DOCKER_LIB_PATH=${DOCKER_ROOT#/mnt/root}
if [ ! -d "${DOCKER_LIB_PATH}" ]; then
ln -s "${DOCKER_ROOT}" "${DOCKER_LIB_PATH}"
fi
if [ -z "$DOCKER_SOCKET" ]; then
export DOCKER_SOCKET=/run/docker.sock
fi
export DBUS_SYSTEM_BUS_ADDRESS="unix:path=/mnt/root/run/dbus/system_bus_socket"
exec node /usr/src/app/dist/app.js

View File

@ -1,38 +0,0 @@
#!/bin/bash
set -o errexit
./test_formatting.sh
go test -v ./gosuper
case "$ARCH" in
'amd64')
export GOARCH=amd64
;;
'i386')
export GOARCH=386
;;
'i386-nlp')
export GOARCH=386
;;
'rpi')
export GOARCH=arm
export GOARM=6
;;
'armv7hf')
export GOARCH=arm
export GOARM=7
;;
'armel')
export GOARCH=arm
export GOARM=5
;;
'aarch64')
export GOARCH=arm64
;;
esac
go install -a -v ./gosuper \
&& cd /go/bin \
&& find -type f -name gosuper -exec mv {} /go/bin/gosuper \; \
&& upx --best /go/bin/gosuper

15
gosuper/glide.lock generated
View File

@ -1,15 +0,0 @@
hash: cb4cc5df2d5f540e768cb8d1033c61d5f082edce93a756840e1bc23b08ca3770
updated: 2017-06-08T15:34:29.722957717-07:00
imports:
- name: github.com/coreos/go-systemd
version: 48702e0da86bd25e76cfef347e2adeb434a0d0a6
subpackages:
- dbus
- login1
- name: github.com/godbus/dbus
version: 012f3c27dcbdbe5d1285634e604e4ef869d83f7d
- name: github.com/gorilla/context
version: 08b5f424b9271eedf6f9f0ce86cb9396ed337a42
- name: github.com/gorilla/mux
version: bcd8bc72b08df0f70df986b97f95590779502d31
testImports: []

View File

@ -1,9 +0,0 @@
package: resin-supervisor/gosuper
import:
- package: github.com/coreos/go-systemd
version: ^14.0.0
subpackages:
- dbus
- login1
- package: github.com/gorilla/mux
version: ^1.4.0

View File

@ -1,78 +0,0 @@
commit 6a0e489a556d753161ce75d85a3114654c031853
Author: Pablo Carranza Velez <pablo@resin.io>
Date: Fri Jun 9 14:57:23 2017 -0700
Do not fail when there's no MMX support
Adapted from https://github.com/resin-io/resin-supervisor/blob/c7a7ba93fb46775006f0739ced41fc0a2059b426/gosuper/go-1.6.3-patches/0001-Revert-runtime-check-and-fail-early-with-a-message-i.patch
Original author: Petros Angelatos <petrosagg@gmail.com>
Signed-off-by: Pablo Carranza Velez <pablo@resin.io>
diff --git a/src/runtime/asm_386.s b/src/runtime/asm_386.s
index 3d0b74c..f4e51ce 100644
--- a/src/runtime/asm_386.s
+++ b/src/runtime/asm_386.s
@@ -26,32 +26,6 @@ TEXT runtime·rt0_go(SB),NOSPLIT,$0
MOVL SP, (g_stack+stack_hi)(BP)
// find out information about the processor we're on
-#ifdef GOOS_nacl // NaCl doesn't like PUSHFL/POPFL
- JMP has_cpuid
-#else
- // first see if CPUID instruction is supported.
- PUSHFL
- PUSHFL
- XORL $(1<<21), 0(SP) // flip ID bit
- POPFL
- PUSHFL
- POPL AX
- XORL 0(SP), AX
- POPFL // restore EFLAGS
- TESTL $(1<<21), AX
- JNE has_cpuid
-#endif
-
-bad_proc: // show that the program requires MMX.
- MOVL $2, 0(SP)
- MOVL $bad_proc_msg<>(SB), 4(SP)
- MOVL $0x3d, 8(SP)
- CALL runtime·write(SB)
- MOVL $1, 0(SP)
- CALL runtime·exit(SB)
- INT $3
-
-has_cpuid:
MOVL $0, AX
CPUID
MOVL AX, SI
@@ -76,11 +50,6 @@ notintel:
MOVL CX, AX // Move to global variable clobbers CX when generating PIC
MOVL AX, runtime·cpuid_ecx(SB)
MOVL DX, runtime·cpuid_edx(SB)
-
- // Check for MMX support
- TESTL $(1<<23), DX // MMX
- JZ bad_proc
-
// Load EAX=7/ECX=0 cpuid flags
CMPL SI, $7
JLT nocpuinfo
@@ -170,17 +139,6 @@ ok:
INT $3
RET
-DATA bad_proc_msg<>+0x00(SB)/8, $"This pro"
-DATA bad_proc_msg<>+0x08(SB)/8, $"gram can"
-DATA bad_proc_msg<>+0x10(SB)/8, $" only be"
-DATA bad_proc_msg<>+0x18(SB)/8, $" run on "
-DATA bad_proc_msg<>+0x20(SB)/8, $"processo"
-DATA bad_proc_msg<>+0x28(SB)/8, $"rs with "
-DATA bad_proc_msg<>+0x30(SB)/8, $"MMX supp"
-DATA bad_proc_msg<>+0x38(SB)/4, $"ort."
-DATA bad_proc_msg<>+0x3c(SB)/1, $0xa
-GLOBL bad_proc_msg<>(SB), RODATA, $0x3d
-
DATA runtime·mainPC+0(SB)/4,$runtime·main(SB)
GLOBL runtime·mainPC(SB),RODATA,$4

View File

@ -1,88 +0,0 @@
commit 03def348bdd766df0c508ee8cbf6ceba00e8d78c
Author: Pablo Carranza Velez <pablo@resin.io>
Date: Fri Jun 9 15:07:55 2017 -0700
Implement atomic quadword ops with FILD/FISTP
Adapted from https://github.com/resin-io/resin-supervisor/blob/c7a7ba93fb46775006f0739ced41fc0a2059b426/gosuper/go-1.6.3-patches/0002-implement-atomic-quadword-ops-with-FILD-FISTP.patch
Original author: Petros Angelatos <petrosagg@gmail.com>
Signed-off-by: Pablo Carranza Velez <pablo@resin.io>
diff --git a/src/runtime/internal/atomic/asm_386.s b/src/runtime/internal/atomic/asm_386.s
index 882906e..d37c675 100644
--- a/src/runtime/internal/atomic/asm_386.s
+++ b/src/runtime/internal/atomic/asm_386.s
@@ -124,12 +124,10 @@ TEXT runtimeinternalatomic·Load64(SB), NOSPLIT, $0-12
JZ 2(PC)
MOVL 0, AX // crash with nil ptr deref
LEAL ret_lo+4(FP), BX
- // MOVQ (%EAX), %MM0
- BYTE $0x0f; BYTE $0x6f; BYTE $0x00
- // MOVQ %MM0, 0(%EBX)
- BYTE $0x0f; BYTE $0x7f; BYTE $0x03
- // EMMS
- BYTE $0x0F; BYTE $0x77
+ // FILDQ (%EAX)
+ BYTE $0xdf; BYTE $0x28
+ // FISTPQ (%EBX)
+ BYTE $0xdf; BYTE $0x3b
RET
// void runtimeinternalatomic·Store64(uint64 volatile* addr, uint64 v);
@@ -138,13 +136,10 @@ TEXT runtimeinternalatomic·Store64(SB), NOSPLIT, $0-12
TESTL $7, AX
JZ 2(PC)
MOVL 0, AX // crash with nil ptr deref
- // MOVQ and EMMS were introduced on the Pentium MMX.
- // MOVQ 0x8(%ESP), %MM0
- BYTE $0x0f; BYTE $0x6f; BYTE $0x44; BYTE $0x24; BYTE $0x08
- // MOVQ %MM0, (%EAX)
- BYTE $0x0f; BYTE $0x7f; BYTE $0x00
- // EMMS
- BYTE $0x0F; BYTE $0x77
+ // FILDQ 0x8(%ESP)
+ BYTE $0xdf; BYTE $0x6c; BYTE $0x24; BYTE $0x08
+ // FISTPQ (%EAX)
+ BYTE $0xdf; BYTE $0x38
// This is essentially a no-op, but it provides required memory fencing.
// It can be replaced with MFENCE, but MFENCE was introduced only on the Pentium4 (SSE2).
MOVL $0, AX
diff --git a/src/sync/atomic/asm_386.s b/src/sync/atomic/asm_386.s
index f2a13da..c7787a4 100644
--- a/src/sync/atomic/asm_386.s
+++ b/src/sync/atomic/asm_386.s
@@ -157,12 +157,10 @@ TEXT ·LoadUint64(SB),NOSPLIT,$0-12
TESTL $7, AX
JZ 2(PC)
MOVL 0, AX // crash with nil ptr deref
- // MOVQ and EMMS were introduced on the Pentium MMX.
- // MOVQ (%EAX), %MM0
- BYTE $0x0f; BYTE $0x6f; BYTE $0x00
- // MOVQ %MM0, 0x8(%ESP)
- BYTE $0x0f; BYTE $0x7f; BYTE $0x44; BYTE $0x24; BYTE $0x08
- EMMS
+ // FILDQ (%EAX)
+ BYTE $0xdf; BYTE $0x28
+ // FISTPQ 0x8(%ESP)
+ BYTE $0xdf; BYTE $0x7c; BYTE $0x24; BYTE $0x08
RET
TEXT ·LoadUintptr(SB),NOSPLIT,$0-8
@@ -188,12 +186,10 @@ TEXT ·StoreUint64(SB),NOSPLIT,$0-12
TESTL $7, AX
JZ 2(PC)
MOVL 0, AX // crash with nil ptr deref
- // MOVQ and EMMS were introduced on the Pentium MMX.
- // MOVQ 0x8(%ESP), %MM0
- BYTE $0x0f; BYTE $0x6f; BYTE $0x44; BYTE $0x24; BYTE $0x08
- // MOVQ %MM0, (%EAX)
- BYTE $0x0f; BYTE $0x7f; BYTE $0x00
- EMMS
+ // FILDQ 0x8(%ESP)
+ BYTE $0xdf; BYTE $0x6c; BYTE $0x24; BYTE $0x08
+ // FISTPQ (%EAX)
+ BYTE $0xdf; BYTE $0x38
// This is essentially a no-op, but it provides required memory fencing.
// It can be replaced with MFENCE, but MFENCE was introduced only on the Pentium4 (SSE2).
XORL AX, AX

View File

@ -1,265 +0,0 @@
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"time"
"resin-supervisor/gosuper/systemd"
)
// APIResponse The api response sent from go supervisor
type APIResponse struct {
Data interface{}
Error string
}
// VPNBody interface for post request received by VPN control end point
type VPNBody struct {
Enable bool
}
type LogToDisplayBody struct {
Enable bool
}
type RestartServiceBody struct {
Name string
}
func jsonResponse(writer http.ResponseWriter, response interface{}, status int) {
jsonBody, err := json.Marshal(response)
if err != nil {
log.Printf("Could not marshal JSON for %+v\n", response)
}
writer.Header().Set("Content-Type", "application/json")
writer.WriteHeader(status)
writer.Write(jsonBody)
}
func parseJSONBody(destination interface{}, request *http.Request) error {
decoder := json.NewDecoder(request.Body)
return decoder.Decode(&destination)
}
func responseSenders(writer http.ResponseWriter) (sendResponse func(interface{}, string, int), sendError func(error)) {
sendResponse = func(data interface{}, errorMsg string, statusCode int) {
jsonResponse(writer, APIResponse{data, errorMsg}, statusCode)
}
sendError = func(err error) {
sendResponse("Error", err.Error(), http.StatusInternalServerError)
}
return
}
func inASecond(theFunc func()) {
time.Sleep(time.Duration(time.Second))
theFunc()
}
//RebootHandler Reboots the device using Systemd
func RebootHandler(writer http.ResponseWriter, request *http.Request) {
log.Println("Rebooting")
sendResponse, sendError := responseSenders(writer)
if systemd.Logind == nil {
sendError(fmt.Errorf("Logind unavailable, cannot reboot."))
return
}
sendResponse("OK", "", http.StatusAccepted)
go inASecond(func() { systemd.Logind.Reboot(false) })
}
//ShutdownHandler Shuts down the device using Systemd
func ShutdownHandler(writer http.ResponseWriter, request *http.Request) {
log.Println("Shutting down")
sendResponse, sendError := responseSenders(writer)
if systemd.Logind == nil {
sendError(fmt.Errorf("Logind unavailable, cannot shut down."))
return
}
sendResponse("OK", "", http.StatusAccepted)
go inASecond(func() { systemd.Logind.PowerOff(false) })
}
//VPNControl is used to control VPN service status with dbus
func VPNControl(writer http.ResponseWriter, request *http.Request) {
sendResponse, sendError := responseSenders(writer)
var body VPNBody
if err := parseJSONBody(&body, request); err != nil {
log.Println(err)
sendResponse("Error", err.Error(), http.StatusBadRequest)
return
}
if systemd.Dbus == nil {
sendError(fmt.Errorf("Systemd dbus unavailable, cannot set VPN state."))
return
}
action := systemd.Dbus.StopUnit
actionDescr := "VPN Disable"
if body.Enable {
action = systemd.Dbus.StartUnit
actionDescr = "VPN Enable"
}
if _, err := action("openvpn-resin.service", "fail", nil); err != nil {
log.Printf("%s: %s\n", actionDescr, err)
sendError(err)
return
}
log.Printf("%sd\n", actionDescr)
sendResponse("OK", "", http.StatusAccepted)
}
func getUnitStatus(unitName string) (state bool, err error) {
if systemd.Dbus == nil {
err = fmt.Errorf("Systemd dbus unavailable, cannot get unit status.")
return
}
if activeState, e := systemd.Dbus.GetUnitProperty(unitName, "ActiveState"); e != nil {
err = fmt.Errorf("Unable to get unit status: %v", e)
return
} else {
activeStateStr := activeState.Value.String()
state = activeStateStr != `"inactive"` && activeStateStr != `"deactivating"`
return
}
}
func unitStatusHandler(serviceName string, writer http.ResponseWriter, request *http.Request) {
sendResponse, sendError := responseSenders(writer)
if status, err := getUnitStatus(serviceName); err != nil {
sendError(fmt.Errorf("Unable to get VPN status: %v", err))
} else {
sendResponse(status, "", http.StatusOK)
}
}
func VPNStatus(writer http.ResponseWriter, request *http.Request) {
unitStatusHandler("openvpn-resin.service", writer, request)
}
func logToDisplayServiceName() (serviceName string, err error) {
serviceName = "resin-info@tty1.service"
serviceNameOld := "tty-replacement.service"
if systemd.Dbus == nil {
err = fmt.Errorf("Systemd dbus unavailable, cannot get log to display service.")
return
}
if loaded, e := systemd.Dbus.GetUnitProperty(serviceName, "LoadState"); e != nil {
err = fmt.Errorf("Unable to get log to display load status: %v", e)
return
} else if loaded.Value.String() == `"not-found"` {
// If the resin-info service is not found, we're on an older OS
// which uses a different service name
serviceName = serviceNameOld
}
if loaded, e := systemd.Dbus.GetUnitProperty(serviceName, "LoadState"); e != nil {
err = fmt.Errorf("Unable to get log to display load status: %v", e)
return
} else if loaded.Value.String() == `"not-found"` {
// We might be in a different OS that just doesn't have the service
serviceName = ""
return
}
return
}
func LogToDisplayStatus(writer http.ResponseWriter, request *http.Request) {
sendResponse, sendError := responseSenders(writer)
serviceName, err := logToDisplayServiceName()
if err != nil {
sendError(err)
return
} else if serviceName == "" {
sendResponse("Error", "Not found", http.StatusNotFound)
return
}
unitStatusHandler(serviceName, writer, request)
}
//LogToDisplayControl is used to control tty-replacement service status with dbus
func LogToDisplayControl(writer http.ResponseWriter, request *http.Request) {
sendResponse, sendError := responseSenders(writer)
var body LogToDisplayBody
if err := parseJSONBody(&body, request); err != nil {
log.Println(err)
sendResponse("Error", err.Error(), http.StatusBadRequest)
return
}
if systemd.Dbus == nil {
sendError(fmt.Errorf("Systemd dbus unavailable, cannot set log to display state."))
return
}
serviceName, err := logToDisplayServiceName()
if err != nil {
sendError(err)
return
} else if serviceName == "" {
sendResponse("Error", "Not found", http.StatusNotFound)
return
}
if status, err := getUnitStatus(serviceName); err != nil {
sendError(fmt.Errorf("Unable to get log to display status: %v", err))
return
} else {
enable := body.Enable
if status == enable {
// Nothing to do, return Data = false to signal nothing was changed
sendResponse(false, "", http.StatusOK)
return
} else if enable {
if _, err := systemd.Dbus.StartUnit(serviceName, "fail", nil); err != nil {
sendError(fmt.Errorf("Unable to start service: %v", err))
return
}
if _, _, err = systemd.Dbus.EnableUnitFiles([]string{serviceName}, false, false); err != nil {
sendError(fmt.Errorf("Unable to enable service: %v", err))
return
}
} else {
if _, err := systemd.Dbus.StopUnit(serviceName, "fail", nil); err != nil {
sendError(fmt.Errorf("Unable to stop service: %v", err))
return
}
if _, err = systemd.Dbus.DisableUnitFiles([]string{serviceName}, false); err != nil {
sendError(fmt.Errorf("Unable to disable service: %v", err))
return
}
}
sendResponse(true, "", http.StatusOK)
}
}
//RestartService is used to restart a systemd service by name
func RestartService(writer http.ResponseWriter, request *http.Request) {
sendResponse, sendError := responseSenders(writer)
var body RestartServiceBody
if err := parseJSONBody(&body, request); err != nil {
log.Println(err)
sendResponse("Error", err.Error(), http.StatusBadRequest)
return
}
if systemd.Dbus == nil {
sendError(fmt.Errorf("Systemd dbus unavailable, cannot restart service."))
return
}
actionDescr := "Service Restart"
if _, err := systemd.Dbus.RestartUnit(body.Name+".service", "fail", nil); err != nil {
log.Printf("%s: %s\n", actionDescr, err)
sendError(err)
return
}
log.Printf("%sd\n", actionDescr)
sendResponse("OK", "", http.StatusOK)
}

View File

@ -1,46 +0,0 @@
package main
import (
"fmt"
"log"
"net"
"net/http"
"os"
"github.com/gorilla/mux"
)
func setupApi(router *mux.Router) {
router.HandleFunc("/ping", func(writer http.ResponseWriter, request *http.Request) {
fmt.Fprintln(writer, "OK")
})
apiv1 := router.PathPrefix("/v1").Subrouter()
apiv1.HandleFunc("/reboot", RebootHandler).Methods("POST")
apiv1.HandleFunc("/shutdown", ShutdownHandler).Methods("POST")
apiv1.HandleFunc("/vpncontrol", VPNControl).Methods("POST")
apiv1.HandleFunc("/vpncontrol", VPNStatus).Methods("GET")
apiv1.HandleFunc("/log-to-display", LogToDisplayControl).Methods("POST")
apiv1.HandleFunc("/log-to-display", LogToDisplayStatus).Methods("GET")
apiv1.HandleFunc("/restart-service", RestartService).Methods("POST")
}
func startApi(listenAddress string, router *mux.Router) {
if listener, err := net.Listen("unix", listenAddress); err != nil {
log.Fatalf("Could not listen on %s: %v", listenAddress, err)
} else {
log.Printf("Starting HTTP server on %s\n", listenAddress)
if err = http.Serve(listener, router); err != nil {
log.Fatalf("Could not start HTTP server: %v", err)
}
}
}
func main() {
log.SetFlags(log.Lshortfile | log.LstdFlags)
log.Println("Resin Go Supervisor starting")
listenAddress := os.Getenv("GOSUPER_SOCKET")
router := mux.NewRouter()
setupApi(router)
startApi(listenAddress, router)
}

View File

@ -1,25 +0,0 @@
package systemd
import (
"log"
"github.com/coreos/go-systemd/dbus"
"github.com/coreos/go-systemd/login1"
)
var (
// Logind Systemd Login1 connection
Logind *login1.Conn
// Dbus Systems Dbus connection
Dbus *dbus.Conn
)
func init() {
var err error
if Logind, err = login1.New(); err != nil {
log.Printf("Failed to connect to host system bus: %s", err)
}
if Dbus, err = dbus.New(); err != nil {
log.Printf("Failed to connect to host DBUS: %s", err)
}
}

View File

@ -1,14 +0,0 @@
#!/bin/bash
for dir in $(find ./* -path ./vendor -prune -or -type d -print); do
errormessage=$(gofmt -l $dir)
if [ -n "$errormessage" ]; then
echo "$errormessage"
failed=1
fi
done
if [ -n "$failed" ]; then
echo "Bad formatting, run make format-gosuper to fix above errors."
exit 1
fi

View File

@ -1,27 +0,0 @@
sudo: required
services:
- docker
env:
global:
- GOPATH=/opt
- BUILD_DIR=/opt/src/github.com/coreos/go-systemd
matrix:
- DOCKER_BASE=ubuntu:16.04
- DOCKER_BASE=debian:stretch
before_install:
- docker pull ${DOCKER_BASE}
- docker run --privileged -e GOPATH=${GOPATH} --cidfile=/tmp/cidfile ${DOCKER_BASE} /bin/bash -c "apt-get update && apt-get install -y build-essential git golang dbus libsystemd-dev libpam-systemd && go get github.com/coreos/pkg/dlopen && go get github.com/godbus/dbus"
- docker commit `cat /tmp/cidfile` go-systemd/container-tests
- rm -f /tmp/cidfile
install:
- docker run -d --cidfile=/tmp/cidfile --privileged -e GOPATH=${GOPATH} -v ${PWD}:${BUILD_DIR} go-systemd/container-tests /bin/systemd --system
script:
- docker exec `cat /tmp/cidfile` /bin/bash -c "cd ${BUILD_DIR} && ./test"
after_script:
- docker kill `cat /tmp/cidfile`

View File

@ -1,77 +0,0 @@
# How to Contribute
CoreOS projects are [Apache 2.0 licensed](LICENSE) and accept contributions via
GitHub pull requests. This document outlines some of the conventions on
development workflow, commit message formatting, contact points and other
resources to make it easier to get your contribution accepted.
# Certificate of Origin
By contributing to this project you agree to the Developer Certificate of
Origin (DCO). This document was created by the Linux Kernel community and is a
simple statement that you, as a contributor, have the legal right to make the
contribution. See the [DCO](DCO) file for details.
# Email and Chat
The project currently uses the general CoreOS email list and IRC channel:
- Email: [coreos-dev](https://groups.google.com/forum/#!forum/coreos-dev)
- IRC: #[coreos](irc://irc.freenode.org:6667/#coreos) IRC channel on freenode.org
Please avoid emailing maintainers found in the MAINTAINERS file directly. They
are very busy and read the mailing lists.
## Getting Started
- Fork the repository on GitHub
- Read the [README](README.md) for build and test instructions
- Play with the project, submit bugs, submit patches!
## Contribution Flow
This is a rough outline of what a contributor's workflow looks like:
- Create a topic branch from where you want to base your work (usually master).
- Make commits of logical units.
- Make sure your commit messages are in the proper format (see below).
- Push your changes to a topic branch in your fork of the repository.
- Make sure the tests pass, and add any new tests as appropriate.
- Submit a pull request to the original repository.
Thanks for your contributions!
### Coding Style
CoreOS projects written in Go follow a set of style guidelines that we've documented
[here](https://github.com/coreos/docs/tree/master/golang). Please follow them when
working on your contributions.
### Format of the Commit Message
We follow a rough convention for commit messages that is designed to answer two
questions: what changed and why. The subject line should feature the what and
the body of the commit should describe the why.
```
scripts: add the test-cluster command
this uses tmux to setup a test cluster that you can easily kill and
start for debugging.
Fixes #38
```
The format can be described more formally as follows:
```
<subsystem>: <what changed>
<BLANK LINE>
<why this change was made>
<BLANK LINE>
<footer>
```
The first line is the subject and should be no longer than 70 characters, the
second line is always blank, and other lines should be wrapped at 80 characters.
This allows the message to be easier to read on GitHub as well as in various
git tools.

View File

@ -1,36 +0,0 @@
Developer Certificate of Origin
Version 1.1
Copyright (C) 2004, 2006 The Linux Foundation and its contributors.
660 York Street, Suite 102,
San Francisco, CA 94110 USA
Everyone is permitted to copy and distribute verbatim copies of this
license document, but changing it is not allowed.
Developer's Certificate of Origin 1.1
By making a contribution to this project, I certify that:
(a) The contribution was created in whole or in part by me and I
have the right to submit it under the open source license
indicated in the file; or
(b) The contribution is based upon previous work that, to the best
of my knowledge, is covered under an appropriate open source
license and I have the right under that license to submit that
work with modifications, whether created in whole or in part
by me, under the same open source license (unless I am
permitted to submit under a different license), as indicated
in the file; or
(c) The contribution was provided directly to me by some other
person who certified (a), (b) or (c) and I have not modified
it.
(d) I understand and agree that this project and the contribution
are public and that a record of the contribution (including all
personal information I submit with it, including my sign-off) is
maintained indefinitely and may be redistributed consistent with
this project or the open source license(s) involved.

View File

@ -1,191 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and
distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright
owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities
that control, are controlled by, or are under common control with that entity.
For the purposes of this definition, "control" means (i) the power, direct or
indirect, to cause the direction or management of such entity, whether by
contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising
permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including
but not limited to software source code, documentation source, and configuration
files.
"Object" form shall mean any form resulting from mechanical transformation or
translation of a Source form, including but not limited to compiled object code,
generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made
available under the License, as indicated by a copyright notice that is included
in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that
is based on (or derived from) the Work and for which the editorial revisions,
annotations, elaborations, or other modifications represent, as a whole, an
original work of authorship. For the purposes of this License, Derivative Works
shall not include works that remain separable from, or merely link (or bind by
name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version
of the Work and any modifications or additions to that Work or Derivative Works
thereof, that is intentionally submitted to Licensor for inclusion in the Work
by the copyright owner or by an individual or Legal Entity authorized to submit
on behalf of the copyright owner. For the purposes of this definition,
"submitted" means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems, and
issue tracking systems that are managed by, or on behalf of, the Licensor for
the purpose of discussing and improving the Work, but excluding communication
that is conspicuously marked or otherwise designated in writing by the copyright
owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf
of whom a Contribution has been received by Licensor and subsequently
incorporated within the Work.
2. Grant of Copyright License.
Subject to the terms and conditions of this License, each Contributor hereby
grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
irrevocable copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the Work and such
Derivative Works in Source or Object form.
3. Grant of Patent License.
Subject to the terms and conditions of this License, each Contributor hereby
grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
irrevocable (except as stated in this section) patent license to make, have
made, use, offer to sell, sell, import, and otherwise transfer the Work, where
such license applies only to those patent claims licensable by such Contributor
that are necessarily infringed by their Contribution(s) alone or by combination
of their Contribution(s) with the Work to which such Contribution(s) was
submitted. If You institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work or a
Contribution incorporated within the Work constitutes direct or contributory
patent infringement, then any patent licenses granted to You under this License
for that Work shall terminate as of the date such litigation is filed.
4. Redistribution.
You may reproduce and distribute copies of the Work or Derivative Works thereof
in any medium, with or without modifications, and in Source or Object form,
provided that You meet the following conditions:
You must give any other recipients of the Work or Derivative Works a copy of
this License; and
You must cause any modified files to carry prominent notices stating that You
changed the files; and
You must retain, in the Source form of any Derivative Works that You distribute,
all copyright, patent, trademark, and attribution notices from the Source form
of the Work, excluding those notices that do not pertain to any part of the
Derivative Works; and
If the Work includes a "NOTICE" text file as part of its distribution, then any
Derivative Works that You distribute must include a readable copy of the
attribution notices contained within such NOTICE file, excluding those notices
that do not pertain to any part of the Derivative Works, in at least one of the
following places: within a NOTICE text file distributed as part of the
Derivative Works; within the Source form or documentation, if provided along
with the Derivative Works; or, within a display generated by the Derivative
Works, if and wherever such third-party notices normally appear. The contents of
the NOTICE file are for informational purposes only and do not modify the
License. You may add Your own attribution notices within Derivative Works that
You distribute, alongside or as an addendum to the NOTICE text from the Work,
provided that such additional attribution notices cannot be construed as
modifying the License.
You may add Your own copyright statement to Your modifications and may provide
additional or different license terms and conditions for use, reproduction, or
distribution of Your modifications, or for any such Derivative Works as a whole,
provided Your use, reproduction, and distribution of the Work otherwise complies
with the conditions stated in this License.
5. Submission of Contributions.
Unless You explicitly state otherwise, any Contribution intentionally submitted
for inclusion in the Work by You to the Licensor shall be under the terms and
conditions of this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify the terms of
any separate license agreement you may have executed with Licensor regarding
such Contributions.
6. Trademarks.
This License does not grant permission to use the trade names, trademarks,
service marks, or product names of the Licensor, except as required for
reasonable and customary use in describing the origin of the Work and
reproducing the content of the NOTICE file.
7. Disclaimer of Warranty.
Unless required by applicable law or agreed to in writing, Licensor provides the
Work (and each Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied,
including, without limitation, any warranties or conditions of TITLE,
NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are
solely responsible for determining the appropriateness of using or
redistributing the Work and assume any risks associated with Your exercise of
permissions under this License.
8. Limitation of Liability.
In no event and under no legal theory, whether in tort (including negligence),
contract, or otherwise, unless required by applicable law (such as deliberate
and grossly negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special, incidental,
or consequential damages of any character arising as a result of this License or
out of the use or inability to use the Work (including but not limited to
damages for loss of goodwill, work stoppage, computer failure or malfunction, or
any and all other commercial damages or losses), even if such Contributor has
been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability.
While redistributing the Work or Derivative Works thereof, You may choose to
offer, and charge a fee for, acceptance of support, warranty, indemnity, or
other liability obligations and/or rights consistent with this License. However,
in accepting such obligations, You may act only on Your own behalf and on Your
sole responsibility, not on behalf of any other Contributor, and only if You
agree to indemnify, defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason of your
accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work
To apply the Apache License to your work, attach the following boilerplate
notice, with the fields enclosed by brackets "[]" replaced with your own
identifying information. (Don't include the brackets!) The text should be
enclosed in the appropriate comment syntax for the file format. We also
recommend that a file or class name and description of purpose be included on
the same "printed page" as the copyright notice for easier identification within
third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@ -1,54 +0,0 @@
# go-systemd
[![Build Status](https://travis-ci.org/coreos/go-systemd.png?branch=master)](https://travis-ci.org/coreos/go-systemd)
[![godoc](https://godoc.org/github.com/coreos/go-systemd?status.svg)](http://godoc.org/github.com/coreos/go-systemd)
Go bindings to systemd. The project has several packages:
- `activation` - for writing and using socket activation from Go
- `dbus` - for starting/stopping/inspecting running services and units
- `journal` - for writing to systemd's logging service, journald
- `sdjournal` - for reading from journald by wrapping its C API
- `machine1` - for registering machines/containers with systemd
- `unit` - for (de)serialization and comparison of unit files
## Socket Activation
An example HTTP server using socket activation can be quickly set up by following this README on a Linux machine running systemd:
https://github.com/coreos/go-systemd/tree/master/examples/activation/httpserver
## Journal
Using the pure-Go `journal` package you can submit journal entries directly to systemd's journal, taking advantage of features like indexed key/value pairs for each log entry.
The `sdjournal` package provides read access to the journal by wrapping around journald's native C API; consequently it requires cgo and the journal headers to be available.
## D-Bus
The `dbus` package connects to the [systemd D-Bus API](http://www.freedesktop.org/wiki/Software/systemd/dbus/) and lets you start, stop and introspect systemd units. The API docs are here:
http://godoc.org/github.com/coreos/go-systemd/dbus
### Debugging
Create `/etc/dbus-1/system-local.conf` that looks like this:
```
<!DOCTYPE busconfig PUBLIC
"-//freedesktop//DTD D-Bus Bus Configuration 1.0//EN"
"http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
<busconfig>
<policy user="root">
<allow eavesdrop="true"/>
<allow eavesdrop="true" send_destination="*"/>
</policy>
</busconfig>
```
## machined
The `machine1` package allows interaction with the [systemd machined D-Bus API](http://www.freedesktop.org/wiki/Software/systemd/machined/).
## Units
The `unit` package provides various functions for working with [systemd unit files](http://www.freedesktop.org/software/systemd/man/systemd.unit.html).

View File

@ -1,52 +0,0 @@
// Copyright 2015 CoreOS, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package activation implements primitives for systemd socket activation.
package activation
import (
"os"
"strconv"
"syscall"
)
// based on: https://gist.github.com/alberts/4640792
const (
listenFdsStart = 3
)
func Files(unsetEnv bool) []*os.File {
if unsetEnv {
defer os.Unsetenv("LISTEN_PID")
defer os.Unsetenv("LISTEN_FDS")
}
pid, err := strconv.Atoi(os.Getenv("LISTEN_PID"))
if err != nil || pid != os.Getpid() {
return nil
}
nfds, err := strconv.Atoi(os.Getenv("LISTEN_FDS"))
if err != nil || nfds == 0 {
return nil
}
files := make([]*os.File, 0, nfds)
for fd := listenFdsStart; fd < listenFdsStart+nfds; fd++ {
syscall.CloseOnExec(fd)
files = append(files, os.NewFile(uintptr(fd), "LISTEN_FD_"+strconv.Itoa(fd)))
}
return files
}

View File

@ -1,82 +0,0 @@
// Copyright 2015 CoreOS, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package activation
import (
"bytes"
"io"
"os"
"os/exec"
"testing"
)
// correctStringWritten fails the text if the correct string wasn't written
// to the other side of the pipe.
func correctStringWritten(t *testing.T, r *os.File, expected string) bool {
bytes := make([]byte, len(expected))
io.ReadAtLeast(r, bytes, len(expected))
if string(bytes) != expected {
t.Fatalf("Unexpected string %s", string(bytes))
}
return true
}
// TestActivation forks out a copy of activation.go example and reads back two
// strings from the pipes that are passed in.
func TestActivation(t *testing.T) {
cmd := exec.Command("go", "run", "../examples/activation/activation.go")
r1, w1, _ := os.Pipe()
r2, w2, _ := os.Pipe()
cmd.ExtraFiles = []*os.File{
w1,
w2,
}
cmd.Env = os.Environ()
cmd.Env = append(cmd.Env, "LISTEN_FDS=2", "FIX_LISTEN_PID=1")
err := cmd.Run()
if err != nil {
t.Fatalf(err.Error())
}
correctStringWritten(t, r1, "Hello world")
correctStringWritten(t, r2, "Goodbye world")
}
func TestActivationNoFix(t *testing.T) {
cmd := exec.Command("go", "run", "../examples/activation/activation.go")
cmd.Env = os.Environ()
cmd.Env = append(cmd.Env, "LISTEN_FDS=2")
out, _ := cmd.CombinedOutput()
if bytes.Contains(out, []byte("No files")) == false {
t.Fatalf("Child didn't error out as expected")
}
}
func TestActivationNoFiles(t *testing.T) {
cmd := exec.Command("go", "run", "../examples/activation/activation.go")
cmd.Env = os.Environ()
cmd.Env = append(cmd.Env, "LISTEN_FDS=0", "FIX_LISTEN_PID=1")
out, _ := cmd.CombinedOutput()
if bytes.Contains(out, []byte("No files")) == false {
t.Fatalf("Child didn't error out as expected")
}
}

View File

@ -1,60 +0,0 @@
// Copyright 2015 CoreOS, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package activation
import (
"crypto/tls"
"net"
)
// Listeners returns a slice containing a net.Listener for each matching socket type
// passed to this process.
//
// The order of the file descriptors is preserved in the returned slice.
// Nil values are used to fill any gaps. For example if systemd were to return file descriptors
// corresponding with "udp, tcp, tcp", then the slice would contain {nil, net.Listener, net.Listener}
func Listeners(unsetEnv bool) ([]net.Listener, error) {
files := Files(unsetEnv)
listeners := make([]net.Listener, len(files))
for i, f := range files {
if pc, err := net.FileListener(f); err == nil {
listeners[i] = pc
}
}
return listeners, nil
}
// TLSListeners returns a slice containing a net.listener for each matching TCP socket type
// passed to this process.
// It uses default Listeners func and forces TCP sockets handlers to use TLS based on tlsConfig.
func TLSListeners(unsetEnv bool, tlsConfig *tls.Config) ([]net.Listener, error) {
listeners, err := Listeners(unsetEnv)
if listeners == nil || err != nil {
return nil, err
}
if tlsConfig != nil && err == nil {
for i, l := range listeners {
// Activate TLS only for TCP sockets
if l.Addr().Network() == "tcp" {
listeners[i] = tls.NewListener(l, tlsConfig)
}
}
}
return listeners, err
}

View File

@ -1,86 +0,0 @@
// Copyright 2015 CoreOS, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package activation
import (
"io"
"net"
"os"
"os/exec"
"testing"
)
// correctStringWritten fails the text if the correct string wasn't written
// to the other side of the pipe.
func correctStringWrittenNet(t *testing.T, r net.Conn, expected string) bool {
bytes := make([]byte, len(expected))
io.ReadAtLeast(r, bytes, len(expected))
if string(bytes) != expected {
t.Fatalf("Unexpected string %s", string(bytes))
}
return true
}
// TestActivation forks out a copy of activation.go example and reads back two
// strings from the pipes that are passed in.
func TestListeners(t *testing.T) {
cmd := exec.Command("go", "run", "../examples/activation/listen.go")
l1, err := net.Listen("tcp", ":9999")
if err != nil {
t.Fatalf(err.Error())
}
l2, err := net.Listen("tcp", ":1234")
if err != nil {
t.Fatalf(err.Error())
}
t1 := l1.(*net.TCPListener)
t2 := l2.(*net.TCPListener)
f1, _ := t1.File()
f2, _ := t2.File()
cmd.ExtraFiles = []*os.File{
f1,
f2,
}
r1, err := net.Dial("tcp", "127.0.0.1:9999")
if err != nil {
t.Fatalf(err.Error())
}
r1.Write([]byte("Hi"))
r2, err := net.Dial("tcp", "127.0.0.1:1234")
if err != nil {
t.Fatalf(err.Error())
}
r2.Write([]byte("Hi"))
cmd.Env = os.Environ()
cmd.Env = append(cmd.Env, "LISTEN_FDS=2", "FIX_LISTEN_PID=1")
out, err := cmd.Output()
if err != nil {
println(string(out))
t.Fatalf(err.Error())
}
correctStringWrittenNet(t, r1, "Hello world")
correctStringWrittenNet(t, r2, "Goodbye world")
}

View File

@ -1,37 +0,0 @@
// Copyright 2015 CoreOS, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package activation
import (
"net"
)
// PacketConns returns a slice containing a net.PacketConn for each matching socket type
// passed to this process.
//
// The order of the file descriptors is preserved in the returned slice.
// Nil values are used to fill any gaps. For example if systemd were to return file descriptors
// corresponding with "udp, tcp, udp", then the slice would contain {net.PacketConn, nil, net.PacketConn}
func PacketConns(unsetEnv bool) ([]net.PacketConn, error) {
files := Files(unsetEnv)
conns := make([]net.PacketConn, len(files))
for i, f := range files {
if pc, err := net.FilePacketConn(f); err == nil {
conns[i] = pc
}
}
return conns, nil
}

View File

@ -1,68 +0,0 @@
// Copyright 2015 CoreOS, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package activation
import (
"net"
"os"
"os/exec"
"testing"
)
// TestActivation forks out a copy of activation.go example and reads back two
// strings from the pipes that are passed in.
func TestPacketConns(t *testing.T) {
cmd := exec.Command("go", "run", "../examples/activation/udpconn.go")
u1, err := net.ListenUDP("udp", &net.UDPAddr{Port: 9999})
if err != nil {
t.Fatalf(err.Error())
}
u2, err := net.ListenUDP("udp", &net.UDPAddr{Port: 1234})
if err != nil {
t.Fatalf(err.Error())
}
f1, _ := u1.File()
f2, _ := u2.File()
cmd.ExtraFiles = []*os.File{
f1,
f2,
}
r1, err := net.Dial("udp", "127.0.0.1:9999")
if err != nil {
t.Fatalf(err.Error())
}
r1.Write([]byte("Hi"))
r2, err := net.Dial("udp", "127.0.0.1:1234")
if err != nil {
t.Fatalf(err.Error())
}
r2.Write([]byte("Hi"))
cmd.Env = os.Environ()
cmd.Env = append(cmd.Env, "LISTEN_FDS=2", "FIX_LISTEN_PID=1")
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("Cmd output '%s', err: '%s'\n", out, err)
}
correctStringWrittenNet(t, r1, "Hello world")
correctStringWrittenNet(t, r2, "Goodbye world")
}

View File

@ -1,63 +0,0 @@
// Copyright 2014 Docker, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code forked from Docker project
package daemon
import (
"net"
"os"
)
// SdNotify sends a message to the init daemon. It is common to ignore the error.
// If `unsetEnvironment` is true, the environment variable `NOTIFY_SOCKET`
// will be unconditionally unset.
//
// It returns one of the following:
// (false, nil) - notification not supported (i.e. NOTIFY_SOCKET is unset)
// (false, err) - notification supported, but failure happened (e.g. error connecting to NOTIFY_SOCKET or while sending data)
// (true, nil) - notification supported, data has been sent
func SdNotify(unsetEnvironment bool, state string) (sent bool, err error) {
socketAddr := &net.UnixAddr{
Name: os.Getenv("NOTIFY_SOCKET"),
Net: "unixgram",
}
// NOTIFY_SOCKET not set
if socketAddr.Name == "" {
return false, nil
}
if unsetEnvironment {
err = os.Unsetenv("NOTIFY_SOCKET")
}
if err != nil {
return false, err
}
conn, err := net.DialUnix(socketAddr.Net, nil, socketAddr)
// Error connecting to NOTIFY_SOCKET
if err != nil {
return false, err
}
defer conn.Close()
_, err = conn.Write([]byte(state))
// Error sending the message
if err != nil {
return false, err
}
return true, nil
}

View File

@ -1,79 +0,0 @@
// Copyright 2016 CoreOS, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package daemon
import (
"fmt"
"io/ioutil"
"net"
"os"
"testing"
)
// TestSdNotify
func TestSdNotify(t *testing.T) {
testDir, e := ioutil.TempDir("/tmp/", "test-")
if e != nil {
panic(e)
}
defer os.RemoveAll(testDir)
notifySocket := testDir + "/notify-socket.sock"
laddr := net.UnixAddr{
Name: notifySocket,
Net: "unixgram",
}
_, e = net.ListenUnixgram("unixgram", &laddr)
if e != nil {
panic(e)
}
tests := []struct {
unsetEnv bool
envSocket string
wsent bool
werr bool
}{
// (true, nil) - notification supported, data has been sent
{false, notifySocket, true, false},
// (false, err) - notification supported, but failure happened
{true, testDir + "/missing.sock", false, true},
// (false, nil) - notification not supported
{true, "", false, false},
}
for i, tt := range tests {
must(os.Unsetenv("NOTIFY_SOCKET"))
if tt.envSocket != "" {
must(os.Setenv("NOTIFY_SOCKET", tt.envSocket))
}
sent, err := SdNotify(tt.unsetEnv, fmt.Sprintf("TestSdNotify test message #%d", i))
if sent != tt.wsent {
t.Errorf("#%d: expected send result %t, got %t", i, tt.wsent, sent)
}
if tt.werr && err == nil {
t.Errorf("#%d: want non-nil err, got nil", i)
} else if !tt.werr && err != nil {
t.Errorf("#%d: want nil err, got %v", i, err)
}
if tt.unsetEnv && tt.envSocket != "" && os.Getenv("NOTIFY_SOCKET") != "" {
t.Errorf("#%d: environment variable not cleaned up", i)
}
}
}

View File

@ -1,72 +0,0 @@
// Copyright 2016 CoreOS, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package daemon
import (
"fmt"
"os"
"strconv"
"time"
)
// SdWatchdogEnabled return watchdog information for a service.
// Process should send daemon.SdNotify("WATCHDOG=1") every time / 2.
// If `unsetEnvironment` is true, the environment variables `WATCHDOG_USEC`
// and `WATCHDOG_PID` will be unconditionally unset.
//
// It returns one of the following:
// (0, nil) - watchdog isn't enabled or we aren't the watched PID.
// (0, err) - an error happened (e.g. error converting time).
// (time, nil) - watchdog is enabled and we can send ping.
// time is delay before inactive service will be killed.
func SdWatchdogEnabled(unsetEnvironment bool) (time.Duration, error) {
wusec := os.Getenv("WATCHDOG_USEC")
wpid := os.Getenv("WATCHDOG_PID")
if unsetEnvironment {
wusecErr := os.Unsetenv("WATCHDOG_USEC")
wpidErr := os.Unsetenv("WATCHDOG_PID")
if wusecErr != nil {
return 0, wusecErr
}
if wpidErr != nil {
return 0, wpidErr
}
}
if wusec == "" {
return 0, nil
}
s, err := strconv.Atoi(wusec)
if err != nil {
return 0, fmt.Errorf("error converting WATCHDOG_USEC: %s", err)
}
if s <= 0 {
return 0, fmt.Errorf("error WATCHDOG_USEC must be a positive number")
}
interval := time.Duration(s) * time.Microsecond
if wpid == "" {
return interval, nil
}
p, err := strconv.Atoi(wpid)
if err != nil {
return 0, fmt.Errorf("error converting WATCHDOG_PID: %s", err)
}
if os.Getpid() != p {
return 0, nil
}
return interval, nil
}

View File

@ -1,85 +0,0 @@
// Copyright 2016 CoreOS, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package daemon
import (
"os"
"strconv"
"testing"
"time"
)
func must(err error) {
if err != nil {
panic(err)
}
}
func TestSdWatchdogEnabled(t *testing.T) {
mypid := strconv.Itoa(os.Getpid())
tests := []struct {
usec string // empty => unset
pid string // empty => unset
unsetEnv bool // arbitrarily set across testcases
werr bool
wdelay time.Duration
}{
// Success cases
{"100", mypid, true, false, 100 * time.Microsecond},
{"50", mypid, true, false, 50 * time.Microsecond},
{"1", mypid, false, false, 1 * time.Microsecond},
{"1", "", true, false, 1 * time.Microsecond},
// No-op cases
{"", mypid, true, false, 0}, // WATCHDOG_USEC not set
{"1", "0", false, false, 0}, // WATCHDOG_PID doesn't match
{"", "", true, false, 0}, // Both not set
// Failure cases
{"-1", mypid, true, true, 0}, // Negative USEC
{"string", "1", false, true, 0}, // Non-integer USEC value
{"1", "string", true, true, 0}, // Non-integer PID value
{"stringa", "stringb", false, true, 0}, // E v e r y t h i n g
{"-10239", "-eleventythree", true, true, 0}, // i s w r o n g
}
for i, tt := range tests {
if tt.usec != "" {
must(os.Setenv("WATCHDOG_USEC", tt.usec))
} else {
must(os.Unsetenv("WATCHDOG_USEC"))
}
if tt.pid != "" {
must(os.Setenv("WATCHDOG_PID", tt.pid))
} else {
must(os.Unsetenv("WATCHDOG_PID"))
}
delay, err := SdWatchdogEnabled(tt.unsetEnv)
if tt.werr && err == nil {
t.Errorf("#%d: want non-nil err, got nil", i)
} else if !tt.werr && err != nil {
t.Errorf("#%d: want nil err, got %v", i, err)
}
if tt.wdelay != delay {
t.Errorf("#%d: want delay=%d, got %d", i, tt.wdelay, delay)
}
if tt.unsetEnv && (os.Getenv("WATCHDOG_PID") != "" || os.Getenv("WATCHDOG_USEC") != "") {
t.Errorf("#%d: environment variables not cleaned up", i)
}
}
}

View File

@ -1,213 +0,0 @@
// Copyright 2015 CoreOS, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Integration with the systemd D-Bus API. See http://www.freedesktop.org/wiki/Software/systemd/dbus/
package dbus
import (
"fmt"
"os"
"strconv"
"strings"
"sync"
"github.com/godbus/dbus"
)
const (
alpha = `abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ`
num = `0123456789`
alphanum = alpha + num
signalBuffer = 100
)
// needsEscape checks whether a byte in a potential dbus ObjectPath needs to be escaped
func needsEscape(i int, b byte) bool {
// Escape everything that is not a-z-A-Z-0-9
// Also escape 0-9 if it's the first character
return strings.IndexByte(alphanum, b) == -1 ||
(i == 0 && strings.IndexByte(num, b) != -1)
}
// PathBusEscape sanitizes a constituent string of a dbus ObjectPath using the
// rules that systemd uses for serializing special characters.
func PathBusEscape(path string) string {
// Special case the empty string
if len(path) == 0 {
return "_"
}
n := []byte{}
for i := 0; i < len(path); i++ {
c := path[i]
if needsEscape(i, c) {
e := fmt.Sprintf("_%x", c)
n = append(n, []byte(e)...)
} else {
n = append(n, c)
}
}
return string(n)
}
// Conn is a connection to systemd's dbus endpoint.
type Conn struct {
// sysconn/sysobj are only used to call dbus methods
sysconn *dbus.Conn
sysobj dbus.BusObject
// sigconn/sigobj are only used to receive dbus signals
sigconn *dbus.Conn
sigobj dbus.BusObject
jobListener struct {
jobs map[dbus.ObjectPath]chan<- string
sync.Mutex
}
subscriber struct {
updateCh chan<- *SubStateUpdate
errCh chan<- error
sync.Mutex
ignore map[dbus.ObjectPath]int64
cleanIgnore int64
}
}
// New establishes a connection to any available bus and authenticates.
// Callers should call Close() when done with the connection.
func New() (*Conn, error) {
conn, err := NewSystemConnection()
if err != nil && os.Geteuid() == 0 {
return NewSystemdConnection()
}
return conn, err
}
// NewSystemConnection establishes a connection to the system bus and authenticates.
// Callers should call Close() when done with the connection
func NewSystemConnection() (*Conn, error) {
return NewConnection(func() (*dbus.Conn, error) {
return dbusAuthHelloConnection(dbus.SystemBusPrivate)
})
}
// NewUserConnection establishes a connection to the session bus and
// authenticates. This can be used to connect to systemd user instances.
// Callers should call Close() when done with the connection.
func NewUserConnection() (*Conn, error) {
return NewConnection(func() (*dbus.Conn, error) {
return dbusAuthHelloConnection(dbus.SessionBusPrivate)
})
}
// NewSystemdConnection establishes a private, direct connection to systemd.
// This can be used for communicating with systemd without a dbus daemon.
// Callers should call Close() when done with the connection.
func NewSystemdConnection() (*Conn, error) {
return NewConnection(func() (*dbus.Conn, error) {
// We skip Hello when talking directly to systemd.
return dbusAuthConnection(func() (*dbus.Conn, error) {
return dbus.Dial("unix:path=/run/systemd/private")
})
})
}
// Close closes an established connection
func (c *Conn) Close() {
c.sysconn.Close()
c.sigconn.Close()
}
// NewConnection establishes a connection to a bus using a caller-supplied function.
// This allows connecting to remote buses through a user-supplied mechanism.
// The supplied function may be called multiple times, and should return independent connections.
// The returned connection must be fully initialised: the org.freedesktop.DBus.Hello call must have succeeded,
// and any authentication should be handled by the function.
func NewConnection(dialBus func() (*dbus.Conn, error)) (*Conn, error) {
sysconn, err := dialBus()
if err != nil {
return nil, err
}
sigconn, err := dialBus()
if err != nil {
sysconn.Close()
return nil, err
}
c := &Conn{
sysconn: sysconn,
sysobj: systemdObject(sysconn),
sigconn: sigconn,
sigobj: systemdObject(sigconn),
}
c.subscriber.ignore = make(map[dbus.ObjectPath]int64)
c.jobListener.jobs = make(map[dbus.ObjectPath]chan<- string)
// Setup the listeners on jobs so that we can get completions
c.sigconn.BusObject().Call("org.freedesktop.DBus.AddMatch", 0,
"type='signal', interface='org.freedesktop.systemd1.Manager', member='JobRemoved'")
c.dispatch()
return c, nil
}
// GetManagerProperty returns the value of a property on the org.freedesktop.systemd1.Manager
// interface. The value is returned in its string representation, as defined at
// https://developer.gnome.org/glib/unstable/gvariant-text.html
func (c *Conn) GetManagerProperty(prop string) (string, error) {
variant, err := c.sysobj.GetProperty("org.freedesktop.systemd1.Manager." + prop)
if err != nil {
return "", err
}
return variant.String(), nil
}
func dbusAuthConnection(createBus func() (*dbus.Conn, error)) (*dbus.Conn, error) {
conn, err := createBus()
if err != nil {
return nil, err
}
// Only use EXTERNAL method, and hardcode the uid (not username)
// to avoid a username lookup (which requires a dynamically linked
// libc)
methods := []dbus.Auth{dbus.AuthExternal(strconv.Itoa(os.Getuid()))}
err = conn.Auth(methods)
if err != nil {
conn.Close()
return nil, err
}
return conn, nil
}
func dbusAuthHelloConnection(createBus func() (*dbus.Conn, error)) (*dbus.Conn, error) {
conn, err := dbusAuthConnection(createBus)
if err != nil {
return nil, err
}
if err = conn.Hello(); err != nil {
conn.Close()
return nil, err
}
return conn, nil
}
func systemdObject(conn *dbus.Conn) dbus.BusObject {
return conn.Object("org.freedesktop.systemd1", dbus.ObjectPath("/org/freedesktop/systemd1"))
}

View File

@ -1,77 +0,0 @@
// Copyright 2015 CoreOS, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package dbus
import (
"testing"
)
func TestNeedsEscape(t *testing.T) {
// Anything not 0-9a-zA-Z should always be escaped
for want, vals := range map[bool][]byte{
false: []byte{'a', 'b', 'z', 'A', 'Q', '1', '4', '9'},
true: []byte{'#', '%', '$', '!', '.', '_', '-', '%', '\\'},
} {
for i := 1; i < 10; i++ {
for _, b := range vals {
got := needsEscape(i, b)
if got != want {
t.Errorf("needsEscape(%d, %c) returned %t, want %t", i, b, got, want)
}
}
}
}
// 0-9 in position 0 should be escaped
for want, vals := range map[bool][]byte{
false: []byte{'A', 'a', 'e', 'x', 'Q', 'Z'},
true: []byte{'0', '4', '5', '9'},
} {
for _, b := range vals {
got := needsEscape(0, b)
if got != want {
t.Errorf("needsEscape(0, %c) returned %t, want %t", b, got, want)
}
}
}
}
func TestPathBusEscape(t *testing.T) {
for in, want := range map[string]string{
"": "_",
"foo.service": "foo_2eservice",
"foobar": "foobar",
"woof@woof.service": "woof_40woof_2eservice",
"0123456": "_30123456",
"account_db.service": "account_5fdb_2eservice",
"got-dashes": "got_2ddashes",
} {
got := PathBusEscape(in)
if got != want {
t.Errorf("bad result for PathBusEscape(%s): got %q, want %q", in, got, want)
}
}
}
// TestNew ensures that New() works without errors.
func TestNew(t *testing.T) {
_, err := New()
if err != nil {
t.Fatal(err)
}
}

View File

@ -1,565 +0,0 @@
// Copyright 2015 CoreOS, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package dbus
import (
"errors"
"path"
"strconv"
"github.com/godbus/dbus"
)
func (c *Conn) jobComplete(signal *dbus.Signal) {
var id uint32
var job dbus.ObjectPath
var unit string
var result string
dbus.Store(signal.Body, &id, &job, &unit, &result)
c.jobListener.Lock()
out, ok := c.jobListener.jobs[job]
if ok {
out <- result
delete(c.jobListener.jobs, job)
}
c.jobListener.Unlock()
}
func (c *Conn) startJob(ch chan<- string, job string, args ...interface{}) (int, error) {
if ch != nil {
c.jobListener.Lock()
defer c.jobListener.Unlock()
}
var p dbus.ObjectPath
err := c.sysobj.Call(job, 0, args...).Store(&p)
if err != nil {
return 0, err
}
if ch != nil {
c.jobListener.jobs[p] = ch
}
// ignore error since 0 is fine if conversion fails
jobID, _ := strconv.Atoi(path.Base(string(p)))
return jobID, nil
}
// StartUnit enqueues a start job and depending jobs, if any (unless otherwise
// specified by the mode string).
//
// Takes the unit to activate, plus a mode string. The mode needs to be one of
// replace, fail, isolate, ignore-dependencies, ignore-requirements. If
// "replace" the call will start the unit and its dependencies, possibly
// replacing already queued jobs that conflict with this. If "fail" the call
// will start the unit and its dependencies, but will fail if this would change
// an already queued job. If "isolate" the call will start the unit in question
// and terminate all units that aren't dependencies of it. If
// "ignore-dependencies" it will start a unit but ignore all its dependencies.
// If "ignore-requirements" it will start a unit but only ignore the
// requirement dependencies. It is not recommended to make use of the latter
// two options.
//
// If the provided channel is non-nil, a result string will be sent to it upon
// job completion: one of done, canceled, timeout, failed, dependency, skipped.
// done indicates successful execution of a job. canceled indicates that a job
// has been canceled before it finished execution. timeout indicates that the
// job timeout was reached. failed indicates that the job failed. dependency
// indicates that a job this job has been depending on failed and the job hence
// has been removed too. skipped indicates that a job was skipped because it
// didn't apply to the units current state.
//
// If no error occurs, the ID of the underlying systemd job will be returned. There
// does exist the possibility for no error to be returned, but for the returned job
// ID to be 0. In this case, the actual underlying ID is not 0 and this datapoint
// should not be considered authoritative.
//
// If an error does occur, it will be returned to the user alongside a job ID of 0.
func (c *Conn) StartUnit(name string, mode string, ch chan<- string) (int, error) {
return c.startJob(ch, "org.freedesktop.systemd1.Manager.StartUnit", name, mode)
}
// StopUnit is similar to StartUnit but stops the specified unit rather
// than starting it.
func (c *Conn) StopUnit(name string, mode string, ch chan<- string) (int, error) {
return c.startJob(ch, "org.freedesktop.systemd1.Manager.StopUnit", name, mode)
}
// ReloadUnit reloads a unit. Reloading is done only if the unit is already running and fails otherwise.
func (c *Conn) ReloadUnit(name string, mode string, ch chan<- string) (int, error) {
return c.startJob(ch, "org.freedesktop.systemd1.Manager.ReloadUnit", name, mode)
}
// RestartUnit restarts a service. If a service is restarted that isn't
// running it will be started.
func (c *Conn) RestartUnit(name string, mode string, ch chan<- string) (int, error) {
return c.startJob(ch, "org.freedesktop.systemd1.Manager.RestartUnit", name, mode)
}
// TryRestartUnit is like RestartUnit, except that a service that isn't running
// is not affected by the restart.
func (c *Conn) TryRestartUnit(name string, mode string, ch chan<- string) (int, error) {
return c.startJob(ch, "org.freedesktop.systemd1.Manager.TryRestartUnit", name, mode)
}
// ReloadOrRestart attempts a reload if the unit supports it and use a restart
// otherwise.
func (c *Conn) ReloadOrRestartUnit(name string, mode string, ch chan<- string) (int, error) {
return c.startJob(ch, "org.freedesktop.systemd1.Manager.ReloadOrRestartUnit", name, mode)
}
// ReloadOrTryRestart attempts a reload if the unit supports it and use a "Try"
// flavored restart otherwise.
func (c *Conn) ReloadOrTryRestartUnit(name string, mode string, ch chan<- string) (int, error) {
return c.startJob(ch, "org.freedesktop.systemd1.Manager.ReloadOrTryRestartUnit", name, mode)
}
// StartTransientUnit() may be used to create and start a transient unit, which
// will be released as soon as it is not running or referenced anymore or the
// system is rebooted. name is the unit name including suffix, and must be
// unique. mode is the same as in StartUnit(), properties contains properties
// of the unit.
func (c *Conn) StartTransientUnit(name string, mode string, properties []Property, ch chan<- string) (int, error) {
return c.startJob(ch, "org.freedesktop.systemd1.Manager.StartTransientUnit", name, mode, properties, make([]PropertyCollection, 0))
}
// KillUnit takes the unit name and a UNIX signal number to send. All of the unit's
// processes are killed.
func (c *Conn) KillUnit(name string, signal int32) {
c.sysobj.Call("org.freedesktop.systemd1.Manager.KillUnit", 0, name, "all", signal).Store()
}
// ResetFailedUnit resets the "failed" state of a specific unit.
func (c *Conn) ResetFailedUnit(name string) error {
return c.sysobj.Call("org.freedesktop.systemd1.Manager.ResetFailedUnit", 0, name).Store()
}
// getProperties takes the unit name and returns all of its dbus object properties, for the given dbus interface
func (c *Conn) getProperties(unit string, dbusInterface string) (map[string]interface{}, error) {
var err error
var props map[string]dbus.Variant
path := unitPath(unit)
if !path.IsValid() {
return nil, errors.New("invalid unit name: " + unit)
}
obj := c.sysconn.Object("org.freedesktop.systemd1", path)
err = obj.Call("org.freedesktop.DBus.Properties.GetAll", 0, dbusInterface).Store(&props)
if err != nil {
return nil, err
}
out := make(map[string]interface{}, len(props))
for k, v := range props {
out[k] = v.Value()
}
return out, nil
}
// GetUnitProperties takes the unit name and returns all of its dbus object properties.
func (c *Conn) GetUnitProperties(unit string) (map[string]interface{}, error) {
return c.getProperties(unit, "org.freedesktop.systemd1.Unit")
}
func (c *Conn) getProperty(unit string, dbusInterface string, propertyName string) (*Property, error) {
var err error
var prop dbus.Variant
path := unitPath(unit)
if !path.IsValid() {
return nil, errors.New("invalid unit name: " + unit)
}
obj := c.sysconn.Object("org.freedesktop.systemd1", path)
err = obj.Call("org.freedesktop.DBus.Properties.Get", 0, dbusInterface, propertyName).Store(&prop)
if err != nil {
return nil, err
}
return &Property{Name: propertyName, Value: prop}, nil
}
func (c *Conn) GetUnitProperty(unit string, propertyName string) (*Property, error) {
return c.getProperty(unit, "org.freedesktop.systemd1.Unit", propertyName)
}
// GetServiceProperty returns property for given service name and property name
func (c *Conn) GetServiceProperty(service string, propertyName string) (*Property, error) {
return c.getProperty(service, "org.freedesktop.systemd1.Service", propertyName)
}
// GetUnitTypeProperties returns the extra properties for a unit, specific to the unit type.
// Valid values for unitType: Service, Socket, Target, Device, Mount, Automount, Snapshot, Timer, Swap, Path, Slice, Scope
// return "dbus.Error: Unknown interface" if the unitType is not the correct type of the unit
func (c *Conn) GetUnitTypeProperties(unit string, unitType string) (map[string]interface{}, error) {
return c.getProperties(unit, "org.freedesktop.systemd1."+unitType)
}
// SetUnitProperties() may be used to modify certain unit properties at runtime.
// Not all properties may be changed at runtime, but many resource management
// settings (primarily those in systemd.cgroup(5)) may. The changes are applied
// instantly, and stored on disk for future boots, unless runtime is true, in which
// case the settings only apply until the next reboot. name is the name of the unit
// to modify. properties are the settings to set, encoded as an array of property
// name and value pairs.
func (c *Conn) SetUnitProperties(name string, runtime bool, properties ...Property) error {
return c.sysobj.Call("org.freedesktop.systemd1.Manager.SetUnitProperties", 0, name, runtime, properties).Store()
}
func (c *Conn) GetUnitTypeProperty(unit string, unitType string, propertyName string) (*Property, error) {
return c.getProperty(unit, "org.freedesktop.systemd1."+unitType, propertyName)
}
type UnitStatus struct {
Name string // The primary unit name as string
Description string // The human readable description string
LoadState string // The load state (i.e. whether the unit file has been loaded successfully)
ActiveState string // The active state (i.e. whether the unit is currently started or not)
SubState string // The sub state (a more fine-grained version of the active state that is specific to the unit type, which the active state is not)
Followed string // A unit that is being followed in its state by this unit, if there is any, otherwise the empty string.
Path dbus.ObjectPath // The unit object path
JobId uint32 // If there is a job queued for the job unit the numeric job id, 0 otherwise
JobType string // The job type as string
JobPath dbus.ObjectPath // The job object path
}
type storeFunc func(retvalues ...interface{}) error
func (c *Conn) listUnitsInternal(f storeFunc) ([]UnitStatus, error) {
result := make([][]interface{}, 0)
err := f(&result)
if err != nil {
return nil, err
}
resultInterface := make([]interface{}, len(result))
for i := range result {
resultInterface[i] = result[i]
}
status := make([]UnitStatus, len(result))
statusInterface := make([]interface{}, len(status))
for i := range status {
statusInterface[i] = &status[i]
}
err = dbus.Store(resultInterface, statusInterface...)
if err != nil {
return nil, err
}
return status, nil
}
// ListUnits returns an array with all currently loaded units. Note that
// units may be known by multiple names at the same time, and hence there might
// be more unit names loaded than actual units behind them.
func (c *Conn) ListUnits() ([]UnitStatus, error) {
return c.listUnitsInternal(c.sysobj.Call("org.freedesktop.systemd1.Manager.ListUnits", 0).Store)
}
// ListUnitsFiltered returns an array with units filtered by state.
// It takes a list of units' statuses to filter.
func (c *Conn) ListUnitsFiltered(states []string) ([]UnitStatus, error) {
return c.listUnitsInternal(c.sysobj.Call("org.freedesktop.systemd1.Manager.ListUnitsFiltered", 0, states).Store)
}
// ListUnitsByPatterns returns an array with units.
// It takes a list of units' statuses and names to filter.
// Note that units may be known by multiple names at the same time,
// and hence there might be more unit names loaded than actual units behind them.
func (c *Conn) ListUnitsByPatterns(states []string, patterns []string) ([]UnitStatus, error) {
return c.listUnitsInternal(c.sysobj.Call("org.freedesktop.systemd1.Manager.ListUnitsByPatterns", 0, states, patterns).Store)
}
// ListUnitsByNames returns an array with units. It takes a list of units'
// names and returns an UnitStatus array. Comparing to ListUnitsByPatterns
// method, this method returns statuses even for inactive or non-existing
// units. Input array should contain exact unit names, but not patterns.
func (c *Conn) ListUnitsByNames(units []string) ([]UnitStatus, error) {
return c.listUnitsInternal(c.sysobj.Call("org.freedesktop.systemd1.Manager.ListUnitsByNames", 0, units).Store)
}
type UnitFile struct {
Path string
Type string
}
func (c *Conn) listUnitFilesInternal(f storeFunc) ([]UnitFile, error) {
result := make([][]interface{}, 0)
err := f(&result)
if err != nil {
return nil, err
}
resultInterface := make([]interface{}, len(result))
for i := range result {
resultInterface[i] = result[i]
}
files := make([]UnitFile, len(result))
fileInterface := make([]interface{}, len(files))
for i := range files {
fileInterface[i] = &files[i]
}
err = dbus.Store(resultInterface, fileInterface...)
if err != nil {
return nil, err
}
return files, nil
}
// ListUnitFiles returns an array of all available units on disk.
func (c *Conn) ListUnitFiles() ([]UnitFile, error) {
return c.listUnitFilesInternal(c.sysobj.Call("org.freedesktop.systemd1.Manager.ListUnitFiles", 0).Store)
}
// ListUnitFilesByPatterns returns an array of all available units on disk matched the patterns.
func (c *Conn) ListUnitFilesByPatterns(states []string, patterns []string) ([]UnitFile, error) {
return c.listUnitFilesInternal(c.sysobj.Call("org.freedesktop.systemd1.Manager.ListUnitFilesByPatterns", 0, states, patterns).Store)
}
type LinkUnitFileChange EnableUnitFileChange
// LinkUnitFiles() links unit files (that are located outside of the
// usual unit search paths) into the unit search path.
//
// It takes a list of absolute paths to unit files to link and two
// booleans. The first boolean controls whether the unit shall be
// enabled for runtime only (true, /run), or persistently (false,
// /etc).
// The second controls whether symlinks pointing to other units shall
// be replaced if necessary.
//
// This call returns a list of the changes made. The list consists of
// structures with three strings: the type of the change (one of symlink
// or unlink), the file name of the symlink and the destination of the
// symlink.
func (c *Conn) LinkUnitFiles(files []string, runtime bool, force bool) ([]LinkUnitFileChange, error) {
result := make([][]interface{}, 0)
err := c.sysobj.Call("org.freedesktop.systemd1.Manager.LinkUnitFiles", 0, files, runtime, force).Store(&result)
if err != nil {
return nil, err
}
resultInterface := make([]interface{}, len(result))
for i := range result {
resultInterface[i] = result[i]
}
changes := make([]LinkUnitFileChange, len(result))
changesInterface := make([]interface{}, len(changes))
for i := range changes {
changesInterface[i] = &changes[i]
}
err = dbus.Store(resultInterface, changesInterface...)
if err != nil {
return nil, err
}
return changes, nil
}
// EnableUnitFiles() may be used to enable one or more units in the system (by
// creating symlinks to them in /etc or /run).
//
// It takes a list of unit files to enable (either just file names or full
// absolute paths if the unit files are residing outside the usual unit
// search paths), and two booleans: the first controls whether the unit shall
// be enabled for runtime only (true, /run), or persistently (false, /etc).
// The second one controls whether symlinks pointing to other units shall
// be replaced if necessary.
//
// This call returns one boolean and an array with the changes made. The
// boolean signals whether the unit files contained any enablement
// information (i.e. an [Install]) section. The changes list consists of
// structures with three strings: the type of the change (one of symlink
// or unlink), the file name of the symlink and the destination of the
// symlink.
func (c *Conn) EnableUnitFiles(files []string, runtime bool, force bool) (bool, []EnableUnitFileChange, error) {
var carries_install_info bool
result := make([][]interface{}, 0)
err := c.sysobj.Call("org.freedesktop.systemd1.Manager.EnableUnitFiles", 0, files, runtime, force).Store(&carries_install_info, &result)
if err != nil {
return false, nil, err
}
resultInterface := make([]interface{}, len(result))
for i := range result {
resultInterface[i] = result[i]
}
changes := make([]EnableUnitFileChange, len(result))
changesInterface := make([]interface{}, len(changes))
for i := range changes {
changesInterface[i] = &changes[i]
}
err = dbus.Store(resultInterface, changesInterface...)
if err != nil {
return false, nil, err
}
return carries_install_info, changes, nil
}
type EnableUnitFileChange struct {
Type string // Type of the change (one of symlink or unlink)
Filename string // File name of the symlink
Destination string // Destination of the symlink
}
// DisableUnitFiles() may be used to disable one or more units in the system (by
// removing symlinks to them from /etc or /run).
//
// It takes a list of unit files to disable (either just file names or full
// absolute paths if the unit files are residing outside the usual unit
// search paths), and one boolean: whether the unit was enabled for runtime
// only (true, /run), or persistently (false, /etc).
//
// This call returns an array with the changes made. The changes list
// consists of structures with three strings: the type of the change (one of
// symlink or unlink), the file name of the symlink and the destination of the
// symlink.
func (c *Conn) DisableUnitFiles(files []string, runtime bool) ([]DisableUnitFileChange, error) {
result := make([][]interface{}, 0)
err := c.sysobj.Call("org.freedesktop.systemd1.Manager.DisableUnitFiles", 0, files, runtime).Store(&result)
if err != nil {
return nil, err
}
resultInterface := make([]interface{}, len(result))
for i := range result {
resultInterface[i] = result[i]
}
changes := make([]DisableUnitFileChange, len(result))
changesInterface := make([]interface{}, len(changes))
for i := range changes {
changesInterface[i] = &changes[i]
}
err = dbus.Store(resultInterface, changesInterface...)
if err != nil {
return nil, err
}
return changes, nil
}
type DisableUnitFileChange struct {
Type string // Type of the change (one of symlink or unlink)
Filename string // File name of the symlink
Destination string // Destination of the symlink
}
// MaskUnitFiles masks one or more units in the system
//
// It takes three arguments:
// * list of units to mask (either just file names or full
// absolute paths if the unit files are residing outside
// the usual unit search paths)
// * runtime to specify whether the unit was enabled for runtime
// only (true, /run/systemd/..), or persistently (false, /etc/systemd/..)
// * force flag
func (c *Conn) MaskUnitFiles(files []string, runtime bool, force bool) ([]MaskUnitFileChange, error) {
result := make([][]interface{}, 0)
err := c.sysobj.Call("org.freedesktop.systemd1.Manager.MaskUnitFiles", 0, files, runtime, force).Store(&result)
if err != nil {
return nil, err
}
resultInterface := make([]interface{}, len(result))
for i := range result {
resultInterface[i] = result[i]
}
changes := make([]MaskUnitFileChange, len(result))
changesInterface := make([]interface{}, len(changes))
for i := range changes {
changesInterface[i] = &changes[i]
}
err = dbus.Store(resultInterface, changesInterface...)
if err != nil {
return nil, err
}
return changes, nil
}
type MaskUnitFileChange struct {
Type string // Type of the change (one of symlink or unlink)
Filename string // File name of the symlink
Destination string // Destination of the symlink
}
// UnmaskUnitFiles unmasks one or more units in the system
//
// It takes two arguments:
// * list of unit files to mask (either just file names or full
// absolute paths if the unit files are residing outside
// the usual unit search paths)
// * runtime to specify whether the unit was enabled for runtime
// only (true, /run/systemd/..), or persistently (false, /etc/systemd/..)
func (c *Conn) UnmaskUnitFiles(files []string, runtime bool) ([]UnmaskUnitFileChange, error) {
result := make([][]interface{}, 0)
err := c.sysobj.Call("org.freedesktop.systemd1.Manager.UnmaskUnitFiles", 0, files, runtime).Store(&result)
if err != nil {
return nil, err
}
resultInterface := make([]interface{}, len(result))
for i := range result {
resultInterface[i] = result[i]
}
changes := make([]UnmaskUnitFileChange, len(result))
changesInterface := make([]interface{}, len(changes))
for i := range changes {
changesInterface[i] = &changes[i]
}
err = dbus.Store(resultInterface, changesInterface...)
if err != nil {
return nil, err
}
return changes, nil
}
type UnmaskUnitFileChange struct {
Type string // Type of the change (one of symlink or unlink)
Filename string // File name of the symlink
Destination string // Destination of the symlink
}
// Reload instructs systemd to scan for and reload unit files. This is
// equivalent to a 'systemctl daemon-reload'.
func (c *Conn) Reload() error {
return c.sysobj.Call("org.freedesktop.systemd1.Manager.Reload", 0).Store()
}
func unitPath(name string) dbus.ObjectPath {
return dbus.ObjectPath("/org/freedesktop/systemd1/unit/" + PathBusEscape(name))
}

View File

@ -1,996 +0,0 @@
// Copyright 2015 CoreOS, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package dbus
import (
"fmt"
"math/rand"
"os"
"os/exec"
"path"
"path/filepath"
"reflect"
"syscall"
"testing"
"time"
"github.com/godbus/dbus"
)
func setupConn(t *testing.T) *Conn {
conn, err := New()
if err != nil {
t.Fatal(err)
}
return conn
}
func findFixture(target string, t *testing.T) string {
abs, err := filepath.Abs("../fixtures/" + target)
if err != nil {
t.Fatal(err)
}
return abs
}
func setupUnit(target string, conn *Conn, t *testing.T) {
// Blindly stop the unit in case it is running
conn.StopUnit(target, "replace", nil)
// Blindly remove the symlink in case it exists
targetRun := filepath.Join("/run/systemd/system/", target)
os.Remove(targetRun)
}
func linkUnit(target string, conn *Conn, t *testing.T) {
abs := findFixture(target, t)
fixture := []string{abs}
changes, err := conn.LinkUnitFiles(fixture, true, true)
if err != nil {
t.Fatal(err)
}
if len(changes) < 1 {
t.Fatalf("Expected one change, got %v", changes)
}
runPath := filepath.Join("/run/systemd/system/", target)
if changes[0].Filename != runPath {
t.Fatal("Unexpected target filename")
}
}
func getUnitStatus(units []UnitStatus, name string) *UnitStatus {
for _, u := range units {
if u.Name == name {
return &u
}
}
return nil
}
func getUnitFile(units []UnitFile, name string) *UnitFile {
for _, u := range units {
if path.Base(u.Path) == name {
return &u
}
}
return nil
}
// Ensure that basic unit starting and stopping works.
func TestStartStopUnit(t *testing.T) {
target := "start-stop.service"
conn := setupConn(t)
setupUnit(target, conn, t)
linkUnit(target, conn, t)
// 2. Start the unit
reschan := make(chan string)
_, err := conn.StartUnit(target, "replace", reschan)
if err != nil {
t.Fatal(err)
}
job := <-reschan
if job != "done" {
t.Fatal("Job is not done:", job)
}
units, err := conn.ListUnits()
if err != nil {
t.Fatal(err)
}
unit := getUnitStatus(units, target)
if unit == nil {
t.Fatalf("Test unit not found in list")
} else if unit.ActiveState != "active" {
t.Fatalf("Test unit not active")
}
// 3. Stop the unit
_, err = conn.StopUnit(target, "replace", reschan)
if err != nil {
t.Fatal(err)
}
// wait for StopUnit job to complete
<-reschan
units, err = conn.ListUnits()
if err != nil {
t.Fatal(err)
}
unit = getUnitStatus(units, target)
if unit != nil {
t.Fatalf("Test unit found in list, should be stopped")
}
}
// Ensure that basic unit restarting works.
func TestRestartUnit(t *testing.T) {
target := "start-stop.service"
conn := setupConn(t)
setupUnit(target, conn, t)
linkUnit(target, conn, t)
// Start the unit
reschan := make(chan string)
_, err := conn.StartUnit(target, "replace", reschan)
if err != nil {
t.Fatal(err)
}
job := <-reschan
if job != "done" {
t.Fatal("Job is not done:", job)
}
units, err := conn.ListUnits()
if err != nil {
t.Fatal(err)
}
unit := getUnitStatus(units, target)
if unit == nil {
t.Fatalf("Test unit not found in list")
} else if unit.ActiveState != "active" {
t.Fatalf("Test unit not active")
}
// Restart the unit
reschan = make(chan string)
_, err = conn.RestartUnit(target, "replace", reschan)
if err != nil {
t.Fatal(err)
}
job = <-reschan
if job != "done" {
t.Fatal("Job is not done:", job)
}
// Stop the unit
_, err = conn.StopUnit(target, "replace", reschan)
if err != nil {
t.Fatal(err)
}
// wait for StopUnit job to complete
<-reschan
units, err = conn.ListUnits()
if err != nil {
t.Fatal(err)
}
unit = getUnitStatus(units, target)
if unit != nil {
t.Fatalf("Test unit found in list, should be stopped")
}
// Try to restart the unit.
// It should still succeed, even if the unit is inactive.
reschan = make(chan string)
_, err = conn.TryRestartUnit(target, "replace", reschan)
if err != nil {
t.Fatal(err)
}
// wait for StopUnit job to complete
<-reschan
units, err = conn.ListUnits()
if err != nil {
t.Fatal(err)
}
unit = getUnitStatus(units, target)
if unit != nil {
t.Fatalf("Test unit found in list, should be stopped")
}
}
// Ensure that basic unit reloading works.
func TestReloadUnit(t *testing.T) {
target := "reload.service"
conn := setupConn(t)
err := conn.Subscribe()
if err != nil {
t.Fatal(err)
}
subSet := conn.NewSubscriptionSet()
evChan, errChan := subSet.Subscribe()
subSet.Add(target)
setupUnit(target, conn, t)
linkUnit(target, conn, t)
// Start the unit
reschan := make(chan string)
_, err = conn.StartUnit(target, "replace", reschan)
if err != nil {
t.Fatal(err)
}
job := <-reschan
if job != "done" {
t.Fatal("Job is not done:", job)
}
units, err := conn.ListUnits()
if err != nil {
t.Fatal(err)
}
unit := getUnitStatus(units, target)
if unit == nil {
t.Fatalf("Test unit not found in list")
} else if unit.ActiveState != "active" {
t.Fatalf("Test unit not active")
}
// Reload the unit
reschan = make(chan string)
_, err = conn.ReloadUnit(target, "replace", reschan)
if err != nil {
t.Fatal(err)
}
job = <-reschan
if job != "done" {
t.Fatal("Job is not done:", job)
}
timeout := make(chan bool, 1)
go func() {
time.Sleep(3 * time.Second)
close(timeout)
}()
// Wait for the event, expecting the target UnitStatus meets all of the
// following conditions:
// * target is non-nil
// * target's ActiveState is active.
waitevent:
for {
select {
case changes := <-evChan:
tch, ok := changes[target]
if !ok {
continue waitevent
}
if tch != nil && tch.Name == target && tch.ActiveState == "active" {
break waitevent
}
case err = <-errChan:
t.Fatal(err)
case <-timeout:
t.Fatal("Reached timeout")
}
}
}
// Ensure that basic unit reload-or-restarting works.
func TestReloadOrRestartUnit(t *testing.T) {
target := "reload.service"
conn := setupConn(t)
setupUnit(target, conn, t)
linkUnit(target, conn, t)
// Start the unit
reschan := make(chan string)
_, err := conn.StartUnit(target, "replace", reschan)
if err != nil {
t.Fatal(err)
}
job := <-reschan
if job != "done" {
t.Fatal("Job is not done:", job)
}
units, err := conn.ListUnits()
if err != nil {
t.Fatal(err)
}
unit := getUnitStatus(units, target)
if unit == nil {
t.Fatalf("Test unit not found in list")
} else if unit.ActiveState != "active" {
t.Fatalf("Test unit not active")
}
// Reload or restart the unit
reschan = make(chan string)
_, err = conn.ReloadOrRestartUnit(target, "replace", reschan)
if err != nil {
t.Fatal(err)
}
job = <-reschan
if job != "done" {
t.Fatal("Job is not done:", job)
}
// Stop the unit
_, err = conn.StopUnit(target, "replace", reschan)
if err != nil {
t.Fatal(err)
}
// wait for StopUnit job to complete
<-reschan
units, err = conn.ListUnits()
if err != nil {
t.Fatal(err)
}
unit = getUnitStatus(units, target)
if unit != nil && unit.ActiveState == "active" {
t.Fatalf("Test unit still active, should be inactive.")
}
// Reload or try to restart the unit
// It should still succeed, even if the unit is inactive.
reschan = make(chan string)
_, err = conn.ReloadOrTryRestartUnit(target, "replace", reschan)
if err != nil {
t.Fatal(err)
}
job = <-reschan
if job != "done" {
t.Fatal("Job is not done:", job)
}
}
// Ensure that ListUnitsByNames works.
func TestListUnitsByNames(t *testing.T) {
target1 := "systemd-journald.service"
target2 := "unexisting.service"
conn := setupConn(t)
units, err := conn.ListUnitsByNames([]string{target1, target2})
if err != nil {
t.Skip(err)
}
unit := getUnitStatus(units, target1)
if unit == nil {
t.Fatalf("%s unit not found in list", target1)
} else if unit.ActiveState != "active" {
t.Fatalf("%s unit should be active but it is %s", target1, unit.ActiveState)
}
unit = getUnitStatus(units, target2)
if unit == nil {
t.Fatalf("Unexisting test unit not found in list")
} else if unit.ActiveState != "inactive" {
t.Fatalf("Test unit should be inactive")
}
}
// Ensure that ListUnitsByPatterns works.
func TestListUnitsByPatterns(t *testing.T) {
target1 := "systemd-journald.service"
target2 := "unexisting.service"
conn := setupConn(t)
units, err := conn.ListUnitsByPatterns([]string{}, []string{"systemd-journald*", target2})
if err != nil {
t.Skip(err)
}
unit := getUnitStatus(units, target1)
if unit == nil {
t.Fatalf("%s unit not found in list", target1)
} else if unit.ActiveState != "active" {
t.Fatalf("Test unit should be active")
}
unit = getUnitStatus(units, target2)
if unit != nil {
t.Fatalf("Unexisting test unit found in list")
}
}
// Ensure that ListUnitsFiltered works.
func TestListUnitsFiltered(t *testing.T) {
target := "systemd-journald.service"
conn := setupConn(t)
units, err := conn.ListUnitsFiltered([]string{"active"})
if err != nil {
t.Fatal(err)
}
unit := getUnitStatus(units, target)
if unit == nil {
t.Fatalf("%s unit not found in list", target)
} else if unit.ActiveState != "active" {
t.Fatalf("Test unit should be active")
}
units, err = conn.ListUnitsFiltered([]string{"inactive"})
if err != nil {
t.Fatal(err)
}
unit = getUnitStatus(units, target)
if unit != nil {
t.Fatalf("Inactive unit should not be found in list")
}
}
// Ensure that ListUnitFilesByPatterns works.
func TestListUnitFilesByPatterns(t *testing.T) {
target1 := "systemd-journald.service"
target2 := "exit.target"
conn := setupConn(t)
units, err := conn.ListUnitFilesByPatterns([]string{"static"}, []string{"systemd-journald*", target2})
if err != nil {
t.Skip(err)
}
unit := getUnitFile(units, target1)
if unit == nil {
t.Fatalf("%s unit not found in list", target1)
} else if unit.Type != "static" {
t.Fatalf("Test unit file should be static")
}
units, err = conn.ListUnitFilesByPatterns([]string{"disabled"}, []string{"systemd-journald*", target2})
if err != nil {
t.Fatal(err)
}
unit = getUnitFile(units, target2)
if unit == nil {
t.Fatalf("%s unit not found in list", target2)
} else if unit.Type != "disabled" {
t.Fatalf("%s unit file should be disabled", target2)
}
}
func TestListUnitFiles(t *testing.T) {
target1 := "systemd-journald.service"
target2 := "exit.target"
conn := setupConn(t)
units, err := conn.ListUnitFiles()
if err != nil {
t.Fatal(err)
}
unit := getUnitFile(units, target1)
if unit == nil {
t.Fatalf("%s unit not found in list", target1)
} else if unit.Type != "static" {
t.Fatalf("Test unit file should be static")
}
unit = getUnitFile(units, target2)
if unit == nil {
t.Fatalf("%s unit not found in list", target2)
} else if unit.Type != "disabled" {
t.Fatalf("%s unit file should be disabled", target2)
}
}
// Enables a unit and then immediately tears it down
func TestEnableDisableUnit(t *testing.T) {
target := "enable-disable.service"
conn := setupConn(t)
setupUnit(target, conn, t)
abs := findFixture(target, t)
runPath := filepath.Join("/run/systemd/system/", target)
// 1. Enable the unit
install, changes, err := conn.EnableUnitFiles([]string{abs}, true, true)
if err != nil {
t.Fatal(err)
}
if install != false {
t.Log("Install was true")
}
if len(changes) < 1 {
t.Fatalf("Expected one change, got %v", changes)
}
if changes[0].Filename != runPath {
t.Fatal("Unexpected target filename")
}
// 2. Disable the unit
dChanges, err := conn.DisableUnitFiles([]string{target}, true)
if err != nil {
t.Fatal(err)
}
if len(dChanges) != 1 {
t.Fatalf("Changes should include the path, %v", dChanges)
}
if dChanges[0].Filename != runPath {
t.Fatalf("Change should include correct filename, %+v", dChanges[0])
}
if dChanges[0].Destination != "" {
t.Fatalf("Change destination should be empty, %+v", dChanges[0])
}
}
// TestGetUnitProperties reads the `-.mount` which should exist on all systemd
// systems and ensures that one of its properties is valid.
func TestGetUnitProperties(t *testing.T) {
conn := setupConn(t)
unit := "-.mount"
info, err := conn.GetUnitProperties(unit)
if err != nil {
t.Fatal(err)
}
desc, _ := info["Description"].(string)
prop, err := conn.GetUnitProperty(unit, "Description")
if err != nil {
t.Fatal(err)
}
if prop.Name != "Description" {
t.Fatal("unexpected property name")
}
val := prop.Value.Value().(string)
if !reflect.DeepEqual(val, desc) {
t.Fatal("unexpected property value")
}
}
// TestGetUnitPropertiesRejectsInvalidName attempts to get the properties for a
// unit with an invalid name. This test should be run with --test.timeout set,
// as a fail will manifest as GetUnitProperties hanging indefinitely.
func TestGetUnitPropertiesRejectsInvalidName(t *testing.T) {
conn := setupConn(t)
unit := "//invalid#$^/"
_, err := conn.GetUnitProperties(unit)
if err == nil {
t.Fatal("Expected an error, got nil")
}
_, err = conn.GetUnitProperty(unit, "Wants")
if err == nil {
t.Fatal("Expected an error, got nil")
}
}
// TestGetServiceProperty reads the `systemd-udevd.service` which should exist
// on all systemd systems and ensures that one of its property is valid.
func TestGetServiceProperty(t *testing.T) {
conn := setupConn(t)
service := "systemd-udevd.service"
prop, err := conn.GetServiceProperty(service, "Type")
if err != nil {
t.Fatal(err)
}
if prop.Name != "Type" {
t.Fatal("unexpected property name")
}
if _, ok := prop.Value.Value().(string); !ok {
t.Fatal("invalid property value")
}
}
// TestSetUnitProperties changes a cgroup setting on the `-.mount`
// which should exist on all systemd systems and ensures that the
// property was set.
func TestSetUnitProperties(t *testing.T) {
conn := setupConn(t)
unit := "-.mount"
if err := conn.SetUnitProperties(unit, true, Property{"CPUShares", dbus.MakeVariant(uint64(1023))}); err != nil {
t.Fatal(err)
}
info, err := conn.GetUnitTypeProperties(unit, "Mount")
if err != nil {
t.Fatal(err)
}
value, _ := info["CPUShares"].(uint64)
if value != 1023 {
t.Fatal("CPUShares of unit is not 1023:", value)
}
}
// Ensure that basic transient unit starting and stopping works.
func TestStartStopTransientUnit(t *testing.T) {
conn := setupConn(t)
props := []Property{
PropExecStart([]string{"/bin/sleep", "400"}, false),
}
target := fmt.Sprintf("testing-transient-%d.service", rand.Int())
// Start the unit
reschan := make(chan string)
_, err := conn.StartTransientUnit(target, "replace", props, reschan)
if err != nil {
t.Fatal(err)
}
job := <-reschan
if job != "done" {
t.Fatal("Job is not done:", job)
}
units, err := conn.ListUnits()
if err != nil {
t.Fatal(err)
}
unit := getUnitStatus(units, target)
if unit == nil {
t.Fatalf("Test unit not found in list")
} else if unit.ActiveState != "active" {
t.Fatalf("Test unit not active")
}
// 3. Stop the unit
_, err = conn.StopUnit(target, "replace", reschan)
if err != nil {
t.Fatal(err)
}
// wait for StopUnit job to complete
<-reschan
units, err = conn.ListUnits()
if err != nil {
t.Fatal(err)
}
unit = getUnitStatus(units, target)
if unit != nil {
t.Fatalf("Test unit found in list, should be stopped")
}
}
// Ensure that putting running programs into scopes works
func TestStartStopTransientScope(t *testing.T) {
conn := setupConn(t)
cmd := exec.Command("/bin/sleep", "400")
err := cmd.Start()
if err != nil {
t.Fatal(err)
}
defer cmd.Process.Kill()
props := []Property{
PropPids(uint32(cmd.Process.Pid)),
}
target := fmt.Sprintf("testing-transient-%d.scope", cmd.Process.Pid)
// Start the unit
reschan := make(chan string)
_, err = conn.StartTransientUnit(target, "replace", props, reschan)
if err != nil {
t.Fatal(err)
}
job := <-reschan
if job != "done" {
t.Fatal("Job is not done:", job)
}
units, err := conn.ListUnits()
if err != nil {
t.Fatal(err)
}
unit := getUnitStatus(units, target)
if unit == nil {
t.Fatalf("Test unit not found in list")
} else if unit.ActiveState != "active" {
t.Fatalf("Test unit not active")
}
// maybe check if pid is really a member of the just created scope
// systemd uses the following api which does not use dbus, but directly
// accesses procfs for cgroup information.
// int sd_pid_get_unit(pid_t pid, char **session)
}
// Ensure that basic unit gets killed by SIGTERM
func TestKillUnit(t *testing.T) {
target := "start-stop.service"
conn := setupConn(t)
err := conn.Subscribe()
if err != nil {
t.Fatal(err)
}
subSet := conn.NewSubscriptionSet()
evChan, errChan := subSet.Subscribe()
subSet.Add(target)
setupUnit(target, conn, t)
linkUnit(target, conn, t)
// Start the unit
reschan := make(chan string)
_, err = conn.StartUnit(target, "replace", reschan)
if err != nil {
t.Fatal(err)
}
job := <-reschan
if job != "done" {
t.Fatal("Job is not done:", job)
}
// send SIGTERM
conn.KillUnit(target, int32(syscall.SIGTERM))
timeout := make(chan bool, 1)
go func() {
time.Sleep(3 * time.Second)
close(timeout)
}()
// Wait for the event, expecting the target UnitStatus meets one of the
// following conditions:
// * target is nil, meaning the unit has completely gone.
// * target is non-nil, and its ActiveState is not active.
waitevent:
for {
select {
case changes := <-evChan:
tch, ok := changes[target]
if !ok {
continue waitevent
}
if tch == nil || (tch != nil && tch.Name == target && tch.ActiveState != "active") {
break waitevent
}
case err = <-errChan:
t.Fatal(err)
case <-timeout:
t.Fatal("Reached timeout")
}
}
}
// Ensure that a failed unit gets reset
func TestResetFailedUnit(t *testing.T) {
target := "start-failed.service"
conn := setupConn(t)
setupUnit(target, conn, t)
linkUnit(target, conn, t)
// Start the unit
reschan := make(chan string)
_, err := conn.StartUnit(target, "replace", reschan)
if err != nil {
t.Fatal(err)
}
job := <-reschan
if job != "failed" {
t.Fatal("Job is not failed:", job)
}
units, err := conn.ListUnits()
if err != nil {
t.Fatal(err)
}
unit := getUnitStatus(units, target)
if unit == nil {
t.Fatalf("Test unit not found in list")
}
// reset the failed unit
err = conn.ResetFailedUnit(target)
if err != nil {
t.Fatal(err)
}
// Ensure that the target unit is actually gone
units, err = conn.ListUnits()
if err != nil {
t.Fatal(err)
}
found := false
for _, u := range units {
if u.Name == target {
found = true
break
}
}
if found {
t.Fatalf("Test unit still found in list. units = %v", units)
}
}
func TestConnJobListener(t *testing.T) {
target := "start-stop.service"
conn := setupConn(t)
setupUnit(target, conn, t)
linkUnit(target, conn, t)
jobSize := len(conn.jobListener.jobs)
reschan := make(chan string)
_, err := conn.StartUnit(target, "replace", reschan)
if err != nil {
t.Fatal(err)
}
<-reschan
_, err = conn.StopUnit(target, "replace", reschan)
if err != nil {
t.Fatal(err)
}
<-reschan
currentJobSize := len(conn.jobListener.jobs)
if jobSize != currentJobSize {
t.Fatal("JobListener jobs leaked")
}
}
// Enables a unit and then masks/unmasks it
func TestMaskUnmask(t *testing.T) {
target := "mask-unmask.service"
conn := setupConn(t)
setupUnit(target, conn, t)
abs := findFixture(target, t)
runPath := filepath.Join("/run/systemd/system/", target)
// 1. Enable the unit
install, changes, err := conn.EnableUnitFiles([]string{abs}, true, true)
if err != nil {
t.Fatal(err)
}
if install != false {
t.Log("Install was true")
}
if len(changes) < 1 {
t.Fatalf("Expected one change, got %v", changes)
}
if changes[0].Filename != runPath {
t.Fatal("Unexpected target filename")
}
// 2. Mask the unit
mChanges, err := conn.MaskUnitFiles([]string{target}, true, true)
if err != nil {
t.Fatal(err)
}
if mChanges[0].Filename != runPath {
t.Fatalf("Change should include correct filename, %+v", mChanges[0])
}
if mChanges[0].Destination != "" {
t.Fatalf("Change destination should be empty, %+v", mChanges[0])
}
// 3. Unmask the unit
uChanges, err := conn.UnmaskUnitFiles([]string{target}, true)
if err != nil {
t.Fatal(err)
}
if uChanges[0].Filename != runPath {
t.Fatalf("Change should include correct filename, %+v", uChanges[0])
}
if uChanges[0].Destination != "" {
t.Fatalf("Change destination should be empty, %+v", uChanges[0])
}
}
// Test a global Reload
func TestReload(t *testing.T) {
conn := setupConn(t)
err := conn.Reload()
if err != nil {
t.Fatal(err)
}
}

View File

@ -1,237 +0,0 @@
// Copyright 2015 CoreOS, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package dbus
import (
"github.com/godbus/dbus"
)
// From the systemd docs:
//
// The properties array of StartTransientUnit() may take many of the settings
// that may also be configured in unit files. Not all parameters are currently
// accepted though, but we plan to cover more properties with future release.
// Currently you may set the Description, Slice and all dependency types of
// units, as well as RemainAfterExit, ExecStart for service units,
// TimeoutStopUSec and PIDs for scope units, and CPUAccounting, CPUShares,
// BlockIOAccounting, BlockIOWeight, BlockIOReadBandwidth,
// BlockIOWriteBandwidth, BlockIODeviceWeight, MemoryAccounting, MemoryLimit,
// DevicePolicy, DeviceAllow for services/scopes/slices. These fields map
// directly to their counterparts in unit files and as normal D-Bus object
// properties. The exception here is the PIDs field of scope units which is
// used for construction of the scope only and specifies the initial PIDs to
// add to the scope object.
type Property struct {
Name string
Value dbus.Variant
}
type PropertyCollection struct {
Name string
Properties []Property
}
type execStart struct {
Path string // the binary path to execute
Args []string // an array with all arguments to pass to the executed command, starting with argument 0
UncleanIsFailure bool // a boolean whether it should be considered a failure if the process exits uncleanly
}
// PropExecStart sets the ExecStart service property. The first argument is a
// slice with the binary path to execute followed by the arguments to pass to
// the executed command. See
// http://www.freedesktop.org/software/systemd/man/systemd.service.html#ExecStart=
func PropExecStart(command []string, uncleanIsFailure bool) Property {
execStarts := []execStart{
execStart{
Path: command[0],
Args: command,
UncleanIsFailure: uncleanIsFailure,
},
}
return Property{
Name: "ExecStart",
Value: dbus.MakeVariant(execStarts),
}
}
// PropRemainAfterExit sets the RemainAfterExit service property. See
// http://www.freedesktop.org/software/systemd/man/systemd.service.html#RemainAfterExit=
func PropRemainAfterExit(b bool) Property {
return Property{
Name: "RemainAfterExit",
Value: dbus.MakeVariant(b),
}
}
// PropType sets the Type service property. See
// http://www.freedesktop.org/software/systemd/man/systemd.service.html#Type=
func PropType(t string) Property {
return Property{
Name: "Type",
Value: dbus.MakeVariant(t),
}
}
// PropDescription sets the Description unit property. See
// http://www.freedesktop.org/software/systemd/man/systemd.unit#Description=
func PropDescription(desc string) Property {
return Property{
Name: "Description",
Value: dbus.MakeVariant(desc),
}
}
func propDependency(name string, units []string) Property {
return Property{
Name: name,
Value: dbus.MakeVariant(units),
}
}
// PropRequires sets the Requires unit property. See
// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#Requires=
func PropRequires(units ...string) Property {
return propDependency("Requires", units)
}
// PropRequiresOverridable sets the RequiresOverridable unit property. See
// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#RequiresOverridable=
func PropRequiresOverridable(units ...string) Property {
return propDependency("RequiresOverridable", units)
}
// PropRequisite sets the Requisite unit property. See
// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#Requisite=
func PropRequisite(units ...string) Property {
return propDependency("Requisite", units)
}
// PropRequisiteOverridable sets the RequisiteOverridable unit property. See
// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#RequisiteOverridable=
func PropRequisiteOverridable(units ...string) Property {
return propDependency("RequisiteOverridable", units)
}
// PropWants sets the Wants unit property. See
// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#Wants=
func PropWants(units ...string) Property {
return propDependency("Wants", units)
}
// PropBindsTo sets the BindsTo unit property. See
// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#BindsTo=
func PropBindsTo(units ...string) Property {
return propDependency("BindsTo", units)
}
// PropRequiredBy sets the RequiredBy unit property. See
// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#RequiredBy=
func PropRequiredBy(units ...string) Property {
return propDependency("RequiredBy", units)
}
// PropRequiredByOverridable sets the RequiredByOverridable unit property. See
// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#RequiredByOverridable=
func PropRequiredByOverridable(units ...string) Property {
return propDependency("RequiredByOverridable", units)
}
// PropWantedBy sets the WantedBy unit property. See
// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#WantedBy=
func PropWantedBy(units ...string) Property {
return propDependency("WantedBy", units)
}
// PropBoundBy sets the BoundBy unit property. See
// http://www.freedesktop.org/software/systemd/main/systemd.unit.html#BoundBy=
func PropBoundBy(units ...string) Property {
return propDependency("BoundBy", units)
}
// PropConflicts sets the Conflicts unit property. See
// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#Conflicts=
func PropConflicts(units ...string) Property {
return propDependency("Conflicts", units)
}
// PropConflictedBy sets the ConflictedBy unit property. See
// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#ConflictedBy=
func PropConflictedBy(units ...string) Property {
return propDependency("ConflictedBy", units)
}
// PropBefore sets the Before unit property. See
// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#Before=
func PropBefore(units ...string) Property {
return propDependency("Before", units)
}
// PropAfter sets the After unit property. See
// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#After=
func PropAfter(units ...string) Property {
return propDependency("After", units)
}
// PropOnFailure sets the OnFailure unit property. See
// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#OnFailure=
func PropOnFailure(units ...string) Property {
return propDependency("OnFailure", units)
}
// PropTriggers sets the Triggers unit property. See
// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#Triggers=
func PropTriggers(units ...string) Property {
return propDependency("Triggers", units)
}
// PropTriggeredBy sets the TriggeredBy unit property. See
// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#TriggeredBy=
func PropTriggeredBy(units ...string) Property {
return propDependency("TriggeredBy", units)
}
// PropPropagatesReloadTo sets the PropagatesReloadTo unit property. See
// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#PropagatesReloadTo=
func PropPropagatesReloadTo(units ...string) Property {
return propDependency("PropagatesReloadTo", units)
}
// PropRequiresMountsFor sets the RequiresMountsFor unit property. See
// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#RequiresMountsFor=
func PropRequiresMountsFor(units ...string) Property {
return propDependency("RequiresMountsFor", units)
}
// PropSlice sets the Slice unit property. See
// http://www.freedesktop.org/software/systemd/man/systemd.resource-control.html#Slice=
func PropSlice(slice string) Property {
return Property{
Name: "Slice",
Value: dbus.MakeVariant(slice),
}
}
// PropPids sets the PIDs field of scope units used in the initial construction
// of the scope only and specifies the initial PIDs to add to the scope object.
// See https://www.freedesktop.org/wiki/Software/systemd/ControlGroupInterface/#properties
func PropPids(pids ...uint32) Property {
return Property{
Name: "PIDs",
Value: dbus.MakeVariant(pids),
}
}

View File

@ -1,47 +0,0 @@
// Copyright 2015 CoreOS, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package dbus
type set struct {
data map[string]bool
}
func (s *set) Add(value string) {
s.data[value] = true
}
func (s *set) Remove(value string) {
delete(s.data, value)
}
func (s *set) Contains(value string) (exists bool) {
_, exists = s.data[value]
return
}
func (s *set) Length() int {
return len(s.data)
}
func (s *set) Values() (values []string) {
for val, _ := range s.data {
values = append(values, val)
}
return
}
func newSet() *set {
return &set{make(map[string]bool)}
}

View File

@ -1,53 +0,0 @@
// Copyright 2015 CoreOS, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package dbus
import (
"testing"
)
// TestBasicSetActions asserts that Add & Remove behavior is correct
func TestBasicSetActions(t *testing.T) {
s := newSet()
if s.Contains("foo") {
t.Fatal("set should not contain 'foo'")
}
s.Add("foo")
if !s.Contains("foo") {
t.Fatal("set should contain 'foo'")
}
v := s.Values()
if len(v) != 1 {
t.Fatal("set.Values did not report correct number of values")
}
if v[0] != "foo" {
t.Fatal("set.Values did not report value")
}
s.Remove("foo")
if s.Contains("foo") {
t.Fatal("set should not contain 'foo'")
}
v = s.Values()
if len(v) != 0 {
t.Fatal("set.Values did not report correct number of values")
}
}

View File

@ -1,250 +0,0 @@
// Copyright 2015 CoreOS, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package dbus
import (
"errors"
"time"
"github.com/godbus/dbus"
)
const (
cleanIgnoreInterval = int64(10 * time.Second)
ignoreInterval = int64(30 * time.Millisecond)
)
// Subscribe sets up this connection to subscribe to all systemd dbus events.
// This is required before calling SubscribeUnits. When the connection closes
// systemd will automatically stop sending signals so there is no need to
// explicitly call Unsubscribe().
func (c *Conn) Subscribe() error {
c.sigconn.BusObject().Call("org.freedesktop.DBus.AddMatch", 0,
"type='signal',interface='org.freedesktop.systemd1.Manager',member='UnitNew'")
c.sigconn.BusObject().Call("org.freedesktop.DBus.AddMatch", 0,
"type='signal',interface='org.freedesktop.DBus.Properties',member='PropertiesChanged'")
err := c.sigobj.Call("org.freedesktop.systemd1.Manager.Subscribe", 0).Store()
if err != nil {
return err
}
return nil
}
// Unsubscribe this connection from systemd dbus events.
func (c *Conn) Unsubscribe() error {
err := c.sigobj.Call("org.freedesktop.systemd1.Manager.Unsubscribe", 0).Store()
if err != nil {
return err
}
return nil
}
func (c *Conn) dispatch() {
ch := make(chan *dbus.Signal, signalBuffer)
c.sigconn.Signal(ch)
go func() {
for {
signal, ok := <-ch
if !ok {
return
}
if signal.Name == "org.freedesktop.systemd1.Manager.JobRemoved" {
c.jobComplete(signal)
}
if c.subscriber.updateCh == nil {
continue
}
var unitPath dbus.ObjectPath
switch signal.Name {
case "org.freedesktop.systemd1.Manager.JobRemoved":
unitName := signal.Body[2].(string)
c.sysobj.Call("org.freedesktop.systemd1.Manager.GetUnit", 0, unitName).Store(&unitPath)
case "org.freedesktop.systemd1.Manager.UnitNew":
unitPath = signal.Body[1].(dbus.ObjectPath)
case "org.freedesktop.DBus.Properties.PropertiesChanged":
if signal.Body[0].(string) == "org.freedesktop.systemd1.Unit" {
unitPath = signal.Path
}
}
if unitPath == dbus.ObjectPath("") {
continue
}
c.sendSubStateUpdate(unitPath)
}
}()
}
// Returns two unbuffered channels which will receive all changed units every
// interval. Deleted units are sent as nil.
func (c *Conn) SubscribeUnits(interval time.Duration) (<-chan map[string]*UnitStatus, <-chan error) {
return c.SubscribeUnitsCustom(interval, 0, func(u1, u2 *UnitStatus) bool { return *u1 != *u2 }, nil)
}
// SubscribeUnitsCustom is like SubscribeUnits but lets you specify the buffer
// size of the channels, the comparison function for detecting changes and a filter
// function for cutting down on the noise that your channel receives.
func (c *Conn) SubscribeUnitsCustom(interval time.Duration, buffer int, isChanged func(*UnitStatus, *UnitStatus) bool, filterUnit func(string) bool) (<-chan map[string]*UnitStatus, <-chan error) {
old := make(map[string]*UnitStatus)
statusChan := make(chan map[string]*UnitStatus, buffer)
errChan := make(chan error, buffer)
go func() {
for {
timerChan := time.After(interval)
units, err := c.ListUnits()
if err == nil {
cur := make(map[string]*UnitStatus)
for i := range units {
if filterUnit != nil && filterUnit(units[i].Name) {
continue
}
cur[units[i].Name] = &units[i]
}
// add all new or changed units
changed := make(map[string]*UnitStatus)
for n, u := range cur {
if oldU, ok := old[n]; !ok || isChanged(oldU, u) {
changed[n] = u
}
delete(old, n)
}
// add all deleted units
for oldN := range old {
changed[oldN] = nil
}
old = cur
if len(changed) != 0 {
statusChan <- changed
}
} else {
errChan <- err
}
<-timerChan
}
}()
return statusChan, errChan
}
type SubStateUpdate struct {
UnitName string
SubState string
}
// SetSubStateSubscriber writes to updateCh when any unit's substate changes.
// Although this writes to updateCh on every state change, the reported state
// may be more recent than the change that generated it (due to an unavoidable
// race in the systemd dbus interface). That is, this method provides a good
// way to keep a current view of all units' states, but is not guaranteed to
// show every state transition they go through. Furthermore, state changes
// will only be written to the channel with non-blocking writes. If updateCh
// is full, it attempts to write an error to errCh; if errCh is full, the error
// passes silently.
func (c *Conn) SetSubStateSubscriber(updateCh chan<- *SubStateUpdate, errCh chan<- error) {
c.subscriber.Lock()
defer c.subscriber.Unlock()
c.subscriber.updateCh = updateCh
c.subscriber.errCh = errCh
}
func (c *Conn) sendSubStateUpdate(path dbus.ObjectPath) {
c.subscriber.Lock()
defer c.subscriber.Unlock()
if c.shouldIgnore(path) {
return
}
info, err := c.GetUnitProperties(string(path))
if err != nil {
select {
case c.subscriber.errCh <- err:
default:
}
}
name := info["Id"].(string)
substate := info["SubState"].(string)
update := &SubStateUpdate{name, substate}
select {
case c.subscriber.updateCh <- update:
default:
select {
case c.subscriber.errCh <- errors.New("update channel full!"):
default:
}
}
c.updateIgnore(path, info)
}
// The ignore functions work around a wart in the systemd dbus interface.
// Requesting the properties of an unloaded unit will cause systemd to send a
// pair of UnitNew/UnitRemoved signals. Because we need to get a unit's
// properties on UnitNew (as that's the only indication of a new unit coming up
// for the first time), we would enter an infinite loop if we did not attempt
// to detect and ignore these spurious signals. The signal themselves are
// indistinguishable from relevant ones, so we (somewhat hackishly) ignore an
// unloaded unit's signals for a short time after requesting its properties.
// This means that we will miss e.g. a transient unit being restarted
// *immediately* upon failure and also a transient unit being started
// immediately after requesting its status (with systemctl status, for example,
// because this causes a UnitNew signal to be sent which then causes us to fetch
// the properties).
func (c *Conn) shouldIgnore(path dbus.ObjectPath) bool {
t, ok := c.subscriber.ignore[path]
return ok && t >= time.Now().UnixNano()
}
func (c *Conn) updateIgnore(path dbus.ObjectPath, info map[string]interface{}) {
c.cleanIgnore()
// unit is unloaded - it will trigger bad systemd dbus behavior
if info["LoadState"].(string) == "not-found" {
c.subscriber.ignore[path] = time.Now().UnixNano() + ignoreInterval
}
}
// without this, ignore would grow unboundedly over time
func (c *Conn) cleanIgnore() {
now := time.Now().UnixNano()
if c.subscriber.cleanIgnore < now {
c.subscriber.cleanIgnore = now + cleanIgnoreInterval
for p, t := range c.subscriber.ignore {
if t < now {
delete(c.subscriber.ignore, p)
}
}
}
}

View File

@ -1,57 +0,0 @@
// Copyright 2015 CoreOS, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package dbus
import (
"time"
)
// SubscriptionSet returns a subscription set which is like conn.Subscribe but
// can filter to only return events for a set of units.
type SubscriptionSet struct {
*set
conn *Conn
}
func (s *SubscriptionSet) filter(unit string) bool {
return !s.Contains(unit)
}
// Subscribe starts listening for dbus events for all of the units in the set.
// Returns channels identical to conn.SubscribeUnits.
func (s *SubscriptionSet) Subscribe() (<-chan map[string]*UnitStatus, <-chan error) {
// TODO: Make fully evented by using systemd 209 with properties changed values
return s.conn.SubscribeUnitsCustom(time.Second, 0,
mismatchUnitStatus,
func(unit string) bool { return s.filter(unit) },
)
}
// NewSubscriptionSet returns a new subscription set.
func (conn *Conn) NewSubscriptionSet() *SubscriptionSet {
return &SubscriptionSet{newSet(), conn}
}
// mismatchUnitStatus returns true if the provided UnitStatus objects
// are not equivalent. false is returned if the objects are equivalent.
// Only the Name, Description and state-related fields are used in
// the comparison.
func mismatchUnitStatus(u1, u2 *UnitStatus) bool {
return u1.Name != u2.Name ||
u1.Description != u2.Description ||
u1.LoadState != u2.LoadState ||
u1.ActiveState != u2.ActiveState ||
u1.SubState != u2.SubState
}

View File

@ -1,82 +0,0 @@
// Copyright 2015 CoreOS, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package dbus
import (
"testing"
"time"
)
// TestSubscribeUnit exercises the basics of subscription of a particular unit.
func TestSubscriptionSetUnit(t *testing.T) {
target := "subscribe-events-set.service"
conn, err := New()
if err != nil {
t.Fatal(err)
}
err = conn.Subscribe()
if err != nil {
t.Fatal(err)
}
subSet := conn.NewSubscriptionSet()
evChan, errChan := subSet.Subscribe()
subSet.Add(target)
setupUnit(target, conn, t)
linkUnit(target, conn, t)
reschan := make(chan string)
_, err = conn.StartUnit(target, "replace", reschan)
if err != nil {
t.Fatal(err)
}
job := <-reschan
if job != "done" {
t.Fatal("Couldn't start", target)
}
timeout := make(chan bool, 1)
go func() {
time.Sleep(3 * time.Second)
close(timeout)
}()
for {
select {
case changes := <-evChan:
tCh, ok := changes[target]
if !ok {
t.Fatal("Unexpected event:", changes)
}
if tCh.ActiveState == "active" && tCh.Name == target {
goto success
}
case err = <-errChan:
t.Fatal(err)
case <-timeout:
t.Fatal("Reached timeout")
}
}
success:
return
}

View File

@ -1,105 +0,0 @@
// Copyright 2015 CoreOS, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package dbus
import (
"testing"
"time"
)
// TestSubscribe exercises the basics of subscription
func TestSubscribe(t *testing.T) {
conn, err := New()
if err != nil {
t.Fatal(err)
}
err = conn.Subscribe()
if err != nil {
t.Fatal(err)
}
err = conn.Unsubscribe()
if err != nil {
t.Fatal(err)
}
}
// TestSubscribeUnit exercises the basics of subscription of a particular unit.
func TestSubscribeUnit(t *testing.T) {
target := "subscribe-events.service"
conn, err := New()
if err != nil {
t.Fatal(err)
}
err = conn.Subscribe()
if err != nil {
t.Fatal(err)
}
err = conn.Unsubscribe()
if err != nil {
t.Fatal(err)
}
evChan, errChan := conn.SubscribeUnits(time.Second)
setupUnit(target, conn, t)
linkUnit(target, conn, t)
reschan := make(chan string)
_, err = conn.StartUnit(target, "replace", reschan)
if err != nil {
t.Fatal(err)
}
job := <-reschan
if job != "done" {
t.Fatal("Couldn't start", target)
}
timeout := make(chan bool, 1)
go func() {
time.Sleep(3 * time.Second)
close(timeout)
}()
for {
select {
case changes := <-evChan:
tCh, ok := changes[target]
// Just continue until we see our event.
if !ok {
continue
}
if tCh.ActiveState == "active" && tCh.Name == target {
goto success
}
case err = <-errChan:
t.Fatal(err)
case <-timeout:
t.Fatal("Reached timeout")
}
}
success:
return
}

View File

@ -1,60 +0,0 @@
// Copyright 2015 CoreOS, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// +build ignore
// Activation example used by the activation unit tests.
package main
import (
"fmt"
"os"
"github.com/coreos/go-systemd/activation"
)
func fixListenPid() {
if os.Getenv("FIX_LISTEN_PID") != "" {
// HACK: real systemd would set LISTEN_PID before exec'ing but
// this is too difficult in golang for the purpose of a test.
// Do not do this in real code.
os.Setenv("LISTEN_PID", fmt.Sprintf("%d", os.Getpid()))
}
}
func main() {
fixListenPid()
files := activation.Files(false)
if len(files) == 0 {
panic("No files")
}
if os.Getenv("LISTEN_PID") == "" || os.Getenv("LISTEN_FDS") == "" {
panic("Should not unset envs")
}
files = activation.Files(true)
if os.Getenv("LISTEN_PID") != "" || os.Getenv("LISTEN_FDS") != "" {
panic("Can not unset envs")
}
// Write out the expected strings to the two pipes
files[0].Write([]byte("Hello world"))
files[1].Write([]byte("Goodbye world"))
return
}

View File

@ -1,19 +0,0 @@
## socket activated http server
This is a simple example of using socket activation with systemd to serve a
simple HTTP server on http://127.0.0.1:8076
To try it out `go get` the httpserver and run it under the systemd-activate helper
```bash
export GOPATH="$PWD"
go get github.com/coreos/go-systemd/examples/activation/httpserver
/usr/lib/systemd/systemd-activate -l 127.0.0.1:8076 ./bin/httpserver
```
Then curl the URL and you will notice that it starts up:
```
curl 127.0.0.1:8076
hello socket activated world!
```

View File

@ -1,11 +0,0 @@
[Unit]
Description=Hello World HTTP
Requires=network.target
After=multi-user.target
[Service]
Type=simple
ExecStart=/usr/local/bin/httpserver
[Install]
WantedBy=multi-user.target

View File

@ -1,5 +0,0 @@
[Socket]
ListenStream=127.0.0.1:8076
[Install]
WantedBy=sockets.target

View File

@ -1,42 +0,0 @@
// Copyright 2015 CoreOS, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// +build ignore
package main
import (
"io"
"net/http"
"github.com/coreos/go-systemd/activation"
)
func HelloServer(w http.ResponseWriter, req *http.Request) {
io.WriteString(w, "hello socket activated world!\n")
}
func main() {
listeners, err := activation.Listeners(true)
if err != nil {
panic(err)
}
if len(listeners) != 1 {
panic("Unexpected number of socket activation fds")
}
http.HandleFunc("/", HelloServer)
http.Serve(listeners[0], nil)
}

View File

@ -1,66 +0,0 @@
// Copyright 2015 CoreOS, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// +build ignore
// Activation example used by the activation unit tests.
package main
import (
"fmt"
"os"
"github.com/coreos/go-systemd/activation"
)
func fixListenPid() {
if os.Getenv("FIX_LISTEN_PID") != "" {
// HACK: real systemd would set LISTEN_PID before exec'ing but
// this is too difficult in golang for the purpose of a test.
// Do not do this in real code.
os.Setenv("LISTEN_PID", fmt.Sprintf("%d", os.Getpid()))
}
}
func main() {
fixListenPid()
listeners, _ := activation.Listeners(false)
if len(listeners) == 0 {
panic("No listeners")
}
if os.Getenv("LISTEN_PID") == "" || os.Getenv("LISTEN_FDS") == "" {
panic("Should not unset envs")
}
listeners, err := activation.Listeners(true)
if err != nil {
panic(err)
}
if os.Getenv("LISTEN_PID") != "" || os.Getenv("LISTEN_FDS") != "" {
panic("Can not unset envs")
}
c0, _ := listeners[0].Accept()
c1, _ := listeners[1].Accept()
// Write out the expected strings to the two pipes
c0.Write([]byte("Hello world"))
c1.Write([]byte("Goodbye world"))
return
}

View File

@ -1,88 +0,0 @@
// Copyright 2015 CoreOS, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// +build ignore
// Activation example used by the activation unit tests.
package main
import (
"fmt"
"net"
"os"
"github.com/coreos/go-systemd/activation"
)
func fixListenPid() {
if os.Getenv("FIX_LISTEN_PID") != "" {
// HACK: real systemd would set LISTEN_PID before exec'ing but
// this is too difficult in golang for the purpose of a test.
// Do not do this in real code.
os.Setenv("LISTEN_PID", fmt.Sprintf("%d", os.Getpid()))
}
}
func main() {
fixListenPid()
pc, _ := activation.PacketConns(false)
if len(pc) == 0 {
panic("No packetConns")
}
if os.Getenv("LISTEN_PID") == "" || os.Getenv("LISTEN_FDS") == "" {
panic("Should not unset envs")
}
pc, err := activation.PacketConns(true)
if err != nil {
panic(err)
}
if os.Getenv("LISTEN_PID") != "" || os.Getenv("LISTEN_FDS") != "" {
panic("Can not unset envs")
}
udp1, ok := pc[0].(*net.UDPConn)
if !ok {
panic("packetConn 1 not UDP")
}
udp2, ok := pc[1].(*net.UDPConn)
if !ok {
panic("packetConn 2 not UDP")
}
_, addr1, err := udp1.ReadFromUDP(nil)
if err != nil {
panic(err)
}
_, addr2, err := udp2.ReadFromUDP(nil)
if err != nil {
panic(err)
}
// Write out the expected strings to the two pipes
_, err = udp1.WriteToUDP([]byte("Hello world"), addr1)
if err != nil {
panic(err)
}
_, err = udp2.WriteToUDP([]byte("Goodbye world"), addr2)
if err != nil {
panic(err)
}
return
}

View File

@ -1,5 +0,0 @@
[Unit]
Description=enable disable test
[Service]
ExecStart=/bin/sleep 400

View File

@ -1,5 +0,0 @@
[Unit]
Description=mask unmask test
[Service]
ExecStart=/bin/sleep 400

View File

@ -1,6 +0,0 @@
[Unit]
Description=reload test
[Service]
ExecStart=/bin/bash -c "trap '' HUP; /bin/sleep 400"
ExecReload=-/bin/systemctl kill -s HUP reload.service

View File

@ -1,6 +0,0 @@
[Unit]
Description=starting a failed test
[Service]
ExecStartPre=/bin/false
ExecStart=/bin/sleep 400

View File

@ -1,5 +0,0 @@
[Unit]
Description=start stop test
[Service]
ExecStart=/bin/sleep 400

View File

@ -1,5 +0,0 @@
[Unit]
Description=start stop test
[Service]
ExecStart=/bin/sleep 400

View File

@ -1,5 +0,0 @@
[Unit]
Description=start stop test
[Service]
ExecStart=/bin/sleep 400

View File

@ -1,179 +0,0 @@
// Copyright 2015 CoreOS, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package journal provides write bindings to the local systemd journal.
// It is implemented in pure Go and connects to the journal directly over its
// unix socket.
//
// To read from the journal, see the "sdjournal" package, which wraps the
// sd-journal a C API.
//
// http://www.freedesktop.org/software/systemd/man/systemd-journald.service.html
package journal
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"io"
"io/ioutil"
"net"
"os"
"strconv"
"strings"
"syscall"
)
// Priority of a journal message
type Priority int
const (
PriEmerg Priority = iota
PriAlert
PriCrit
PriErr
PriWarning
PriNotice
PriInfo
PriDebug
)
var conn net.Conn
func init() {
var err error
conn, err = net.Dial("unixgram", "/run/systemd/journal/socket")
if err != nil {
conn = nil
}
}
// Enabled returns true if the local systemd journal is available for logging
func Enabled() bool {
return conn != nil
}
// Send a message to the local systemd journal. vars is a map of journald
// fields to values. Fields must be composed of uppercase letters, numbers,
// and underscores, but must not start with an underscore. Within these
// restrictions, any arbitrary field name may be used. Some names have special
// significance: see the journalctl documentation
// (http://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html)
// for more details. vars may be nil.
func Send(message string, priority Priority, vars map[string]string) error {
if conn == nil {
return journalError("could not connect to journald socket")
}
data := new(bytes.Buffer)
appendVariable(data, "PRIORITY", strconv.Itoa(int(priority)))
appendVariable(data, "MESSAGE", message)
for k, v := range vars {
appendVariable(data, k, v)
}
_, err := io.Copy(conn, data)
if err != nil && isSocketSpaceError(err) {
file, err := tempFd()
if err != nil {
return journalError(err.Error())
}
defer file.Close()
_, err = io.Copy(file, data)
if err != nil {
return journalError(err.Error())
}
rights := syscall.UnixRights(int(file.Fd()))
/* this connection should always be a UnixConn, but better safe than sorry */
unixConn, ok := conn.(*net.UnixConn)
if !ok {
return journalError("can't send file through non-Unix connection")
}
unixConn.WriteMsgUnix([]byte{}, rights, nil)
} else if err != nil {
return journalError(err.Error())
}
return nil
}
// Print prints a message to the local systemd journal using Send().
func Print(priority Priority, format string, a ...interface{}) error {
return Send(fmt.Sprintf(format, a...), priority, nil)
}
func appendVariable(w io.Writer, name, value string) {
if !validVarName(name) {
journalError("variable name contains invalid character, ignoring")
}
if strings.ContainsRune(value, '\n') {
/* When the value contains a newline, we write:
* - the variable name, followed by a newline
* - the size (in 64bit little endian format)
* - the data, followed by a newline
*/
fmt.Fprintln(w, name)
binary.Write(w, binary.LittleEndian, uint64(len(value)))
fmt.Fprintln(w, value)
} else {
/* just write the variable and value all on one line */
fmt.Fprintf(w, "%s=%s\n", name, value)
}
}
func validVarName(name string) bool {
/* The variable name must be in uppercase and consist only of characters,
* numbers and underscores, and may not begin with an underscore. (from the docs)
*/
valid := name[0] != '_'
for _, c := range name {
valid = valid && ('A' <= c && c <= 'Z') || ('0' <= c && c <= '9') || c == '_'
}
return valid
}
func isSocketSpaceError(err error) bool {
opErr, ok := err.(*net.OpError)
if !ok {
return false
}
sysErr, ok := opErr.Err.(syscall.Errno)
if !ok {
return false
}
return sysErr == syscall.EMSGSIZE || sysErr == syscall.ENOBUFS
}
func tempFd() (*os.File, error) {
file, err := ioutil.TempFile("/dev/shm/", "journal.XXXXX")
if err != nil {
return nil, err
}
syscall.Unlink(file.Name())
if err != nil {
return nil, err
}
return file, nil
}
func journalError(s string) error {
s = "journal error: " + s
fmt.Fprintln(os.Stderr, s)
return errors.New(s)
}

View File

@ -1,108 +0,0 @@
// Copyright 2015 CoreOS, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Integration with the systemd logind API. See http://www.freedesktop.org/wiki/Software/systemd/logind/
package login1
import (
"fmt"
"os"
"strconv"
"github.com/godbus/dbus"
)
const (
dbusInterface = "org.freedesktop.login1.Manager"
dbusPath = "/org/freedesktop/login1"
)
// Conn is a connection to systemds dbus endpoint.
type Conn struct {
conn *dbus.Conn
object dbus.BusObject
}
// New() establishes a connection to the system bus and authenticates.
func New() (*Conn, error) {
c := new(Conn)
if err := c.initConnection(); err != nil {
return nil, err
}
return c, nil
}
func (c *Conn) initConnection() error {
var err error
c.conn, err = dbus.SystemBusPrivate()
if err != nil {
return err
}
// Only use EXTERNAL method, and hardcode the uid (not username)
// to avoid a username lookup (which requires a dynamically linked
// libc)
methods := []dbus.Auth{dbus.AuthExternal(strconv.Itoa(os.Getuid()))}
err = c.conn.Auth(methods)
if err != nil {
c.conn.Close()
return err
}
err = c.conn.Hello()
if err != nil {
c.conn.Close()
return err
}
c.object = c.conn.Object("org.freedesktop.login1", dbus.ObjectPath(dbusPath))
return nil
}
// Reboot asks logind for a reboot optionally asking for auth.
func (c *Conn) Reboot(askForAuth bool) {
c.object.Call(dbusInterface+".Reboot", 0, askForAuth)
}
// Inhibit takes inhibition lock in logind.
func (c *Conn) Inhibit(what, who, why, mode string) (*os.File, error) {
var fd dbus.UnixFD
err := c.object.Call(dbusInterface+".Inhibit", 0, what, who, why, mode).Store(&fd)
if err != nil {
return nil, err
}
return os.NewFile(uintptr(fd), "inhibit"), nil
}
// Subscribe to signals on the logind dbus
func (c *Conn) Subscribe(members ...string) chan *dbus.Signal {
for _, member := range members {
c.conn.BusObject().Call("org.freedesktop.DBus.AddMatch", 0,
fmt.Sprintf("type='signal',interface='org.freedesktop.login1.Manager',member='%s'", member))
}
ch := make(chan *dbus.Signal, 10)
c.conn.Signal(ch)
return ch
}
// PowerOff asks logind for a power off optionally asking for auth.
func (c *Conn) PowerOff(askForAuth bool) {
c.object.Call(dbusInterface+".PowerOff", 0, askForAuth)
}

View File

@ -1,28 +0,0 @@
// Copyright 2015 CoreOS, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package login1
import (
"testing"
)
// TestNew ensures that New() works without errors.
func TestNew(t *testing.T) {
_, err := New()
if err != nil {
t.Fatal(err)
}
}

View File

@ -1,81 +0,0 @@
/*
Copyright 2015 CoreOS Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Integration with the systemd machined API. See http://www.freedesktop.org/wiki/Software/systemd/machined/
package machine1
import (
"os"
"strconv"
"github.com/godbus/dbus"
)
const (
dbusInterface = "org.freedesktop.machine1.Manager"
dbusPath = "/org/freedesktop/machine1"
)
// Conn is a connection to systemds dbus endpoint.
type Conn struct {
conn *dbus.Conn
object dbus.BusObject
}
// New() establishes a connection to the system bus and authenticates.
func New() (*Conn, error) {
c := new(Conn)
if err := c.initConnection(); err != nil {
return nil, err
}
return c, nil
}
func (c *Conn) initConnection() error {
var err error
c.conn, err = dbus.SystemBusPrivate()
if err != nil {
return err
}
// Only use EXTERNAL method, and hardcode the uid (not username)
// to avoid a username lookup (which requires a dynamically linked
// libc)
methods := []dbus.Auth{dbus.AuthExternal(strconv.Itoa(os.Getuid()))}
err = c.conn.Auth(methods)
if err != nil {
c.conn.Close()
return err
}
err = c.conn.Hello()
if err != nil {
c.conn.Close()
return err
}
c.object = c.conn.Object("org.freedesktop.machine1", dbus.ObjectPath(dbusPath))
return nil
}
// RegisterMachine registers the container with the systemd-machined
func (c *Conn) RegisterMachine(name string, id []byte, service string, class string, pid int, root_directory string) error {
return c.object.Call(dbusInterface+".RegisterMachine", 0, name, id, service, class, uint32(pid), root_directory).Err
}

View File

@ -1,30 +0,0 @@
/*
Copyright 2015 CoreOS Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package machine1
import (
"testing"
)
// TestNew ensures that New() works without errors.
func TestNew(t *testing.T) {
_, err := New()
if err != nil {
t.Fatal(err)
}
}

View File

@ -1,66 +0,0 @@
// Copyright 2015 RedHat, Inc.
// Copyright 2015 CoreOS, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package sdjournal
import (
"github.com/coreos/pkg/dlopen"
"sync"
"unsafe"
)
var (
// lazy initialized
libsystemdHandle *dlopen.LibHandle
libsystemdMutex = &sync.Mutex{}
libsystemdFunctions = map[string]unsafe.Pointer{}
libsystemdNames = []string{
// systemd < 209
"libsystemd-journal.so.0",
"libsystemd-journal.so",
// systemd >= 209 merged libsystemd-journal into libsystemd proper
"libsystemd.so.0",
"libsystemd.so",
}
)
func getFunction(name string) (unsafe.Pointer, error) {
libsystemdMutex.Lock()
defer libsystemdMutex.Unlock()
if libsystemdHandle == nil {
h, err := dlopen.GetHandle(libsystemdNames)
if err != nil {
return nil, err
}
libsystemdHandle = h
}
f, ok := libsystemdFunctions[name]
if !ok {
var err error
f, err = libsystemdHandle.GetSymbolPointer(name)
if err != nil {
return nil, err
}
libsystemdFunctions[name] = f
}
return f, nil
}

View File

@ -1,36 +0,0 @@
// Copyright 2015 RedHat, Inc.
// Copyright 2015 CoreOS, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package sdjournal
import "testing"
func TestGetFunction(t *testing.T) {
f, err := getFunction("sd_journal_open")
if err != nil {
t.Errorf("Error getting an existing function: %s", err)
}
if f == nil {
t.Error("Got nil function pointer")
}
_, err = getFunction("non_existent_function")
if err == nil {
t.Error("Expected to get an error, got nil")
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,399 +0,0 @@
// Copyright 2015 RedHat, Inc.
// Copyright 2015 CoreOS, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package sdjournal
import (
"bytes"
"errors"
"fmt"
"io"
"io/ioutil"
"math/rand"
"os"
"strings"
"testing"
"time"
"github.com/coreos/go-systemd/journal"
)
func TestJournalFollow(t *testing.T) {
r, err := NewJournalReader(JournalReaderConfig{
Since: time.Duration(-15) * time.Second,
Matches: []Match{
{
Field: SD_JOURNAL_FIELD_SYSTEMD_UNIT,
Value: "NetworkManager.service",
},
},
})
if err != nil {
t.Fatalf("Error opening journal: %s", err)
}
if r == nil {
t.Fatal("Got a nil reader")
}
defer r.Close()
// start writing some test entries
done := make(chan struct{}, 1)
defer close(done)
go func() {
for {
select {
case <-done:
return
default:
if err := journal.Print(journal.PriInfo, "test message %s", time.Now()); err != nil {
t.Fatalf("Error writing to journal: %s", err)
}
time.Sleep(time.Second)
}
}
}()
// and follow the reader synchronously
timeout := time.Duration(5) * time.Second
if err = r.Follow(time.After(timeout), os.Stdout); err != ErrExpired {
t.Fatalf("Error during follow: %s", err)
}
}
func TestJournalGetUsage(t *testing.T) {
j, err := NewJournal()
if err != nil {
t.Fatalf("Error opening journal: %s", err)
}
if j == nil {
t.Fatal("Got a nil journal")
}
defer j.Close()
_, err = j.GetUsage()
if err != nil {
t.Fatalf("Error getting journal size: %s", err)
}
}
func TestJournalCursorGetSeekAndTest(t *testing.T) {
j, err := NewJournal()
if err != nil {
t.Fatalf("Error opening journal: %s", err)
}
if j == nil {
t.Fatal("Got a nil journal")
}
defer j.Close()
waitAndNext := func(j *Journal) error {
r := j.Wait(time.Duration(1) * time.Second)
if r < 0 {
return errors.New("Error waiting to journal")
}
n, err := j.Next()
if err != nil {
return fmt.Errorf("Error reading to journal: %s", err)
}
if n == 0 {
return fmt.Errorf("Error reading to journal: %s", io.EOF)
}
return nil
}
err = journal.Print(journal.PriInfo, "test message for cursor %s", time.Now())
if err != nil {
t.Fatalf("Error writing to journal: %s", err)
}
if err = waitAndNext(j); err != nil {
t.Fatalf(err.Error())
}
c, err := j.GetCursor()
if err != nil {
t.Fatalf("Error getting cursor from journal: %s", err)
}
err = j.SeekCursor(c)
if err != nil {
t.Fatalf("Error seeking cursor to journal: %s", err)
}
if err = waitAndNext(j); err != nil {
t.Fatalf(err.Error())
}
err = j.TestCursor(c)
if err != nil {
t.Fatalf("Error testing cursor to journal: %s", err)
}
}
func TestNewJournalFromDir(t *testing.T) {
// test for error handling
dir := "/ClearlyNonExistingPath/"
j, err := NewJournalFromDir(dir)
if err == nil {
defer j.Close()
t.Fatalf("Error expected when opening dummy path (%s)", dir)
}
// test for main code path
dir, err = ioutil.TempDir("", "go-systemd-test")
if err != nil {
t.Fatalf("Error creating tempdir: %s", err)
}
defer os.RemoveAll(dir)
j, err = NewJournalFromDir(dir)
if err != nil {
t.Fatalf("Error opening journal: %s", err)
}
if j == nil {
t.Fatal("Got a nil journal")
}
j.Close()
}
func setupJournalRoundtrip() (*Journal, map[string]string, error) {
j, err := NewJournal()
if err != nil {
return nil, nil, fmt.Errorf("Error opening journal: %s", err)
}
if j == nil {
return nil, nil, fmt.Errorf("Got a nil journal")
}
j.FlushMatches()
matchField := "TESTJOURNALENTRY"
matchValue := fmt.Sprintf("%d", time.Now().UnixNano())
m := Match{Field: matchField, Value: matchValue}
err = j.AddMatch(m.String())
if err != nil {
return nil, nil, fmt.Errorf("Error adding matches to journal: %s", err)
}
msg := fmt.Sprintf("test journal get entry message %s", time.Now())
data := map[string]string{matchField: matchValue}
err = journal.Send(msg, journal.PriInfo, data)
if err != nil {
return nil, nil, fmt.Errorf("Error writing to journal: %s", err)
}
time.Sleep(time.Duration(1) * time.Second)
n, err := j.Next()
if err != nil {
return nil, nil, fmt.Errorf("Error reading from journal: %s", err)
}
if n == 0 {
return nil, nil, fmt.Errorf("Error reading from journal: %s", io.EOF)
}
data["MESSAGE"] = msg
return j, data, nil
}
func TestJournalGetData(t *testing.T) {
j, wantEntry, err := setupJournalRoundtrip()
if err != nil {
t.Fatal(err.Error())
}
defer j.Close()
for k, v := range wantEntry {
data := fmt.Sprintf("%s=%s", k, v)
dataStr, err := j.GetData(k)
if err != nil {
t.Fatalf("GetData() error: %v", err)
}
if dataStr != data {
t.Fatalf("Invalid data for \"%s\": got %s, want %s", k, dataStr, data)
}
dataBytes, err := j.GetDataBytes(k)
if err != nil {
t.Fatalf("GetDataBytes() error: %v", err)
}
if string(dataBytes) != data {
t.Fatalf("Invalid data bytes for \"%s\": got %s, want %s", k, string(dataBytes), data)
}
valStr, err := j.GetDataValue(k)
if err != nil {
t.Fatalf("GetDataValue() error: %v", err)
}
if valStr != v {
t.Fatalf("Invalid data value for \"%s\": got %s, want %s", k, valStr, v)
}
valBytes, err := j.GetDataValueBytes(k)
if err != nil {
t.Fatalf("GetDataValueBytes() error: %v", err)
}
if string(valBytes) != v {
t.Fatalf("Invalid data value bytes for \"%s\": got %s, want %s", k, string(valBytes), v)
}
}
}
func TestJournalGetEntry(t *testing.T) {
j, wantEntry, err := setupJournalRoundtrip()
if err != nil {
t.Fatal(err.Error())
}
defer j.Close()
entry, err := j.GetEntry()
if err != nil {
t.Fatalf("Error getting the entry to journal: %s", err)
}
for k, wantV := range wantEntry {
gotV := entry.Fields[k]
if gotV != wantV {
t.Fatalf("Bad result for entry.Fields[\"%s\"]: got %s, want %s", k, gotV, wantV)
}
}
}
// Check for incorrect read into small buffers,
// see https://github.com/coreos/go-systemd/issues/172
func TestJournalReaderSmallReadBuffer(t *testing.T) {
// Write a long entry ...
delim := "%%%%%%"
longEntry := strings.Repeat("a", 256)
matchField := "TESTJOURNALREADERSMALLBUF"
matchValue := fmt.Sprintf("%d", time.Now().UnixNano())
r, err := NewJournalReader(JournalReaderConfig{
Since: time.Duration(-15) * time.Second,
Matches: []Match{
{
Field: matchField,
Value: matchValue,
},
},
})
if err != nil {
t.Fatalf("Error opening journal: %s", err)
}
if r == nil {
t.Fatal("Got a nil reader")
}
defer r.Close()
want := fmt.Sprintf("%slongentry %s%s", delim, longEntry, delim)
err = journal.Send(want, journal.PriInfo, map[string]string{matchField: matchValue})
if err != nil {
t.Fatal("Error writing to journal", err)
}
time.Sleep(time.Second)
// ... and try to read it back piece by piece via a small buffer
finalBuff := new(bytes.Buffer)
var e error
for c := -1; c != 0 && e == nil; {
smallBuf := make([]byte, 5)
c, e = r.Read(smallBuf)
if c > len(smallBuf) {
t.Fatalf("Got unexpected read length: %d vs %d", c, len(smallBuf))
}
_, _ = finalBuff.Write(smallBuf)
}
b := finalBuff.String()
got := strings.Split(b, delim)
if len(got) != 3 {
t.Fatalf("Got unexpected entry %s", b)
}
if got[1] != strings.Trim(want, delim) {
t.Fatalf("Got unexpected message %s", got[1])
}
}
func TestJournalGetUniqueValues(t *testing.T) {
j, err := NewJournal()
if err != nil {
t.Fatal(err)
}
defer j.Close()
uniqueString := generateRandomField(20)
testEntries := []string{"A", "B", "C", "D"}
for _, v := range testEntries {
err := journal.Send("TEST: "+uniqueString, journal.PriInfo, map[string]string{uniqueString: v})
if err != nil {
t.Fatal(err)
}
}
// TODO: add proper `waitOnMatch` function which should wait for journal entry with filter to commit.
time.Sleep(time.Millisecond * 500)
values, err := j.GetUniqueValues(uniqueString)
if err != nil {
t.Fatal(err)
}
if len(values) != len(testEntries) {
t.Fatalf("Expect %d entries. Got %d", len(testEntries), len(values))
}
if !contains(values, "A") || !contains(values, "B") || !contains(values, "C") || !contains(values, "D") {
t.Fatalf("Expect 4 values for %s field: A,B,C,D. Got %s", uniqueString, values)
}
}
func contains(s []string, v string) bool {
for _, entry := range s {
if entry == v {
return true
}
}
return false
}
func generateRandomField(n int) string {
letters := []rune("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
s := make([]rune, n)
rand.Seed(time.Now().UnixNano())
for i := range s {
s[i] = letters[rand.Intn(len(letters))]
}
return string(s)
}

View File

@ -1,260 +0,0 @@
// Copyright 2015 RedHat, Inc.
// Copyright 2015 CoreOS, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package sdjournal
import (
"errors"
"fmt"
"io"
"log"
"strings"
"time"
)
var (
ErrExpired = errors.New("Timeout expired")
)
// JournalReaderConfig represents options to drive the behavior of a JournalReader.
type JournalReaderConfig struct {
// The Since, NumFromTail and Cursor options are mutually exclusive and
// determine where the reading begins within the journal. The order in which
// options are written is exactly the order of precedence.
Since time.Duration // start relative to a Duration from now
NumFromTail uint64 // start relative to the tail
Cursor string // start relative to the cursor
// Show only journal entries whose fields match the supplied values. If
// the array is empty, entries will not be filtered.
Matches []Match
// If not empty, the journal instance will point to a journal residing
// in this directory. The supplied path may be relative or absolute.
Path string
}
// JournalReader is an io.ReadCloser which provides a simple interface for iterating through the
// systemd journal. A JournalReader is not safe for concurrent use by multiple goroutines.
type JournalReader struct {
journal *Journal
msgReader *strings.Reader
}
// NewJournalReader creates a new JournalReader with configuration options that are similar to the
// systemd journalctl tool's iteration and filtering features.
func NewJournalReader(config JournalReaderConfig) (*JournalReader, error) {
r := &JournalReader{}
// Open the journal
var err error
if config.Path != "" {
r.journal, err = NewJournalFromDir(config.Path)
} else {
r.journal, err = NewJournal()
}
if err != nil {
return nil, err
}
// Add any supplied matches
for _, m := range config.Matches {
r.journal.AddMatch(m.String())
}
// Set the start position based on options
if config.Since != 0 {
// Start based on a relative time
start := time.Now().Add(config.Since)
if err := r.journal.SeekRealtimeUsec(uint64(start.UnixNano() / 1000)); err != nil {
return nil, err
}
} else if config.NumFromTail != 0 {
// Start based on a number of lines before the tail
if err := r.journal.SeekTail(); err != nil {
return nil, err
}
// Move the read pointer into position near the tail. Go one further than
// the option so that the initial cursor advancement positions us at the
// correct starting point.
skip, err := r.journal.PreviousSkip(config.NumFromTail + 1)
if err != nil {
return nil, err
}
// If we skipped fewer lines than expected, we have reached journal start.
// Thus, we seek to head so that next invocation can read the first line.
if skip != config.NumFromTail+1 {
if err := r.journal.SeekHead(); err != nil {
return nil, err
}
}
} else if config.Cursor != "" {
// Start based on a custom cursor
if err := r.journal.SeekCursor(config.Cursor); err != nil {
return nil, err
}
}
return r, nil
}
// Read reads entries from the journal. Read follows the Reader interface so
// it must be able to read a specific amount of bytes. Journald on the other
// hand only allows us to read full entries of arbitrary size (without byte
// granularity). JournalReader is therefore internally buffering entries that
// don't fit in the read buffer. Callers should keep calling until 0 and/or an
// error is returned.
func (r *JournalReader) Read(b []byte) (int, error) {
var err error
if r.msgReader == nil {
var c uint64
// Advance the journal cursor. It has to be called at least one time
// before reading
c, err = r.journal.Next()
// An unexpected error
if err != nil {
return 0, err
}
// EOF detection
if c == 0 {
return 0, io.EOF
}
// Build a message
var msg string
msg, err = r.buildMessage()
if err != nil {
return 0, err
}
r.msgReader = strings.NewReader(msg)
}
// Copy and return the message
var sz int
sz, err = r.msgReader.Read(b)
if err == io.EOF {
// The current entry has been fully read. Don't propagate this
// EOF, so the next entry can be read at the next Read()
// iteration.
r.msgReader = nil
return sz, nil
}
if err != nil {
return sz, err
}
if r.msgReader.Len() == 0 {
r.msgReader = nil
}
return sz, nil
}
// Close closes the JournalReader's handle to the journal.
func (r *JournalReader) Close() error {
return r.journal.Close()
}
// Rewind attempts to rewind the JournalReader to the first entry.
func (r *JournalReader) Rewind() error {
r.msgReader = nil
return r.journal.SeekHead()
}
// Follow synchronously follows the JournalReader, writing each new journal entry to writer. The
// follow will continue until a single time.Time is received on the until channel.
func (r *JournalReader) Follow(until <-chan time.Time, writer io.Writer) (err error) {
// Process journal entries and events. Entries are flushed until the tail or
// timeout is reached, and then we wait for new events or the timeout.
var msg = make([]byte, 64*1<<(10))
process:
for {
c, err := r.Read(msg)
if err != nil && err != io.EOF {
break process
}
select {
case <-until:
return ErrExpired
default:
if c > 0 {
if _, err = writer.Write(msg[:c]); err != nil {
break process
}
continue process
}
}
// We're at the tail, so wait for new events or time out.
// Holds journal events to process. Tightly bounded for now unless there's a
// reason to unblock the journal watch routine more quickly.
events := make(chan int, 1)
pollDone := make(chan bool, 1)
go func() {
for {
select {
case <-pollDone:
return
default:
events <- r.journal.Wait(time.Duration(1) * time.Second)
}
}
}()
select {
case <-until:
pollDone <- true
return ErrExpired
case e := <-events:
pollDone <- true
switch e {
case SD_JOURNAL_NOP, SD_JOURNAL_APPEND, SD_JOURNAL_INVALIDATE:
// TODO: need to account for any of these?
default:
log.Printf("Received unknown event: %d\n", e)
}
continue process
}
}
return
}
// buildMessage returns a string representing the current journal entry in a simple format which
// includes the entry timestamp and MESSAGE field.
func (r *JournalReader) buildMessage() (string, error) {
var msg string
var usec uint64
var err error
if msg, err = r.journal.GetData("MESSAGE"); err != nil {
return "", err
}
if usec, err = r.journal.GetRealtimeUsec(); err != nil {
return "", err
}
timestamp := time.Unix(0, int64(usec)*int64(time.Microsecond))
return fmt.Sprintf("%s %s\n", timestamp, msg), nil
}

View File

@ -1,87 +0,0 @@
#!/bin/bash -e
#
# Run all tests
# ./test
# ./test -v
#
# Run tests for one package
# PKG=./foo ./test
# PKG=bar ./test
#
# Invoke ./cover for HTML output
COVER=${COVER:-"-cover"}
PROJ="go-systemd"
ORG_PATH="github.com/coreos"
REPO_PATH="${ORG_PATH}/${PROJ}"
# As a convenience, set up a self-contained GOPATH if none set
if [ -z "$GOPATH" ]; then
if [ ! -h gopath/src/${REPO_PATH} ]; then
mkdir -p gopath/src/${ORG_PATH}
ln -s ../../../.. gopath/src/${REPO_PATH} || exit 255
fi
export GOPATH=${PWD}/gopath
go get -u github.com/godbus/dbus
go get -u github.com/coreos/pkg/dlopen
fi
TESTABLE="activation daemon journal login1 machine1 unit"
FORMATTABLE="$TESTABLE sdjournal dbus"
if [ -e "/run/systemd/system/" ]; then
TESTABLE="${TESTABLE} sdjournal"
if [ "$EUID" == "0" ]; then
# testing actual systemd behaviour requires root
TESTABLE="${TESTABLE} dbus"
fi
fi
# user has not provided PKG override
if [ -z "$PKG" ]; then
TEST=$TESTABLE
FMT=$FORMATTABLE
# user has provided PKG override
else
# strip out slashes and dots from PKG=./foo/
TEST=${PKG//\//}
TEST=${TEST//./}
# only run gofmt on packages provided by user
FMT="$TEST"
fi
# split TEST into an array and prepend REPO_PATH to each local package
split=(${TEST// / })
TEST=${split[@]/#/${REPO_PATH}/}
echo "Running tests..."
go test -v ${COVER} $@ ${TEST}
echo "Checking gofmt..."
fmtRes=$(gofmt -l $FMT)
if [ -n "${fmtRes}" ]; then
echo -e "gofmt checking failed:\n${fmtRes}"
exit 255
fi
echo "Checking govet..."
vetRes=$(go vet $TEST)
if [ -n "${vetRes}" ]; then
echo -e "govet checking failed:\n${vetRes}"
exit 255
fi
echo "Checking for license header..."
licRes=$(for file in $(find . -type f -iname '*.go' ! -path './gopath/*'); do
head -n3 "${file}" | grep -Eq "(Copyright|generated|GENERATED)" || echo -e " ${file}"
done;)
if [ -n "${licRes}" ]; then
echo -e "license header checking failed:\n${licRes}"
exit 255
fi
echo "Success"

View File

@ -1,276 +0,0 @@
// Copyright 2015 CoreOS, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package unit
import (
"bufio"
"bytes"
"errors"
"fmt"
"io"
"strings"
"unicode"
)
const (
// SYSTEMD_LINE_MAX mimics the maximum line length that systemd can use.
// On typical systemd platforms (i.e. modern Linux), this will most
// commonly be 2048, so let's use that as a sanity check.
// Technically, we should probably pull this at runtime:
// SYSTEMD_LINE_MAX = int(C.sysconf(C.__SC_LINE_MAX))
// but this would introduce an (unfortunate) dependency on cgo
SYSTEMD_LINE_MAX = 2048
// characters that systemd considers indicate a newline
SYSTEMD_NEWLINE = "\r\n"
)
var (
ErrLineTooLong = fmt.Errorf("line too long (max %d bytes)", SYSTEMD_LINE_MAX)
)
// Deserialize parses a systemd unit file into a list of UnitOption objects.
func Deserialize(f io.Reader) (opts []*UnitOption, err error) {
lexer, optchan, errchan := newLexer(f)
go lexer.lex()
for opt := range optchan {
opts = append(opts, &(*opt))
}
err = <-errchan
return opts, err
}
func newLexer(f io.Reader) (*lexer, <-chan *UnitOption, <-chan error) {
optchan := make(chan *UnitOption)
errchan := make(chan error, 1)
buf := bufio.NewReader(f)
return &lexer{buf, optchan, errchan, ""}, optchan, errchan
}
type lexer struct {
buf *bufio.Reader
optchan chan *UnitOption
errchan chan error
section string
}
func (l *lexer) lex() {
var err error
defer func() {
close(l.optchan)
close(l.errchan)
}()
next := l.lexNextSection
for next != nil {
if l.buf.Buffered() >= SYSTEMD_LINE_MAX {
// systemd truncates lines longer than LINE_MAX
// https://bugs.freedesktop.org/show_bug.cgi?id=85308
// Rather than allowing this to pass silently, let's
// explicitly gate people from encountering this
line, err := l.buf.Peek(SYSTEMD_LINE_MAX)
if err != nil {
l.errchan <- err
return
}
if bytes.IndexAny(line, SYSTEMD_NEWLINE) == -1 {
l.errchan <- ErrLineTooLong
return
}
}
next, err = next()
if err != nil {
l.errchan <- err
return
}
}
}
type lexStep func() (lexStep, error)
func (l *lexer) lexSectionName() (lexStep, error) {
sec, err := l.buf.ReadBytes(']')
if err != nil {
return nil, errors.New("unable to find end of section")
}
return l.lexSectionSuffixFunc(string(sec[:len(sec)-1])), nil
}
func (l *lexer) lexSectionSuffixFunc(section string) lexStep {
return func() (lexStep, error) {
garbage, _, err := l.toEOL()
if err != nil {
return nil, err
}
garbage = bytes.TrimSpace(garbage)
if len(garbage) > 0 {
return nil, fmt.Errorf("found garbage after section name %s: %v", l.section, garbage)
}
return l.lexNextSectionOrOptionFunc(section), nil
}
}
func (l *lexer) ignoreLineFunc(next lexStep) lexStep {
return func() (lexStep, error) {
for {
line, _, err := l.toEOL()
if err != nil {
return nil, err
}
line = bytes.TrimSuffix(line, []byte{' '})
// lack of continuation means this line has been exhausted
if !bytes.HasSuffix(line, []byte{'\\'}) {
break
}
}
// reached end of buffer, safe to exit
return next, nil
}
}
func (l *lexer) lexNextSection() (lexStep, error) {
r, _, err := l.buf.ReadRune()
if err != nil {
if err == io.EOF {
err = nil
}
return nil, err
}
if r == '[' {
return l.lexSectionName, nil
} else if isComment(r) {
return l.ignoreLineFunc(l.lexNextSection), nil
}
return l.lexNextSection, nil
}
func (l *lexer) lexNextSectionOrOptionFunc(section string) lexStep {
return func() (lexStep, error) {
r, _, err := l.buf.ReadRune()
if err != nil {
if err == io.EOF {
err = nil
}
return nil, err
}
if unicode.IsSpace(r) {
return l.lexNextSectionOrOptionFunc(section), nil
} else if r == '[' {
return l.lexSectionName, nil
} else if isComment(r) {
return l.ignoreLineFunc(l.lexNextSectionOrOptionFunc(section)), nil
}
l.buf.UnreadRune()
return l.lexOptionNameFunc(section), nil
}
}
func (l *lexer) lexOptionNameFunc(section string) lexStep {
return func() (lexStep, error) {
var partial bytes.Buffer
for {
r, _, err := l.buf.ReadRune()
if err != nil {
return nil, err
}
if r == '\n' || r == '\r' {
return nil, errors.New("unexpected newline encountered while parsing option name")
}
if r == '=' {
break
}
partial.WriteRune(r)
}
name := strings.TrimSpace(partial.String())
return l.lexOptionValueFunc(section, name, bytes.Buffer{}), nil
}
}
func (l *lexer) lexOptionValueFunc(section, name string, partial bytes.Buffer) lexStep {
return func() (lexStep, error) {
for {
line, eof, err := l.toEOL()
if err != nil {
return nil, err
}
if len(bytes.TrimSpace(line)) == 0 {
break
}
partial.Write(line)
// lack of continuation means this value has been exhausted
idx := bytes.LastIndex(line, []byte{'\\'})
if idx == -1 || idx != (len(line)-1) {
break
}
if !eof {
partial.WriteRune('\n')
}
return l.lexOptionValueFunc(section, name, partial), nil
}
val := partial.String()
if strings.HasSuffix(val, "\n") {
// A newline was added to the end, so the file didn't end with a backslash.
// => Keep the newline
val = strings.TrimSpace(val) + "\n"
} else {
val = strings.TrimSpace(val)
}
l.optchan <- &UnitOption{Section: section, Name: name, Value: val}
return l.lexNextSectionOrOptionFunc(section), nil
}
}
// toEOL reads until the end-of-line or end-of-file.
// Returns (data, EOFfound, error)
func (l *lexer) toEOL() ([]byte, bool, error) {
line, err := l.buf.ReadBytes('\n')
// ignore EOF here since it's roughly equivalent to EOL
if err != nil && err != io.EOF {
return nil, false, err
}
line = bytes.TrimSuffix(line, []byte{'\r'})
line = bytes.TrimSuffix(line, []byte{'\n'})
return line, err == io.EOF, nil
}
func isComment(r rune) bool {
return r == '#' || r == ';'
}

View File

@ -1,381 +0,0 @@
// Copyright 2015 CoreOS, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package unit
import (
"bytes"
"fmt"
"reflect"
"testing"
)
func TestDeserialize(t *testing.T) {
tests := []struct {
input []byte
output []*UnitOption
}{
// multiple options underneath a section
{
[]byte(`[Unit]
Description=Foo
Description=Bar
Requires=baz.service
After=baz.service
`),
[]*UnitOption{
&UnitOption{"Unit", "Description", "Foo"},
&UnitOption{"Unit", "Description", "Bar"},
&UnitOption{"Unit", "Requires", "baz.service"},
&UnitOption{"Unit", "After", "baz.service"},
},
},
// multiple sections
{
[]byte(`[Unit]
Description=Foo
[Service]
ExecStart=/usr/bin/sleep infinity
[X-Third-Party]
Pants=on
`),
[]*UnitOption{
&UnitOption{"Unit", "Description", "Foo"},
&UnitOption{"Service", "ExecStart", "/usr/bin/sleep infinity"},
&UnitOption{"X-Third-Party", "Pants", "on"},
},
},
// multiple sections with no options
{
[]byte(`[Unit]
[Service]
[X-Third-Party]
`),
[]*UnitOption{},
},
// multiple values not special-cased
{
[]byte(`[Service]
Environment= "FOO=BAR" "BAZ=QUX"
`),
[]*UnitOption{
&UnitOption{"Service", "Environment", "\"FOO=BAR\" \"BAZ=QUX\""},
},
},
// line continuations unmodified
{
[]byte(`[Unit]
Description= Unnecessarily wrapped \
words here
`),
[]*UnitOption{
&UnitOption{"Unit", "Description", `Unnecessarily wrapped \
words here`},
},
},
// comments ignored
{
[]byte(`; comment alpha
# comment bravo
[Unit]
; comment charlie
# comment delta
#Description=Foo
Description=Bar
; comment echo
# comment foxtrot
`),
[]*UnitOption{
&UnitOption{"Unit", "Description", "Bar"},
},
},
// apparent comment lines inside of line continuations not ignored
{
[]byte(`[Unit]
Description=Bar\
# comment alpha
Description=Bar\
# comment bravo \
Baz
`),
[]*UnitOption{
&UnitOption{"Unit", "Description", "Bar\\\n# comment alpha"},
&UnitOption{"Unit", "Description", "Bar\\\n# comment bravo \\\nBaz"},
},
},
// options outside of sections are ignored
{
[]byte(`Description=Foo
[Unit]
Description=Bar
`),
[]*UnitOption{
&UnitOption{"Unit", "Description", "Bar"},
},
},
// garbage outside of sections are ignored
{
[]byte(`<<<<<<<<
[Unit]
Description=Bar
`),
[]*UnitOption{
&UnitOption{"Unit", "Description", "Bar"},
},
},
// garbage used as unit option
{
[]byte(`[Unit]
<<<<<<<<=Bar
`),
[]*UnitOption{
&UnitOption{"Unit", "<<<<<<<<", "Bar"},
},
},
// option name with spaces are valid
{
[]byte(`[Unit]
Some Thing = Bar
`),
[]*UnitOption{
&UnitOption{"Unit", "Some Thing", "Bar"},
},
},
// lack of trailing newline doesn't cause problem for non-continued file
{
[]byte(`[Unit]
Description=Bar`),
[]*UnitOption{
&UnitOption{"Unit", "Description", "Bar"},
},
},
// unit file with continuation but no following line is ok, too
{
[]byte(`[Unit]
Description=Bar \`),
[]*UnitOption{
&UnitOption{"Unit", "Description", "Bar \\"},
},
},
// Assert utf8 characters are preserved
{
[]byte(`[©]
µ=ÇôrèÕ$`),
[]*UnitOption{
&UnitOption{"©", "µ☃", "ÇôrèÕ$"},
},
},
// whitespace removed around option name
{
[]byte(`[Unit]
Description =words here
`),
[]*UnitOption{
&UnitOption{"Unit", "Description", "words here"},
},
},
// whitespace around option value stripped
{
[]byte(`[Unit]
Description= words here `),
[]*UnitOption{
&UnitOption{"Unit", "Description", "words here"},
},
},
// whitespace around option value stripped, regardless of continuation
{
[]byte(`[Unit]
Description= words here \
`),
[]*UnitOption{
&UnitOption{"Unit", "Description", "words here \\\n"},
},
},
// backslash not considered continuation if followed by text
{
[]byte(`[Service]
ExecStart=/bin/bash -c "while true; do echo \"ping\"; sleep 1; done"
`),
[]*UnitOption{
&UnitOption{"Service", "ExecStart", `/bin/bash -c "while true; do echo \"ping\"; sleep 1; done"`},
},
},
// backslash not considered continuation if followed by whitespace, but still trimmed
{
[]byte(`[Service]
ExecStart=/bin/bash echo poof \ `),
[]*UnitOption{
&UnitOption{"Service", "ExecStart", `/bin/bash echo poof \`},
},
},
// a long unit file line that's just equal to the maximum permitted length
{
[]byte(`[Service]
ExecStart=/bin/bash -c "echo ................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................."`),
[]*UnitOption{
&UnitOption{"Service", "ExecStart", `/bin/bash -c "echo ................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................."`},
},
},
// the same, but with a trailing newline
{
[]byte(`[Service]
ExecStart=/bin/bash -c "echo ................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................."
Option=value
`),
[]*UnitOption{
&UnitOption{"Service", "ExecStart", `/bin/bash -c "echo ................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................."`},
&UnitOption{"Service", "Option", "value"},
},
},
}
assert := func(expect, output []*UnitOption) error {
if len(expect) != len(output) {
return fmt.Errorf("expected %d items, got %d", len(expect), len(output))
}
for i, _ := range expect {
if !reflect.DeepEqual(expect[i], output[i]) {
return fmt.Errorf("item %d: expected %v, got %v", i, expect[i], output[i])
}
}
return nil
}
for i, tt := range tests {
output, err := Deserialize(bytes.NewReader(tt.input))
if err != nil {
t.Errorf("case %d: unexpected error parsing unit: %v", i, err)
continue
}
err = assert(tt.output, output)
if err != nil {
t.Errorf("case %d: %v", i, err)
t.Log("Expected options:")
logUnitOptionSlice(t, tt.output)
t.Log("Actual options:")
logUnitOptionSlice(t, output)
}
}
}
func TestDeserializeFail(t *testing.T) {
tests := [][]byte{
// malformed section header
[]byte(`[Unit
Description=Foo
`),
// garbage following section header
[]byte(`[Unit] pants
Description=Foo
`),
// option without value
[]byte(`[Unit]
Description
`),
// garbage inside of section
[]byte(`[Unit]
<<<<<<
Description=Foo
`),
}
for i, tt := range tests {
output, err := Deserialize(bytes.NewReader(tt))
if err == nil {
t.Errorf("case %d: unexpected nil error", i)
t.Log("Output:")
logUnitOptionSlice(t, output)
}
}
}
func logUnitOptionSlice(t *testing.T, opts []*UnitOption) {
for idx, opt := range opts {
t.Logf("%d: %v", idx, opt)
}
}
func TestDeserializeLineTooLong(t *testing.T) {
tests := [][]byte{
// section header that's far too long
[]byte(`[Seeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeervice]
`),
// sane-looking unit file with a line just greater than the maximum allowed (currently, 2048)
[]byte(`[Service]
ExecStart=/bin/bash -c "echo ..................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................."
`),
// sane-looking unit file with option value way too long
[]byte(`
# test unit file
[Service]
ExecStartPre=-/usr/bin/docker rm %p
ExecStartPre=-/usr/bin/docker pull busybox
ExecStart=/usr/bin/docker run --rm --name %p --net=host \
-e "test=1123t" \
-e "test=1123t" \
-e "fiz=1123t" \
-e "buz=1123t" \
-e "FOO=BARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBABARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARRBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBAR"BARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBABARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARRBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBAR" \
busybox sleep 10
ExecStop=-/usr/bin/docker kill %p
SyslogIdentifier=busybox
Restart=always
RestartSec=10s
`),
// single arbitrary line that's way too long
[]byte(`arbitrary and extraordinarily long line that is far greater than 2048 characters arbitrary and extraordinarily long line that is far greater than 2048 character arbitrary and extraordinarily long line that is far greater than 2048 characters arbitrary and extraordinarily long line that is far greater than 2048 characters arbitrary and extraordinarily long line that is far greater than 2048 characters arbitrary and extraordinarily long line that is far greater than 2048 characters arbitrary and extraordinarily long line that is far greater than 2048 characters arbitrary and extraordinarily long line that is far greater than 2048 characters arbitrary and extraordinarily long line that is far greater than 2048 characters arbitrary and extraordinarily long line that is far greater than 2048 characters arbitrary and extraordinarily long line that is far greater than 2048 characters arbitrary and extraordinarily long line that is far greater than 2048 characters arbitrary and extraordinarily long line that is far greater than 2048 characters arbitrary and extraordinarily long line that is far greater than 2048 characters arbitrary and extraordinarily long line that is far greater than 2048 characters arbitrary and extraordinarily long line that is far greater than 2048 character arbitrary and extraordinarily long line that is far greater than 2048 characters arbitrary and extraordinarily long line that is far greater than 2048 characters arbitrary and extraordinarily long line that is far greater than 2048 characters arbitrary and extraordinarily long line that is far greater than 2048 characters arbitrary and extraordinarily long line that is far greater than 2048 characters arbitrary and extraordinarily long line that is far greater than 2048 characters arbitrary and extraordinarily long line that is far greater than 2048 characters arbitrary and extraordinarily long line that is far greater than 2048 characters arbitrary and extraordinarily long line that is far greater than 2048 characters arbitrary and extraordinarily long line that is far greater than 2048 characters arbitrary and extraordinarily long line that is far greater than 2048 characters arbitrary and extraordinarily long line that is far greater than 2048 characters arbitrary and extraordinarily long line that is far greater than 2048 characters arbitrary and extraordinarily long line that is far greater than 2048 character arbitrary and extraordinarily long line that is far greater than 2048 characters arbitrary and extraordinarily long line that is far greater than 2048 characters arbitrary and extraordinarily long line that is far greater than 2048 characters arbitrary and extraordinarily long line that is far greater than 2048 characters arbitrary and extraordinarily long line that is far greater than 2048 characters arbitrary and extraordinarily long line that is far greater than 2048 characters arbitrary and extraordinarily long line that is far greater than 2048 characters arbitrary and extraordinarily long line that is far greater than 2048 characters arbitrary and extraordinarily long line that is far greater than 2048 characters arbitrary and extraordinarily long line that is far greater than 2048 characters arbitrary and extraordinarily long line that is far greater than 2048 characters arbitrary and extraordinarily long line that is far greater than 2048 characters arbitrary and extraordinarily long line that is far greater than 2048 characters arbitrary and extraordinarily long line that is far greater than 2048 character arbitrary and extraordinarily long line that is far greater than 2048 characters arbitrary and extraordinarily long line that is far greater than 2048 characters arbitrary and extraordinarily long line that is far greater than 2048 characters arbitrary and extraordinarily long line that is far greater than 2048 characters arbitrary and extraordinarily long line that is far greater than 2048 characters arbitrary and extraordinarily long line that is far greater than 2048 characters arbitrary and extraordinarily long line that is far greater than 2048 characters arbitrary and extraordinarily long line that is far greater than 2048 characters arbitrary and extraordinarily long line that is far greater than 2048 characters arbitrary and extraordinarily long line that is far greater than 2048 characters arbitrary and extraordinarily long line that is far greater than 2048 characters arbitrary and extraordinarily long line that is far greater than 2048 characters`),
// sane-looking unit file with option name way too long
[]byte(`[Service]
ExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStartExecStart=/bin/true
`),
}
for i, tt := range tests {
output, err := Deserialize(bytes.NewReader(tt))
if err != ErrLineTooLong {
t.Errorf("case %d: unexpected err: %v", i, err)
t.Log("Output:")
logUnitOptionSlice(t, output)
}
}
}

View File

@ -1,88 +0,0 @@
// Copyright 2015 CoreOS, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package unit
import (
"bytes"
"io/ioutil"
"testing"
)
func TestDeserializeAndReserialize(t *testing.T) {
tests := []struct {
in string
wout string
}{
{
`[Service]
ExecStart=/bin/bash -c "while true; do echo \"ping\"; sleep 1; done"
`,
`[Service]
ExecStart=/bin/bash -c "while true; do echo \"ping\"; sleep 1; done"
`},
{
`[Unit]
Description= Unnecessarily wrapped \
words here`,
`[Unit]
Description=Unnecessarily wrapped \
words here
`,
},
{
`[Unit]
Description=Demo \
Requires=docker.service
`,
`[Unit]
Description=Demo \
Requires=docker.service
`,
},
{
`; comment alpha
# comment bravo
[Unit]
; comment charlie
# comment delta
#Description=Foo
Description=Bar
; comment echo
# comment foxtrot
`,
`[Unit]
Description=Bar
`},
}
for i, tt := range tests {
ds, err := Deserialize(bytes.NewBufferString(tt.in))
if err != nil {
t.Errorf("case %d: unexpected error parsing unit: %v", i, err)
continue
}
out, err := ioutil.ReadAll(Serialize(ds))
if err != nil {
t.Errorf("case %d: unexpected error serializing unit: %v", i, err)
continue
}
if g := string(out); g != tt.wout {
t.Errorf("case %d: incorrect output", i)
t.Logf("Expected:\n%#v", tt.wout)
t.Logf("Actual:\n%#v", g)
}
}
}

View File

@ -1,116 +0,0 @@
// Copyright 2015 CoreOS, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Implements systemd-escape [--unescape] [--path]
package unit
import (
"fmt"
"strconv"
"strings"
)
const (
allowed = `:_.abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789`
)
// If isPath is true:
// We remove redundant '/'s, the leading '/', and trailing '/'.
// If the result is empty, a '/' is inserted.
//
// We always:
// Replace the following characters with `\x%x`:
// Leading `.`
// `-`, `\`, and anything not in this set: `:-_.\[0-9a-zA-Z]`
// Replace '/' with '-'.
func escape(unescaped string, isPath bool) string {
e := []byte{}
inSlashes := false
start := true
for i := 0; i < len(unescaped); i++ {
c := unescaped[i]
if isPath {
if c == '/' {
inSlashes = true
continue
} else if inSlashes {
inSlashes = false
if !start {
e = append(e, '-')
}
}
}
if c == '/' {
e = append(e, '-')
} else if start && c == '.' || strings.IndexByte(allowed, c) == -1 {
e = append(e, []byte(fmt.Sprintf(`\x%x`, c))...)
} else {
e = append(e, c)
}
start = false
}
if isPath && len(e) == 0 {
e = append(e, '-')
}
return string(e)
}
// If isPath is true:
// We always return a string beginning with '/'.
//
// We always:
// Replace '-' with '/'.
// Replace `\x%x` with the value represented in hex.
func unescape(escaped string, isPath bool) string {
u := []byte{}
for i := 0; i < len(escaped); i++ {
c := escaped[i]
if c == '-' {
c = '/'
} else if c == '\\' && len(escaped)-i >= 4 && escaped[i+1] == 'x' {
n, err := strconv.ParseInt(escaped[i+2:i+4], 16, 8)
if err == nil {
c = byte(n)
i += 3
}
}
u = append(u, c)
}
if isPath && (len(u) == 0 || u[0] != '/') {
u = append([]byte("/"), u...)
}
return string(u)
}
// UnitNameEscape escapes a string as `systemd-escape` would
func UnitNameEscape(unescaped string) string {
return escape(unescaped, false)
}
// UnitNameUnescape unescapes a string as `systemd-escape --unescape` would
func UnitNameUnescape(escaped string) string {
return unescape(escaped, false)
}
// UnitNamePathEscape escapes a string as `systemd-escape --path` would
func UnitNamePathEscape(unescaped string) string {
return escape(unescaped, true)
}
// UnitNamePathUnescape unescapes a string as `systemd-escape --path --unescape` would
func UnitNamePathUnescape(escaped string) string {
return unescape(escaped, true)
}

View File

@ -1,211 +0,0 @@
// Copyright 2015 CoreOS, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package unit
import (
"testing"
)
func TestUnitNameEscape(t *testing.T) {
tests := []struct {
in string
out string
isPath bool
}{
// turn empty string path into escaped /
{
in: "",
out: "-",
isPath: true,
},
// turn redundant ////s into single escaped /
{
in: "/////////",
out: "-",
isPath: true,
},
// remove all redundant ////s
{
in: "///foo////bar/////tail//////",
out: "foo-bar-tail",
isPath: true,
},
// leave empty string empty
{
in: "",
out: "",
isPath: false,
},
// escape leading dot
{
in: ".",
out: `\x2e`,
isPath: true,
},
// escape leading dot
{
in: "/.",
out: `\x2e`,
isPath: true,
},
// escape leading dot
{
in: "/////////.",
out: `\x2e`,
isPath: true,
},
// escape leading dot
{
in: "/////////.///////////////",
out: `\x2e`,
isPath: true,
},
// escape leading dot
{
in: ".....",
out: `\x2e....`,
isPath: true,
},
// escape leading dot
{
in: "/.foo/.bar",
out: `\x2efoo-.bar`,
isPath: true,
},
// escape leading dot
{
in: ".foo/.bar",
out: `\x2efoo-.bar`,
isPath: true,
},
// escape leading dot
{
in: ".foo/.bar",
out: `\x2efoo-.bar`,
isPath: false,
},
// escape disallowed
{
in: `///..\-!#??///`,
out: `---..\x5c\x2d\x21\x23\x3f\x3f---`,
isPath: false,
},
// escape disallowed
{
in: `///..\-!#??///`,
out: `\x2e.\x5c\x2d\x21\x23\x3f\x3f`,
isPath: true,
},
// escape real-world example
{
in: `user-cloudinit@/var/lib/coreos/vagrant/vagrantfile-user-data.service`,
out: `user\x2dcloudinit\x40-var-lib-coreos-vagrant-vagrantfile\x2duser\x2ddata.service`,
isPath: false,
},
}
for i, tt := range tests {
var s string
if tt.isPath {
s = UnitNamePathEscape(tt.in)
} else {
s = UnitNameEscape(tt.in)
}
if s != tt.out {
t.Errorf("case %d: failed escaping %v isPath: %v - expected %v, got %v", i, tt.in, tt.isPath, tt.out, s)
}
}
}
func TestUnitNameUnescape(t *testing.T) {
tests := []struct {
in string
out string
isPath bool
}{
// turn empty string path into /
{
in: "",
out: "/",
isPath: true,
},
// leave empty string empty
{
in: "",
out: "",
isPath: false,
},
// turn ////s into
{
in: "---------",
out: "/////////",
isPath: true,
},
// unescape hex
{
in: `---..\x5c\x2d\x21\x23\x3f\x3f---`,
out: `///..\-!#??///`,
isPath: false,
},
// unescape hex
{
in: `\x2e.\x5c\x2d\x21\x23\x3f\x3f`,
out: `/..\-!#??`,
isPath: true,
},
// unescape hex, retain invalids
{
in: `\x2e.\x5c\x2d\xaZ\x.o\x21\x23\x3f\x3f`,
out: `/..\-\xaZ\x.o!#??`,
isPath: true,
},
// unescape hex, retain invalids, partial tail
{
in: `\x2e.\x5c\x\x2d\xaZ\x.o\x21\x23\x3f\x3f\x3`,
out: `/..\\x-\xaZ\x.o!#??\x3`,
isPath: true,
},
// unescape hex, retain invalids, partial tail
{
in: `\x2e.\x5c\x\x2d\xaZ\x.o\x21\x23\x3f\x3f\x`,
out: `/..\\x-\xaZ\x.o!#??\x`,
isPath: true,
},
// unescape hex, retain invalids, partial tail
{
in: `\x2e.\x5c\x\x2d\xaZ\x.o\x21\x23\x3f\x3f\`,
out: `/..\\x-\xaZ\x.o!#??\`,
isPath: true,
},
// unescape real-world example
{
in: `user\x2dcloudinit\x40-var-lib-coreos-vagrant-vagrantfile\x2duser\x2ddata.service`,
out: `user-cloudinit@/var/lib/coreos/vagrant/vagrantfile-user-data.service`,
isPath: false,
},
}
for i, tt := range tests {
var s string
if tt.isPath {
s = UnitNamePathUnescape(tt.in)
} else {
s = UnitNameUnescape(tt.in)
}
if s != tt.out {
t.Errorf("case %d: failed unescaping %v isPath: %v - expected %v, got %v", i, tt.in, tt.isPath, tt.out, s)
}
}
}

View File

@ -1,54 +0,0 @@
// Copyright 2015 CoreOS, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package unit
import (
"fmt"
)
type UnitOption struct {
Section string
Name string
Value string
}
func NewUnitOption(section, name, value string) *UnitOption {
return &UnitOption{Section: section, Name: name, Value: value}
}
func (uo *UnitOption) String() string {
return fmt.Sprintf("{Section: %q, Name: %q, Value: %q}", uo.Section, uo.Name, uo.Value)
}
func (uo *UnitOption) Match(other *UnitOption) bool {
return uo.Section == other.Section &&
uo.Name == other.Name &&
uo.Value == other.Value
}
func AllMatch(u1 []*UnitOption, u2 []*UnitOption) bool {
length := len(u1)
if length != len(u2) {
return false
}
for i := 0; i < length; i++ {
if !u1[i].Match(u2[i]) {
return false
}
}
return true
}

View File

@ -1,214 +0,0 @@
// Copyright 2015 CoreOS, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package unit
import (
"testing"
)
func TestAllMatch(t *testing.T) {
tests := []struct {
u1 []*UnitOption
u2 []*UnitOption
match bool
}{
// empty lists match
{
u1: []*UnitOption{},
u2: []*UnitOption{},
match: true,
},
// simple match of a single option
{
u1: []*UnitOption{
{Section: "Unit", Name: "Description", Value: "FOO"},
},
u2: []*UnitOption{
{Section: "Unit", Name: "Description", Value: "FOO"},
},
match: true,
},
// single option mismatched
{
u1: []*UnitOption{
{Section: "Unit", Name: "Description", Value: "FOO"},
},
u2: []*UnitOption{
{Section: "Unit", Name: "Description", Value: "BAR"},
},
match: false,
},
// multiple options match
{
u1: []*UnitOption{
{Section: "Unit", Name: "Description", Value: "FOO"},
{Section: "Unit", Name: "BindsTo", Value: "bar.service"},
{Section: "Service", Name: "ExecStart", Value: "/bin/true"},
},
u2: []*UnitOption{
{Section: "Unit", Name: "Description", Value: "FOO"},
{Section: "Unit", Name: "BindsTo", Value: "bar.service"},
{Section: "Service", Name: "ExecStart", Value: "/bin/true"},
},
match: true,
},
// mismatch length
{
u1: []*UnitOption{
{Section: "Unit", Name: "Description", Value: "FOO"},
{Section: "Unit", Name: "BindsTo", Value: "bar.service"},
},
u2: []*UnitOption{
{Section: "Unit", Name: "Description", Value: "FOO"},
{Section: "Unit", Name: "BindsTo", Value: "bar.service"},
{Section: "Service", Name: "ExecStart", Value: "/bin/true"},
},
match: false,
},
// multiple options misordered
{
u1: []*UnitOption{
{Section: "Unit", Name: "Description", Value: "FOO"},
{Section: "Service", Name: "ExecStart", Value: "/bin/true"},
},
u2: []*UnitOption{
{Section: "Service", Name: "ExecStart", Value: "/bin/true"},
{Section: "Unit", Name: "Description", Value: "FOO"},
},
match: false,
},
// interleaved sections mismatch
{
u1: []*UnitOption{
{Section: "Unit", Name: "Description", Value: "FOO"},
{Section: "Unit", Name: "BindsTo", Value: "bar.service"},
{Section: "Service", Name: "ExecStart", Value: "/bin/true"},
{Section: "Service", Name: "ExecStop", Value: "/bin/true"},
},
u2: []*UnitOption{
{Section: "Unit", Name: "Description", Value: "FOO"},
{Section: "Service", Name: "ExecStart", Value: "/bin/true"},
{Section: "Unit", Name: "BindsTo", Value: "bar.service"},
{Section: "Service", Name: "ExecStop", Value: "/bin/true"},
},
match: false,
},
}
for i, tt := range tests {
match := AllMatch(tt.u1, tt.u2)
if match != tt.match {
t.Errorf("case %d: failed comparing u1 to u2 - expected match=%t, got %t", i, tt.match, match)
}
match = AllMatch(tt.u2, tt.u1)
if match != tt.match {
t.Errorf("case %d: failed comparing u2 to u1 - expected match=%t, got %t", i, tt.match, match)
}
}
}
func TestMatch(t *testing.T) {
tests := []struct {
o1 *UnitOption
o2 *UnitOption
match bool
}{
// empty options match
{
o1: &UnitOption{},
o2: &UnitOption{},
match: true,
},
// all fields match
{
o1: &UnitOption{
Section: "Unit",
Name: "Description",
Value: "FOO",
},
o2: &UnitOption{
Section: "Unit",
Name: "Description",
Value: "FOO",
},
match: true,
},
// Section mismatch
{
o1: &UnitOption{
Section: "Unit",
Name: "Description",
Value: "FOO",
},
o2: &UnitOption{
Section: "X-Other",
Name: "Description",
Value: "FOO",
},
match: false,
},
// Name mismatch
{
o1: &UnitOption{
Section: "Unit",
Name: "Description",
Value: "FOO",
},
o2: &UnitOption{
Section: "Unit",
Name: "BindsTo",
Value: "FOO",
},
match: false,
},
// Value mismatch
{
o1: &UnitOption{
Section: "Unit",
Name: "Description",
Value: "FOO",
},
o2: &UnitOption{
Section: "Unit",
Name: "Description",
Value: "BAR",
},
match: false,
},
}
for i, tt := range tests {
match := tt.o1.Match(tt.o2)
if match != tt.match {
t.Errorf("case %d: failed comparing o1 to o2 - expected match=%t, got %t", i, tt.match, match)
}
match = tt.o2.Match(tt.o1)
if match != tt.match {
t.Errorf("case %d: failed comparing o2 to o1 - expected match=%t, got %t", i, tt.match, match)
}
}
}

View File

@ -1,75 +0,0 @@
// Copyright 2015 CoreOS, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package unit
import (
"bytes"
"io"
)
// Serialize encodes all of the given UnitOption objects into a
// unit file. When serialized the options are sorted in their
// supplied order but grouped by section.
func Serialize(opts []*UnitOption) io.Reader {
var buf bytes.Buffer
if len(opts) == 0 {
return &buf
}
// Index of sections -> ordered options
idx := map[string][]*UnitOption{}
// Separately preserve order in which sections were seen
sections := []string{}
for _, opt := range opts {
sec := opt.Section
if _, ok := idx[sec]; !ok {
sections = append(sections, sec)
}
idx[sec] = append(idx[sec], opt)
}
for i, sect := range sections {
writeSectionHeader(&buf, sect)
writeNewline(&buf)
opts := idx[sect]
for _, opt := range opts {
writeOption(&buf, opt)
writeNewline(&buf)
}
if i < len(sections)-1 {
writeNewline(&buf)
}
}
return &buf
}
func writeNewline(buf *bytes.Buffer) {
buf.WriteRune('\n')
}
func writeSectionHeader(buf *bytes.Buffer, section string) {
buf.WriteRune('[')
buf.WriteString(section)
buf.WriteRune(']')
}
func writeOption(buf *bytes.Buffer, opt *UnitOption) {
buf.WriteString(opt.Name)
buf.WriteRune('=')
buf.WriteString(opt.Value)
}

View File

@ -1,170 +0,0 @@
// Copyright 2015 CoreOS, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package unit
import (
"io/ioutil"
"testing"
)
func TestSerialize(t *testing.T) {
tests := []struct {
input []*UnitOption
output string
}{
// no options results in empty file
{
[]*UnitOption{},
``,
},
// options with same section share the header
{
[]*UnitOption{
&UnitOption{"Unit", "Description", "Foo"},
&UnitOption{"Unit", "BindsTo", "bar.service"},
},
`[Unit]
Description=Foo
BindsTo=bar.service
`,
},
// options with same name are not combined
{
[]*UnitOption{
&UnitOption{"Unit", "Description", "Foo"},
&UnitOption{"Unit", "Description", "Bar"},
},
`[Unit]
Description=Foo
Description=Bar
`,
},
// multiple options printed under different section headers
{
[]*UnitOption{
&UnitOption{"Unit", "Description", "Foo"},
&UnitOption{"Service", "ExecStart", "/usr/bin/sleep infinity"},
},
`[Unit]
Description=Foo
[Service]
ExecStart=/usr/bin/sleep infinity
`,
},
// options are grouped into sections
{
[]*UnitOption{
&UnitOption{"Unit", "Description", "Foo"},
&UnitOption{"Service", "ExecStart", "/usr/bin/sleep infinity"},
&UnitOption{"Unit", "BindsTo", "bar.service"},
},
`[Unit]
Description=Foo
BindsTo=bar.service
[Service]
ExecStart=/usr/bin/sleep infinity
`,
},
// options are ordered within groups, and sections are ordered in the order in which they were first seen
{
[]*UnitOption{
&UnitOption{"Unit", "Description", "Foo"},
&UnitOption{"Service", "ExecStart", "/usr/bin/sleep infinity"},
&UnitOption{"Unit", "BindsTo", "bar.service"},
&UnitOption{"X-Foo", "Bar", "baz"},
&UnitOption{"Service", "ExecStop", "/usr/bin/sleep 1"},
&UnitOption{"Unit", "Documentation", "https://foo.com"},
},
`[Unit]
Description=Foo
BindsTo=bar.service
Documentation=https://foo.com
[Service]
ExecStart=/usr/bin/sleep infinity
ExecStop=/usr/bin/sleep 1
[X-Foo]
Bar=baz
`,
},
// utf8 characters are not a problem
{
[]*UnitOption{
&UnitOption{"©", "µ☃", "ÇôrèÕ$"},
},
`[©]
µ=ÇôrèÕ$
`,
},
// no verification is done on section names
{
[]*UnitOption{
&UnitOption{"Un\nit", "Description", "Foo"},
},
`[Un
it]
Description=Foo
`,
},
// no verification is done on option names
{
[]*UnitOption{
&UnitOption{"Unit", "Desc\nription", "Foo"},
},
`[Unit]
Desc
ription=Foo
`,
},
// no verification is done on option values
{
[]*UnitOption{
&UnitOption{"Unit", "Description", "Fo\no"},
},
`[Unit]
Description=Fo
o
`,
},
}
for i, tt := range tests {
outReader := Serialize(tt.input)
outBytes, err := ioutil.ReadAll(outReader)
if err != nil {
t.Errorf("case %d: encountered error while reading output: %v", i, err)
continue
}
output := string(outBytes)
if tt.output != output {
t.Errorf("case %d: incorrect output", i)
t.Logf("Expected:\n%s", tt.output)
t.Logf("Actual:\n%s", output)
}
}
}

View File

@ -1,90 +0,0 @@
// Copyright 2015 CoreOS, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package util contains utility functions related to systemd that applications
// can use to check things like whether systemd is running. Note that some of
// these functions attempt to manually load systemd libraries at runtime rather
// than linking against them.
package util
import (
"fmt"
"io/ioutil"
"os"
"strings"
)
var (
ErrNoCGO = fmt.Errorf("go-systemd built with CGO disabled")
)
// GetRunningSlice attempts to retrieve the name of the systemd slice in which
// the current process is running.
// This function is a wrapper around the libsystemd C library; if it cannot be
// opened, an error is returned.
func GetRunningSlice() (string, error) {
return getRunningSlice()
}
// RunningFromSystemService tries to detect whether the current process has
// been invoked from a system service. The condition for this is whether the
// process is _not_ a user process. User processes are those running in session
// scopes or under per-user `systemd --user` instances.
//
// To avoid false positives on systems without `pam_systemd` (which is
// responsible for creating user sessions), this function also uses a heuristic
// to detect whether it's being invoked from a session leader process. This is
// the case if the current process is executed directly from a service file
// (e.g. with `ExecStart=/this/cmd`). Note that this heuristic will fail if the
// command is instead launched in a subshell or similar so that it is not
// session leader (e.g. `ExecStart=/bin/bash -c "/this/cmd"`)
//
// This function is a wrapper around the libsystemd C library; if this is
// unable to successfully open a handle to the library for any reason (e.g. it
// cannot be found), an error will be returned.
func RunningFromSystemService() (bool, error) {
return runningFromSystemService()
}
// CurrentUnitName attempts to retrieve the name of the systemd system unit
// from which the calling process has been invoked. It wraps the systemd
// `sd_pid_get_unit` call, with the same caveat: for processes not part of a
// systemd system unit, this function will return an error.
func CurrentUnitName() (string, error) {
return currentUnitName()
}
// IsRunningSystemd checks whether the host was booted with systemd as its init
// system. This functions similarly to systemd's `sd_booted(3)`: internally, it
// checks whether /run/systemd/system/ exists and is a directory.
// http://www.freedesktop.org/software/systemd/man/sd_booted.html
func IsRunningSystemd() bool {
fi, err := os.Lstat("/run/systemd/system")
if err != nil {
return false
}
return fi.IsDir()
}
// GetMachineID returns a host's 128-bit machine ID as a string. This functions
// similarly to systemd's `sd_id128_get_machine`: internally, it simply reads
// the contents of /etc/machine-id
// http://www.freedesktop.org/software/systemd/man/sd_id128_get_machine.html
func GetMachineID() (string, error) {
machineID, err := ioutil.ReadFile("/etc/machine-id")
if err != nil {
return "", fmt.Errorf("failed to read /etc/machine-id: %v", err)
}
return strings.TrimSpace(string(machineID)), nil
}

View File

@ -1,174 +0,0 @@
// Copyright 2016 CoreOS, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// +build cgo
package util
// #include <stdlib.h>
// #include <sys/types.h>
// #include <unistd.h>
//
// int
// my_sd_pid_get_owner_uid(void *f, pid_t pid, uid_t *uid)
// {
// int (*sd_pid_get_owner_uid)(pid_t, uid_t *);
//
// sd_pid_get_owner_uid = (int (*)(pid_t, uid_t *))f;
// return sd_pid_get_owner_uid(pid, uid);
// }
//
// int
// my_sd_pid_get_unit(void *f, pid_t pid, char **unit)
// {
// int (*sd_pid_get_unit)(pid_t, char **);
//
// sd_pid_get_unit = (int (*)(pid_t, char **))f;
// return sd_pid_get_unit(pid, unit);
// }
//
// int
// my_sd_pid_get_slice(void *f, pid_t pid, char **slice)
// {
// int (*sd_pid_get_slice)(pid_t, char **);
//
// sd_pid_get_slice = (int (*)(pid_t, char **))f;
// return sd_pid_get_slice(pid, slice);
// }
//
// int
// am_session_leader()
// {
// return (getsid(0) == getpid());
// }
import "C"
import (
"fmt"
"syscall"
"unsafe"
"github.com/coreos/pkg/dlopen"
)
var libsystemdNames = []string{
// systemd < 209
"libsystemd-login.so.0",
"libsystemd-login.so",
// systemd >= 209 merged libsystemd-login into libsystemd proper
"libsystemd.so.0",
"libsystemd.so",
}
func getRunningSlice() (slice string, err error) {
var h *dlopen.LibHandle
h, err = dlopen.GetHandle(libsystemdNames)
if err != nil {
return
}
defer func() {
if err1 := h.Close(); err1 != nil {
err = err1
}
}()
sd_pid_get_slice, err := h.GetSymbolPointer("sd_pid_get_slice")
if err != nil {
return
}
var s string
sl := C.CString(s)
defer C.free(unsafe.Pointer(sl))
ret := C.my_sd_pid_get_slice(sd_pid_get_slice, 0, &sl)
if ret < 0 {
err = fmt.Errorf("error calling sd_pid_get_slice: %v", syscall.Errno(-ret))
return
}
return C.GoString(sl), nil
}
func runningFromSystemService() (ret bool, err error) {
var h *dlopen.LibHandle
h, err = dlopen.GetHandle(libsystemdNames)
if err != nil {
return
}
defer func() {
if err1 := h.Close(); err1 != nil {
err = err1
}
}()
sd_pid_get_owner_uid, err := h.GetSymbolPointer("sd_pid_get_owner_uid")
if err != nil {
return
}
var uid C.uid_t
errno := C.my_sd_pid_get_owner_uid(sd_pid_get_owner_uid, 0, &uid)
serrno := syscall.Errno(-errno)
// when we're running from a unit file, sd_pid_get_owner_uid returns
// ENOENT (systemd <220) or ENXIO (systemd >=220)
switch {
case errno >= 0:
ret = false
case serrno == syscall.ENOENT, serrno == syscall.ENXIO:
// Since the implementation of sessions in systemd relies on
// the `pam_systemd` module, using the sd_pid_get_owner_uid
// heuristic alone can result in false positives if that module
// (or PAM itself) is not present or properly configured on the
// system. As such, we also check if we're the session leader,
// which should be the case if we're invoked from a unit file,
// but not if e.g. we're invoked from the command line from a
// user's login session
ret = C.am_session_leader() == 1
default:
err = fmt.Errorf("error calling sd_pid_get_owner_uid: %v", syscall.Errno(-errno))
}
return
}
func currentUnitName() (unit string, err error) {
var h *dlopen.LibHandle
h, err = dlopen.GetHandle(libsystemdNames)
if err != nil {
return
}
defer func() {
if err1 := h.Close(); err1 != nil {
err = err1
}
}()
sd_pid_get_unit, err := h.GetSymbolPointer("sd_pid_get_unit")
if err != nil {
return
}
var s string
u := C.CString(s)
defer C.free(unsafe.Pointer(u))
ret := C.my_sd_pid_get_unit(sd_pid_get_unit, 0, &u)
if ret < 0 {
err = fmt.Errorf("error calling sd_pid_get_unit: %v", syscall.Errno(-ret))
return
}
unit = C.GoString(u)
return
}

View File

@ -1,23 +0,0 @@
// Copyright 2016 CoreOS, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// +build !cgo
package util
func getRunningSlice() (string, error) { return "", ErrNoCGO }
func runningFromSystemService() (bool, error) { return false, ErrNoCGO }
func currentUnitName() (string, error) { return "", ErrNoCGO }

View File

@ -1,74 +0,0 @@
// Copyright 2016 CoreOS, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package util
import (
"testing"
)
func testIsRunningSystemd(t *testing.T) {
if !IsRunningSystemd() {
t.Skip("Not running on a systemd host")
}
}
func TestRunningFromSystemService(t *testing.T) {
testIsRunningSystemd(t)
t.Parallel()
// tests shouldn't be running as a service
s, err := RunningFromSystemService()
if err != nil {
t.Error(err.Error())
} else if s {
t.Errorf("tests aren't expected to run as a service")
}
}
func TestCurrentUnitName(t *testing.T) {
testIsRunningSystemd(t)
s, err := CurrentUnitName()
if err != nil {
t.Error(err.Error())
}
if s == "" {
t.Error("CurrentUnitName returned a empty string")
}
}
func TestGetMachineID(t *testing.T) {
testIsRunningSystemd(t)
id, err := GetMachineID()
if err != nil {
t.Error(err.Error())
}
if id == "" {
t.Error("GetMachineID returned a empty string")
}
}
func TestGetRunningSlice(t *testing.T) {
testIsRunningSystemd(t)
s, err := getRunningSlice()
if err != nil {
t.Error(err.Error())
}
if s == "" {
t.Error("getRunningSlice returned a empty string")
}
}

View File

@ -1,40 +0,0 @@
dist: precise
language: go
go_import_path: github.com/godbus/dbus
sudo: true
go:
- 1.6.3
- 1.7.3
- tip
env:
global:
matrix:
- TARGET=amd64
- TARGET=arm64
- TARGET=arm
- TARGET=386
- TARGET=ppc64le
matrix:
fast_finish: true
allow_failures:
- go: tip
exclude:
- go: tip
env: TARGET=arm
- go: tip
env: TARGET=arm64
- go: tip
env: TARGET=386
- go: tip
env: TARGET=ppc64le
addons:
apt:
packages:
- dbus
- dbus-x11
before_install:

View File

@ -1,50 +0,0 @@
# How to Contribute
## Getting Started
- Fork the repository on GitHub
- Read the [README](README.markdown) for build and test instructions
- Play with the project, submit bugs, submit patches!
## Contribution Flow
This is a rough outline of what a contributor's workflow looks like:
- Create a topic branch from where you want to base your work (usually master).
- Make commits of logical units.
- Make sure your commit messages are in the proper format (see below).
- Push your changes to a topic branch in your fork of the repository.
- Make sure the tests pass, and add any new tests as appropriate.
- Submit a pull request to the original repository.
Thanks for your contributions!
### Format of the Commit Message
We follow a rough convention for commit messages that is designed to answer two
questions: what changed and why. The subject line should feature the what and
the body of the commit should describe the why.
```
scripts: add the test-cluster command
this uses tmux to setup a test cluster that you can easily kill and
start for debugging.
Fixes #38
```
The format can be described more formally as follows:
```
<subsystem>: <what changed>
<BLANK LINE>
<why this change was made>
<BLANK LINE>
<footer>
```
The first line is the subject and should be no longer than 70 characters, the
second line is always blank, and other lines should be wrapped at 80 characters.
This allows the message to be easier to read on GitHub as well as in various
git tools.

View File

@ -1,25 +0,0 @@
Copyright (c) 2013, Georg Reinke (<guelfey at gmail dot com>), Google
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

View File

@ -1,3 +0,0 @@
Brandon Philips <brandon@ifup.org> (@philips)
Brian Waldon <brian@waldon.cc> (@bcwaldon)
John Southworth <jsouthwo@brocade.com> (@jsouthworth)

View File

@ -1,43 +0,0 @@
[![Build Status](https://travis-ci.org/godbus/dbus.svg?branch=master)](https://travis-ci.org/godbus/dbus)
dbus
----
dbus is a simple library that implements native Go client bindings for the
D-Bus message bus system.
### Features
* Complete native implementation of the D-Bus message protocol
* Go-like API (channels for signals / asynchronous method calls, Goroutine-safe connections)
* Subpackages that help with the introspection / property interfaces
### Installation
This packages requires Go 1.1. If you installed it and set up your GOPATH, just run:
```
go get github.com/godbus/dbus
```
If you want to use the subpackages, you can install them the same way.
### Usage
The complete package documentation and some simple examples are available at
[godoc.org](http://godoc.org/github.com/godbus/dbus). Also, the
[_examples](https://github.com/godbus/dbus/tree/master/_examples) directory
gives a short overview over the basic usage.
#### Projects using godbus
- [notify](https://github.com/esiqveland/notify) provides desktop notifications over dbus into a library.
Please note that the API is considered unstable for now and may change without
further notice.
### License
go.dbus is available under the Simplified BSD License; see LICENSE for the full
text.
Nearly all of the credit for this library goes to github.com/guelfey/go.dbus.

View File

@ -1,25 +0,0 @@
package main
import (
"fmt"
"os"
"github.com/godbus/dbus"
)
func main() {
conn, err := dbus.SystemBus()
if err != nil {
fmt.Fprintln(os.Stderr, "Failed to connect to SystemBus bus:", err)
os.Exit(1)
}
var s string
err = conn.Object("org.bluez", "/").Call("org.freedesktop.DBus.Introspectable.Introspect", 0).Store(&s)
if err != nil {
fmt.Fprintln(os.Stderr, "Failed to introspect bluez", err)
os.Exit(1)
}
fmt.Println(s)
}

View File

@ -1,30 +0,0 @@
package main
import (
"fmt"
"github.com/godbus/dbus"
"os"
)
func main() {
conn, err := dbus.SessionBus()
if err != nil {
fmt.Fprintln(os.Stderr, "Failed to connect to session bus:", err)
os.Exit(1)
}
for _, v := range []string{"method_call", "method_return", "error", "signal"} {
call := conn.BusObject().Call("org.freedesktop.DBus.AddMatch", 0,
"eavesdrop='true',type='"+v+"'")
if call.Err != nil {
fmt.Fprintln(os.Stderr, "Failed to add match:", call.Err)
os.Exit(1)
}
}
c := make(chan *dbus.Message, 10)
conn.Eavesdrop(c)
fmt.Println("Listening for everything")
for v := range c {
fmt.Println(v)
}
}

View File

@ -1,21 +0,0 @@
package main
import (
"encoding/json"
"github.com/godbus/dbus"
"github.com/godbus/dbus/introspect"
"os"
)
func main() {
conn, err := dbus.SessionBus()
if err != nil {
panic(err)
}
node, err := introspect.Call(conn.Object("org.freedesktop.DBus", "/org/freedesktop/DBus"))
if err != nil {
panic(err)
}
data, _ := json.MarshalIndent(node, "", " ")
os.Stdout.Write(data)
}

View File

@ -1,27 +0,0 @@
package main
import (
"fmt"
"github.com/godbus/dbus"
"os"
)
func main() {
conn, err := dbus.SessionBus()
if err != nil {
fmt.Fprintln(os.Stderr, "Failed to connect to session bus:", err)
os.Exit(1)
}
var s []string
err = conn.BusObject().Call("org.freedesktop.DBus.ListNames", 0).Store(&s)
if err != nil {
fmt.Fprintln(os.Stderr, "Failed to get list of owned names:", err)
os.Exit(1)
}
fmt.Println("Currently owned names on the session bus:")
for _, v := range s {
fmt.Println(v)
}
}

View File

@ -1,17 +0,0 @@
package main
import "github.com/godbus/dbus"
func main() {
conn, err := dbus.SessionBus()
if err != nil {
panic(err)
}
obj := conn.Object("org.freedesktop.Notifications", "/org/freedesktop/Notifications")
call := obj.Call("org.freedesktop.Notifications.Notify", 0, "", uint32(0),
"", "Test", "This is a test of the DBus bindings for go.", []string{},
map[string]dbus.Variant{}, int32(5000))
if call.Err != nil {
panic(call.Err)
}
}

View File

@ -1,68 +0,0 @@
package main
import (
"fmt"
"github.com/godbus/dbus"
"github.com/godbus/dbus/introspect"
"github.com/godbus/dbus/prop"
"os"
)
type foo string
func (f foo) Foo() (string, *dbus.Error) {
fmt.Println(f)
return string(f), nil
}
func main() {
conn, err := dbus.SessionBus()
if err != nil {
panic(err)
}
reply, err := conn.RequestName("com.github.guelfey.Demo",
dbus.NameFlagDoNotQueue)
if err != nil {
panic(err)
}
if reply != dbus.RequestNameReplyPrimaryOwner {
fmt.Fprintln(os.Stderr, "name already taken")
os.Exit(1)
}
propsSpec := map[string]map[string]*prop.Prop{
"com.github.guelfey.Demo": {
"SomeInt": {
int32(0),
true,
prop.EmitTrue,
func(c *prop.Change) *dbus.Error {
fmt.Println(c.Name, "changed to", c.Value)
return nil
},
},
},
}
f := foo("Bar")
conn.Export(f, "/com/github/guelfey/Demo", "com.github.guelfey.Demo")
props := prop.New(conn, "/com/github/guelfey/Demo", propsSpec)
n := &introspect.Node{
Name: "/com/github/guelfey/Demo",
Interfaces: []introspect.Interface{
introspect.IntrospectData,
prop.IntrospectData,
{
Name: "com.github.guelfey.Demo",
Methods: introspect.Methods(f),
Properties: props.Introspection("com.github.guelfey.Demo"),
},
},
}
conn.Export(introspect.NewIntrospectable(n), "/com/github/guelfey/Demo",
"org.freedesktop.DBus.Introspectable")
fmt.Println("Listening on com.github.guelfey.Demo / /com/github/guelfey/Demo ...")
c := make(chan *dbus.Signal)
conn.Signal(c)
for _ = range c {
}
}

View File

@ -1,45 +0,0 @@
package main
import (
"fmt"
"github.com/godbus/dbus"
"github.com/godbus/dbus/introspect"
"os"
)
const intro = `
<node>
<interface name="com.github.guelfey.Demo">
<method name="Foo">
<arg direction="out" type="s"/>
</method>
</interface>` + introspect.IntrospectDataString + `</node> `
type foo string
func (f foo) Foo() (string, *dbus.Error) {
fmt.Println(f)
return string(f), nil
}
func main() {
conn, err := dbus.SessionBus()
if err != nil {
panic(err)
}
reply, err := conn.RequestName("com.github.guelfey.Demo",
dbus.NameFlagDoNotQueue)
if err != nil {
panic(err)
}
if reply != dbus.RequestNameReplyPrimaryOwner {
fmt.Fprintln(os.Stderr, "name already taken")
os.Exit(1)
}
f := foo("Bar!")
conn.Export(f, "/com/github/guelfey/Demo", "com.github.guelfey.Demo")
conn.Export(introspect.Introspectable(intro), "/com/github/guelfey/Demo",
"org.freedesktop.DBus.Introspectable")
fmt.Println("Listening on com.github.guelfey.Demo / /com/github/guelfey/Demo ...")
select {}
}

View File

@ -1,24 +0,0 @@
package main
import (
"fmt"
"github.com/godbus/dbus"
"os"
)
func main() {
conn, err := dbus.SessionBus()
if err != nil {
fmt.Fprintln(os.Stderr, "Failed to connect to session bus:", err)
os.Exit(1)
}
conn.BusObject().Call("org.freedesktop.DBus.AddMatch", 0,
"type='signal',path='/org/freedesktop/DBus',interface='org.freedesktop.DBus',sender='org.freedesktop.DBus'")
c := make(chan *dbus.Signal, 10)
conn.Signal(c)
for v := range c {
fmt.Println(v)
}
}

View File

@ -1,253 +0,0 @@
package dbus
import (
"bufio"
"bytes"
"errors"
"io"
"os"
"strconv"
)
// AuthStatus represents the Status of an authentication mechanism.
type AuthStatus byte
const (
// AuthOk signals that authentication is finished; the next command
// from the server should be an OK.
AuthOk AuthStatus = iota
// AuthContinue signals that additional data is needed; the next command
// from the server should be a DATA.
AuthContinue
// AuthError signals an error; the server sent invalid data or some
// other unexpected thing happened and the current authentication
// process should be aborted.
AuthError
)
type authState byte
const (
waitingForData authState = iota
waitingForOk
waitingForReject
)
// Auth defines the behaviour of an authentication mechanism.
type Auth interface {
// Return the name of the mechnism, the argument to the first AUTH command
// and the next status.
FirstData() (name, resp []byte, status AuthStatus)
// Process the given DATA command, and return the argument to the DATA
// command and the next status. If len(resp) == 0, no DATA command is sent.
HandleData(data []byte) (resp []byte, status AuthStatus)
}
// Auth authenticates the connection, trying the given list of authentication
// mechanisms (in that order). If nil is passed, the EXTERNAL and
// DBUS_COOKIE_SHA1 mechanisms are tried for the current user. For private
// connections, this method must be called before sending any messages to the
// bus. Auth must not be called on shared connections.
func (conn *Conn) Auth(methods []Auth) error {
if methods == nil {
uid := strconv.Itoa(os.Getuid())
methods = []Auth{AuthExternal(uid), AuthCookieSha1(uid, getHomeDir())}
}
in := bufio.NewReader(conn.transport)
err := conn.transport.SendNullByte()
if err != nil {
return err
}
err = authWriteLine(conn.transport, []byte("AUTH"))
if err != nil {
return err
}
s, err := authReadLine(in)
if err != nil {
return err
}
if len(s) < 2 || !bytes.Equal(s[0], []byte("REJECTED")) {
return errors.New("dbus: authentication protocol error")
}
s = s[1:]
for _, v := range s {
for _, m := range methods {
if name, data, status := m.FirstData(); bytes.Equal(v, name) {
var ok bool
err = authWriteLine(conn.transport, []byte("AUTH"), []byte(v), data)
if err != nil {
return err
}
switch status {
case AuthOk:
err, ok = conn.tryAuth(m, waitingForOk, in)
case AuthContinue:
err, ok = conn.tryAuth(m, waitingForData, in)
default:
panic("dbus: invalid authentication status")
}
if err != nil {
return err
}
if ok {
if conn.transport.SupportsUnixFDs() {
err = authWriteLine(conn, []byte("NEGOTIATE_UNIX_FD"))
if err != nil {
return err
}
line, err := authReadLine(in)
if err != nil {
return err
}
switch {
case bytes.Equal(line[0], []byte("AGREE_UNIX_FD")):
conn.EnableUnixFDs()
conn.unixFD = true
case bytes.Equal(line[0], []byte("ERROR")):
default:
return errors.New("dbus: authentication protocol error")
}
}
err = authWriteLine(conn.transport, []byte("BEGIN"))
if err != nil {
return err
}
go conn.inWorker()
go conn.outWorker()
return nil
}
}
}
}
return errors.New("dbus: authentication failed")
}
// tryAuth tries to authenticate with m as the mechanism, using state as the
// initial authState and in for reading input. It returns (nil, true) on
// success, (nil, false) on a REJECTED and (someErr, false) if some other
// error occured.
func (conn *Conn) tryAuth(m Auth, state authState, in *bufio.Reader) (error, bool) {
for {
s, err := authReadLine(in)
if err != nil {
return err, false
}
switch {
case state == waitingForData && string(s[0]) == "DATA":
if len(s) != 2 {
err = authWriteLine(conn.transport, []byte("ERROR"))
if err != nil {
return err, false
}
continue
}
data, status := m.HandleData(s[1])
switch status {
case AuthOk, AuthContinue:
if len(data) != 0 {
err = authWriteLine(conn.transport, []byte("DATA"), data)
if err != nil {
return err, false
}
}
if status == AuthOk {
state = waitingForOk
}
case AuthError:
err = authWriteLine(conn.transport, []byte("ERROR"))
if err != nil {
return err, false
}
}
case state == waitingForData && string(s[0]) == "REJECTED":
return nil, false
case state == waitingForData && string(s[0]) == "ERROR":
err = authWriteLine(conn.transport, []byte("CANCEL"))
if err != nil {
return err, false
}
state = waitingForReject
case state == waitingForData && string(s[0]) == "OK":
if len(s) != 2 {
err = authWriteLine(conn.transport, []byte("CANCEL"))
if err != nil {
return err, false
}
state = waitingForReject
}
conn.uuid = string(s[1])
return nil, true
case state == waitingForData:
err = authWriteLine(conn.transport, []byte("ERROR"))
if err != nil {
return err, false
}
case state == waitingForOk && string(s[0]) == "OK":
if len(s) != 2 {
err = authWriteLine(conn.transport, []byte("CANCEL"))
if err != nil {
return err, false
}
state = waitingForReject
}
conn.uuid = string(s[1])
return nil, true
case state == waitingForOk && string(s[0]) == "REJECTED":
return nil, false
case state == waitingForOk && (string(s[0]) == "DATA" ||
string(s[0]) == "ERROR"):
err = authWriteLine(conn.transport, []byte("CANCEL"))
if err != nil {
return err, false
}
state = waitingForReject
case state == waitingForOk:
err = authWriteLine(conn.transport, []byte("ERROR"))
if err != nil {
return err, false
}
case state == waitingForReject && string(s[0]) == "REJECTED":
return nil, false
case state == waitingForReject:
return errors.New("dbus: authentication protocol error"), false
default:
panic("dbus: invalid auth state")
}
}
}
// authReadLine reads a line and separates it into its fields.
func authReadLine(in *bufio.Reader) ([][]byte, error) {
data, err := in.ReadBytes('\n')
if err != nil {
return nil, err
}
data = bytes.TrimSuffix(data, []byte("\r\n"))
return bytes.Split(data, []byte{' '}), nil
}
// authWriteLine writes the given line in the authentication protocol format
// (elements of data separated by a " " and terminated by "\r\n").
func authWriteLine(out io.Writer, data ...[]byte) error {
buf := make([]byte, 0)
for i, v := range data {
buf = append(buf, v...)
if i != len(data)-1 {
buf = append(buf, ' ')
}
}
buf = append(buf, '\r')
buf = append(buf, '\n')
n, err := out.Write(buf)
if err != nil {
return err
}
if n != len(buf) {
return io.ErrUnexpectedEOF
}
return nil
}

View File

@ -1,26 +0,0 @@
package dbus
import (
"encoding/hex"
)
// AuthExternal returns an Auth that authenticates as the given user with the
// EXTERNAL mechanism.
func AuthExternal(user string) Auth {
return authExternal{user}
}
// AuthExternal implements the EXTERNAL authentication mechanism.
type authExternal struct {
user string
}
func (a authExternal) FirstData() ([]byte, []byte, AuthStatus) {
b := make([]byte, 2*len(a.user))
hex.Encode(b, []byte(a.user))
return []byte("EXTERNAL"), b, AuthOk
}
func (a authExternal) HandleData(b []byte) ([]byte, AuthStatus) {
return nil, AuthError
}

View File

@ -1,102 +0,0 @@
package dbus
import (
"bufio"
"bytes"
"crypto/rand"
"crypto/sha1"
"encoding/hex"
"os"
)
// AuthCookieSha1 returns an Auth that authenticates as the given user with the
// DBUS_COOKIE_SHA1 mechanism. The home parameter should specify the home
// directory of the user.
func AuthCookieSha1(user, home string) Auth {
return authCookieSha1{user, home}
}
type authCookieSha1 struct {
user, home string
}
func (a authCookieSha1) FirstData() ([]byte, []byte, AuthStatus) {
b := make([]byte, 2*len(a.user))
hex.Encode(b, []byte(a.user))
return []byte("DBUS_COOKIE_SHA1"), b, AuthContinue
}
func (a authCookieSha1) HandleData(data []byte) ([]byte, AuthStatus) {
challenge := make([]byte, len(data)/2)
_, err := hex.Decode(challenge, data)
if err != nil {
return nil, AuthError
}
b := bytes.Split(challenge, []byte{' '})
if len(b) != 3 {
return nil, AuthError
}
context := b[0]
id := b[1]
svchallenge := b[2]
cookie := a.getCookie(context, id)
if cookie == nil {
return nil, AuthError
}
clchallenge := a.generateChallenge()
if clchallenge == nil {
return nil, AuthError
}
hash := sha1.New()
hash.Write(bytes.Join([][]byte{svchallenge, clchallenge, cookie}, []byte{':'}))
hexhash := make([]byte, 2*hash.Size())
hex.Encode(hexhash, hash.Sum(nil))
data = append(clchallenge, ' ')
data = append(data, hexhash...)
resp := make([]byte, 2*len(data))
hex.Encode(resp, data)
return resp, AuthOk
}
// getCookie searches for the cookie identified by id in context and returns
// the cookie content or nil. (Since HandleData can't return a specific error,
// but only whether an error occured, this function also doesn't bother to
// return an error.)
func (a authCookieSha1) getCookie(context, id []byte) []byte {
file, err := os.Open(a.home + "/.dbus-keyrings/" + string(context))
if err != nil {
return nil
}
defer file.Close()
rd := bufio.NewReader(file)
for {
line, err := rd.ReadBytes('\n')
if err != nil {
return nil
}
line = line[:len(line)-1]
b := bytes.Split(line, []byte{' '})
if len(b) != 3 {
return nil
}
if bytes.Equal(b[0], id) {
return b[2]
}
}
}
// generateChallenge returns a random, hex-encoded challenge, or nil on error
// (see above).
func (a authCookieSha1) generateChallenge() []byte {
b := make([]byte, 16)
n, err := rand.Read(b)
if err != nil {
return nil
}
if n != 16 {
return nil
}
enc := make([]byte, 32)
hex.Encode(enc, b)
return enc
}

View File

@ -1,36 +0,0 @@
package dbus
import (
"errors"
)
// Call represents a pending or completed method call.
type Call struct {
Destination string
Path ObjectPath
Method string
Args []interface{}
// Strobes when the call is complete.
Done chan *Call
// After completion, the error status. If this is non-nil, it may be an
// error message from the peer (with Error as its type) or some other error.
Err error
// Holds the response once the call is done.
Body []interface{}
}
var errSignature = errors.New("dbus: mismatched signature")
// Store stores the body of the reply into the provided pointers. It returns
// an error if the signatures of the body and retvalues don't match, or if
// the error status is not nil.
func (c *Call) Store(retvalues ...interface{}) error {
if c.Err != nil {
return c.Err
}
return Store(c.Body, retvalues...)
}

View File

@ -1,683 +0,0 @@
package dbus
import (
"errors"
"io"
"os"
"reflect"
"strings"
"sync"
)
var (
systemBus *Conn
systemBusLck sync.Mutex
sessionBus *Conn
sessionBusLck sync.Mutex
sessionEnvLck sync.Mutex
)
// ErrClosed is the error returned by calls on a closed connection.
var ErrClosed = errors.New("dbus: connection closed by user")
// Conn represents a connection to a message bus (usually, the system or
// session bus).
//
// Connections are either shared or private. Shared connections
// are shared between calls to the functions that return them. As a result,
// the methods Close, Auth and Hello must not be called on them.
//
// Multiple goroutines may invoke methods on a connection simultaneously.
type Conn struct {
transport
busObj BusObject
unixFD bool
uuid string
names []string
namesLck sync.RWMutex
serialLck sync.Mutex
nextSerial uint32
serialUsed map[uint32]bool
calls map[uint32]*Call
callsLck sync.RWMutex
handler Handler
out chan *Message
closed bool
outLck sync.RWMutex
signalHandler SignalHandler
eavesdropped chan<- *Message
eavesdroppedLck sync.Mutex
}
// SessionBus returns a shared connection to the session bus, connecting to it
// if not already done.
func SessionBus() (conn *Conn, err error) {
sessionBusLck.Lock()
defer sessionBusLck.Unlock()
if sessionBus != nil {
return sessionBus, nil
}
defer func() {
if conn != nil {
sessionBus = conn
}
}()
conn, err = SessionBusPrivate()
if err != nil {
return
}
if err = conn.Auth(nil); err != nil {
conn.Close()
conn = nil
return
}
if err = conn.Hello(); err != nil {
conn.Close()
conn = nil
}
return
}
func getSessionBusAddress() (string, error) {
sessionEnvLck.Lock()
defer sessionEnvLck.Unlock()
address := os.Getenv("DBUS_SESSION_BUS_ADDRESS")
if address != "" && address != "autolaunch:" {
return address, nil
}
return getSessionBusPlatformAddress()
}
// SessionBusPrivate returns a new private connection to the session bus.
func SessionBusPrivate() (*Conn, error) {
address, err := getSessionBusAddress()
if err != nil {
return nil, err
}
return Dial(address)
}
// SessionBusPrivate returns a new private connection to the session bus.
func SessionBusPrivateHandler(handler Handler, signalHandler SignalHandler) (*Conn, error) {
address, err := getSessionBusAddress()
if err != nil {
return nil, err
}
return DialHandler(address, handler, signalHandler)
}
// SystemBus returns a shared connection to the system bus, connecting to it if
// not already done.
func SystemBus() (conn *Conn, err error) {
systemBusLck.Lock()
defer systemBusLck.Unlock()
if systemBus != nil {
return systemBus, nil
}
defer func() {
if conn != nil {
systemBus = conn
}
}()
conn, err = SystemBusPrivate()
if err != nil {
return
}
if err = conn.Auth(nil); err != nil {
conn.Close()
conn = nil
return
}
if err = conn.Hello(); err != nil {
conn.Close()
conn = nil
}
return
}
// SystemBusPrivate returns a new private connection to the system bus.
func SystemBusPrivate() (*Conn, error) {
return Dial(getSystemBusPlatformAddress())
}
// SystemBusPrivateHandler returns a new private connection to the system bus, using the provided handlers.
func SystemBusPrivateHandler(handler Handler, signalHandler SignalHandler) (*Conn, error) {
return DialHandler(getSystemBusPlatformAddress(), handler, signalHandler)
}
// Dial establishes a new private connection to the message bus specified by address.
func Dial(address string) (*Conn, error) {
tr, err := getTransport(address)
if err != nil {
return nil, err
}
return newConn(tr, newDefaultHandler(), newDefaultSignalHandler())
}
// DialHandler establishes a new private connection to the message bus specified by address, using the supplied handlers.
func DialHandler(address string, handler Handler, signalHandler SignalHandler) (*Conn, error) {
tr, err := getTransport(address)
if err != nil {
return nil, err
}
return newConn(tr, handler, signalHandler)
}
// NewConn creates a new private *Conn from an already established connection.
func NewConn(conn io.ReadWriteCloser) (*Conn, error) {
return NewConnHandler(conn, newDefaultHandler(), newDefaultSignalHandler())
}
// NewConnHandler creates a new private *Conn from an already established connection, using the supplied handlers.
func NewConnHandler(conn io.ReadWriteCloser, handler Handler, signalHandler SignalHandler) (*Conn, error) {
return newConn(genericTransport{conn}, handler, signalHandler)
}
// newConn creates a new *Conn from a transport.
func newConn(tr transport, handler Handler, signalHandler SignalHandler) (*Conn, error) {
conn := new(Conn)
conn.transport = tr
conn.calls = make(map[uint32]*Call)
conn.out = make(chan *Message, 10)
conn.handler = handler
conn.signalHandler = signalHandler
conn.nextSerial = 1
conn.serialUsed = map[uint32]bool{0: true}
conn.busObj = conn.Object("org.freedesktop.DBus", "/org/freedesktop/DBus")
return conn, nil
}
// BusObject returns the object owned by the bus daemon which handles
// administrative requests.
func (conn *Conn) BusObject() BusObject {
return conn.busObj
}
// Close closes the connection. Any blocked operations will return with errors
// and the channels passed to Eavesdrop and Signal are closed. This method must
// not be called on shared connections.
func (conn *Conn) Close() error {
conn.outLck.Lock()
if conn.closed {
// inWorker calls Close on read error, the read error may
// be caused by another caller calling Close to shutdown the
// dbus connection, a double-close scenario we prevent here.
conn.outLck.Unlock()
return nil
}
close(conn.out)
conn.closed = true
conn.outLck.Unlock()
if term, ok := conn.signalHandler.(Terminator); ok {
term.Terminate()
}
if term, ok := conn.handler.(Terminator); ok {
term.Terminate()
}
conn.eavesdroppedLck.Lock()
if conn.eavesdropped != nil {
close(conn.eavesdropped)
}
conn.eavesdroppedLck.Unlock()
return conn.transport.Close()
}
// Eavesdrop causes conn to send all incoming messages to the given channel
// without further processing. Method replies, errors and signals will not be
// sent to the appropiate channels and method calls will not be handled. If nil
// is passed, the normal behaviour is restored.
//
// The caller has to make sure that ch is sufficiently buffered;
// if a message arrives when a write to ch is not possible, the message is
// discarded.
func (conn *Conn) Eavesdrop(ch chan<- *Message) {
conn.eavesdroppedLck.Lock()
conn.eavesdropped = ch
conn.eavesdroppedLck.Unlock()
}
// getSerial returns an unused serial.
func (conn *Conn) getSerial() uint32 {
conn.serialLck.Lock()
defer conn.serialLck.Unlock()
n := conn.nextSerial
for conn.serialUsed[n] {
n++
}
conn.serialUsed[n] = true
conn.nextSerial = n + 1
return n
}
// Hello sends the initial org.freedesktop.DBus.Hello call. This method must be
// called after authentication, but before sending any other messages to the
// bus. Hello must not be called for shared connections.
func (conn *Conn) Hello() error {
var s string
err := conn.busObj.Call("org.freedesktop.DBus.Hello", 0).Store(&s)
if err != nil {
return err
}
conn.namesLck.Lock()
conn.names = make([]string, 1)
conn.names[0] = s
conn.namesLck.Unlock()
return nil
}
// inWorker runs in an own goroutine, reading incoming messages from the
// transport and dispatching them appropiately.
func (conn *Conn) inWorker() {
for {
msg, err := conn.ReadMessage()
if err == nil {
conn.eavesdroppedLck.Lock()
if conn.eavesdropped != nil {
select {
case conn.eavesdropped <- msg:
default:
}
conn.eavesdroppedLck.Unlock()
continue
}
conn.eavesdroppedLck.Unlock()
dest, _ := msg.Headers[FieldDestination].value.(string)
found := false
if dest == "" {
found = true
} else {
conn.namesLck.RLock()
if len(conn.names) == 0 {
found = true
}
for _, v := range conn.names {
if dest == v {
found = true
break
}
}
conn.namesLck.RUnlock()
}
if !found {
// Eavesdropped a message, but no channel for it is registered.
// Ignore it.
continue
}
switch msg.Type {
case TypeMethodReply, TypeError:
serial := msg.Headers[FieldReplySerial].value.(uint32)
conn.callsLck.Lock()
if c, ok := conn.calls[serial]; ok {
if msg.Type == TypeError {
name, _ := msg.Headers[FieldErrorName].value.(string)
c.Err = Error{name, msg.Body}
} else {
c.Body = msg.Body
}
c.Done <- c
conn.serialLck.Lock()
delete(conn.serialUsed, serial)
conn.serialLck.Unlock()
delete(conn.calls, serial)
}
conn.callsLck.Unlock()
case TypeSignal:
iface := msg.Headers[FieldInterface].value.(string)
member := msg.Headers[FieldMember].value.(string)
// as per http://dbus.freedesktop.org/doc/dbus-specification.html ,
// sender is optional for signals.
sender, _ := msg.Headers[FieldSender].value.(string)
if iface == "org.freedesktop.DBus" && sender == "org.freedesktop.DBus" {
if member == "NameLost" {
// If we lost the name on the bus, remove it from our
// tracking list.
name, ok := msg.Body[0].(string)
if !ok {
panic("Unable to read the lost name")
}
conn.namesLck.Lock()
for i, v := range conn.names {
if v == name {
conn.names = append(conn.names[:i],
conn.names[i+1:]...)
}
}
conn.namesLck.Unlock()
} else if member == "NameAcquired" {
// If we acquired the name on the bus, add it to our
// tracking list.
name, ok := msg.Body[0].(string)
if !ok {
panic("Unable to read the acquired name")
}
conn.namesLck.Lock()
conn.names = append(conn.names, name)
conn.namesLck.Unlock()
}
}
go conn.handleSignal(msg)
case TypeMethodCall:
go conn.handleCall(msg)
}
} else if _, ok := err.(InvalidMessageError); !ok {
// Some read error occured (usually EOF); we can't really do
// anything but to shut down all stuff and returns errors to all
// pending replies.
conn.Close()
conn.callsLck.RLock()
for _, v := range conn.calls {
v.Err = err
v.Done <- v
}
conn.callsLck.RUnlock()
return
}
// invalid messages are ignored
}
}
func (conn *Conn) handleSignal(msg *Message) {
iface := msg.Headers[FieldInterface].value.(string)
member := msg.Headers[FieldMember].value.(string)
// as per http://dbus.freedesktop.org/doc/dbus-specification.html ,
// sender is optional for signals.
sender, _ := msg.Headers[FieldSender].value.(string)
signal := &Signal{
Sender: sender,
Path: msg.Headers[FieldPath].value.(ObjectPath),
Name: iface + "." + member,
Body: msg.Body,
}
conn.signalHandler.DeliverSignal(iface, member, signal)
}
// Names returns the list of all names that are currently owned by this
// connection. The slice is always at least one element long, the first element
// being the unique name of the connection.
func (conn *Conn) Names() []string {
conn.namesLck.RLock()
// copy the slice so it can't be modified
s := make([]string, len(conn.names))
copy(s, conn.names)
conn.namesLck.RUnlock()
return s
}
// Object returns the object identified by the given destination name and path.
func (conn *Conn) Object(dest string, path ObjectPath) BusObject {
return &Object{conn, dest, path}
}
// outWorker runs in an own goroutine, encoding and sending messages that are
// sent to conn.out.
func (conn *Conn) outWorker() {
for msg := range conn.out {
err := conn.SendMessage(msg)
conn.callsLck.RLock()
if err != nil {
if c := conn.calls[msg.serial]; c != nil {
c.Err = err
c.Done <- c
}
conn.serialLck.Lock()
delete(conn.serialUsed, msg.serial)
conn.serialLck.Unlock()
} else if msg.Type != TypeMethodCall {
conn.serialLck.Lock()
delete(conn.serialUsed, msg.serial)
conn.serialLck.Unlock()
}
conn.callsLck.RUnlock()
}
}
// Send sends the given message to the message bus. You usually don't need to
// use this; use the higher-level equivalents (Call / Go, Emit and Export)
// instead. If msg is a method call and NoReplyExpected is not set, a non-nil
// call is returned and the same value is sent to ch (which must be buffered)
// once the call is complete. Otherwise, ch is ignored and a Call structure is
// returned of which only the Err member is valid.
func (conn *Conn) Send(msg *Message, ch chan *Call) *Call {
var call *Call
msg.serial = conn.getSerial()
if msg.Type == TypeMethodCall && msg.Flags&FlagNoReplyExpected == 0 {
if ch == nil {
ch = make(chan *Call, 5)
} else if cap(ch) == 0 {
panic("dbus: unbuffered channel passed to (*Conn).Send")
}
call = new(Call)
call.Destination, _ = msg.Headers[FieldDestination].value.(string)
call.Path, _ = msg.Headers[FieldPath].value.(ObjectPath)
iface, _ := msg.Headers[FieldInterface].value.(string)
member, _ := msg.Headers[FieldMember].value.(string)
call.Method = iface + "." + member
call.Args = msg.Body
call.Done = ch
conn.callsLck.Lock()
conn.calls[msg.serial] = call
conn.callsLck.Unlock()
conn.outLck.RLock()
if conn.closed {
call.Err = ErrClosed
call.Done <- call
} else {
conn.out <- msg
}
conn.outLck.RUnlock()
} else {
conn.outLck.RLock()
if conn.closed {
call = &Call{Err: ErrClosed}
} else {
conn.out <- msg
call = &Call{Err: nil}
}
conn.outLck.RUnlock()
}
return call
}
// sendError creates an error message corresponding to the parameters and sends
// it to conn.out.
func (conn *Conn) sendError(err error, dest string, serial uint32) {
var e *Error
switch em := err.(type) {
case Error:
e = &em
case *Error:
e = em
case DBusError:
name, body := em.DBusError()
e = NewError(name, body)
default:
e = MakeFailedError(err)
}
msg := new(Message)
msg.Type = TypeError
msg.serial = conn.getSerial()
msg.Headers = make(map[HeaderField]Variant)
if dest != "" {
msg.Headers[FieldDestination] = MakeVariant(dest)
}
msg.Headers[FieldErrorName] = MakeVariant(e.Name)
msg.Headers[FieldReplySerial] = MakeVariant(serial)
msg.Body = e.Body
if len(e.Body) > 0 {
msg.Headers[FieldSignature] = MakeVariant(SignatureOf(e.Body...))
}
conn.outLck.RLock()
if !conn.closed {
conn.out <- msg
}
conn.outLck.RUnlock()
}
// sendReply creates a method reply message corresponding to the parameters and
// sends it to conn.out.
func (conn *Conn) sendReply(dest string, serial uint32, values ...interface{}) {
msg := new(Message)
msg.Type = TypeMethodReply
msg.serial = conn.getSerial()
msg.Headers = make(map[HeaderField]Variant)
if dest != "" {
msg.Headers[FieldDestination] = MakeVariant(dest)
}
msg.Headers[FieldReplySerial] = MakeVariant(serial)
msg.Body = values
if len(values) > 0 {
msg.Headers[FieldSignature] = MakeVariant(SignatureOf(values...))
}
conn.outLck.RLock()
if !conn.closed {
conn.out <- msg
}
conn.outLck.RUnlock()
}
func (conn *Conn) defaultSignalAction(fn func(h *defaultSignalHandler, ch chan<- *Signal), ch chan<- *Signal) {
if !isDefaultSignalHandler(conn.signalHandler) {
return
}
handler := conn.signalHandler.(*defaultSignalHandler)
fn(handler, ch)
}
// Signal registers the given channel to be passed all received signal messages.
// The caller has to make sure that ch is sufficiently buffered; if a message
// arrives when a write to c is not possible, it is discarded.
//
// Multiple of these channels can be registered at the same time.
//
// These channels are "overwritten" by Eavesdrop; i.e., if there currently is a
// channel for eavesdropped messages, this channel receives all signals, and
// none of the channels passed to Signal will receive any signals.
func (conn *Conn) Signal(ch chan<- *Signal) {
conn.defaultSignalAction((*defaultSignalHandler).addSignal, ch)
}
// RemoveSignal removes the given channel from the list of the registered channels.
func (conn *Conn) RemoveSignal(ch chan<- *Signal) {
conn.defaultSignalAction((*defaultSignalHandler).removeSignal, ch)
}
// SupportsUnixFDs returns whether the underlying transport supports passing of
// unix file descriptors. If this is false, method calls containing unix file
// descriptors will return an error and emitted signals containing them will
// not be sent.
func (conn *Conn) SupportsUnixFDs() bool {
return conn.unixFD
}
// Error represents a D-Bus message of type Error.
type Error struct {
Name string
Body []interface{}
}
func NewError(name string, body []interface{}) *Error {
return &Error{name, body}
}
func (e Error) Error() string {
if len(e.Body) >= 1 {
s, ok := e.Body[0].(string)
if ok {
return s
}
}
return e.Name
}
// Signal represents a D-Bus message of type Signal. The name member is given in
// "interface.member" notation, e.g. org.freedesktop.D-Bus.NameLost.
type Signal struct {
Sender string
Path ObjectPath
Name string
Body []interface{}
}
// transport is a D-Bus transport.
type transport interface {
// Read and Write raw data (for example, for the authentication protocol).
io.ReadWriteCloser
// Send the initial null byte used for the EXTERNAL mechanism.
SendNullByte() error
// Returns whether this transport supports passing Unix FDs.
SupportsUnixFDs() bool
// Signal the transport that Unix FD passing is enabled for this connection.
EnableUnixFDs()
// Read / send a message, handling things like Unix FDs.
ReadMessage() (*Message, error)
SendMessage(*Message) error
}
var (
transports = make(map[string]func(string) (transport, error))
)
func getTransport(address string) (transport, error) {
var err error
var t transport
addresses := strings.Split(address, ";")
for _, v := range addresses {
i := strings.IndexRune(v, ':')
if i == -1 {
err = errors.New("dbus: invalid bus address (no transport)")
continue
}
f := transports[v[:i]]
if f == nil {
err = errors.New("dbus: invalid bus address (invalid or unsupported transport)")
continue
}
t, err = f(v[i+1:])
if err == nil {
return t, nil
}
}
return nil, err
}
// dereferenceAll returns a slice that, assuming that vs is a slice of pointers
// of arbitrary types, containes the values that are obtained from dereferencing
// all elements in vs.
func dereferenceAll(vs []interface{}) []interface{} {
for i := range vs {
v := reflect.ValueOf(vs[i])
v = v.Elem()
vs[i] = v.Interface()
}
return vs
}
// getKey gets a key from a the list of keys. Returns "" on error / not found...
func getKey(s, key string) string {
for _, keyEqualsValue := range strings.Split(s, ",") {
keyValue := strings.SplitN(keyEqualsValue, "=", 2)
if len(keyValue) == 2 && keyValue[0] == key {
return keyValue[1]
}
}
return ""
}

View File

@ -1,33 +0,0 @@
package dbus
import (
"errors"
"fmt"
"os"
"os/exec"
)
const defaultSystemBusAddress = "unix:path=/opt/local/var/run/dbus/system_bus_socket"
func getSessionBusPlatformAddress() (string, error) {
cmd := exec.Command("launchctl", "getenv", "DBUS_LAUNCHD_SESSION_BUS_SOCKET")
b, err := cmd.CombinedOutput()
if err != nil {
return "", err
}
if len(b) == 0 {
return "", errors.New("dbus: couldn't determine address of session bus")
}
return "unix:path=" + string(b[:len(b)-1]), nil
}
func getSystemBusPlatformAddress() string {
address := os.Getenv("DBUS_LAUNCHD_SESSION_BUS_SOCKET")
if address != "" {
return fmt.Sprintf("unix:path=%s", address)
}
return defaultSystemBusAddress
}

View File

@ -1,42 +0,0 @@
// +build !darwin
package dbus
import (
"bytes"
"errors"
"fmt"
"os"
"os/exec"
)
const defaultSystemBusAddress = "unix:path=/var/run/dbus/system_bus_socket"
func getSessionBusPlatformAddress() (string, error) {
cmd := exec.Command("dbus-launch")
b, err := cmd.CombinedOutput()
if err != nil {
return "", err
}
i := bytes.IndexByte(b, '=')
j := bytes.IndexByte(b, '\n')
if i == -1 || j == -1 {
return "", errors.New("dbus: couldn't determine address of session bus")
}
env, addr := string(b[0:i]), string(b[i+1:j])
os.Setenv(env, addr)
return addr, nil
}
func getSystemBusPlatformAddress() string {
address := os.Getenv("DBUS_SYSTEM_BUS_ADDRESS")
if address != "" {
return fmt.Sprintf("unix:path=%s", address)
}
return defaultSystemBusAddress
}

View File

@ -1,307 +0,0 @@
package dbus
import (
"encoding/binary"
"io"
"io/ioutil"
"testing"
)
func TestSessionBus(t *testing.T) {
_, err := SessionBus()
if err != nil {
t.Error(err)
}
}
func TestSystemBus(t *testing.T) {
_, err := SystemBus()
if err != nil {
t.Error(err)
}
}
func TestSend(t *testing.T) {
bus, err := SessionBus()
if err != nil {
t.Fatal(err)
}
ch := make(chan *Call, 1)
msg := &Message{
Type: TypeMethodCall,
Flags: 0,
Headers: map[HeaderField]Variant{
FieldDestination: MakeVariant(bus.Names()[0]),
FieldPath: MakeVariant(ObjectPath("/org/freedesktop/DBus")),
FieldInterface: MakeVariant("org.freedesktop.DBus.Peer"),
FieldMember: MakeVariant("Ping"),
},
}
call := bus.Send(msg, ch)
<-ch
if call.Err != nil {
t.Error(call.Err)
}
}
func TestRemoveSignal(t *testing.T) {
bus, err := NewConn(nil)
if err != nil {
t.Error(err)
}
signals := bus.signalHandler.(*defaultSignalHandler).signals
ch := make(chan *Signal)
ch2 := make(chan *Signal)
for _, ch := range []chan *Signal{ch, ch2, ch, ch2, ch2, ch} {
bus.Signal(ch)
}
signals = bus.signalHandler.(*defaultSignalHandler).signals
if len(signals) != 6 {
t.Errorf("remove signal: signals length not equal: got '%d', want '6'", len(signals))
}
bus.RemoveSignal(ch)
signals = bus.signalHandler.(*defaultSignalHandler).signals
if len(signals) != 3 {
t.Errorf("remove signal: signals length not equal: got '%d', want '3'", len(signals))
}
signals = bus.signalHandler.(*defaultSignalHandler).signals
for _, bch := range signals {
if bch != ch2 {
t.Errorf("remove signal: removed signal present: got '%v', want '%v'", bch, ch2)
}
}
}
type rwc struct {
io.Reader
io.Writer
}
func (rwc) Close() error { return nil }
type fakeAuth struct {
}
func (fakeAuth) FirstData() (name, resp []byte, status AuthStatus) {
return []byte("name"), []byte("resp"), AuthOk
}
func (fakeAuth) HandleData(data []byte) (resp []byte, status AuthStatus) {
return nil, AuthOk
}
func TestCloseBeforeSignal(t *testing.T) {
reader, pipewriter := io.Pipe()
defer pipewriter.Close()
defer reader.Close()
bus, err := NewConn(rwc{Reader: reader, Writer: ioutil.Discard})
if err != nil {
t.Fatal(err)
}
// give ch a buffer so sends won't block
ch := make(chan *Signal, 1)
bus.Signal(ch)
go func() {
_, err := pipewriter.Write([]byte("REJECTED name\r\nOK myuuid\r\n"))
if err != nil {
t.Errorf("error writing to pipe: %v", err)
}
}()
err = bus.Auth([]Auth{fakeAuth{}})
if err != nil {
t.Fatal(err)
}
err = bus.Close()
if err != nil {
t.Fatal(err)
}
msg := &Message{
Type: TypeSignal,
Headers: map[HeaderField]Variant{
FieldInterface: MakeVariant("foo.bar"),
FieldMember: MakeVariant("bar"),
FieldPath: MakeVariant(ObjectPath("/baz")),
},
}
err = msg.EncodeTo(pipewriter, binary.LittleEndian)
if err != nil {
t.Fatal(err)
}
}
type server struct{}
func (server) Double(i int64) (int64, *Error) {
return 2 * i, nil
}
func BenchmarkCall(b *testing.B) {
b.StopTimer()
var s string
bus, err := SessionBus()
if err != nil {
b.Fatal(err)
}
name := bus.Names()[0]
obj := bus.BusObject()
b.StartTimer()
for i := 0; i < b.N; i++ {
err := obj.Call("org.freedesktop.DBus.GetNameOwner", 0, name).Store(&s)
if err != nil {
b.Fatal(err)
}
if s != name {
b.Errorf("got %s, wanted %s", s, name)
}
}
}
func BenchmarkCallAsync(b *testing.B) {
b.StopTimer()
bus, err := SessionBus()
if err != nil {
b.Fatal(err)
}
name := bus.Names()[0]
obj := bus.BusObject()
c := make(chan *Call, 50)
done := make(chan struct{})
go func() {
for i := 0; i < b.N; i++ {
v := <-c
if v.Err != nil {
b.Error(v.Err)
}
s := v.Body[0].(string)
if s != name {
b.Errorf("got %s, wanted %s", s, name)
}
}
close(done)
}()
b.StartTimer()
for i := 0; i < b.N; i++ {
obj.Go("org.freedesktop.DBus.GetNameOwner", 0, c, name)
}
<-done
}
func BenchmarkServe(b *testing.B) {
b.StopTimer()
srv, err := SessionBus()
if err != nil {
b.Fatal(err)
}
cli, err := SessionBusPrivate()
if err != nil {
b.Fatal(err)
}
if err = cli.Auth(nil); err != nil {
b.Fatal(err)
}
if err = cli.Hello(); err != nil {
b.Fatal(err)
}
benchmarkServe(b, srv, cli)
}
func BenchmarkServeAsync(b *testing.B) {
b.StopTimer()
srv, err := SessionBus()
if err != nil {
b.Fatal(err)
}
cli, err := SessionBusPrivate()
if err != nil {
b.Fatal(err)
}
if err = cli.Auth(nil); err != nil {
b.Fatal(err)
}
if err = cli.Hello(); err != nil {
b.Fatal(err)
}
benchmarkServeAsync(b, srv, cli)
}
func BenchmarkServeSameConn(b *testing.B) {
b.StopTimer()
bus, err := SessionBus()
if err != nil {
b.Fatal(err)
}
benchmarkServe(b, bus, bus)
}
func BenchmarkServeSameConnAsync(b *testing.B) {
b.StopTimer()
bus, err := SessionBus()
if err != nil {
b.Fatal(err)
}
benchmarkServeAsync(b, bus, bus)
}
func benchmarkServe(b *testing.B, srv, cli *Conn) {
var r int64
var err error
dest := srv.Names()[0]
srv.Export(server{}, "/org/guelfey/DBus/Test", "org.guelfey.DBus.Test")
obj := cli.Object(dest, "/org/guelfey/DBus/Test")
b.StartTimer()
for i := 0; i < b.N; i++ {
err = obj.Call("org.guelfey.DBus.Test.Double", 0, int64(i)).Store(&r)
if err != nil {
b.Fatal(err)
}
if r != 2*int64(i) {
b.Errorf("got %d, wanted %d", r, 2*int64(i))
}
}
}
func benchmarkServeAsync(b *testing.B, srv, cli *Conn) {
dest := srv.Names()[0]
srv.Export(server{}, "/org/guelfey/DBus/Test", "org.guelfey.DBus.Test")
obj := cli.Object(dest, "/org/guelfey/DBus/Test")
c := make(chan *Call, 50)
done := make(chan struct{})
go func() {
for i := 0; i < b.N; i++ {
v := <-c
if v.Err != nil {
b.Fatal(v.Err)
}
i, r := v.Args[0].(int64), v.Body[0].(int64)
if 2*i != r {
b.Errorf("got %d, wanted %d", r, 2*i)
}
}
close(done)
}()
b.StartTimer()
for i := 0; i < b.N; i++ {
obj.Go("org.guelfey.DBus.Test.Double", 0, c, int64(i))
}
<-done
}
func TestGetKey(t *testing.T) {
keys := "host=1.2.3.4,port=5678,family=ipv4"
if host := getKey(keys, "host"); host != "1.2.3.4" {
t.Error(`Expected "1.2.3.4", got`, host)
}
if port := getKey(keys, "port"); port != "5678" {
t.Error(`Expected "5678", got`, port)
}
if family := getKey(keys, "family"); family != "ipv4" {
t.Error(`Expected "ipv4", got`, family)
}
}

Some files were not shown because too many files have changed in this diff Show More