github.com/netdata/go.d.plugin@v0.58.1/modules/logind/connection.go (about)

     1  // SPDX-License-Identifier: GPL-3.0-or-later
     2  
     3  //go:build linux
     4  // +build linux
     5  
     6  package logind
     7  
     8  import (
     9  	"context"
    10  	"time"
    11  
    12  	"github.com/coreos/go-systemd/v22/login1"
    13  	"github.com/godbus/dbus/v5"
    14  )
    15  
    16  type logindConnection interface {
    17  	Close()
    18  
    19  	ListSessions() ([]login1.Session, error)
    20  	GetSessionProperties(dbus.ObjectPath) (map[string]dbus.Variant, error)
    21  
    22  	ListUsers() ([]login1.User, error)
    23  	GetUserProperty(dbus.ObjectPath, string) (*dbus.Variant, error)
    24  }
    25  
    26  func newLogindConnection(timeout time.Duration) (logindConnection, error) {
    27  	conn, err := login1.New()
    28  	if err != nil {
    29  		return nil, err
    30  	}
    31  	return &logindDBusConnection{
    32  		conn:    conn,
    33  		timeout: timeout,
    34  	}, nil
    35  }
    36  
    37  type logindDBusConnection struct {
    38  	conn    *login1.Conn
    39  	timeout time.Duration
    40  }
    41  
    42  func (c *logindDBusConnection) Close() {
    43  	if c.conn != nil {
    44  		c.conn.Close()
    45  		c.conn = nil
    46  	}
    47  }
    48  
    49  func (c *logindDBusConnection) ListSessions() ([]login1.Session, error) {
    50  	ctx, cancel := context.WithTimeout(context.Background(), c.timeout)
    51  	defer cancel()
    52  
    53  	return c.conn.ListSessionsContext(ctx)
    54  }
    55  
    56  func (c *logindDBusConnection) ListUsers() ([]login1.User, error) {
    57  	ctx, cancel := context.WithTimeout(context.Background(), c.timeout)
    58  	defer cancel()
    59  
    60  	return c.conn.ListUsersContext(ctx)
    61  }
    62  
    63  func (c *logindDBusConnection) GetSessionProperties(path dbus.ObjectPath) (map[string]dbus.Variant, error) {
    64  	ctx, cancel := context.WithTimeout(context.Background(), c.timeout)
    65  	defer cancel()
    66  
    67  	return c.conn.GetSessionPropertiesContext(ctx, path)
    68  }
    69  
    70  func (c *logindDBusConnection) GetUserProperty(path dbus.ObjectPath, property string) (*dbus.Variant, error) {
    71  	ctx, cancel := context.WithTimeout(context.Background(), c.timeout)
    72  	defer cancel()
    73  
    74  	return c.conn.GetUserPropertyContext(ctx, path, property)
    75  }