summaryrefslogtreecommitdiffstats
path: root/src/go/collectors/go.d.plugin/modules/logind/connection.go
blob: b97387acf06a0e0199c001b969929081a29c82a1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// SPDX-License-Identifier: GPL-3.0-or-later

//go:build linux
// +build linux

package logind

import (
	"context"
	"time"

	"github.com/coreos/go-systemd/v22/login1"
	"github.com/godbus/dbus/v5"
)

type logindConnection interface {
	Close()

	ListSessions() ([]login1.Session, error)
	GetSessionProperties(dbus.ObjectPath) (map[string]dbus.Variant, error)

	ListUsers() ([]login1.User, error)
	GetUserProperty(dbus.ObjectPath, string) (*dbus.Variant, error)
}

func newLogindConnection(timeout time.Duration) (logindConnection, error) {
	conn, err := login1.New()
	if err != nil {
		return nil, err
	}
	return &logindDBusConnection{
		conn:    conn,
		timeout: timeout,
	}, nil
}

type logindDBusConnection struct {
	conn    *login1.Conn
	timeout time.Duration
}

func (c *logindDBusConnection) Close() {
	if c.conn != nil {
		c.conn.Close()
		c.conn = nil
	}
}

func (c *logindDBusConnection) ListSessions() ([]login1.Session, error) {
	ctx, cancel := context.WithTimeout(context.Background(), c.timeout)
	defer cancel()

	return c.conn.ListSessionsContext(ctx)
}

func (c *logindDBusConnection) ListUsers() ([]login1.User, error) {
	ctx, cancel := context.WithTimeout(context.Background(), c.timeout)
	defer cancel()

	return c.conn.ListUsersContext(ctx)
}

func (c *logindDBusConnection) GetSessionProperties(path dbus.ObjectPath) (map[string]dbus.Variant, error) {
	ctx, cancel := context.WithTimeout(context.Background(), c.timeout)
	defer cancel()

	return c.conn.GetSessionPropertiesContext(ctx, path)
}

func (c *logindDBusConnection) GetUserProperty(path dbus.ObjectPath, property string) (*dbus.Variant, error) {
	ctx, cancel := context.WithTimeout(context.Background(), c.timeout)
	defer cancel()

	return c.conn.GetUserPropertyContext(ctx, path, property)
}